<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Supun Bandara on Medium]]></title>
        <description><![CDATA[Stories by Supun Bandara on Medium]]></description>
        <link>https://medium.com/@supunbandara?source=rss-8afa21e8efce------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XgZm7Atb0ab7oofSmlRucQ.png</url>
            <title>Stories by Supun Bandara on Medium</title>
            <link>https://medium.com/@supunbandara?source=rss-8afa21e8efce------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 00:45:25 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@supunbandara/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Designing Data Tables That Remain Fast with Thousands of Records]]></title>
            <link>https://medium.com/@supunbandara/designing-data-tables-that-remain-fast-with-thousands-of-records-b9040ff50ada?source=rss-8afa21e8efce------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9040ff50ada</guid>
            <category><![CDATA[database-indexing]]></category>
            <category><![CDATA[react-performance]]></category>
            <category><![CDATA[tanstack-table]]></category>
            <category><![CDATA[web-performance]]></category>
            <category><![CDATA[pagination]]></category>
            <dc:creator><![CDATA[Supun Bandara]]></dc:creator>
            <pubDate>Wed, 02 Dec 2026 11:10:05 GMT</pubDate>
            <atom:updated>2026-12-02T11:10:05.676Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Slow tables usually have one of three problems: a slow database query, too much data sent over the network, or too much for the browser to draw. The trick is fixing the right one.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZfnE2UMjgRcaQz6vkUeabw.png" /><figcaption>Image created and edited by the author</figcaption></figure><p>The demo worked great with 50 rows. Then the table met production: 80,000 orders, a search box, six filters and an Export button that sometimes crashed the server.</p><p>The usual reaction is to grab a trick: add React.memo, add virtualization, add a loading spinner. But a table is really a chain: <strong>database → server → network → browser</strong>. Any link in that chain can be the slow one, and fixing the wrong link changes nothing.</p><p>This article walks along the chain in order. Every idea is explained in plain words first, then shown with a small example.</p><h3>Step 0: Find Out What Is Slow</h3><p>Every speed up for tables targets one of three places:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tkY7pYFVz9dW3po0AJLyUw.png" /></figure><p>Open your browser’s DevTools. In the <strong>Network</strong> tab, is the request slow or huge? In the <strong>Performance</strong> tab, is the browser busy for a long time after the data arrives? Your answer tells you where to start. If the API takes 3 seconds, virtualization won’t help. If the API takes 40 ms but the page freezes while you type, an index won’t help.</p><h3>Do You Need the Server to Do the Work?</h3><p>Here’s something that surprises people: <strong>a few thousand rows is often not “big”.</strong></p><p>The TanStack Table docs say client-side processing is usually the simplest choice, and they stress-test it with a million rows. If you download all the rows once, sorting and filtering feel instant because nothing waits on the network.</p><p>Move the work to the server when:</p><ul><li>There is too much data to download, or it makes the browser slow</li><li>The data changes often, so a big download goes stale</li><li>The backend must enforce who can see which rows</li><li>The database can search and sort faster than the browser can</li></ul><p>If none of these are true, keep it simple. The rest of this article is for when the answer is “yes, the server should do the work.”</p><h3>Server Side Pagination: Load One Page at a Time</h3><p>Think of a library. You don’t carry every book home. You ask for the shelf you need. A table works the same way: <strong>the browser only holds the rows it is about to show.</strong></p><p>Instead of GET /orders returning everything, the browser asks for one slice:</p><pre>GET /orders?pageSize=50&amp;page=3&amp;sort=-createdAt&amp;status=paid</pre><p>The table library keeps track of the <em>settings</em> (which page, which sort, which filters). Your code turns those settings into a request. In TanStack Table v9 (now stable), you tell the table “the server already did this work” using manual* options:</p><pre>const query = useQuery({<br>  // Everything the server needs to know goes in the key<br>  queryKey: [&#39;orders&#39;, { sorting, filters, pagination }],<br>  queryFn: ({ signal }) =&gt; fetchOrders({ sorting, filters, pagination }, signal),<br>  placeholderData: keepPreviousData, // keep the old page visible while loading<br>})<br><br>const table = useTable({<br>  features,<br>  columns,<br>  data: query.data?.rows ?? [],<br>  rowCount: query.data?.rowCount,<br>  manualPagination: true, // server does paging<br>  manualSorting: true,    // server does sorting<br>  manualFiltering: true,  // server does filtering<br>})</pre><p><em>(This is a sketch. The v9 “Client Side vs Server Side” guide shows the full state setup.)</em></p><p>Three habits make this feel smooth:</p><ul><li><strong>Put every setting in the query key.</strong> Change the sort and a new request starts automatically. Go back to a page you already saw and it can load from cache.</li><li><strong>Keep the old page visible while the new one loads.</strong> Otherwise the table flashes empty on every click.</li><li><strong>Go back to page 1 when filters change.</strong> If you are on page 9 and a filter leaves only 2 pages, you would be asking for a page that doesn’t exist.</li></ul><p>One trap to avoid: <strong>if the server does the paging, the server must also do the sorting and filtering.</strong> Otherwise the browser sorts only the 50 rows it has, not all 80,000. It looks right, but the answer is wrong.</p><h3>Sorting and Filtering Belong on the Server Too</h3><p>The browser sends <em>what it wants</em> (“paid orders, newest first”). The server turns that into a database query. Two rules keep this safe and correct.</p><p><strong>Rule 1: Only allow known columns.</strong> Never paste a column name from the URL straight into SQL. Use a short allow-list instead:</p><pre>const SORTABLE = {<br>  createdAt: &#39;created_at&#39;,<br>  total: &#39;total_cents&#39;,<br>  status: &#39;status&#39;,<br>} as const<br><br>// Unknown names fall back to a safe default<br>const column = SORTABLE[key] ?? SORTABLE.createdAt</pre><p><strong>Rule 2: Always add a tie-breaker.</strong> Imagine sorting by status when 1,000 orders share the status &quot;paid&quot;. The database may return them in any order, so a row can show up on two pages or on none. Add a unique column like id as the last sort key (ORDER BY status, id) and the order stays fixed.</p><h3>Offset vs. Cursor Pagination</h3><p>There are two ways to say “give me the next page”.</p><p><strong>Offset pagination</strong> means “skip the first N rows, then give me 50”:</p><pre>SELECT * FROM orders<br>ORDER BY created_at DESC, id DESC<br>LIMIT 50 OFFSET 100000;</pre><p>It’s simple, and it lets users jump to page 37. But the database still has to count past those 100,000 rows before it can return yours. The deeper you go, the slower it gets. It can also show duplicates if new rows arrive while someone is paging.</p><p><strong>Cursor pagination</strong> (also called keyset pagination) means “give me the 50 rows after <em>this</em> one”. Think of it as a <strong>bookmark</strong>:</p><pre>SELECT * FROM orders<br>WHERE (created_at, id) &lt; ($1, $2)   -- the last row the user saw<br>ORDER BY created_at DESC, id DESC<br>LIMIT 51;                           -- one extra row tells you if there is a next page</pre><p>The database jumps straight to the bookmark using an index, so page 1 and page 1,000 cost about the same.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oxdp-mHbWPHKs2MmG4u1bg.png" /></figure><p>A simple rule: <strong>if users really need page numbers and the table is moderate, use offset. If the table is huge, live, or scrolls forever, use cursors.</strong></p><p>Two things to remember with cursors:</p><ul><li><strong>Send the cursor as an opaque token</strong> (an encoded string), not as raw values the user can edit.</li><li><strong>Exact total counts are expensive.</strong> Counting millions of filtered rows can cost more than the page itself. Consider showing “10,000+” instead of an exact number.</li></ul><h3>Database Indexes: The Index at the Back of a Book</h3><p>Imagine finding every mention of “cursor” in a 500-page book. You could read every page. Or you could open the <strong>index</strong>at the back and jump straight to the right pages.</p><p>A database index does the same job. Without one, the database reads every row (a “full table scan”). With one, it jumps to the right place. On a big table, that’s the difference between milliseconds and seconds.</p><p>The key idea: <strong>build the index to match the query your table actually runs.</strong> If the table is filtered by status and sorted by newest:</p><pre>CREATE INDEX orders_status_created_idx<br>  ON orders (status, created_at DESC, id DESC);</pre><p>Order matters. Put the filter column first (status), then the sort columns in the same direction as your ORDER BY. The database can then read rows already in the right order and stop after 50.</p><p>A few things that catch people out:</p><ul><li><strong>Search with a leading wildcard ignores normal indexes.</strong> WHERE name ILIKE &#39;%acme%&#39; can&#39;t use a regular index. In PostgreSQL, use a trigram index (pg_trgm) or full-text search.</li><li><strong>You can’t index every filter combination.</strong> Look at which filters people really use together, and index those.</li><li><strong>Indexes slow down writes and use space.</strong> Add the ones you need, and remove the ones nobody uses.</li><li><strong>Check the query plan, don’t guess.</strong> Run EXPLAIN (ANALYZE, BUFFERS) on the real query. If it says &quot;sequential scan&quot; on millions of rows, you&#39;ve found the problem.</li></ul><p>A good habit: for each table, write down its default sort, its supported filters, and the index that serves them. If you can’t name the index, you probably don’t have one.</p><h3>Debounced Search: Wait Until the User Pauses</h3><p>If someone types “invoice”, a naive search box sends 7 requests: “i”, “in”, “inv” and so on. Six of them are wasted. Worse, they can come back in the wrong order, so an old result can replace a newer one.</p><p><strong>Debouncing</strong> means “wait until the user stops typing for a moment, then search once.”</p><pre>function useDebouncedValue&lt;T&gt;(value: T, delay = 300) {<br>  const [debounced, setDebounced] = useState(value)<br>  useEffect(() =&gt; {<br>    const id = setTimeout(() =&gt; setDebounced(value), delay)<br>    return () =&gt; clearTimeout(id) // typing again cancels the wait<br>  }, [value, delay])<br>  return debounced<br>}<br><br>const [input, setInput] = useState(&#39;&#39;)               // updates on every key<br>const search = useDebouncedValue(input, 300)          // updates after a pause<br>// Show `input` in the text box. Send `search` to the server.</pre><p>Three habits go with it:</p><ol><li><strong>Keep two values.</strong> The text box updates instantly so typing feels smooth. The debounced value is the one sent to the server.</li><li><strong>Cancel old requests.</strong> Pass the signal from your data library to fetch so a slow old request can&#39;t overwrite a newer one.</li><li><strong>Keep showing the old results</strong> until the new ones arrive.</li></ol><p>A delay of about 250 to 400 ms is a good starting point. Also consider waiting for 2 or 3 characters before searching.</p><h3>Keep Table State in the URL</h3><p>Search text, filters, sort order and page size describe <em>what the user is looking at</em>. That kind of state belongs in the address bar:</p><pre>/orders?status=paid&amp;q=acme&amp;sort=-createdAt&amp;pageSize=50</pre><p>Why? People paste links to filtered views into chat. They refresh the page. They press Back. A table that forgets everything on refresh feels broken, and a table whose URL carries its state just works. The URL becomes the single source of truth, and your query key is built from it.</p><p>A few rules to follow:</p><ul><li><strong>Check the values coming in.</strong> Unknown sort names, silly page sizes and broken cursors should fall back to defaults instead of crashing.</li><li><strong>Write to the URL after the debounce,</strong> not on every keystroke, so browser history doesn’t fill up with half-typed words.</li><li><strong>Reset the page or cursor when a filter changes.</strong> A bookmark from one result set means nothing in another.</li><li><strong>Don’t put secrets in the URL.</strong> Filters are fine. Anything sensitive is not.</li></ul><p>The same URL values can also describe an export job, which we’ll cover soon.</p><h3>Send Fewer Columns, Draw Lighter Cells</h3><p>The cheapest cell to render is the one you never send.</p><p><strong>Trim the response.</strong> The list needs six fields. Don’t return the whole order with nested items, long descriptions and audit logs. Smaller responses are faster to query, send and read.</p><p><strong>Hide rarely used columns by default.</strong> Fewer columns means fewer cells for the browser to build.</p><p><strong>Keep cells simple.</strong> The numbers add up fast: 50 rows × 12 columns is 600 cells per page. If every cell mounts a dropdown menu, a tooltip and an image, that’s a lot of work. Show the menu <em>button</em> in each row and build the menu itself only when someone clicks it.</p><p><strong>Keep your column list stable.</strong> Define columns outside your component (or memoize it) and don&#39;t create a new dataarray on every render. A brand-new array each time makes the table think everything changed.</p><h3>Stable Keys and Memoized Rows</h3><p>Two ideas here sound advanced but are simple.</p><p><strong>Keys are name tags.</strong> When the data changes, React uses each row’s key to decide &quot;is this the same row as before?&quot; If you use the row&#39;s position (index) as the key, then after sorting, React matches the wrong rows and mixes up their state. Use the real ID from your backend:</p><pre>// Bad: position as key. Sort the data and rows get mixed up.<br>{rows.map((row, i) =&gt; &lt;Row key={i} row={row} /&gt;)}<br><br>// Good: the record&#39;s own ID<br>{rows.map(row =&gt; &lt;Row key={row.original.id} row={row} /&gt;)}</pre><p>Tell the table library the same thing with getRowId. Then selections and expanded rows stay attached to the right record after a refetch.</p><p><strong>Memoization means “don’t redo work if nothing changed.”</strong> If you type in the search box, the 50 rows below shouldn’t all redraw when none of them changed.</p><p>For years the advice was to wrap rows in React.memo and functions in useCallback by hand. Today <strong>React Compiler is stable</strong>, and it adds this kind of memoization automatically at build time. React&#39;s docs now recommend: for new code, let the compiler handle it, and use useMemo and useCallback only when you need precise control. For existing code, leave your current memoization in place.</p><p>So in practice:</p><ul><li><strong>Turn on the compiler</strong> if you can, and write normal components first.</li><li><strong>Measure before you optimize.</strong> Use the React DevTools Profiler to see which rows redraw when they shouldn’t.</li><li><strong>Use </strong><strong>React.memo only for expensive rows</strong> with stable props. For a tiny row, the check can cost more than the redraw.</li></ul><h3>Row Virtualization: Draw Only What You Can See</h3><p>Picture a very long scroll of paper, viewed through a small window. You can only see a few lines at a time, so there’s no need to paint the whole scroll.</p><p><strong>Virtualization</strong> does exactly that. It draws only the rows inside (and just around) the visible area, and uses empty space to make the scrollbar feel normal. A browser handles a few hundred rows fine, but tens of thousands slow down scrolling and memory use.</p><p>TanStack Table doesn’t include virtualization itself, because it’s a drawing technique, not a table feature. The official partner is TanStack Virtual:</p><pre>import { useVirtualizer } from &#39;@tanstack/react-virtual&#39;<br><br>const rows = table.getRowModel().rows<br>const parentRef = useRef&lt;HTMLDivElement&gt;(null)<br><br>const rowVirtualizer = useVirtualizer({<br>  count: rows.length,<br>  getScrollElement: () =&gt; parentRef.current,<br>  estimateSize: () =&gt; 44, // each row is about 44px tall<br>  overscan: 8,            // draw a few extra rows so scrolling never shows blanks<br>})<br><br>return (<br>  &lt;div ref={parentRef} style={{ height: 600, overflow: &#39;auto&#39; }}&gt;<br>    &lt;div style={{ height: rowVirtualizer.getTotalSize(), position: &#39;relative&#39; }}&gt;<br>      {rowVirtualizer.getVirtualItems().map(virtualRow =&gt; {<br>        const row = rows[virtualRow.index]<br>        return (<br>          &lt;div<br>            key={row.id}<br>            style={{<br>              position: &#39;absolute&#39;,<br>              top: 0,<br>              width: &#39;100%&#39;,<br>              height: virtualRow.size,<br>              transform: `translateY(${virtualRow.start}px)`,<br>            }}<br>          &gt;<br>            {/* draw the cells for this row */}<br>          &lt;/div&gt;<br>        )<br>      })}<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>)</pre><p>Things to know before you use it:</p><ul><li><strong>It does not replace server-side pagination.</strong> Virtualization only shrinks what’s <em>drawn</em>. The data still has to be loaded into the browser first.</li><li><strong>Keep sorting and filtering on the server</strong> if the server owns the data. When the sort changes, scroll back to the top.</li><li><strong>Fixed row heights are much easier.</strong> Rows with changing heights need extra measuring.</li><li><strong>Check accessibility.</strong> Rows that aren’t drawn can’t be found with Ctrl+F, and screen readers may not know the real table size. Test keyboard navigation.</li><li><strong>Don’t add it too early.</strong> For a normal 50-row page, it adds complexity and no speed.</li></ul><h3>Export Jobs: Big Downloads in the Background</h3><p>Sooner or later someone clicks “Export all 400,000 rows to CSV.” The simple way is to do everything inside one request: read every row, build a huge file in memory and send it back. That’s how servers run out of memory or time out.</p><p>Think of ordering a very large cake. The bakery doesn’t make you stand at the counter. They take your order, say “we’ll call you when it’s ready”, and bake it in the back. Exports should work the same way, as <strong>background jobs</strong>:</p><ol><li>Browser : POST /exports with the current filters and sort</li><li>Server : checks permissions, creates a job, replies right away with a job ID</li><li>Worker : reads the rows in small batches and writes them to a file in storage, never holding everything in memory</li><li>Browser : checks the job status (or gets an email / notification)</li><li>Done : the user gets a short lived download link</li></ol><p>Why this works well:</p><ul><li><strong>The user isn’t stuck waiting.</strong> They can keep working.</li><li><strong>The database isn’t overloaded.</strong> A worker reads in controlled batches.</li><li><strong>Memory stays low.</strong> One batch at a time, even for a million rows.</li><li><strong>It matches the table.</strong> The same filters and sort the user sees are used for the file.</li></ul><p>Details that matter in production:</p><ul><li><strong>Check permissions again when the job runs,</strong> not only when it’s created.</li><li><strong>Save the filters inside the job record</strong> so the export can be reproduced.</li><li><strong>Set limits</strong> (maximum rows, exports per user) to prevent accidents.</li><li><strong>Expire the files and links.</strong> Exports often contain sensitive data.</li><li><strong>Allow retries and show clear status:</strong> queued, running, done, failed.</li><li><strong>Small exports can be instant.</strong> The current page or a few thousand rows can be streamed directly. Switch to a job above a size limit.</li></ul><h3>A Simple Performance Checklist</h3><p>Numbers keep you honest. Use these as a starting point and adjust for your product:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h_OdY8TvWMDNM-NdWcuRCg.png" /></figure><p>Test with <strong>real data volume</strong> and an older laptop, not your fast machine with 50 rows.</p><h3>The Order to Work In</h3><p>If you’re improving a slow table, don’t start with the fanciest trick. Work down this list:</p><ol><li>Measure: is it the database, the network, or the browser?</li><li>Paginate, sort and filter on the server.</li><li>Add the index your main query needs. Check EXPLAIN.</li><li>Send only the columns you show.</li><li>Debounce search, cancel old requests, keep old results visible.</li><li>Keep table state in the URL.</li><li>Use stable row IDs. Profile re-renders before memoizing.</li><li>Add virtualization only if the screen still draws too much.</li><li>Move big exports to background jobs.</li></ol><h3>Final Thoughts</h3><p>Fast tables don’t come from one clever trick. They come from small, boring decisions made in the right order: let the database do database work, send only what the screen needs, and draw only what’s visible.</p><p>Next time a table feels slow, don’t reach for React.memo first. Ask where the time is really going: the database, the network, or the browser. Then fix that one.</p><p><em>What’s the biggest table you’ve had to speed up, and what finally worked? I’d love to hear about it.</em></p><p><strong>References:</strong> <a href="https://tanstack.com/table/latest/docs/guide/client-side-vs-server-side">TanStack Table: Client-Side vs Server-Side</a> · <a href="https://tanstack.com/table/latest/docs/framework/react/guide/virtualization">TanStack Table: Virtualization guide</a> · <a href="https://tanstack.com/blog/announcing-tanstack-table-v9">Announcing TanStack Table v9</a> · <a href="https://react.dev/learn/react-compiler/introduction">React Compiler</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9040ff50ada" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Where Should State Live in a Modern React Application?]]></title>
            <link>https://medium.com/@supunbandara/where-should-state-live-in-a-modern-react-application-a5c3b6eec4d1?source=rss-8afa21e8efce------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5c3b6eec4d1</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react-query]]></category>
            <dc:creator><![CDATA[Supun Bandara]]></dc:creator>
            <pubDate>Mon, 30 Nov 2026 19:48:25 GMT</pubDate>
            <atom:updated>2026-11-30T19:48:25.177Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Stop asking “which library?” Start asking “who owns this, and how long does it live?”</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RiPDmM4c0yraHlu23bXbKQ.png" /><figcaption>Image created and edited by the author</figcaption></figure><p>It’s Friday afternoon. A teammate demos the new product page. They filter by “Shoes”, sort by price, open a product, hit the back button, and the filters are gone. Then they refresh and the page forgets everything. Then they paste the link into Slack and the recipient sees a different page entirely.</p><p>Nobody wrote a bad component. The state was simply stored in the wrong place.</p><p>Most React state bugs aren’t logic bugs. They are <em>ownership</em> bugs. We put something in useState that should have lived in the URL, copied server data into a Redux store that should have been a cache, or lifted a value into global state when only one component ever cared about it.</p><p>This article gives you a mental model that makes those decisions boring. Two questions do almost all the work:</p><ol><li><strong>Who owns this data?</strong> The user, the server, the browser, or a single component?</li><li><strong>How long should it live?</strong> A keystroke, a page view, a session, or forever?</li></ol><p>Once you know the owner and the lifetime, the right tool nearly picks itself.</p><h3>The Six Homes of State</h3><p>Think of state as having six possible homes. Each one answers the ownership and lifetime questions differently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-vdoK9yympwF6KOxJfiadg.png" /></figure><p>Let’s walk through them from the smallest to the largest, and I’ll flag the mistakes I see most often.</p><h3>1. Local Component State: The Default</h3><p>If only one component (and maybe its children) cares about a value, keep it there. Is a dropdown open? Is a tooltip visible? What’s in the search box <em>before</em> the user submits?</p><pre>function Accordion({ title, children }) {<br>  const [open, setOpen] = useState(false);<br>  return (<br>    &lt;section&gt;<br>      &lt;button onClick={() =&gt; setOpen(o =&gt; !o)}&gt;{title}&lt;/button&gt;<br>      {open &amp;&amp; children}<br>    &lt;/section&gt;<br>  );<br>}</pre><p><strong>The rule:</strong> start local. Move state up or out only when something forces you to, not because it <em>might</em> be needed someday. Premature globalization is the root of most overgrown stores.</p><p>If you find yourself passing a value through three or four components that don’t use it, you have options before reaching for a global store: restructure with composition (pass children or elements instead of data), or lift the state only to the nearest common parent.</p><h3>2. URL State: The Most Underused Tool in React</h3><p>Here’s a test. Ask: <em>“If a user copied this page’s URL and sent it to a friend, should the friend see the same thing?”</em></p><p>If yes, that state belongs in the URL. Search queries, filters, sort order, pagination, selected tabs, and an open modal’s target ID all qualify.</p><pre>import { useSearchParams } from &#39;react-router-dom&#39;;<br><br>function ProductFilters() {<br>  const [params, setParams] = useSearchParams();<br>  const category = params.get(&#39;category&#39;) ?? &#39;all&#39;;<br>  const sort = params.get(&#39;sort&#39;) ?? &#39;popular&#39;;<br><br>  const update = (key, value) =&gt;<br>    setParams(prev =&gt; {<br>      const next = new URLSearchParams(prev);<br>      value ? next.set(key, value) : next.delete(key);<br>      next.set(&#39;page&#39;, &#39;1&#39;); // changing a filter resets pagination<br>      return next;<br>    });<br><br>  return (<br>    &lt;select value={category} onChange={e =&gt; update(&#39;category&#39;, e.target.value)}&gt;<br>      {/* options */}<br>    &lt;/select&gt;<br>  );<br>}</pre><p>What you get for free:</p><ul><li><strong>Shareable links.</strong> Paste it anywhere and it just works.</li><li><strong>Refresh safety.</strong> Nothing is lost on reload.</li><li><strong>Back/forward buttons</strong> behave the way users expect.</li><li><strong>A single source of truth</strong> that both your UI and your data fetching read from.</li></ul><p>The common mistake is mirroring the URL into useState and trying to keep both in sync. Don&#39;t. The URL <em>is</em> the state. Read from it directly.</p><p>One caution: keep URL state to things that are meaningful to share. A half-typed search box is local state; the <em>submitted</em>query is URL state. Debounce if you want live search to update the address bar.</p><h3>3. Form State: Short-Lived and Special</h3><p>Forms look like local state, but they come with extras: validation, dirty and touched flags, error messages, submission status, and field arrays. Hand-rolling all that in useState is how a signup form ends up as 300 lines.</p><p>The ownership model is simple: <strong>the form owns its values until the user commits them.</strong> After submit, the server owns the data.</p><pre>const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm();<br><br>const onSubmit = async values =&gt; {<br>  await updateProfile(values); // now the server owns it<br>};</pre><p>Two habits worth building:</p><ul><li><strong>Don’t put draft form values in global state.</strong> They’re temporary and private to the form.</li><li><strong>Uncontrolled inputs are fine.</strong> Libraries like React Hook Form avoid re-rendering the whole form on every keystroke, which matters for big forms.</li></ul><p>If a draft needs to survive a refresh (a long article editor, say), that’s when you reach for persisted state, which we’ll get to below.</p><h3>4. Server State: Not Really Your State</h3><p>This is where most apps go wrong, and where the biggest mental shift lives.</p><p>Data from an API isn’t your state. It’s a <strong>cached snapshot of someone else’s state</strong>, and it can go stale at any moment. It needs caching, deduplication, background refetching, retries, and invalidation. None of that has anything to do with how the UI behaves.</p><p>For years we stuffed API responses into Redux and hand-wrote isLoading, error, and data for every endpoint. A server-state library replaces all of it.</p><pre>import { useQuery, useMutation, useQueryClient } from &#39;@tanstack/react-query&#39;;<br><br>function useProducts(filters) {<br>  return useQuery({<br>    queryKey: [&#39;products&#39;, filters],<br>    queryFn: () =&gt; api.getProducts(filters),<br>    staleTime: 60_000,<br>  });<br>}<br><br>function useUpdateProduct() {<br>  const qc = useQueryClient();<br>  return useMutation({<br>    mutationFn: api.updateProduct,<br>    onSuccess: () =&gt; qc.invalidateQueries({ queryKey: [&#39;products&#39;] }),<br>  });<br>}</pre><p>Notice the queryKey includes filters. Those filters come from the URL. That&#39;s the pattern in action: <strong>URL state drives the query, and the query cache holds the result.</strong> Change a filter, the key changes, and React Query fetches (or serves from cache) automatically.</p><p>Why this beats a hand-rolled approach:</p><ul><li>Two components requesting the same data trigger one request.</li><li>Navigating back shows cached data instantly, then refreshes quietly.</li><li>Loading, error, and refetching states are built in.</li><li>Mutations plus invalidation keep the UI honest after writes.</li></ul><p>The cardinal sin here is <strong>copying query data into </strong><strong>useState</strong>:</p><pre>// Don&#39;t<br>const { data } = useProducts(filters);<br>const [products, setProducts] = useState([]);<br>useEffect(() =&gt; setProducts(data ?? []), [data]);</pre><p>Now you have two copies, a render with stale data, and an effect doing work React could do during render. Use datadirectly.</p><h3>5. Shared Client State: Context vs. Redux (and Friends)</h3><p>Once you’ve moved URL state to the URL and server data to a cache, something interesting happens: <strong>most of your “global state” disappears.</strong> What’s left is genuinely client-only and genuinely shared. Think theme, sidebar open/closed, a multi-step wizard’s progress, a shopping cart that hasn’t been sent yet, or toast notifications.</p><p>Now the old question: Context or Redux?</p><p><strong>Context</strong> is a <em>dependency injection</em> mechanism, not a state manager. It’s perfect for values that change rarely and are read widely: theme, locale, the current user, a feature-flag object. Its weakness is that every consumer re-renders when the context value changes, regardless of which slice it actually reads.</p><pre>const ThemeContext = createContext(&#39;light&#39;);<br><br>function App() {<br>  const [theme, setTheme] = useState(&#39;light&#39;);<br>  const value = useMemo(() =&gt; ({ theme, setTheme }), [theme]);<br>  return (<br>    &lt;ThemeContext.Provider value={value}&gt;<br>      &lt;Routes /&gt;<br>    &lt;/ThemeContext.Provider&gt;<br>  );<br>}</pre><p><strong>Redux (Toolkit), Zustand, or Jotai</strong> are the better fit when state changes often, many unrelated components read different slices, or you want devtools, time-travel debugging, middleware, or strict update patterns.</p><pre>import { create } from &#39;zustand&#39;;<br><br>const useCart = create(set =&gt; ({<br>  items: [],<br>  add: item =&gt; set(s =&gt; ({ items: [...s.items, item] })),<br>  remove: id =&gt; set(s =&gt; ({ items: s.items.filter(i =&gt; i.id !== id) })),<br>}));<br><br>// Only re-renders when the item count changes<br>const count = useCart(s =&gt; s.items.length);</pre><p>A practical way to choose:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*INQSQ1pYfBezyLW5FIfchw.png" /></figure><p>The honest answer is that <strong>Context versus Redux is a smaller decision than people think.</strong> If you’ve correctly separated server and URL state, either will often work. Pick based on update frequency and team needs, not ideology.</p><h3>6. Persisted Browser State: Lifetime Is the Whole Point</h3><p>Some state should outlive the tab: theme preference, a collapsed sidebar, a dismissed banner, or an unsent draft. This isn’t a separate <em>kind</em> of state so much as a separate <em>lifetime</em>. Usually it’s shared client state with a persistence layer attached.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XNvQlJGzqNMS-LQqu7WVKQ.png" /></figure><p>Most state libraries have a persistence helper. Zustand’s persist middleware does it in a few lines:</p><pre>import { persist } from &#39;zustand/middleware&#39;;<br><br>const useSettings = create(<br>  persist(<br>    set =&gt; ({ compact: false, toggle: () =&gt; set(s =&gt; ({ compact: !s.compact })) }),<br>    { name: &#39;settings&#39; }<br>  )<br>);</pre><p>Three rules to keep you out of trouble:</p><ul><li><strong>Never persist secrets or tokens in </strong><strong>localStorage.</strong> It&#39;s readable by any script on the page.</li><li><strong>Version your persisted shape.</strong> Old data from last month’s release will eventually break this month’s code.</li><li><strong>Don’t persist what the server already knows.</strong> That’s just a second, staler cache.</li></ul><h3>Avoiding Duplicated State</h3><p>Every bug in the opening story came from the same disease: the same fact living in two places. When two copies disagree, one of them is lying, and you won’t know which.</p><p>The cure is one question: <strong>“Can this be calculated from something I already have?”</strong> If so, calculate it.</p><pre>// Duplicated: three things to keep in sync<br>const [items, setItems] = useState([]);<br>const [total, setTotal] = useState(0);<br>const [isEmpty, setIsEmpty] = useState(true);<br><br>// Derived: one source of truth<br>const [items, setItems] = useState([]);<br>const total = items.reduce((sum, i) =&gt; sum + i.price, 0);<br>const isEmpty = items.length === 0;</pre><p>A few patterns that prevent duplication:</p><ul><li><strong>Store IDs, not objects.</strong> Keep selectedId, then look up the object from your query data. When the data refreshes, the selection stays correct instead of pointing at a stale copy.</li><li><strong>Derive during render.</strong> Filtering, sorting, and counting are cheap. Reach for useMemo only if you&#39;ve measured a problem.</li><li><strong>Avoid </strong><strong>useEffect for syncing state.</strong> If an effect&#39;s only job is setX(f(y)), x should probably be derived from y.</li><li><strong>Normalize shared entities.</strong> If the same user appears in five lists, let your cache handle identity rather than hand-maintaining five copies.</li></ul><h3>The Decision Tree: Ownership, Then Lifetime</h3><p>Here’s the whole model in one place. Walk down it for any piece of state you’re about to create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDlymQqh873BhHnwajxxOw.png" /></figure><p>The order matters. Checking “can I derive it?” first eliminates the most state. Checking “is it server data?” second removes the most boilerplate. Only what survives those filters needs a home of its own.</p><h3>Putting It Together: A Product Listing Page</h3><p>Let’s replay the opening story with the model applied.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ISVcEoPAy_YBVXyGQpmwcg.png" /></figure><p>No Redux store holding API responses. No useEffect shuffling data between copies. Back, refresh, and share all work, not because we wrote special code for them, but because the state lives where its owner naturally keeps it.</p><h3>Final Thoughts</h3><p>State management used to feel like a library choice: Redux or MobX, Context or something newer. The modern answer is quieter and more useful. <strong>There isn’t one place for state. There are several, and each is the right home for a particular owner and lifetime.</strong></p><p>Next time you type useState or create(...), pause for five seconds and ask:</p><ol><li>Who really owns this?</li><li>How long should it live?</li><li>Can I derive it instead?</li></ol><p>Those three questions will save you more bugs than any library ever will.</p><p><em>What’s the most painful state bug you’ve debugged? I’d love to hear which of these homes it should have lived in.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5c3b6eec4d1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The AWS Bill Is an Architecture Report: What Unexpected Costs Reveal]]></title>
            <link>https://medium.com/@supunbandara/the-aws-bill-is-an-architecture-report-what-unexpected-costs-reveal-173cfbf7929f?source=rss-8afa21e8efce------2</link>
            <guid isPermaLink="false">https://medium.com/p/173cfbf7929f</guid>
            <category><![CDATA[cloud-architecture]]></category>
            <category><![CDATA[cloud-cost-optimization]]></category>
            <category><![CDATA[aws-billing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Supun Bandara]]></dc:creator>
            <pubDate>Thu, 17 Sep 2026 14:10:14 GMT</pubDate>
            <atom:updated>2026-09-17T14:10:14.478Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ByuebBblOSWy8bweyoIepw.png" /><figcaption>Image created and edited by the author</figcaption></figure><p>A few months ago, I opened AWS Cost Explorer expecting to see a small, predictable increase.</p><p>Instead, I found that our costs had grown significantly in a single billing cycle even though nobody on the team had deployed anything unusual.</p><p>My first instinct was to blame AWS pricing.</p><p>My second instinct the correct one was to stop and read the bill line by line.</p><p>What I found wasn’t simply a pricing problem.</p><p>It was an architecture problem wearing a dollar sign.</p><p>That is the real lesson of this article: <strong>your AWS bill is not just a cost statement. It is a diagnostic report of your system’s design decisions the ones you made intentionally and the ones you never realized you were making.</strong></p><h3>Cost Is an Engineering Signal, Not Just a Finance Problem</h3><p>It is easy to treat the AWS bill as something the finance team worries about once a month.</p><p>But almost every charge maps back to a technical decision:</p><ul><li>An instance size selected two years ago</li><li>A load balancer nobody decommissioned</li><li>A database sized for traffic that never arrived</li><li>A logging configuration copied from a tutorial</li><li>A development environment running throughout the night</li><li>Data travelling through an expensive network path</li></ul><p>When you start reading the bill as an engineer instead of an accountant, it stops being just a number.</p><p>It becomes a map — one that points directly to parts of the system nobody has examined in a while.</p><p>Your architecture diagram shows what you intended to build.</p><p>Your AWS bill shows what the system is actually doing.</p><h3>Start by Slicing the Bill, Not Staring at the Total</h3><p>The total monthly spend tells you very little by itself.</p><p>The useful information appears when you break it down:</p><ul><li><strong>By service:</strong> Is compute, storage, logging or data transfer driving the increase?</li><li><strong>By account:</strong> If environments use separate accounts, which account is responsible?</li><li><strong>By Region:</strong> Is an unexpected workload running somewhere nobody regularly checks?</li><li><strong>By environment:</strong> Is staging quietly costing almost as much as production?</li><li><strong>By usage type:</strong> Is the charge coming from running time, storage, requests or transferred data?</li><li><strong>By tag:</strong> Which team, project or application owns the cost?</li></ul><p>Without consistent tagging, this investigation becomes much harder.</p><p>That is often the first architectural finding.</p><p>A confusing bill can be a symptom of a confusing ownership model. If resources cannot be connected to an application, environment and owner, the problem is bigger than cost visibility.</p><p>Good tags can include:</p><ul><li>Application</li><li>Environment</li><li>Team</li><li>Owner</li><li>Cost centre</li><li>Project</li></ul><p>Tagging will not reduce the bill directly. It will make the bill explainable and explainability is the first step towards controlling it.</p><h3>The Usual Suspects: Overprovisioned EC2 and RDS</h3><p>In my case, the biggest line item was not caused by a new feature or a sudden traffic spike.</p><p>It came from an RDS instance that had been sized for a launch that never fully materialized. A year later, it was still running with the same specifications.</p><p>Overprovisioning is rarely one dramatic mistake.</p><p>It is usually the slow accumulation of decisions such as:</p><blockquote><em>“Let’s give it more capacity to be safe.”</em></blockquote><p>That can be reasonable during a stressful launch. The problem is that the decision is rarely reviewed after the pressure disappears.</p><p>EC2 instances, ECS tasks and databases often receive more CPU and memory than they regularly use. That unused capacity still costs money every hour.</p><p>However, rightsizing should not be guesswork.</p><p>Before reducing capacity, examine:</p><ul><li>CPU utilization</li><li>Memory utilization</li><li>Database connections</li><li>Query latency</li><li>Disk activity</li><li>Free storage</li><li>Request volume</li><li>Application response time</li><li>Container or instance restarts</li><li>Peak usage not only averages</li></ul><p>An instance with low average CPU may still experience important short-lived spikes. A database may appear oversized while its real problem is an inefficient query or missing index.</p><p>The question should not be:</p><blockquote><em>“Can we choose a smaller instance?”</em></blockquote><p>It should be:</p><blockquote><em>“What resources does this workload actually require, including its normal peaks and reliability needs?”</em></blockquote><p>Cost without utilization data is only a number.</p><p>Cost combined with utilization data becomes an engineering decision.</p><h3>The Silent Spenders: Load Balancers, Volumes and Elastic IPs</h3><p>Some resources continue charging even when no useful application is using them.</p><p>Common examples include:</p><ul><li>Load balancers left behind after services were decommissioned</li><li>EBS volumes detached from terminated instances</li><li>Old database snapshots</li><li>Unused Elastic IP addresses</li><li>Forgotten test environments</li><li>Container repositories filled with old images</li></ul><p>These resources may not be individually expensive. But across a system that has been evolving for several years, they can create a meaningful amount of waste.</p><p>They are particularly dangerous because they do not normally generate application errors.</p><p>An unused load balancer does not crash.</p><p>A detached volume does not fail a health check.</p><p>A forgotten snapshot does not wake anyone at midnight.</p><p>The system continues working, so nobody investigates. Only the bill remembers that the resources exist.</p><p>This reveals an important architectural gap: the team has a process for creating infrastructure but no process for retiring it.</p><p>Provisioning is only half of a resource’s lifecycle. A mature cloud process should also define when that resource must be reviewed, archived or deleted.</p><h3>NAT Gateways: The Quiet Budget Killer</h3><p>NAT Gateway costs often surprise teams because a NAT Gateway does not feel like an application feature.</p><p>It sits quietly inside the network architecture, allowing resources in private subnets to access destinations outside those subnets.</p><p>For example, ECS tasks in private subnets may need to:</p><ul><li>Pull container images</li><li>Retrieve secrets</li><li>Send logs</li><li>Download packages</li><li>Access AWS services</li><li>Call third party APIs</li></ul><p>A NAT Gateway can create both hourly costs and data processing charges. If a large amount of traffic passes through it, the total can grow quickly.</p><p>The useful question is not simply:</p><blockquote><em>“Why is the NAT Gateway expensive?”</em></blockquote><p>A better question is:</p><blockquote><em>“Why is this traffic using the NAT Gateway?”</em></blockquote><p>Perhaps the path is correct because the application genuinely needs internet access.</p><p>But the bill may also reveal that:</p><ul><li>A service calls an external API far more often than necessary</li><li>A large file is repeatedly downloaded instead of cached</li><li>AWS service traffic could use an appropriate VPC endpoint</li><li>An internal service is calling a public endpoint</li><li>Traffic is crossing Availability Zones unnecessarily</li><li>Multiple NAT Gateways exist in environments that barely receive traffic</li></ul><p>In one common pattern, a chatty service repeatedly calls the same external API. Caching the result or reducing the request frequency can lower both network cost and response latency.</p><p>The NAT charge is therefore not merely saying that networking is expensive.</p><p>It is saying that a significant amount of data is following a particular route.</p><p>That is architectural evidence.</p><h3>Data Transfer Charges Reveal Hidden Distance</h3><p>Two resources can appear close together in an architecture diagram while still being separated by a billable network boundary.</p><p>Data may travel:</p><ul><li>Between Availability Zones</li><li>Between AWS Regions</li><li>From AWS to the public internet</li><li>Through a NAT Gateway</li><li>Through a load balancer</li><li>Between public and private endpoints</li><li>Repeatedly from an origin because caching is ineffective</li></ul><p>For example, your application tasks, database, cache and NAT Gateway may all live inside the same VPC.</p><p>But “inside the same VPC” does not automatically mean “without meaningful transfer cost.”</p><p>If the components communicate across Availability Zones, or traffic takes an indirect path, the invoice may reveal a distance that the architecture diagram hides.</p><p>A useful investigation question is:</p><blockquote><em>“Which boundaries does every byte cross during one complete request?”</em></blockquote><p>Trace the path from the user to the application and back:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UuwO40JPzpK9xZSZxQie5A.png" /></figure><p>Then add the Region, Availability Zone and public/private boundaries.</p><p>This request path diagram is often more informative than the original architecture diagram because it describes how data moves not only which components exist.</p><h3>CloudWatch Logs: Paying to Store What Nobody Will Read</h3><p>Logging feels almost free when an application is small.</p><p>Then the traffic grows.</p><p>A single request might create logs for:</p><ul><li>Request details</li><li>Authentication</li><li>Database queries</li><li>Cache operations</li><li>External API calls</li><li>Retry attempts</li><li>Response details</li><li>Errors and stack traces</li></ul><p>Multiply that by every request, every container and every day.</p><p>CloudWatch can then become a visible line item not because logging is inherently wasteful, but because nobody decided which logs were valuable or how long they should remain.</p><p>Common causes include:</p><ul><li>Debug logging left enabled in production</li><li>Complete request and response bodies being recorded</li><li>Health checks generating logs every few seconds</li><li>Errors repeated inside retry loops</li><li>Verbose database logging</li><li>Long or unlimited retention periods</li><li>Duplicate collection from multiple agents</li><li>High cardinality custom metrics</li></ul><p>The solution is not to disable logging blindly. That may save money today and make the next production incident much harder to diagnose.</p><p>Instead:</p><ul><li>Use appropriate log levels</li><li>Keep production logs structured</li><li>Avoid recording secrets or sensitive payloads</li><li>Reduce unnecessary success logs</li><li>Sample high volume events when appropriate</li><li>Set retention periods for each log group</li><li>Archive only logs that genuinely require long term retention</li><li>Convert important operational signals into useful metrics and alarms</li></ul><p>The CloudWatch bill asks a valuable question:</p><blockquote><em>“Are we collecting this information because it is useful or because we never decided what useful means?”</em></blockquote><h3>S3: The Right Storage Class at the Right Time</h3><p>S3 is often described as inexpensive storage and it can be.</p><p>But inexpensive objects become expensive when millions of them remain in a storage class that no longer matches how they are used.</p><p>Common examples include:</p><ul><li>Old application exports</li><li>Previous versions of uploaded files</li><li>Incomplete multipart uploads</li><li>Historical reports</li><li>Backups copied to S3</li><li>User generated content that is rarely accessed</li><li>Temporary files that were never deleted</li></ul><p>Lifecycle policies can automatically transition suitable objects to lower cost storage classes or delete them when they are no longer required.</p><p>However, moving everything to the cheapest looking storage class is not automatically the best choice. Some classes introduce retrieval charges, minimum storage durations or slower access.</p><p>The correct storage class depends on:</p><ul><li>How frequently the data is accessed</li><li>How quickly it must be retrieved</li><li>How long it must be retained</li><li>Whether deletion is legally or operationally allowed</li><li>The cost of retrieving it when needed</li></ul><p>The deeper lesson is that storage needs a lifecycle.</p><p>“Keep everything forever” is still a retention policy — it is simply the most expensive one.</p><h3>Container Images and Snapshots Also Need Lifecycles</h3><p>Every deployment may push a new image to Amazon ECR.</p><p>Versioned images are valuable because they improve traceability and make rollback possible. But if every image is retained forever, repository storage grows continuously.</p><p>The goal is not to delete all old images.</p><p>The goal is to keep enough known good versions for rollback while automatically removing untagged, temporary or outdated images according to a clear policy.</p><p>The same principle applies to:</p><ul><li>EBS snapshots</li><li>RDS snapshots</li><li>Machine images</li><li>Database exports</li><li>S3 object versions</li><li>Build artifacts</li></ul><p>Every stored artifact should have an answer to three questions:</p><ol><li>Why are we keeping it?</li><li>How long must we keep it?</li><li>Who is responsible for deleting or archiving it?</li></ol><p>If nobody can answer those questions, the bill eventually will.</p><h3>Scaling Configuration Mistakes</h3><p>Auto Scaling is supposed to match capacity to demand.</p><p>Configured badly, it can do the opposite.</p><p>A service might:</p><ul><li>Scale out too aggressively</li><li>Scale using the wrong metric</li><li>Scale in too slowly</li><li>Maintain an unnecessarily high minimum capacity</li><li>React to background jobs as if they were user traffic</li><li>Create new tasks because existing tasks are repeatedly failing</li><li>Remain overprovisioned after a temporary traffic spike</li></ul><p>These costs may look like normal compute usage in the bill.</p><p>The problem becomes visible only when you compare:</p><ul><li>Actual request volume</li><li>CPU and memory utilization</li><li>Running instance or task count</li><li>Scaling events</li><li>Application latency</li><li>Error rates</li><li>Container restarts</li></ul><p>Suppose traffic falls at midnight, but the service continues running the same number of tasks until morning.</p><p>The bill is not only showing extra compute cost. It is showing that the scaling policy does not match the traffic pattern.</p><p>Autoscaling is not automatically cost optimization.</p><p>It is only as intelligent as the metrics, thresholds, minimums, maximums and cooldown periods behind it.</p><h3>Development Resources That Never Sleep</h3><p>One of the most common and fixable sources of waste is a development or staging environment running 24 hours a day.</p><p>It may have:</p><ul><li>Production sized instances</li><li>A dedicated load balancer</li><li>A NAT Gateway</li><li>A managed database</li><li>Multiple application tasks</li><li>Long log retention</li><li>Large attached volumes</li></ul><p>Yet nobody uses it during nights or weekends.</p><p>Sometimes non production environments must closely match production. They may be needed for performance testing, release validation or incident reproduction.</p><p>But many development environments are only used during working hours.</p><p>Scheduling them to scale down or stop outside those hours can be one of the highest leverage cost improvements available.</p><p>This does not always require a major architectural change.</p><p>It requires the discipline to stop paying for idle time.</p><p>An environment without an off switch is making a permanent cost commitment even if the environment itself is temporary.</p><h3>Unexpected Request Costs Reveal Chatty Systems</h3><p>Some AWS charges grow with requests or operations rather than continuously running capacity.</p><p>Individually, each operation may appear insignificant. At scale, an inefficient pattern becomes visible.</p><p>Examples include:</p><ul><li>A frontend repeatedly requesting unchanged data</li><li>A queue consumer polling too frequently when no work exists</li><li>One user action triggering several unnecessary functions</li><li>An application performing many small storage operations</li><li>A health check calling expensive downstream services</li><li>Multiple database queries that could be batched</li><li>A failed request being retried hundreds of times</li></ul><p>Retry behaviour is particularly dangerous.</p><p>A temporary failure may cause one service to retry. Its caller may also retry. A queue may redeliver the message. The user may press the button again.</p><p>One failed operation becomes dozens or thousands of operations.</p><p>The bill can therefore reveal a system that is too chatty.</p><p>When request based charges grow, do not ask only:</p><blockquote><em>“How can we make each request cheaper?”</em></blockquote><p>Also ask:</p><blockquote><em>“Does every request need to exist?”</em></blockquote><h3>A Sudden Cost Spike Can Be an Incident Signal</h3><p>Not every cost increase happens gradually.</p><p>Sometimes yesterday was normal and today is not.</p><p>That may indicate:</p><ul><li>A traffic spike</li><li>A deployment loop</li><li>A broken cache</li><li>Repeated task failures</li><li>A runaway background job</li><li>Uncontrolled retries</li><li>An unexpectedly large data download</li><li>Abusive traffic</li><li>Leaked or misused credentials</li><li>A logging loop producing huge volumes of data</li></ul><p>In these situations, cost monitoring becomes part of operational monitoring.</p><p>A latency alarm tells you the application is slow.</p><p>An error alarm tells you requests are failing.</p><p>A cost anomaly can tell you the system is doing something at an unexpected scale.</p><p>It may not identify the exact cause, but it provides another signal that system behaviour has changed.</p><h3>Let AWS Watch the Bill for You</h3><p>This process becomes much easier when you stop relying on someone manually checking Cost Explorer once a month.</p><p>AWS Budgets can notify you when spending or forecasted spending crosses defined thresholds.</p><p>Cost Anomaly Detection can identify unusual spending patterns based on historical usage and alert you before the issue continues for an entire billing cycle.</p><p>You can also create several thresholds instead of waiting for one final limit:</p><ul><li>Early warning</li><li>Investigation required</li><li>Critical budget level</li></ul><p>The goal is not to check the bill obsessively.</p><p>The goal is to make cost monitoring behave like application monitoring: notify the responsible people when something moves outside its expected range.</p><p>Budget alerts are not hard spending limits. They warn you about what is happening; your team must still investigate and respond.</p><h3>The More Useful Metric: Cost per Customer, Request or Transaction</h3><p>After removing obvious waste, the more interesting question becomes:</p><blockquote><em>“Is the cost structure sustainable as the application grows?”</em></blockquote><p>Total spending increasing is not automatically bad.</p><p>If the application serves twice as many customers and AWS spending grows by 20%, the architecture may have become more efficient.</p><p>But if spending grows by 40% while traffic stays almost unchanged, something deserves investigation.</p><p>Depending on the product, useful metrics might include:</p><ul><li>Cost per active customer</li><li>Cost per API request</li><li>Cost per order</li><li>Cost per payment</li><li>Cost per uploaded file</li><li>Cost per generated report</li><li>Cost per game session</li></ul><p>These unit cost metrics connect infrastructure spending to business activity.</p><p>They also help distinguish healthy growth from architectural inefficiency.</p><p>A rising AWS bill can be good news when it represents growth.</p><p>A rising cost per transaction is more concerning because it suggests the system becomes less efficient as usage increases.</p><h3>A Practical Process for Investigating an Unexpected Bill</h3><p>Avoid randomly deleting resources or choosing smaller instances before understanding the cause.</p><p>Use a systematic process.</p><h3>1. Find What Changed</h3><p>Compare the current billing period with the previous one.</p><p>Identify which service, account, Region, usage type or tag changed the most.</p><p>Start with the largest change not necessarily the largest total cost.</p><h3>2. Translate the Charge into System Behaviour</h3><p>“CloudWatch cost increased” is too vague.</p><p>Was the increase caused by:</p><ul><li>Log ingestion?</li><li>Log storage?</li><li>Custom metrics?</li><li>Alarms?</li><li>Log queries?</li></ul><p>“EC2 cost increased” may also refer to related storage, networking or IP usage not only virtual machine runtime.</p><p>Understand the specific usage type behind the charge.</p><h3>3. Identify the Responsible Resource</h3><p>Use resource identifiers, tags, Regions, deployment history and service consoles to connect the cost to an actual workload.</p><p>If you cannot identify its owner or purpose, record that as a separate governance problem.</p><h3>4. Draw the Real Request Path</h3><p>For network costs, trace where the data enters, where it travels and where it exits.</p><p>Include:</p><ul><li>Regions</li><li>Availability Zones</li><li>Public and private subnets</li><li>Load balancers</li><li>NAT Gateways</li><li>VPC endpoints</li><li>Databases</li><li>Caches</li><li>External services</li></ul><h3>5. Compare Cost with Utilization</h3><p>For compute and databases, compare spending against CPU, memory, connections, traffic, latency and restart behaviour.</p><p>Do not reduce capacity based only on a low average.</p><h3>6. Decide Whether the Cost Is Useful</h3><p>Not every large charge is waste.</p><p>Backups, redundancy, monitoring, security controls and multi zone availability all cost money because reliability costs money.</p><p>The objective is not the smallest possible bill.</p><p>The objective is a bill the team can explain and justify.</p><h3>7. Fix the Cause</h3><p>Deleting an unused volume fixes unused storage.</p><p>Changing a retry strategy fixes repeated work.</p><p>Adding caching can reduce external requests and NAT traffic.</p><p>Correcting a network route can reduce unnecessary data transfer.</p><p>Choose the fix that addresses the system behaviour, not only the line item.</p><h3>8. Add a Guardrail</h3><p>After resolving the problem, prevent it from returning:</p><ul><li>Create budget alerts</li><li>Enable anomaly detection</li><li>Enforce tagging</li><li>Add storage lifecycle policies</li><li>Schedule non production environments</li><li>Review costs after major deployments</li><li>Assign an owner to every environment</li><li>Include cost in architecture reviews</li></ul><p>A cleanup saves money once.</p><p>A guardrail keeps saving it.</p><h3>Questions to Ask During a Cloud Cost Review</h3><p>Here is a practical checklist:</p><ol><li>What are the five most expensive services?</li><li>Which cost changed the most from the previous period?</li><li>Is the charge based on time, capacity, storage, requests or transferred data?</li><li>Can every major cost be connected to an application and owner?</li><li>Are unused resources still running?</li><li>Are logs, images, snapshots or object versions growing indefinitely?</li><li>Does traffic cross a NAT Gateway, Availability Zone or Region unnecessarily?</li><li>Are retries or unhealthy workloads multiplying requests?</li><li>Do non-production environments need to run continuously?</li><li>Are scaling policies aligned with real traffic patterns?</li><li>Is an expensive component providing reliability, security or performance the business genuinely needs?</li><li>Is cost per customer, request or transaction improving or getting worse?</li></ol><p>If a team cannot answer these questions, the problem is larger than the AWS bill.</p><p>It means important system behaviour is not fully understood.</p><h3>Cost Optimization Is Architecture Optimization</h3><p>It is tempting to treat cloud cost as something to consider at the end:</p><blockquote><em>Build first. Deploy. Optimize later.</em></blockquote><p>But cost is created by architecture from the beginning.</p><p>Choosing serverless instead of continuously running compute changes the cost model.</p><p>Choosing private subnets changes network paths.</p><p>Choosing multi zone reliability changes redundancy and data movement.</p><p>Choosing detailed logging changes ingestion and storage.</p><p>Choosing a CDN changes how often users reach the origin.</p><p>Choosing immutable container tags changes traceability and repository growth.</p><p>Cost is therefore a non functional requirement — just like security, reliability and performance.</p><p>These concerns also affect one another:</p><ul><li>Aggressive cost reduction can weaken reliability.</li><li>Excessive redundancy can create waste.</li><li>Poor application performance can increase compute and database costs.</li><li>Weak observability can hide waste.</li><li>Excessive observability can become waste.</li><li>Weak security can lead to unauthorized resource usage.</li><li>Poor scaling policies can harm both performance and cost.</li></ul><p>The goal is not to make every component as cheap as possible.</p><p>The goal is to build a system whose cost matches its business value and operational requirements.</p><h3>The Takeaway</h3><p>Not every finding requires a major redesign.</p><p>Many unexpected charges come from resources, configurations and assumptions that have outlived their original purpose.</p><p>An instance was sized for a launch that never happened.</p><p>A load balancer remained after the service disappeared.</p><p>A log group kept data nobody needed.</p><p>A staging environment behaved like production.</p><p>A service repeated work that should have been cached.</p><p>The bill did not lie.</p><p>It simply was not being read carefully enough.</p><p>Treat your AWS invoice the way you treat a monitoring dashboard: something to review deliberately, not something to glance at and forget.</p><p>Every unexpected cost is a small architectural confession — and often an easy improvement once you understand what caused it.</p><p>So when a cost surprises you, do not begin only with:</p><blockquote><em>“Which service should we turn off?”</em></blockquote><p>Begin with:</p><blockquote><em>“Which architectural behaviour created this charge?”</em></blockquote><p>That question leads to better answers.</p><p>Your architecture diagram explains what you planned.</p><p><strong>Your AWS bill explains what you built.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=173cfbf7929f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From git push to a Running Backend: Deploying Docker Images to AWS ECR and an Auto Scaling Group]]></title>
            <link>https://medium.com/@supunbandara/from-git-push-to-a-running-backend-deploying-docker-images-to-aws-ecr-and-an-auto-scaling-group-7ee80dadb535?source=rss-8afa21e8efce------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ee80dadb535</guid>
            <category><![CDATA[github-actions]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Supun Bandara]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 18:42:59 GMT</pubDate>
            <atom:updated>2026-09-08T22:01:57.262Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A practical walkthrough of a GitHub Actions pipeline using Docker, Amazon ECR, EC2 Auto Scaling, Systems Manager, and OIDC without storing permanent AWS access keys in GitHub.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IO5iLYIrLAkmUhIY1UGxvg.png" /><figcaption>Image created and edited by the author</figcaption></figure><p>Most deployment diagrams make continuous delivery look almost magical:</p><blockquote><em>Push code → build container → deploy → done.</em></blockquote><p>But the interesting engineering lives between those arrows.</p><p>How does GitHub authenticate with AWS? How does the new image reach every EC2 instance in an Auto Scaling Group? How do we know that the container actually started? What happens if one instance fails while the others succeed?</p><p>The following GitHub Actions workflow answers those questions by creating a complete deployment path:</p><ol><li>A commit is pushed to main.</li><li>GitHub Actions builds a Docker image.</li><li>The image is pushed to Amazon Elastic Container Registry (ECR).</li><li>The workflow discovers all healthy EC2 instances in an Auto Scaling Group (ASG).</li><li>AWS Systems Manager (SSM) runs deployment commands remotely on every instance.</li><li>Each instance pulls the new image, restarts the backend, and checks its health endpoint.</li><li>GitHub waits until every remote deployment has succeeded or reports a failure.</li></ol><p>This is more than a collection of shell commands. It is a small deployment system.</p><h3>The architecture at a glance</h3><p>The workflow connects several services, each with one clear responsibility:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q5pLV3WiY_SihUz75o0rJQ.png" /></figure><p>The overall flow looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7pfzR4-XeF3JGqCZ_LcQyA.png" /></figure><h3>1. The workflow begins with a controlled trigger</h3><pre>on:<br>  push:<br>    branches: [main]<br>  workflow_dispatch:</pre><p>The pipeline starts automatically whenever code reaches the main branch. It can also be started manually through workflow_dispatch.</p><p>That manual option is small but valuable. It lets us rerun a deployment after correcting infrastructure or permissions without creating a meaningless new commit.</p><p>Both jobs use GitHub’s production environment. This is useful for keeping production variables and secrets separate and, if required, adding approval rules before deployment.</p><h3>2. GitHub authenticates without permanent AWS access keys</h3><pre>permissions:<br>  id-token: write<br>  contents: read</pre><p>The workflow needs contents: read to check out the repository. The more interesting permission is id-token: write.</p><p>It allows GitHub Actions to request an OpenID Connect token. AWS verifies that token and permits the workflow to assume a configured IAM role:</p><pre>- name: Configure AWS credentials (OIDC)<br>  uses: aws-actions/configure-aws-credentials@v4<br>  with:<br>    role-to-assume: ${{ secrets.AWS_ROLE_ARN }}<br>    aws-region: ${{ env.AWS_REGION }}</pre><p>GitHub therefore receives temporary AWS credentials for this run. We do not need to save a long lived AWS access key and secret in the repository settings.</p><p>This matters because permanent credentials are easy to forget, leak, or leave active after they are no longer needed. OIDC replaces that static secret with short lived credentials and an explicit trust relationship.</p><p>The trust policy should be restricted to the intended repository, branch, and environment not every GitHub repository.</p><h3>3. Build once and identify the exact artifact</h3><p>After signing in to ECR, the workflow creates an image tag from the first seven characters of the Git commit SHA:</p><pre>SHORT_SHA=$(echo &quot;${{ github.sha }}&quot; | cut -c1-7)<br>echo &quot;image_tag=${SHORT_SHA}&quot; &gt;&gt; &quot;$GITHUB_OUTPUT&quot;</pre><p>If the commit is:</p><pre>9fd82c73139c7d...</pre><p>the resulting image might be:</p><pre>&lt;aws-account-id&gt;.dkr.ecr.&lt;aws-region&gt;.amazonaws.com/&lt;ecr-repository&gt;:9fd82c7</pre><p>This is far better than deploying only latest.</p><p>latest answers, “Which image was pushed most recently?” A commit tag answers, “Which exact version are we deploying?”</p><p>That difference improves traceability. When something fails, we can connect the running container to a commit. It also gives us a specific image to use for rollback.</p><p>The build step publishes both tags:</p><pre>docker build -t $FULL_IMAGE:$IMAGE_TAG -f Dockerfile .<br>docker tag $FULL_IMAGE:$IMAGE_TAG $FULL_IMAGE:latest<br>docker push $FULL_IMAGE:$IMAGE_TAG<br>docker push $FULL_IMAGE:latest</pre><p>The commit tag is the deployment identity. The latest tag is a convenient moving reference for humans or other environments.</p><h3>4. Job outputs connect build and deployment</h3><p>GitHub Actions jobs run independently. The deployment job does not automatically know which tag the build job created.</p><p>The workflow deliberately exposes it:</p><pre>outputs:<br>  image_tag: ${{ steps.meta.outputs.image_tag }}</pre><p>The deployment job then reads it using:</p><pre>IMAGE_TAG: ${{ needs.build-and-push.outputs.image_tag }}</pre><p>This creates an important guarantee: the deployment job attempts to run the exact image produced by the build job that it depends on.</p><p>It also avoids rebuilding on the server. Production instances only pull and run a prepared artifact. That makes deployments faster and reduces differences between instances.</p><h3>5. The workflow discovers the current ASG instances</h3><p>An Auto Scaling Group is dynamic. An instance may have been replaced, added, or removed since the previous deployment. Hard coding instance IDs would quickly become incorrect.</p><p>Instead, the workflow asks AWS for the instances currently marked InService:</p><pre>INSTANCE_IDS=$(aws autoscaling describe-auto-scaling-groups \<br>  --auto-scaling-group-names &quot;${{ vars.ASG_NAME }}&quot; \<br>  --query &quot;AutoScalingGroups[0].Instances[?LifecycleState==&#39;InService&#39;].InstanceId&quot; \<br>  --output text)</pre><p>The JMESPath query selects only instances that belong to the ASG and are actively serving capacity.</p><p>The empty result check is equally important:</p><pre>if [ -z &quot;$INSTANCE_IDS&quot; ]; then<br>  echo &quot;No running instances in ASG&quot;<br>  exit 1<br>fi</pre><p>Without it, the deployment could appear to continue even though there was nowhere to deploy. Failing loudly is safer than reporting a false success.</p><h3>6. SSM replaces direct SSH access</h3><p>The workflow does not open an SSH connection, manage private keys, or require port 22 to be exposed to GitHub hosted runners.</p><p>Instead, it sends the AWS-RunShellScript document through Systems Manager:</p><pre>aws ssm send-command \<br>  --targets &quot;Key=instanceids,Values=...&quot; \<br>  --document-name &quot;AWS-RunShellScript&quot; \<br>  --parameters commands=&#39;[...]&#39;</pre><p>SSM sends the same deployment command to every selected instance and returns a command ID. That ID becomes the handle used to track the distributed operation.</p><p>For this to work, every EC2 instance must:</p><ul><li>run and register the SSM Agent;</li><li>have an IAM instance profile that permits Systems Manager communication;</li><li>be able to reach SSM endpoints, through internet/NAT access or VPC endpoints;</li><li>have Docker, Docker Compose, and the AWS CLI installed;</li><li>have permission to pull images from ECR.</li></ul><p>SSM removes the need for SSH, but it does not remove the need for correct networking and IAM.</p><h3>7. What actually happens on each server</h3><p>The remote script is where the deployment becomes real:</p><pre>set -euo pipefail<br>cd /opt/backend-app<br>aws ecr get-login-password --region &quot;$AWS_REGION&quot; \<br>  | docker login --username AWS --password-stdin &quot;$ECR_REGISTRY&quot;<br>export IMAGE_TAG=&quot;$IMAGE_TAG&quot;<br>docker compose pull backend<br>docker compose up -d backend<br>sleep 15<br>curl -sf http://localhost:8080/health || {<br>  echo HEALTH_CHECK_FAILED<br>  docker compose logs --tail=50 backend<br>  exit 1<br>}<br>docker image prune -f<br>echo DEPLOY_SUCCESS</pre><p>Let us break down why each instruction exists.</p><h3>set -euo pipefail</h3><p>This makes the shell script stricter:</p><ul><li>-e stops when a command fails.</li><li>-u treats an unset variable as an error.</li><li>pipefail makes a pipeline fail when any important command within it fails.</li></ul><p>Deployment scripts should not casually continue after an authentication, pull, or startup failure.</p><h3>Authenticate the EC2 instance with ECR</h3><p>ECR authentication performed on the GitHub runner does not authenticate the EC2 machines. Each server must obtain its own ECR login token using its instance role.</p><p>This separation is healthy: GitHub receives permissions required to publish and orchestrate, while EC2 receives permissions required to pull and run.</p><h3>Export the image tag</h3><pre>export IMAGE_TAG=&quot;$IMAGE_TAG&quot;</pre><p>The corresponding compose.yaml must actually consume this variable, for example:</p><pre>services:<br>  backend:<br>    image: ${ECR_REGISTRY}/${ECR_REPOSITORY}:${IMAGE_TAG}</pre><p>If the Compose file is hard coded to latest, exporting IMAGE_TAG changes nothing. This is an easy mistake that can make the logs claim one version was deployed while Docker runs another.</p><p>Using an immutable commit tag in Compose ensures the intended artifact is pulled.</p><h3>Pull before restart</h3><pre>docker compose pull backend<br>docker compose up -d backend</pre><p>pull downloads the selected image. up -d recreates the backend service when the image or configuration has changed and leaves it running in the background.</p><p>Only the backend service is targeted, so unrelated Compose services are not unnecessarily restarted.</p><h3>Verify the application, not merely the container</h3><pre>curl -sf http://localhost:8080/health</pre><p>A running container is not proof of a working application.</p><p>The Node.js process could be crashing repeatedly. A required secret could be missing. The database might be unreachable. The application might be listening on the wrong port.</p><p>The health request verifies that the backend can answer over HTTP. If it fails, the script prints the last 50 log lines and exits with a failure code. Those logs provide immediate context without requiring a separate server login.</p><p>The fixed 15 second sleep is simple, but not ideal for every application. A retry loop with a defined timeout is usually more resilient because startup duration can vary.</p><h3>Remove unused images</h3><pre>docker image prune -f</pre><p>Repeated deployments leave old, unreferenced layers on disk. Pruning them helps prevent the EC2 volume from quietly filling over time.</p><p>It should still be paired with disk monitoring. Cleanup is maintenance, not observability.</p><h3>8. One command ID represents many deployments</h3><p>SSM’s send-command call returns quickly. It confirms that AWS accepted the instruction not that every server completed it.</p><p>The final workflow step polls the command status:</p><pre>aws ssm list-command-invocations \<br>  --command-id &quot;$COMMAND_ID&quot; \<br>  --query &quot;CommandInvocations[*].Status&quot; \<br>  --output text</pre><p>It evaluates all returned instance statuses:</p><ul><li>Pending or InProgress: keep waiting.</li><li>Failed, Cancelled, or TimedOut: fail the workflow.</li><li>all instances complete successfully: finish the deployment.</li></ul><p>This is a distributed success condition. If four servers update correctly and one fails, production is inconsistent. The workflow correctly treats that as a failed deployment instead of averaging the result into success.</p><p>The loop waits up to 60 times with a ten second interval, so the GitHub job allows roughly ten minutes before declaring its own timeout. The remote SSM command has a separate 300 second timeout. These two limits serve different layers and should be configured intentionally.</p><h3>The IAM model behind the pipeline</h3><p>There are two AWS identities, and they should not be confused.</p><h3>GitHub Actions role</h3><p>The OIDC assumed role needs only the permissions required to:</p><ul><li>authenticate and push to the selected ECR repository;</li><li>describe the specified Auto Scaling Group;</li><li>send the approved SSM document to intended instances;</li><li>inspect SSM command results.</li></ul><p>Permissions should be resource scoped wherever AWS supports it.</p><h3>EC2 instance role</h3><p>The instance profile needs permissions required to:</p><ul><li>register and communicate with Systems Manager;</li><li>authenticate with ECR;</li><li>download the required ECR image layers;</li><li>access any runtime services the backend requires, such as Secrets Manager.</li></ul><p>The GitHub role pushes and coordinates. The EC2 role pulls and runs. Separating these responsibilities makes the system easier to secure and debug.</p><h3>Important production limitations</h3><p>This workflow is practical, but it is not automatically zero downtime.</p><p>It sends the deployment to all InService instances at once. During docker compose up, each instance may briefly stop its old backend before the new container is ready. If every instance restarts simultaneously, the load balancer may temporarily have no healthy targets.</p><p>For a small application, that trade off may be acceptable. For a production system with strict availability requirements, consider:</p><ul><li>SSM concurrency controls, such as updating one instance or a percentage at a time;</li><li>load balancer de-registration and re-registration around each restart;</li><li>an ASG instance refresh using a new launch template version;</li><li>blue/green deployment with separate target groups;</li><li>ECS or another orchestrator designed for controlled rolling deployments.</li></ul><p>There is also no automatic rollback in the current script. The commit based tag makes rollback possible, but the workflow still needs logic to restore the previous known good tag when health checks fail.</p><h3>Improvements I would make next</h3><p>The strongest next upgrades are:</p><ol><li><strong>Replace the fixed sleep with health retries.</strong> Try the endpoint every few seconds until it succeeds or a clear deadline expires.</li><li><strong>Deploy in batches.</strong> Limit SSM concurrency so healthy capacity remains available during updates.</li><li><strong>Capture detailed failure output.</strong> Print each failed invocation’s standard output and standard error in the GitHub job.</li><li><strong>Add rollback logic.</strong> Record the previously deployed tag and restore it if the new version fails its health check.</li><li><strong>Verify the running version.</strong> Let /health or /version return the Git SHA and compare it with IMAGE_TAG.</li><li><strong>Use deployment locking or concurrency controls.</strong> Prevent two rapid pushes from deploying out of order.</li><li><strong>Add post deployment monitoring.</strong> A successful local health check is the beginning of verification, not the end. Check load balancer target health, error rate, latency, and container restarts.</li></ol><h3>Final takeaway</h3><p>A reliable deployment is not just docker push followed by docker compose up.</p><p>It is a chain of verified handoffs:</p><ul><li>GitHub proves its identity to AWS.</li><li>The build produces a traceable image.</li><li>ECR stores that immutable version.</li><li>The ASG reveals the machines currently serving traffic.</li><li>SSM delivers commands without SSH.</li><li>Each instance authenticates independently and pulls the image.</li><li>The application proves that it is healthy.</li><li>GitHub confirms that every remote execution reached a terminal success state.</li></ul><p>That is what makes this workflow interesting. It transforms a simple push to main into an observable, auditable deployment across a changing group of servers.</p><p>And it also teaches one of the most important lessons in DevOps:</p><blockquote><em>A command completing is not the same as a system working. A deployment is complete only when the new application version is running, reachable, and verified.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ee80dadb535" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Application Was Healthy, but the Load Balancer Said It Wasn’t]]></title>
            <link>https://medium.com/@supunbandara/my-application-was-healthy-but-the-load-balancer-said-it-wasnt-1d5abf41cdd8?source=rss-8afa21e8efce------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d5abf41cdd8</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[amazon-ecs]]></category>
            <category><![CDATA[load-balancing]]></category>
            <dc:creator><![CDATA[Supun Bandara]]></dc:creator>
            <pubDate>Sun, 06 Sep 2026 10:47:56 GMT</pubDate>
            <atom:updated>2026-09-06T13:50:14.401Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>The container was running. The logs looked normal. Yet every request returned 503.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4rD5quzNFCZSYw9VeFES3g.png" /><figcaption>Image created and edited by the author</figcaption></figure><p>Before getting into the problem, it helps to understand why I was using Amazon ECS in the first place.</p><h3><strong>What is Amazon ECS, and why use it?</strong></h3><p>Amazon Elastic Container Service, usually called <strong>ECS</strong>, is an AWS service for running and managing containerized applications.</p><p>In simple terms, I package my application and everything it needs into a Docker container. ECS then helps run that container in AWS, restart it if it fails, launch multiple copies when more capacity is needed, and connect those copies to services such as load balancers, logs, and monitoring.</p><p>Instead of manually logging into a server every time I need to deploy or restart an application, I define how the application should run using an ECS task definition. An ECS service then tries to keep the required number of tasks running.</p><p>Teams commonly use ECS because it provides:</p><ul><li>Repeatable container-based deployments</li><li>Automatic replacement of failed tasks</li><li>Easy integration with AWS services</li><li>The ability to run and scale multiple application instances</li><li>Rolling deployments with less manual server management</li></ul><p>For this application, the basic request path looked like this:</p><blockquote>User → Application Load Balancer → ECS task → Node.js application</blockquote><p>The Application Load Balancer, or ALB, accepted incoming requests and sent them to the ECS tasks. Before sending user traffic to a task, however, it first needed to decide whether that task was healthy.</p><p>That is where my confusing problem began.</p><p>The deployment looked successful.</p><p>My ECS task was running. The application logs said the server had started. There were no obvious crashes, and the container stayed alive.</p><p>Then I opened the application.</p><p><strong>503 Service Unavailable.</strong></p><p>I checked the target group. The new task was marked <strong>unhealthy</strong>.</p><p>That felt contradictory. How could the application be running while the load balancer insisted that it was unhealthy?</p><p>The answer taught me an important production lesson:</p><blockquote>A running application is not automatically a reachable, ready, or healthy target.</blockquote><p>The process inside a container can be alive while the Application Load Balancer cannot connect to it. The load balancer may connect successfully but receive the wrong response. Or the application may accept requests before it is truly ready to serve them.</p><p>All three situations can look similar from the outside: an unhealthy target and a 503 response.</p><p>This article explains how I learned to separate those problems and debug them systematically.</p><h3>“The app is healthy” can mean several different things</h3><p>When developers say an application is healthy, we may mean:</p><ul><li>The process has not crashed.</li><li>The container is running.</li><li>The server is listening on a port.</li><li>A health endpoint returns 200 OK.</li><li>The application can reach its database and other required services.</li><li>Real users can successfully complete requests.</li></ul><p>These are related, but they are not the same.</p><p>ECS may report that a task is running because its container process is still alive. Docker may report the container as healthy because an internal command succeeds. Meanwhile, the ALB may mark the same task unhealthy because it cannot reach the expected port or path.</p><p>Each system is asking a different question.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LAqLrleIreRZLTlR_cen1A.png" /></figure><p>My first mistake was treating all these signals as if they meant the same thing.</p><h3>How an ALB health check actually works</h3><p>An Application Load Balancer does not study your logs or ask ECS whether the process is alive. It performs a network request to each registered target using the target group’s health-check settings.</p><p>In simplified form, it does this:</p><blockquote>ALB → target IP → configured port → configured path</blockquote><p>For example:</p><pre>GET http://10.0.2.41:3000/health</pre><p>The target is considered healthy only if the connection succeeds, the application responds within the timeout, and the response code matches the configured success codes.</p><p>The ALB repeats this check at an interval. A target normally has to succeed several times before becoming healthy, and fail several times before becoming unhealthy. This prevents one temporary network problem from immediately changing its state.</p><p>If the target group has no healthy targets, the load balancer has nowhere safe to send normal traffic. That is when users may see a 503.</p><p>The important point is simple:</p><blockquote>The ALB does not care that your process exists. It cares whether it can successfully complete its own health-check request.</blockquote><h3>Problem 1: The health check path is wrong</h3><p>One of the most common causes is also one of the easiest to miss.</p><p>Suppose the application exposes:</p><pre>GET /health</pre><p>But the target group checks:</p><pre>GET /</pre><p>If / returns 404, redirects to another page, requires authentication, or waits for frontend rendering, the ALB may mark the target unhealthy even though /health works perfectly.</p><p>Path mistakes can be less obvious than a missing slash. The application may use:</p><pre>/api/health</pre><p>while the target group uses:</p><pre>/health</pre><p>An Nginx rule may add or remove a prefix. A new API version may move the route. A case difference may matter. Authentication middleware may accidentally protect the endpoint.</p><p>The quickest check is to call the exact path not approximately the same path from a location that can reach the target:</p><pre>curl -i http://TARGET_IP:PORT/health</pre><p>Look at the status code, response time, redirects, and body. Do not stop after seeing a response in a browser. The ALB may be using a different path, port, or protocol.</p><h3>Problem 2: The port or protocol does not match</h3><p>A health-check path can be correct while the request is still going to the wrong place.</p><p>Imagine that the Node.js application listens on port 3000, but the ECS container definition maps port 8080. Or the target group forwards to port 80. The server is running, yet nothing is listening where the ALB expects it.</p><p>Several port values must agree:</p><ul><li>The port used by the application</li><li>The container port in the task definition</li><li>The port mapping used by ECS</li><li>The target group’s traffic and health-check port</li></ul><p>With dynamic port mapping, ECS can register a different host port for each task. In that case, the target group must use the registered traffic port rather than a manually assumed one.</p><p>Protocol mismatches cause a similar problem. If the target group sends HTTPS directly to a container that serves plain HTTP, the TLS handshake will fail. A common architecture is:</p><blockquote>Client — HTTPS → ALB — HTTP → ECS task</blockquote><p>TLS ends at the load balancer, and the load balancer communicates with the task over HTTP inside the VPC. Configuring HTTPS on the target group without configuring TLS in the container breaks that arrangement.</p><p>When debugging, write down the full route explicitly:</p><pre>Listener protocol/port → target-group protocol/port → container port → application port</pre><p>If you cannot trace one continuous path through those values, you have probably found the problem.</p><h3>Problem 3: The server is listening only on localhost</h3><p>This issue is especially confusing because everything works from inside the container.</p><p>The application may start like this:</p><pre>app.listen(3000, &quot;127.0.0.1&quot;);</pre><p>or use localhost as the host.</p><p>Inside the container, this may succeed:</p><pre>curl http://localhost:3000/health</pre><p>But localhost refers to the container itself. A request arriving through the container’s network interface is different. If the server listens only on the loopback interface, the ALB cannot reach it.</p><p>For a containerized application that should accept external network traffic, the server normally needs to listen on all interfaces:</p><pre>app.listen(3000, &quot;0.0.0.0&quot;);</pre><p>This small configuration difference creates a classic situation:</p><ul><li>The process is running.</li><li>An internal health check passes.</li><li>The ALB health check fails.</li></ul><p>Testing only from inside the container can therefore give false confidence. You must also test through the same network path used by the load balancer.</p><h3>Problem 4: Security groups or networking block the request</h3><p>Sometimes the application and health endpoint are both correct. The request simply never reaches them.</p><p>In a typical setup, the ALB and ECS tasks have separate security groups. A safer rule is not “allow the whole internet to access the container.” It is:</p><blockquote><em>Allow inbound traffic to the task’s application port from the ALB security group.</em></blockquote><p>For example:</p><pre>Task security group inbound rule<br>Source: ALB security group<br>Port: 3000<br>Protocol: TCP</pre><p>Common networking mistakes include:</p><ul><li>The task security group allows the wrong port.</li><li>It allows an old ALB security group instead of the current one.</li><li>Network ACL rules block the traffic or return path.</li><li>Tasks are registered in the wrong subnets.</li><li>The target group uses an incompatible target type.</li><li>Route-table or VPC configuration prevents communication.</li></ul><p>Networking failures often produce timeouts rather than application error codes. That difference is useful.</p><p>If the target returns 404 or 500, the request probably reached an HTTP server. If the health check times out or reports a connection error, investigate the port, binding, security group, and network path first.</p><h3>Problem 5: The endpoint responds, but not in the way the ALB expects</h3><p>By default, a health check usually expects a successful HTTP response. The exact accepted range can be configured using the target group’s matcher.</p><p>Your endpoint may return:</p><ul><li>301 or 302 because HTTP redirects to HTTPS</li><li>401 because authentication middleware protects the route</li><li>403 because a host or access rule rejects the request</li><li>404 because the route is wrong</li><li>500 because a dependency check throws an error</li><li>503 because the application reports that it is not ready</li></ul><p>Even a healthy looking endpoint may be too slow. If it performs several database queries, calls an external API, or waits for a slow dependency, it can exceed the ALB health-check timeout.</p><p>A health endpoint should be fast, predictable, and intentionally designed. It should not render a full page or perform expensive work.</p><p>Also be careful with redirects. A browser follows them automatically, which can make a URL look successful. A health checker may judge the redirect response itself. Test with a tool that shows the original status code:</p><pre>curl -i http://TARGET_IP:PORT/health</pre><h3>ECS container health and ALB target health are different</h3><p>This distinction caused much of my initial confusion.</p><p>An ECS container health check runs a command inside the container. For example:</p><pre>{<br>  &quot;command&quot;: [<br>    &quot;CMD-SHELL&quot;,<br>    &quot;curl -f http://localhost:3000/health || exit 1&quot;<br>  ],<br>  &quot;interval&quot;: 30,<br>  &quot;timeout&quot;: 5,<br>  &quot;retries&quot;: 3,<br>  &quot;startPeriod&quot;: 60<br>}</pre><p>This answers:</p><blockquote><em>Can the container check its own application?</em></blockquote><p>The ALB check comes from outside the container and answers:</p><blockquote><em>Can the load balancer reach this target through the configured network route?</em></blockquote><p>Both checks can use /health, yet produce different results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dE_ZBwzZro_aK7oJbuDz-A.png" /></figure><p>A container health check can pass while the ALB check fails because of localhost binding, port mapping, security groups, or target-group configuration.</p><p>The reverse is also possible. A badly written container health command may fail because curl is not installed, even while the ALB successfully reaches the application.</p><p>Never assume one health signal proves the other.</p><h3>Startup time can make a healthy deployment look broken</h3><p>Some applications need time to become ready. They may run database migrations, establish connections, load configuration, warm caches, or initialize large modules.</p><p>During that period, the process may exist, but /health may fail or time out.</p><p>If ECS starts evaluating ALB failures too soon, it may stop the task and launch a replacement. The replacement experiences the same startup delay and is also stopped. This creates a loop in which the application never receives enough time to become healthy.</p><p>That is what the health check grace period is designed to prevent. It gives a new task time to start before ECS treats load-balancer health failures as a reason to replace it.</p><p>The grace period should reflect measured startup behavior, not a random large number. If the application normally becomes ready in 40 seconds, a short grace period may be reasonable. If it sometimes takes several minutes, investigate why and configure the deployment accordingly.</p><p>A long grace period can hide a genuinely broken deployment. A short one can kill a slow but valid startup. The right value comes from observing real startup time.</p><h3>Liveness and readiness should answer different questions</h3><p>Using one /health endpoint for everything is simple, but it can mix two separate concerns.</p><h4>Liveness: Is the process alive?</h4><p>A liveness endpoint should answer whether the application is running and capable of responding at a basic level.</p><pre>GET /health/live</pre><p>It should normally avoid failing just because a temporary external dependency is unavailable. Otherwise, a brief database outage could cause every application task to restart at the same time, making recovery harder.</p><p>Example response:</p><pre>{<br>  &quot;status&quot;: &quot;alive&quot;<br>}</pre><h3>Readiness: Can this instance safely receive traffic?</h3><p>A readiness endpoint should answer whether the task is prepared to serve real requests.</p><pre>GET /health/ready</pre><p>It may check critical dependencies such as configuration, database connectivity, or required initialization. If the application cannot serve requests correctly, readiness should fail so the load balancer temporarily removes the task from rotation.</p><p>Example response:</p><pre>{<br>  &quot;status&quot;: &quot;ready&quot;<br>}</pre><p>A useful design is:</p><ul><li>Use liveness for the container-level check.</li><li>Use readiness for the ALB target-group check.</li></ul><p>This is not a universal rule, but it creates clearer signals. A task can remain alive long enough to recover from a temporary dependency problem while the load balancer avoids sending user traffic to it.</p><p>Keep readiness checks small and time-bounded. If the endpoint checks ten dependencies sequentially, the health check itself can become a new failure source.</p><h3>The debugging order that saved me time</h3><p>During the incident, it was tempting to change several settings at once: security groups, health paths, ports, and timeouts. That makes troubleshooting harder because even if the target becomes healthy, you do not know which change fixed it.</p><p>A better approach is to follow the request from the application outward.</p><h4>1. Confirm that the process is running</h4><p>Check the ECS task status and application logs. Confirm that the server started without immediately crashing or restarting.</p><p>Look for the actual listening port in the logs rather than assuming it matches the environment configuration.</p><h4>2. Test inside the container</h4><p>If possible, run:</p><pre>curl -i http://localhost:3000/health</pre><p>If this fails, the problem is probably inside the application or container: wrong path, wrong port, missing route, slow startup, or application error.</p><h4>3. Confirm the listening interface</h4><p>Verify that the application listens on 0.0.0.0, not only 127.0.0.1 or localhost.</p><h4>4. Compare every port</h4><p>Check the application port, task definition container port, ECS port mapping, registered target port, and target group health check port.</p><h4>5. Reproduce the exact ALB request</h4><p>Test the same protocol, port, and path used by the target group. Inspect the original response code and time.</p><h4>6. Read the target health reason</h4><p>Do not stop at the word <strong>unhealthy</strong>. The target group provides a reason such as timeout, connection error, or response code mismatch. That reason tells you which layer to investigate next.</p><h4>7. Check security groups and network flow</h4><p>Confirm that the task allows inbound traffic from the ALB security group on the correct application port. Then inspect subnet, network ACL, route, and target registration details if necessary.</p><h4>8. Check the success code matcher</h4><p>Confirm that the endpoint returns an accepted response code. Avoid widening the matcher just to hide a wrong 404, 401, or redirect.</p><h4>9. Measure response and startup time</h4><p>Compare endpoint response time with the configured timeout. Compare application startup time with the container start period and ECS health check grace period.</p><h4>10. Change one thing at a time</h4><p>After each change, wait for enough health check cycles and inspect the result. This produces evidence instead of guesses.</p><h3>A practical checklist</h3><p>When an ECS task is running but the ALB target is unhealthy, I now check these questions:</p><h4>Application</h4><ul><li>Is the process actually staying alive?</li><li>Which port is the application really using?</li><li>Is it listening on 0.0.0.0?</li><li>Does the exact health route exist?</li><li>Does it respond quickly without authentication?</li><li>What status code does it return?</li></ul><h4>ECS and container</h4><ul><li>Does the task definition expose the correct container port?</li><li>Does the port mapping match the application?</li><li>Is the container health command valid?</li><li>Are required tools such as curl available inside the image?</li><li>Does the app need a start period before container health checks begin?</li></ul><h4>Target group and ALB</h4><ul><li>Is the correct target group attached to the service?</li><li>Is the protocol HTTP or HTTPS as intended?</li><li>Is the health-check port correct or set to the traffic port?</li><li>Is the health check path exact?</li><li>Do the expected success codes match the actual response?</li><li>Is the timeout long enough for a normal response?</li><li>What specific target health reason is reported?</li></ul><h3>Networking</h3><ul><li>Does the task security group allow the ALB security group?</li><li>Is the allowed port correct?</li><li>Are the tasks registered in the intended VPC and subnets?</li><li>Are network ACLs and routes allowing the request and response?</li></ul><h3>Deployment timing</h3><ul><li>How long does the application take to become ready?</li><li>Is the ECS health-check grace period appropriate?</li><li>Does the deployment continuously start and stop tasks before they finish initializing?</li></ul><h3>The lesson behind the 503</h3><p>The most useful lesson was not a single AWS setting.</p><p>It was learning to treat “health” as a path rather than a boolean value.</p><p>For a user request to succeed, every part of the route must agree:</p><blockquote>ALB listener</blockquote><blockquote>→ target group</blockquote><blockquote>→ network rules</blockquote><blockquote>→ registered port</blockquote><blockquote>→ container interface</blockquote><blockquote>→ application route</blockquote><blockquote>→ required dependencies</blockquote><p>The application can be healthy at one layer and unreachable at the next.</p><p>Once I understood that, the 503 stopped feeling mysterious. Instead of asking, “Why does AWS think my app is broken?” I started asking more precise questions:</p><ul><li>Can the application answer locally?</li><li>Can it answer through its network interface?</li><li>Can the ALB reach that interface and port?</li><li>Does the exact health path return an accepted response in time?</li><li>Is the application alive, or is it truly ready for traffic?</li></ul><p>Those questions turn a frustrating deployment problem into a traceable request path.</p><p>Your container may be running. Your logs may look clean. Your application may even respond perfectly on localhost.</p><p>But production health is not defined by what the application says about itself.</p><p>It is defined by whether the next system in the chain can reach it, trust it, and safely send it traffic.</p><p><em>A running task tells you that the process exists. A healthy target tells you that the system can actually use it.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d5abf41cdd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Secure, Performant, Modular: A GraphQL Blueprint]]></title>
            <link>https://medium.com/@supunbandara/secure-performant-modular-a-graphql-blueprint-350bee17fbfa?source=rss-8afa21e8efce------2</link>
            <guid isPermaLink="false">https://medium.com/p/350bee17fbfa</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[prisma]]></category>
            <dc:creator><![CDATA[Supun Bandara]]></dc:creator>
            <pubDate>Thu, 10 Jul 2025 17:39:57 GMT</pubDate>
            <atom:updated>2026-09-09T17:47:54.222Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xaRe6rRFml87tGHGJh8TWA.png" /></figure><p>Imagine you’re building a modern web app, say a dashboard that fetches user details, settings, and activity logs.</p><p>You hit your REST API. One endpoint returns too much data. Another gives too little. You nest API calls. You paginate. You filter. You patch responses on the client.</p><p><strong>Soon… you’re drowning in over-fetching, under-fetching, and endless boilerplate.</strong></p><p>You start asking:</p><p><em>“Why can’t my client just ask for exactly what it needs?”<br>“Why do I need 4 round-trips to build a simple view?”<br>“Why am I writing so many endpoints for different use cases?”</em></p><p>This is where <strong>GraphQL</strong> enters the picture.</p><p>Born at Facebook and battle tested at scale, GraphQL flips the traditional API paradigm. Instead of the server dictating what data is returned, <strong>the client asks for exactly what it needs nothing more, nothing less.</strong></p><p>With a single endpoint, powerful querying capabilities, and a strongly-typed schema that acts as living documentation, GraphQL offers a much more flexible and scalable way to build APIs.</p><h3>What This Article Demonstrates</h3><p>This article walks you through the architecture and best practices behind building a modular, secure, and scalable GraphQL API — the kind of backend you’d be proud to showcase in your portfolio or deploy in a real-world environment.</p><h3>Key Features Highlighted</h3><ul><li><strong>Modular Architecture<br></strong>Explore a clean separation of concerns, schema definitions (SDL), resolvers, services, and utilities making your codebase maintainable and team-friendly.</li><li><strong>Schema-First Development<br></strong>Experience a workflow where your GraphQL schema drives implementation, fostering clear contracts between frontend and backend.</li><li><strong>Efficient Data Fetching with DataLoader<br></strong>Discover how to eliminate the classic N+1 query problem, optimizing performance through smart batching and caching.</li><li><strong>Role-Based Authorization with graphql-shield<br></strong>See how to enforce fine-grained access control, ensuring that each user only accesses what they’re permitted to.</li><li><strong>Scalable, Readable Folder Structure</strong><br>Adopt a project layout that’s easy to navigate, extend, and collaborate on ideal for growing teams and evolving requirements.</li></ul><h3><strong>The Tech Stack We’ll Use</strong></h3><p>We’re building a modern, scalable GraphQL API using a powerful, modular Node.js ecosystem. Here’s what powers it:</p><ul><li><strong>Node.js</strong> — Our server-side JavaScript runtime environment</li><li><strong>Apollo Server (v4)</strong> — Production-ready GraphQL engine with plugin-based extensibility</li><li><strong>Prisma</strong> — Type-safe, auto-generated ORM for PostgreSQL</li><li><strong>PostgreSQL</strong> — Robust, SQL-based relational database</li><li><strong>graphql-shield</strong> — Middleware for fine-grained role-based access control</li><li><strong>DataLoader</strong> — Utility for solving the N+1 problem via request-level batching and caching</li></ul><p>By the end, you’ll not only understand GraphQL, but also build confidently using it with a clean folder structure, reusable patterns, and extendable architecture.</p><p>Let’s start by scaffolding our project and getting the essentials in place.</p><h3>Understanding GraphQL Fundamentals</h3><p>GraphQL is an open-source query language and runtime for APIs, developed by Facebook in 2012 and released publicly in 2015. It enables clients to request exactly the data they need from a server, nothing more and nothing less. Unlike traditional REST APIs, which expose multiple endpoints for different resources, GraphQL exposes a single endpoint and allows clients to specify their data requirements in a structured query format. This approach provides flexibility, efficiency, and a strongly-typed schema that defines the capabilities of the API.</p><h4>Why Use GraphQL? (Problems It Solves Compared to REST)</h4><p>GraphQL addresses several limitations commonly encountered with RESTful APIs:</p><ul><li><strong>Over-fetching and Under-fetching: </strong>REST endpoints often return fixed data structures, leading to clients receiving too much or too little data. GraphQL allows clients to specify exactly what fields they need, reducing unnecessary data transfer.</li><li><strong>Multiple Round Trips: </strong>Gathering related data in REST may require multiple requests to different endpoints. With GraphQL, clients can fetch related resources in a single query, improving performance and reducing network overhead.</li><li><strong>Strongly-Typed Schema: </strong>GraphQL APIs are defined by a schema that specifies types and relationships, enabling better validation, introspection, and auto-generated documentation.</li><li><strong>Rapid Iteration: </strong>Frontend teams can evolve their data requirements without requiring backend changes for every new field, as long as the data exists in the schema.</li><li><strong>Single Endpoint: </strong>GraphQL APIs expose a unified endpoint, simplifying client-server interactions and API management.</li></ul><h4>When Not to Use GraphQL</h4><p>While GraphQL offers many advantages, it is not always the best fit for every project. Consider alternatives in the following scenarios:</p><ul><li><strong>Simple or CRUD-Only APIs:</strong> If your API is straightforward, with basic create/read/update/delete operations and limited relationships, REST may be simpler and more efficient.</li><li><strong>Caching Requirements: </strong>REST leverages HTTP caching out of the box. GraphQL’s single endpoint approach complicates traditional caching strategies, requiring additional tooling.</li><li><strong>Binary/File Uploads:</strong> REST is often better suited for handling file uploads and binary data, though GraphQL has workarounds.</li><li><strong>Rate Limiting and Security: </strong>Fine-grained rate limiting and access control can be more complex with GraphQL, especially for deeply nested queries.</li><li><strong>Learning Curve and Tooling: </strong>Teams unfamiliar with GraphQL may face a steeper learning curve, and existing REST infrastructure may be easier to maintain for small projects.</li></ul><h3>Understanding Key GraphQL Concepts</h3><p>To build a powerful and maintainable GraphQL API, it’s important to understand the core components that define how data is structured, accessed, and modified. These fundamental concepts form the foundation of every GraphQL service.</p><h4>Schema: The Blueprint of Your API</h4><p>At the heart of every GraphQL API lies the schema — a strongly typed contract that defines exactly what data is available and how clients can interact with it. You can think of the schema as the API’s blueprint or map, describing:</p><ul><li>Types of data your API exposes (e.g., Course, Instructor, User)</li><li>Operations clients can perform (queries to fetch data, mutations to modify data)</li><li>Relationships between different data types (e.g., a Course has an Instructor)</li></ul><p>The schema is written using the Schema Definition Language (SDL), a concise, language-agnostic syntax designed to clearly express your API’s structure. For example:</p><pre>type Course {<br> id: ID!<br> title: String!<br> description: String<br>}</pre><pre>type Instructor {<br> id: ID!<br> fullName: String!<br> bio: String<br> expertise: String<br>}</pre><p>Here, Course and Instructor are object types with fields that have specific scalar or object types. The exclamation mark (!) denotes a non-nullable field, meaning it must always have a value.</p><p>Why schemas matter:</p><ul><li>They provide a clear, shared contract between frontend and backend teams.</li><li>They enable strong validation of queries and mutations.</li><li>They allow API evolution with predictable changes.</li></ul><h4>Queries: Fetching Exactly What You Need</h4><p>Queries are how clients request data from the API. Unlike traditional REST APIs, which often return fixed data structures and may require multiple endpoints, GraphQL queries give clients the power to specify exactly what data they want — no more, no less.</p><p>For example, a client can request a course’s title and the instructor’s name in a single query:</p><pre>query {<br>  course(id: &quot;1&quot;) {<br>    title<br>    instructor {<br>      fullName<br>    }<br>  }<br>}</pre><p>This flexibility means:</p><ul><li>Reduced over-fetching: Clients don’t receive unnecessary data.</li><li>Reduced under-fetching: Clients don’t need to make multiple requests to get related data.</li><li>Simplified network architecture: One endpoint handles all queries.</li></ul><p>GraphQL queries mirror the shape of the response, making it intuitive to understand what data will be returned just by looking at the query.</p><h4>Mutations: Modifying Data Safely and Predictably</h4><p>While queries are for reading data, mutations are the way to create, update, or delete data. They correspond to the “write” operations in your API and are essential for any interactive application.</p><p>Mutations are executed sequentially, ensuring that side effects happen in a predictable order. This is important when multiple changes depend on one another.</p><p>Example mutation to create a new instructor:</p><pre>mutation {<br>  createInstructor(input: { name: &quot;John Doe&quot; }) {<br>    id<br>    name<br>  }<br>}</pre><p>Key points about mutations:</p><ul><li>They can accept input arguments, often wrapped in input objects for clarity.</li><li>They return the updated or created data, enabling clients to update their UI immediately.</li><li>They ensure data integrity by running in sequence.</li></ul><h4>Resolvers: Behind the Scenes Logic</h4><p>Resolvers are the functions that execute the logic behind each field in your schema. When a client requests a field, the corresponding resolver fetches or computes the data for that field.</p><p>Resolvers connect your GraphQL schema to your data sources, whether that’s a database (e.g., via Prisma), an external API, or even static data.</p><pre>export const resolvers = {<br>  Query: {<br>    userById: (obj, { id }, context, info) =&gt; {<br>      return userService.findById(id);<br>    },<br><br>    users: (obj, args, context, info) =&gt; {<br>      return userService.findAll();<br>    },<br>  },<br><br>  Mutation: {<br>    editUser: (obj, { id, editUserReq }, context, info) =&gt; {<br>      return userService.editUser(id, editUserReq);<br>    },<br><br>    deleteUser: (obj, { id }, context, info) =&gt; {<br>      return userService.deleteUser(id);<br>    },<br>  },<br>};</pre><p>Important aspects of resolvers:</p><ul><li>They receive arguments, context (for authentication, caching, etc.), and the parent object.</li><li>They run per field, allowing fine-grained control over data fetching.</li><li>They can be composed and reused to keep your code modular.</li><li>They are the ideal place to implement authorization and business logic.</li></ul><h4>Subscriptions: Real-Time Magic</h4><p>GraphQL subscriptions enable your API to push real-time updates to clients over WebSockets. This feature is perfect for applications that require instant responsiveness, such as chat apps, live dashboards, or stock tickers.</p><p><strong>Important:</strong> Subscriptions require setting up a WebSocket server and managing persistent connections, which adds complexity. Because this is an advanced topic with many nuances, we won’t cover subscriptions in this article.</p><p>However, we’ll explore real-time GraphQL subscriptions in a future deep dive!</p><h3>Exploring Different GraphQL Server Architectures</h3><p>GraphQL’s flexibility means it can be deployed in various ways, depending on your project’s needs and existing infrastructure. Let’s look at three popular architectural patterns that show how GraphQL can fit into different scenarios.</p><h4>1. Dedicated GraphQL Server with Direct Database Access</h4><p>This is the simplest setup and works well for new projects or greenfield applications. Here, the GraphQL server acts as the single source of truth, directly connected to your database.</p><ul><li>The schema is designed to closely reflect your database structure.</li><li>Resolver functions handle all data fetching and mutations by querying the database.</li><li>Clients interact with a single GraphQL endpoint that manages all operations.</li></ul><p>Example:<br>Imagine building a blog platform where posts, authors, and comments are stored in a PostgreSQL database. The GraphQL server defines types like Post and Author and directly queries the database to serve client requests.</p><p>This approach is straightforward to implement and maintain when your data lives in one place and your app is starting fresh.</p><h4>2. GraphQL as a Unified Layer Over Existing Systems</h4><p>In many real-world cases, you already have multiple backend systems, legacy databases, micro services, or third-party APIs. GraphQL can serve as a middleware layer, providing a single, consistent API that aggregates data from these diverse sources.</p><ul><li>The GraphQL server routes queries and mutations to the appropriate backend systems.</li><li>Resolvers act as connectors, fetching or modifying data across different services.</li><li>Clients benefit from a simplified interface that hides the complexity of multiple data sources.</li></ul><p>Example:<br>An e-commerce platform might pull product details from a legacy database, inventory status from a warehouse microservice, and payment info from an external payment gateway all unified behind one GraphQL API.</p><p>This pattern helps modernize existing systems without rewriting them and enables new client apps to interact with complex backends more easily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhWXrZtoQPLESaMbJD5K7A.png" /><figcaption>Image source: <a href="https://stepzen.com/">StepZen</a></figcaption></figure><h4>3. Hybrid Approach</h4><p>The hybrid model blends the two approaches above. Your GraphQL server manages some data directly through a connected database while also integrating external services for other parts of the system.</p><ul><li>Some resolvers query your own database for core data.</li><li>Other resolvers delegate to external APIs or microservices.</li><li>This setup offers fine-grained control and flexibility.</li></ul><p>Example:<br>In a blogging app, you might store posts and user profiles in your database but use a third-party service like Disqus to handle comments. Your GraphQL server seamlessly combines both sources into a single API.</p><p>This approach is ideal when you want to maintain control over critical data while leveraging external tools and services.</p><h4>Why These Architectures Matter</h4><p>Each architecture highlights GraphQL’s adaptability:</p><ul><li>Standalone servers are perfect for new projects with centralized data.</li><li>Middleware layers simplify complex, distributed backends.</li><li>Hybrid setups provide the best of both worlds, balancing control and integration.</li></ul><p>Choosing the right architecture depends on your project’s scale, existing infrastructure, and long-term goals. GraphQL’s flexibility ensures it can grow with your application, whether you’re starting fresh or evolving legacy systems.</p><h3>Diving Into the Code: Exploring the Project Architecture</h3><p>Ready to see how all the pieces fit together? You can start by cloning the full project repository here: <a href="https://github.com/supunbandara/graphql-api-server-prisma-apollo">GraphQL API Server — Prisma — Apollo</a>.</p><p>In the upcoming sections, we’ll unpack the core architectural components step-by-step revealing how the schema, resolvers, services, and utilities collaborate to create a clean, modular, and scalable GraphQL API.</p><p>Think of this as your guided tour through the project’s blueprint, where each part plays a vital role in delivering a secure and efficient backend. Whether you’re following along or exploring on your own, this walkthrough will equip you with practical insights and best practices used by real-world teams.</p><p>Let’s jump in and start building!</p><h3>Schema Setup with Apollo Server</h3><pre>import { ApolloServer } from &quot;@apollo/server&quot;;<br>import { apiExplorer } from &quot;./api/index.js&quot;;</pre><ul><li>We use Apollo Server v4 — a modular version that’s framework agnostic and designed to work seamlessly with Express via @apollo/server/express4.</li><li>apiExplorer.getSchema() returns the compiled GraphQL schema, loaded dynamically via SDL files, resolvers, middleware (we’ll look at this in the next section).</li></ul><pre>const apolloServer = new ApolloServer({<br>   schema,<br>   introspection: false,<br>   formatError: (error) =&gt; {<br>     logger.error(error);<br>     return error;<br>   },<br>   validationRules: [depthLimit(5)],<br>   debug: true,<br> });</pre><p>Here:</p><ul><li>We register our executable schema.</li><li>formatError is used to intercept and log GraphQL errors cleanly.</li><li>depthLimit(5) restricts overly nested queries for performance and security.</li><li>debug: true is enabled for better developer feedback during development.</li></ul><pre>import express from &quot;express&quot;;<br>import cookieParser from &quot;cookie-parser&quot;;<br>import cors from &quot;cors&quot;;<br>import dotenv from &quot;dotenv&quot;;<br><br>import depthLimit from &quot;graphql-depth-limit&quot;;<br>import { ApolloServer } from &quot;@apollo/server&quot;;<br>import { apiExplorer } from &quot;./api/index.js&quot;;<br>import { verify } from &quot;./utils/jwt.js&quot;;<br>import { logger } from &quot;./utils/logging.js&quot;;<br>import { expressMiddleware } from &quot;@apollo/server/express4&quot;;<br><br>dotenv.config({<br>  path: `.env.${process.env.NODE_ENV || &quot;development&quot;}`,<br>});<br><br>const port = process.env.PORT || 8080;<br><br>async function startServer() {<br>  try {<br>    const schema = await apiExplorer.getSchema();<br><br>    const apolloServer = new ApolloServer({<br>      schema,<br>      introspection: false,<br>      formatError: (error) =&gt; {<br>        logger.error(error);<br>        return error;<br>      },<br>      validationRules: [depthLimit(5)],<br>      debug: true,<br>    });<br><br>    await apolloServer.start();<br><br>    const app = express();<br><br>    // Middleware setup<br>    app.use(cors());<br>    app.use(express.json());<br>    app.use(express.urlencoded({ extended: false }));<br>    app.use(cookieParser());<br><br>    // GraphQL endpoint with proper context<br>    app.use(<br>      &quot;/graphql&quot;,<br>      expressMiddleware(apolloServer, {<br>        context: async ({ req, res }) =&gt; {<br>          const authUser = verify(req, res); // Extract authUser from JWT<br>          return { authUser }; // Now accessible in resolvers &amp; shield<br>        },<br>      })<br>    );<br><br>    // Start listening<br>    app.listen({ port }, () =&gt; {<br>      logger.info(`Server ready at http://localhost:${port}`);<br>    });<br>  } catch (err) {<br>    logger.error(&quot;Failed to start server:&quot;, err);<br>  }<br>}<br><br>startServer();</pre><h3>Connecting to the Database with Prisma</h3><p>To manage our database schema and safely interact with data, we use <a href="https://www.prisma.io/">Prisma ORM</a>, a type-safe, modern database toolkit for Node.js and TypeScript.</p><h4>Why Prisma?</h4><p>In this project, Prisma provides:</p><ul><li>Autocompletion &amp; type-safety in service code (based on your schema).</li><li>Readable schema definitions using Prisma making it easier to model relationships.</li><li>Auto generated client that removes the need for raw SQL or handwritten queries.</li><li>Built-in migration system to evolve your DB schema safely.</li></ul><p>This is especially useful in GraphQL projects where type consistency is crucial Prisma ensures your service layer aligns with your GraphQL SDL and resolver logic.</p><h4>PostgreSQL with Railway</h4><p>We use <a href="https://railway.app/">Railway</a> to quickly spin up a PostgreSQL database with:</p><ul><li>1-click deployable projects</li><li>Environment variable support (DATABASE_URL)</li><li>Free tier access for testing or demo use</li></ul><p>Once the DB is ready, you can connect it via your .env:</p><p>DATABASE_URL=postgresql://username:password@hostname:port/dbname</p><h4>Defining Your Models</h4><p>Your Prisma models live inside prisma/schema.prisma. For example:</p><pre>model User {<br> id        Int      @id @default(autoincrement())<br> createdAt DateTime @default(now())<br> updatedAt DateTime @updatedAt<br> fullName  String<br> email     String   @unique<br> password  String?<br> role      String<br><br> instructors Instructor[] @relation(&quot;CreatedInstructors&quot;)<br> courses     Course[]     @relation(&quot;CreatedCourses&quot;)<br><br> @@map(&quot;users&quot;)<br>}</pre><p>This schema represents the data structure and relationships between User, Instructor, and Course.</p><h4>Running Migrations</h4><p>Whenever you update your model, run:</p><p>npx prisma migrate dev — name init</p><p>This will:</p><ul><li>Create SQL migration files</li><li>Push changes to the connected PostgreSQL database</li><li>Regenerate the Prisma client for type-safe usage in code</li></ul><h4>Using Prisma in Resolvers</h4><p>Prisma integrates seamlessly in your user.service.js, instructor.service.js, and course.service.js files:</p><pre>import { PrismaClient } from &#39;@prisma/client&#39;;<br><br>const prisma = new PrismaClient();<br>const user = await prisma.user.findUnique({ where: { id: userId } });</pre><p>This replaces manual queries or raw SQL and ensures safety, validation, and autocompletion.</p><h3>Splitting the GraphQL Schema for Scalability</h3><p>As your GraphQL API grows in complexity introducing more features, types, and business logic keeping the entire schema in a single file quickly becomes unmanageable. To maintain clarity and scalability, it’s best to split your schema into modular files.</p><p>Thankfully, the makeExecutableSchema function (from @graphql-tools/schema, used internally by Apollo Server) supports passing arrays of type definitions and resolver maps. This makes it easy to split your schema across multiple files and organize them by domain.</p><p>In this project, I’ve divided the schema into the following parts:</p><ul><li>auth.api.graphql — Handles user authentication and registration</li><li>user.api.graphql — Manages user-related CRUD operations</li><li>root.api.graphql — Serves as the root entry point and includes global types like advanced scalars</li></ul><p>Depending on your domain, you could further split files into things like course.api.graphql, instructor.api.graphql, or any other domain module.</p><h4><strong>Root Schema vs Extended Schemas</strong></h4><p>To make this modular structure work, we follow a key GraphQL pattern:</p><p><strong>Root schema:</strong> One schema file (typically root.api.graphql) defines the base Query, Mutation, and optionally Subscription types:</p><pre>scalar Date<br>scalar Time<br>scalar DateTime<br><br><br>type Query {<br> sayHello(name: String!): String!<br>}<br><br><br>type Mutation {<br> sayHello(name: String!): String!<br>}</pre><p><strong>Extended schemas:</strong> Other schema modules extend these base types using extend:</p><pre>extend type Query {<br>  userById(id: ID!): User<br><br>  users: [User!]!<br>}<br><br>extend type Mutation {<br>  editUser(id: ID!, editUserReq: EditUserReq!): User<br><br>  deleteUser(id: ID!): User<br>}<br><br>type User {<br>  id: ID!<br>  createdAt: DateTime!<br>  updatedAt: DateTime!<br>  fullName: String!<br>  email: String!<br>}<br><br>input EditUserReq {<br>  fullName: String!<br>  email: String!<br>}</pre><p>This setup helps isolate different areas of the API while still composing them together into a single schema.</p><p>The ApiExplorer utility automatically scans these files and merges them into a fully functional GraphQL schema at runtime. You don’t need to manually combine imports, just drop a new schema and resolver file in the appropriate folder.</p><h3>Implementing Resolvers</h3><p>This module defines the resolvers related to user operations, such as fetching a user by ID, listing all users, editing a user, and deleting a user. It imports the corresponding SDL (user.api.graphql) and maps resolver functions to service-layer methods (userService). This abstraction keeps resolver logic clean and focused, while business logic stays encapsulated in the service.</p><pre>import fs from &quot;fs&quot;;<br>import { userService } from &quot;../../services/user.service.js&quot;;<br>import path from &quot;path&quot;;<br>import { fileURLToPath } from &quot;url&quot;;<br><br>const __filename = fileURLToPath(import.meta.url);<br>const __dirname = path.dirname(__filename);<br><br>export const typeDefs = fs.readFileSync(path.join(__dirname, &quot;user.api.graphql&quot;), &quot;utf8&quot;);<br><br><br>export const resolvers = {<br>  Query: {<br>    userById: (obj, { id }, context, info) =&gt; {<br>      return userService.findById(id);<br>    },<br><br>    users: (obj, args, context, info) =&gt; {<br>      return userService.findAll();<br>    },<br>  },<br><br>  Mutation: {<br>    editUser: (obj, { id, editUserReq }, context, info) =&gt; {<br>      return userService.editUser(id, editUserReq);<br>    },<br><br>    deleteUser: (obj, { id }, context, info) =&gt; {<br>      return userService.deleteUser(id);<br>    },<br>  },<br>};</pre><p>This is the root module of the GraphQL schema. It registers the base Query and Mutation types (not extend) and binds custom scalar types (Date, Time, DateTime) using the graphql-scalars library. A basic sayHello query and mutation are included to verify the server is working correctly. This acts as the foundation on which all other schema modules extend.</p><pre>import fs from &quot;fs&quot;;<br>import { GraphQLDate, GraphQLDateTime, GraphQLTime } from &quot;graphql-scalars&quot;;<br>import path from &#39;path&#39;;<br>import { fileURLToPath } from &#39;url&#39;;<br><br>const __filename = fileURLToPath(import.meta.url);<br>const __dirname = path.dirname(__filename);<br><br>export const typeDefs = fs.readFileSync(path.join(__dirname, &quot;root.api.graphql&quot;), &quot;utf8&quot;);<br><br>export const resolvers = {<br>  Date: GraphQLDate,<br>  Time: GraphQLTime,<br>  DateTime: GraphQLDateTime,<br><br>  Query: {<br>    sayHello: (obj, args, context, info) =&gt; {<br>      return `Hello ${args.name}!`;<br>    },<br>  },<br><br>  Mutation: {<br>    sayHello: (obj, args, context, info) =&gt; {<br>      return `Hello ${args.name}!`;<br>    },<br>  },<br>};</pre><h3>Authentication and Authorization</h3><p>In most production ready GraphQL APIs, enforcing <strong>Authentication</strong> and <strong>Authorization</strong> is essential to prevent unauthorized access and control which users can perform which operations. This section will walk through how our sample project achieves this using <strong>JWT based authentication</strong>, <strong>Apollo Server context</strong>, and <strong>graphql-shield</strong> for fine-grained access control.</p><p>We use <strong>JSON Web Tokens (JWT)</strong> to confirm user identity. The token is passed via the Authorization header (typically as Bearer &lt;token&gt;) and validated on every request. Instead of checking this in each resolver manually, we configure <strong>Apollo Server’s context</strong> function to handle it globally.</p><pre>app.use(<br>    &quot;/graphql&quot;,<br>    expressMiddleware(apolloServer, {<br>      context: async ({ req, res }) =&gt; {<br>        const authUser = verify(req, res); // Extract authUser from JWT<br>        return { authUser }; // Now accessible in resolvers &amp; shield<br>      },<br>    })<br>  );</pre><p>This is the core of how authentication flows into your GraphQL app:</p><ul><li>The verify() function reads the JWT from headers, verifies it, and returns the authUser payload.</li><li>This authUser is then injected into the GraphQL context, so any resolver or middleware (like graphql-shield) can access it.</li></ul><h4>Authorization with graphql-shield</h4><p>For role-based access control, our project uses <a href="https://github.com/dimatill/graphql-shield">graphql-shield</a>. It lets us create <strong>declarative permission rules</strong> and attach them to resolvers without writing manual checks in each one.</p><h4>Defining Rules</h4><p>Rules are defined using rule() from graphql-shield. Here’s how we set up basic permissions:</p><pre>import { rule } from &quot;graphql-shield&quot;;<br><br>export const isAuthorized = rule()((obj, args, { authUser }, info) =&gt; {<br>  return authUser &amp;&amp; true;<br>});<br><br>export const isUserAdmin = rule()(<br>  (obj, args, { authUser }, info) =&gt;<br>    authUser &amp;&amp; authUser.role === &quot;ADMIN&quot;<br>);</pre><h4>Mapping Rules to Permissions</h4><p>Permissions are applied per field or type in your schema using a map:</p><pre>import { isAuthorized, isUserAdmin } from &quot;../../utils/shield.js&quot;;<br><br>export const permissions = {<br>  Query: {<br>    userById: isAuthorized,<br><br>    users: isAuthorized,<br>  },<br><br>  Mutation: {<br>    editUser: isUserAdmin,<br><br>    deleteUser: isUserAdmin,<br>  },<br>};</pre><p>In this example:</p><ul><li>users and userById can be accessed by any authenticated user.</li><li>editUser and deleteUser are restricted to users with ADMIN roles.</li></ul><h4>Organizing Permissions per Module</h4><p>Unlike resolvers and typeDefs (which Apollo supports as arrays), graphql-shield requires a <strong>single permissions object</strong>. To maintain modularity, each GraphQL module (e.g., user, instructor, course) has its own permission file. These are later merged inside apiExplorer.js.</p><p>In apiExplorer, all permission maps from each module are merged into one and passed to shield().</p><p>The allowExternalErrors: true option ensures that errors from resolvers are not swallowed by graphql-shield.</p><pre>import fs from &quot;fs&quot;;<br>import path from &quot;path&quot;;<br>import { GraphQLError } from &quot;graphql&quot;;<br>import { makeExecutableSchema } from &quot;@graphql-tools/schema&quot;;<br>import { applyMiddleware } from &quot;graphql-middleware&quot;;<br>import { shield } from &quot;graphql-shield&quot;;<br>import { fileURLToPath } from &#39;url&#39;;<br><br>const __filename = fileURLToPath(import.meta.url);<br>const __dirname = path.dirname(__filename);<br><br>class ApiExplorer {<br>  constructor() {<br>    this._read = true;<br>    this._typeDefs = [];<br>    this._resolvers = [];<br>    this._permissions = {};<br>    this._validators = {};<br>  }<br><br>  _merge(target, source) {<br>    target.Query = target.Query ? target.Query : {};<br>    source.Query = source.Query ? source.Query : {};<br>    target.Mutation = target.Mutation ? target.Mutation : {};<br>    source.Mutation = source.Mutation ? source.Mutation : {};<br><br>    const preQuery = target.Query;<br>    const preMutation = target.Mutation;<br><br>    Object.assign(target, source);<br>    Object.assign(target.Query, preQuery);<br>    Object.assign(target.Mutation, preMutation);<br>  }<br><br>  async _scan(directory) {<br>    const files = fs<br>      .readdirSync(directory)<br>      .filter((file) =&gt; fs.lstatSync(path.join(directory, file)).isFile())<br>      .filter((file) =&gt; file.indexOf(&quot;.&quot;) !== 0 &amp;&amp; file.slice(-3) === &quot;.js&quot;);<br><br>    const dirs = fs<br>      .readdirSync(directory)<br>      .filter((file) =&gt; fs.lstatSync(path.join(directory, file)).isDirectory());<br><br>    for (const file of files) {<br>      const obj = await import(path.join(directory, file));<br><br>      if (obj.typeDefs) {<br>        this._typeDefs.push(obj.typeDefs);<br>      }<br>      if (obj.resolvers) {<br>        this._resolvers.push(obj.resolvers);<br>      }<br>      if (obj.permissions) {<br>        this._merge(this._permissions, obj.permissions);<br>      }<br>      if (obj.validators) {<br>        this._merge(this._validators, obj.validators);<br>      }<br>    }<br><br>    for (const dir of dirs) {<br>      await this._scan(path.join(directory, dir));<br>    }<br>  }<br><br>  async getSchema() {<br>    if (this._read) {<br>      await this._scan(__dirname);<br>      this._read = false;<br>    }<br><br>    // Create graphql schema with middleware<br>    const schema = makeExecutableSchema({<br>      typeDefs: this._typeDefs,<br>      resolvers: this._resolvers,<br>    });<br><br>    return applyMiddleware(<br>      schema,<br>      this._validators,<br>      shield(this._permissions, {<br>        allowExternalErrors: true,<br>        fallbackError: new GraphQLError(&quot;Not Authorised!&quot;, {<br>          extensions: {<br>            code: &quot;FORBIDDEN&quot;,<br>            myExtension: &quot;foo&quot;,<br>          },<br>        }),<br>      })<br>    );<br>  }<br>}<br><br>export const apiExplorer = new ApiExplorer();</pre><h3><strong>Tackling the N + 1 Query Problem in GraphQL</strong></h3><p>When working with GraphQL APIs, especially those that model relationships like one-to-many or many-to-one, you may encounter a common performance pitfall known as the N + 1 query problem. Understanding and addressing this issue is crucial for building efficient, scalable APIs.</p><h4>What Is the N + 1 Query Problem?</h4><p>The <strong>N + 1 problem</strong> arises in GraphQL APIs when a list of parent records is fetched, and for each of them, a separate query is triggered to resolve a related field (like a foreign key). This results in <strong>1 query for the parent + N queries for the children</strong>, which becomes very inefficient.</p><p>Let’s look at a <strong>real scenario</strong> from our project involving Course and its creator field (a User):</p><pre>type Course {<br>  id: ID!<br>  title: String!<br>  creator: User!<br>}</pre><h4>Problematic Resolver (Causes N + 1)</h4><pre>export const resolvers = {<br>  Query: {<br>    courses: () =&gt; courseService.findAll(), // Returns 10 courses<br>  },<br>  Course: {<br>    creator: (course) =&gt; userService.findById(course.creatorId),<br>  },<br>};</pre><p>What Happens in SQL</p><pre>-- 1 query for all courses<br>SELECT * FROM courses;<br><br>-- Then 1 query for each creator (10 total)<br>SELECT * FROM users WHERE id = 1;<br>SELECT * FROM users WHERE id = 2;<br>SELECT * FROM users WHERE id = 3;<br>...</pre><p>If you return 100 courses, this results in <strong>101 queries</strong>! This is inefficient and strains your database.</p><h4>Why Does This Happen in GraphQL?</h4><p>GraphQL resolvers are typically called for each field in the response. If your resolver for the creator field fetches the user by ID for every course, you inadvertently trigger a separate database call for each course’s creator — even if multiple courses share the same creator.</p><h4>How to Solve It: DataLoader to the Rescue</h4><p>To address this, the GraphQL community (and Facebook’s engineering team) introduced a tool called DataLoader. DataLoader batches multiple requests for the same type of data into a single query, dramatically reducing the number of database calls.</p><h4>How DataLoader Works</h4><ul><li>Batching: During a single GraphQL request, DataLoader collects all the IDs that need to be fetched for a particular field (like creatorId for courses).</li><li>Single Query: Instead of firing off a query for each ID, it makes one query using all the collected IDs (e.g., SELECT * FROM users WHERE id IN (…)).</li><li>Caching: DataLoader also caches results for the duration of the request, so if the same ID is requested multiple times, the database is only queried once.</li></ul><h4>Refactoring the Resolver with DataLoader</h4><p>Here’s how you can use DataLoader to optimize the creator field in your Course type:</p><pre>import DataLoader from &#39;dataloader&#39;;<br>import { userService } from &#39;../services/user.service.js&#39;;<br><br>export class UserDataLoader extends DataLoader {<br><br>  constructor() {<br>    const batchLoader = async userIds =&gt; {<br>      const users = await userService.findByIds(userIds);<br>        return userIds.map(<br>            userId =&gt; users.filter(user =&gt; user.id === userId)[0]<br>        );<br>    };<br><br>    super(batchLoader);<br>  }<br><br>  static getInstance(context) {<br>    if (!context.userDataLoader) {<br>      context.userDataLoader = new UserDataLoader();<br>    }<br><br>    return context.userDataLoader;<br>  }<br><br>}</pre><p>In your resolver</p><pre>Course: {<br>   creator: ({ creatorId }, args, context, info) =&gt; {<br>     const userDataLoader = UserDataLoader.getInstance(context);<br><br>     return userDataLoader.load(creatorId);<br>   },<br> },</pre><p>Key Points:</p><ul><li>The batch function receives an array of IDs and returns a Promise that resolves to an array of users in the same order.</li><li>The DataLoader instance should be created once per request and stored in the context object, ensuring cache isolation between requests.</li><li>With this setup, fetching creators for a list of courses now results in just two queries: one for the course and one for all the relevant users.</li></ul><h4>Why Proper Ordering Matters</h4><p>DataLoader expects the batch function to return results in the same order as the input IDs. This guarantees that each loaded item maps correctly to its corresponding request. Always map your results accordingly to avoid mismatches.</p><h3>Input Validation in GraphQL APIs</h3><p>While GraphQL’s Schema Definition Language (SDL) allows you to specify which fields are required or optional, it doesn’t offer much for enforcing more complex validation rules like checking email formats or password strength. To ensure robust input validation, you’ll need to implement additional logic beyond SDL constraints.</p><h4>Why Not Validate in Resolvers?</h4><p>Although you can add validation directly inside resolver functions, this approach quickly becomes messy and repetitive, especially as your API grows. Instead, using middleware for validation keeps your codebase clean, modular, and easier to maintain.</p><h4>A Modern Approach: Middleware-Based Validation</h4><p>Middleware allows you to intercept and validate incoming requests before they reach your business logic. This is especially useful for mutations like user signup, where you want to enforce rules such as:</p><ul><li>Email must be valid</li><li>Passwords must match</li><li>Password must meet strength requirements</li></ul><p><strong>Example: </strong>Signup and Login Input Validation Middleware</p><p>Below is a refactored, modern example demonstrating how to implement input validation middleware for both signup and login mutations. This approach ensures that user inputs are properly validated before reaching your business logic, keeping your API secure and robust.</p><pre>import { ApolloServerErrorCode } from &#39;@apollo/server/errors&#39;;<br>import PasswordValidator from &#39;password-validator&#39;;<br>import validator from &#39;validator&#39;;<br><br><br>const passwordSchema = new PasswordValidator()<br>  .is().min(8)<br>  .is().max(20)<br>  .has().letters()<br>  .has().digits()<br>  .has().symbols()<br>  .has().not().spaces();<br><br>export const validators = {<br><br>  Mutation: {<br><br>    login: (resolve, obj, args, context) =&gt; {<br>      const { email } = args;<br><br>      if (!validator.isEmail(email)) {<br>        throw new ApolloServerErrorCode.BAD_USER_INPUT(&#39;Invalid Email address!&#39;);<br>      }<br><br>      return resolve(obj, args, context);<br>    },<br><br>    signup: (resolve, obj, args, context) =&gt; {<br>      const { email, password, rePassword } = args.signupReq;<br><br>      if (!validator.isEmail(email)) {<br>        throw new ApolloServerErrorCode.BAD_USER_INPUT(&#39;Invalid Email address!&#39;);<br>      }<br><br>      if (password !== rePassword) {<br>        throw new ApolloServerErrorCode.BAD_USER_INPUT(&#39;Passwords don\&#39;t match!&#39;);<br>      }<br><br>      if (!passwordSchema.validate(password)) {<br>        throw new ApolloServerErrorCode.BAD_USER_INPUT(&#39;Password is not strong enough!&#39;);<br>      }<br><br>      return resolve(obj, args, context);<br>    },<br>  }<br>};</pre><h4>Best Practices</h4><ul><li><strong>Keep validation logic out of resolvers</strong> to maintain separation of concerns.</li><li><strong>Use third-party libraries</strong> (like validator and password-validator) for common validation tasks.</li><li><strong>Create middleware per mutation</strong> to keep your validation rules organized and reusable.</li><li><strong>Combine validation with authorization</strong> for a secure, maintainable API.</li></ul><p>By adopting middleware for input validation, you keep your GraphQL API clean, robust, and easy to extend as your project grows.</p><h3>Securing Your GraphQL API</h3><p>GraphQL’s flexibility empowers clients to craft precise, powerful queries but this openness also introduces new security risks. Without proper safeguards, attackers can exploit your API to overload your server or extract sensitive information. Here’s how to address the most critical security concerns in a modern GraphQL backend.</p><h4>Why Security Matters in GraphQL</h4><p>Unlike traditional REST endpoints, GraphQL exposes a single, highly dynamic entry point. This means:</p><ul><li>Clients can construct deeply nested or complex queries.</li><li>Attackers can probe your schema to discover all available data and operations.</li><li>Unrestricted access can lead to denial-of-service (DoS) attacks or data leaks.</li></ul><p>Proactive security measures are essential to keep your API robust and reliable.</p><h4>1. Disabling Schema Introspection in Production</h4><p><strong>Introspection</strong> allows clients (and tools like GraphiQL) to query your API for its full schema definition. While invaluable during development, leaving introspection enabled in production can help attackers map out your entire API.</p><p><strong>How to disable introspection in Apollo Server:</strong></p><pre>const apolloServer = new ApolloServer({<br>  schema,<br>  introspection: false, // Disables introspection queries<br>});</pre><ul><li><strong>When to disable:<br></strong>Turn off introspection in production environments to prevent schema discovery by unauthorized users.</li><li><strong>When to keep enabled:<br></strong>During development, introspection is useful for debugging and tooling.</li></ul><h4>2. Limiting Query Depth to Prevent Abuse</h4><p>GraphQL’s powerful nesting capability can be abused by crafting <strong>excessively deep or recursive queries</strong>, especially in schemas with circular relationships like in our case: Course → Instructor → Course → ….</p><p>If left unchecked, malicious clients could send deeply nested queries that <strong>consume excessive CPU or memory</strong>, potentially leading to <strong>denial of service (DoS)</strong> attacks.</p><p>To safeguard your API, you can:</p><ul><li><strong>Use query depth limits</strong>: Tools like graphql-depth-limit help restrict the maximum depth of queries.</li></ul><pre>import depthLimit from &#39;graphql-depth-limit&#39;;<br><br>const apolloServer = new ApolloServer({<br>  schema,<br>  introspection: false,<br>  validationRules: [depthLimit(5)], // Restrict query nesting<br>});</pre><p><strong>Why this matters:<br></strong>This prevents users from sending queries that could crash your server or degrade performance by requesting deeply nested data.</p><h4>3. Additional Security Best Practices</h4><ul><li><strong>Rate Limiting:<br></strong>Throttle requests per user or IP to block brute-force or spam attacks.</li><li><strong>Authorization Middleware:<br></strong>Use libraries like graphql-shield to enforce fine-grained permissions on queries and mutations.</li><li><strong>Input Validation:<br></strong>Validate all incoming data to prevent injection attacks and ensure data integrity.</li><li><strong>Error Handling:<br></strong>Avoid leaking sensitive information in error messages return generic errors in production.</li><li><strong>Query Complexity Analysis:<br></strong>Use tools to estimate the computational cost of a query and reject overly expensive requests.</li></ul><h4>Key Takeaways</h4><ul><li><strong>Disable introspection</strong> in production to hide your schema from attackers.</li><li><strong>Limit query depth</strong> to prevent resource exhaustion from deeply nested queries.</li><li><strong>Layer security</strong>: Combine middleware, validation, rate limiting, and error handling for a robust defense.</li></ul><p>By proactively addressing these areas, you ensure your GraphQL API remains both powerful and secure ready for real-world use.</p><h3><strong>Putting Our GraphQL API to the Test: Real-World Validation with Postman</strong></h3><p>Building a robust GraphQL API is only half the battle; the other half is making sure every piece works flawlessly under real-world conditions. That’s where Postman comes in, our go to tool for manual API testing and exploration.</p><p>Postman lets us simulate authentic user interactions, pass along authentication tokens, and inspect responses in a clear, visual way. This hands-on approach helps us catch issues early, validate permission rules, and ensure our API behaves exactly as intended.</p><p>Here are snapshots of the critical flows we put through their paces:</p><h4>1. User Signup Mutation</h4><p>We kick things off by creating new users. The signup mutation not only registers a user but also returns a success message and user details confirming the process works end to end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9zdVmRN-6FGvlY5rn3n8oQ.png" /></figure><h4>2. Login Mutation</h4><p>Next, we test user authentication. Logging in returns a JWT token, the golden key for accessing protected parts of our API. Postman makes it easy to grab this token and use it in subsequent requests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RH76i0IJXYu6hBVTlJMUNQ.png" /></figure><h4>3. Fetch Authenticated User Query</h4><p>With the token in hand, we verify that authenticated queries work as expected. This test fetches the current user’s profile, proving that our authentication middleware correctly identifies and authorized users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MeGq1r_qikjDGiuDaPqhig.gif" /></figure><h4><strong>4. Create Instructor Mutation (Authenticated)</strong></h4><p>Only logged-in users should be able to create new instructors. This mutation test confirms that permission rules are enforced — unauthorized attempts are blocked, while valid requests succeed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r_WYbHbrr4wyDPFO41krlw.gif" /></figure><h4>5. Courses by Instructor Query</h4><p>Finally, we dive into nested queries, fetching all courses linked to a specific instructor. This test ensures data relationships are correctly resolved and permissions respected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HzuNCG2IPDwvCv83R-xvJQ.png" /></figure><h3>Why These Tests Matter</h3><p>Manual testing with Postman is more than just ticking boxes. It’s about simulating real user journeys, uncovering edge cases, and validating that our graphql-shield permissions and authentication layers are rock solid. These interactive tests form the first critical layer of quality assurance before we move on to automated testing.</p><p>By sharing these Postman test cases, we hope to give you a practical blueprint for verifying your own GraphQL APIs making sure they’re secure, reliable, and ready for the real world.</p><p>Besides Postman, GraphQL APIs can be tested using tools like <strong>GraphQL Playground</strong> or <strong>Altair</strong> for interactive querying, and automated testing with <strong>Jest</strong> and <strong>Supertest</strong> for integration-level checks. <strong>Apollo Client DevTools</strong> is useful for frontend debugging, while <strong>DataLoader behaviors</strong> and <strong>authorization rules</strong> can be unit tested in isolation. For production readiness, it’s also important to consider <strong>security testing</strong> and <strong>query performance profiling</strong>.</p><h3>Wrapping Up: What We Built and the Road Ahead</h3><p>In this journey, we’ve crafted a full featured GraphQL API defining a clear schema, implementing resolvers, securing the server with authentication and authorization, and ensuring robust data access with Prisma. Along the way you’ve learned how to:</p><ul><li>Design a schema-first API that cleanly separates your data contract from implementation</li><li>Handle user signup, login, and JWT-based authentication</li><li>Enforce role-based access control using graphql-shield</li><li>Perform efficient CRUD operations on interconnected entities like books and authors</li><li>Optimize performance by tackling the N+1 query problem with DataLoader</li><li>Validate inputs and protect your API with middleware and security best practices</li><li>Test your API interactively using tools like Postman, simulating real-world scenarios</li></ul><p>But this is just the beginning.</p><h3>Next Steps: Expanding Your GraphQL Mastery</h3><p>To elevate your API to the next level, consider exploring:</p><ul><li><strong>Subscriptions: </strong>Enable real-time updates with WebSocket-powered GraphQL subscriptions, perfect for chat apps, live feeds, or notifications.</li><li><strong>Schema Federation:</strong> Build a distributed GraphQL architecture by composing multiple services into a single graph, enabling scalable micro services development.</li><li><strong>Advanced Caching and Performance:</strong> Leverage Apollo’s caching strategies and persisted queries to boost responsiveness and reduce server load.</li><li><strong>Deployment and Monitoring:</strong> Learn best practices for deploying GraphQL APIs securely and monitoring them in production using tools like Apollo Studio or Grafana.</li><li><strong>Automated Testing: </strong>Expand from manual Postman tests to automated unit, integration, and end-to-end tests for continuous quality assurance.</li></ul><h4>GitHub Repository</h4><p><a href="https://github.com/supunbandara/graphql-api-server-prisma-apollo">View the source code on GitHub</a></p><h3>Resources for Deeper Learning</h3><ul><li><a href="https://www.apollographql.com/blog">Apollo GraphQL Blog</a> — In-depth tutorials and best practices</li><li><a href="https://graphql.org/learn/">GraphQL.org Learn Section</a> — Official documentation and concepts</li></ul><p>GraphQL opens up a world of possibilities for building flexible, efficient, and developer-friendly APIs. With the foundation you’ve built here, you’re well equipped to tackle complex data requirements and deliver seamless experiences to your users.</p><p>The more you build with GraphQL, the more you’ll realize it’s not just a query language, it’s a new way of thinking about your backend architecture.</p><p>Let this project be your launchpad to mastering the GraphQL ecosystem.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=350bee17fbfa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React at Scale: Why I Use Server Actions for Mutations & React Query for Fetching]]></title>
            <link>https://medium.com/@supunbandara/react-at-scale-why-i-use-server-actions-for-mutations-react-query-for-fetching-a2c582354010?source=rss-8afa21e8efce------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2c582354010</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[nextjs-server-action]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-query]]></category>
            <dc:creator><![CDATA[Supun Bandara]]></dc:creator>
            <pubDate>Mon, 16 Jun 2025 13:06:20 GMT</pubDate>
            <atom:updated>2025-06-16T14:21:42.688Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Ty9igUG3GvF0AvVPIvKFA.png" /><figcaption>Image created and edited by the author</figcaption></figure><p>Here’s the thing about React apps — they have a way of humbling you.</p><p>You start with that beautiful, clean component structure. Your data fetching is organized. Your forms work perfectly. You feel like a React wizard.</p><p>Then your app grows. Suddenly you’re drowning in scattered fetch calls across dozens of components. Loading states are everywhere, but none of them are consistent. Your forms break in mysterious ways that make you question your life choices. Welcome to the pain of scale.</p><p>This article is for developers who’ve already built a few React projects and are starting to feel the pain of scale. That uncomfortable moment when you realize your codebase has grown beyond what simple useState and useEffect can elegantly handle.</p><p>As applications grow, data management becomes one of the most significant sources of technical debt. To address these challenges, I rely on a proven pattern that leverages <strong>Server Actions in Next.js 15</strong> together with <strong>React Query</strong> (TanStack Query). This approach delivers clean, scalable, and maintainable data handling eliminating much of the friction that comes with traditional client-side fetching and mutations.</p><p>Server Actions, introduced in recent versions of Next.js, allow you to execute server-side logic directly from your components. This means you can handle mutations, form submissions, and business logic securely on the server, without the overhead of separate API endpoints. React Query, on the other hand, excels at managing client-side cache, synchronizing UI state, and keeping your interface responsive and up-to-date.</p><p>By combining these tools, you get the best of both worlds: type-safe, secure server-side mutations with Server Actions, and powerful client-side caching and state management with React Query. This pattern not only simplifies your codebase but also ensures your application remains fast, reliable, and easy to maintain as it scales.</p><p>And if you’re building a serious React app in 2025, Next.js should be your default choice. Even the official React documentation recommends Next.js as the standard framework, thanks to its built-in routing, server-side logic, and performance optimizations out of the box.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBSLd_g7PpAImDgHjVIn2w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mp_HDavS7lWcjkgMNdESbA.png" /></figure><p>In the sections that follow, I’ll break down why this pattern works, when to use each tool, and how to implement it effectively in your Next.js projects.</p><h3>What we’ll cover:</h3><ol><li>React Query: The Client-Side Champion</li><li>Server Actions: The Game Changer</li><li>Why This Combination Works: Addressing the Real Problems</li><li>The Ideal Pattern: Server Actions + React Query</li><li>When This Pattern Might Not Be Right</li><li>Conclusion</li></ol><h3>Pre-requisites</h3><p>Before we dive in, make sure you have experience with:</p><ul><li>Building React apps using functional components and hooks</li><li>Familiarity with Next.js (pages, routing, server/client component concepts)</li><li>Basic understanding of React Query or similar libraries like SWR</li><li>Experience working with APIs, mutations, or form submissions</li></ul><h3><strong>React Query: The Client-Side Champion</strong></h3><p>Think of React Query (TanStack Query) as your application’s memory but smarter. While your components forget everything between renders, React Query remembers, optimizes, and keeps your data perfectly synchronized.</p><p>TanStack Query isn’t just another state management solution. It’s purpose-built to solve the unique challenges of server state — that tricky space where your UI needs to stay in sync with data that lives somewhere else and can change at any time.</p><p>Here’s what makes it particularly valuable:</p><ol><li><strong>Robust Caching System</strong>: TanStack Query provides an intelligent caching mechanism that can significantly improve your application’s performance and user experience. Even with server components handling the initial data fetch, subsequent interactions can benefit from this caching layer.</li><li><strong>Automatic Background Updates</strong>: The library manages background data refreshing and revalidation, ensuring your UI stays in sync with server data without manual intervention.</li><li><strong>Complex State Management</strong>: It handles loading, error, and success states automatically, reducing boilerplate code and making your components cleaner and more maintainable.</li><li><strong>Optimistic Updates</strong>: When modifying data, TanStack Query allows you to update the UI immediately while handling the server communication in the background, creating a more responsive user experience.</li></ol><h4><strong>Why React Query remains essential in the Next.js era:</strong></h4><p>Even with Server Components handling initial data loading, React Query shines in the interactive layers of your application. It’s perfect for:</p><ul><li>Caching and deduplicating GET requests across your component tree.</li><li>Managing real-time data that changes based on user interactions.</li><li>Handling complex UX patterns like infinite scroll and pagination.</li><li>Keeping your UI responsive with background updates and smart refetching.</li><li>Simplifying cache invalidation with intuitive APIs like queryClient.invalidateQueries()</li></ul><p>The magic happens when React Query and Server Actions work together — Server Actions handle the heavy lifting of mutations and initial data loading, while React Query ensures your client-side experience remains smooth, cached, and always up-to-date.</p><h3><strong>Server Actions: The Game Changer</strong></h3><p>Next.js introduces a powerful and streamlined way to update data using Server Actions. Server Actions are asynchronous functions that run securely on the server and can be invoked directly from your React components — either through forms or event handlers. This approach eliminates the need for custom API routes and keeps your data logic close to your UI.</p><p>When you use a Server Action, Next.js integrates this with its caching system. That means when you perform an update, Next.js can send both the updated UI and new data back to the client in a single server roundtrip. This results in faster, more efficient updates and a smoother user experience.</p><p>Key features of updating data in Next.js:</p><ul><li>Server Actions: Define async functions with the use server directive. These can be called from forms (using the action prop) or buttons (using the formAction prop).</li><li>Automatic POST Handling: Server Actions are invoked using the POST method, keeping mutations secure and efficient.</li><li>Cache Revalidation: After an update, you can call revalidatePath or revalidateTag to ensure your UI reflects the latest data.</li><li>Progressive Enhancement: Forms using Server Actions work even if JavaScript is disabled, providing robust support for all users.</li><li>Seamless Integration: You can pass Server Actions as props, invoke them in event handlers, and even combine them with React’s useActionState for pending/loading states.</li></ul><p>By leveraging Server Actions, Next.js makes it easier to keep your data up-to-date, your UI responsive, and your codebase clean all without boilerplate or extra API endpoints.</p><h3><strong>Why This Combination Works: Addressing the Real Problems</strong></h3><p>Before diving into implementation, let’s understand the core issues that make this pattern so effective. Every limitation below is a reason why I default to Server Actions + React Query for large applications.</p><h3><strong>Issue #1: Client-Side fetch() Isn’t Enough</strong></h3><h4>Server-Side Strengths</h4><p>Next.js offers a powerful way to fetch data <strong>on the server side</strong> using the native fetch() API. One of the key features is that fetch() in server components is <strong>automatically cached and deduplicated</strong> by Next.js.</p><p>This makes it perfect for <strong>static generation (SSG)</strong> or <strong>server-side rendering (SSR)</strong> — and if your data doesn’t change often, you might not even need client-side state.</p><h4>The Client-Side Problem</h4><p>But here’s the issue: <strong>On the Client Side, fetch() Isn’t Enough</strong></p><p>Once you’re in <strong>client components</strong> — especially when you need:</p><ul><li>Background updates</li><li>Loading &amp; error states</li><li>Pagination or infinite scroll</li><li>Cache invalidation after mutations</li><li>Stale data management</li></ul><p>fetch() alone gets cumbersome. You’ll end up building your own mini-query system… which is exactly what <strong>React Query</strong> already solves brilliantly.</p><h4>The Solution</h4><p>That’s why my recommendation is:</p><ul><li>Use fetch() in Server Components when SSR/SSG makes sense</li><li>Use <strong>React Query</strong> for <strong>interactive, client-side</strong> fetching where real-time UX matters</li></ul><h3><strong>Issue #2: Common Pitfall — Don’t Call Server Actions in queryFn</strong></h3><p>You might be tempted to use <strong>React Query</strong> on the <strong>client side</strong>, but call a <strong>Server Action</strong> in the queryFn like this:</p><pre>const getData = async () =&gt; {<br>  &#39;use server&#39;<br>  // Server-side logic here<br>}<br>const { data } = useQuery([&#39;my-data&#39;], () =&gt; getData())</pre><p>Or perhaps you’re wrapping it in an API-like utility call.</p><h4>Why It Feels Smart</h4><ul><li>You still <strong>use Server Actions</strong> for logic centralization and security (e.g., DB calls, secrets)</li><li>You <strong>gain React Query benefits</strong> like caching, background refetching, and error/loading state handling</li><li>It seems like the best of both worlds</li></ul><h4>The Correct Approach</h4><p>If you want to use React Query on the client, you should <strong>separate the concerns</strong>:</p><h4>Option 1: Use API Routes or Fetchers</h4><p>Create a fetcher that hits an API route or external endpoint:</p><pre>// lib/fetchers.ts<br>export const fetchUsers = async () =&gt; {<br>  const res = await fetch(&#39;/api/users&#39;)<br>  return res.json()<br>}<br><br>// In your component<br>const { data, isLoading } = useQuery([&#39;users&#39;], fetchUsers)</pre><h4>Option 2: Move Server Action to Component Boundary</h4><p>If the Server Action is for mutations, use it <strong>where form submission happens</strong>, not inside a queryFn:</p><pre>// Server Action for mutations only<br>async function createUser(formData: FormData) {<br>  &#39;use server&#39;<br>  // Handle the mutation<br>}<br><br>// React Query for fetching<br>const { data: users } = useQuery([&#39;users&#39;], fetchUsers)<br><br>// Server Action called on form submission<br>&lt;form action={createUser}&gt;<br>  {/* form fields */}<br>&lt;/form&gt;</pre><p>This separation keeps Server Actions where they belong (server-side mutations) and React Query where it excels (client-side state management).</p><h3><strong>Issue #3: Understanding Server Actions’ True Purpose</strong></h3><p>Server Actions have a specific, well-defined purpose that many developers misunderstand. Let’s break it down:</p><p>When mutating data, it is usually a form submission. You can call server actions without a form submission, but then you are likely just looking for a success or fail response — possibly with useOptimistic having already updated the UI. Absolutely, no documentation or recommendation in the docs to fetch initial or polling data with server actions.</p><p>Server Actions are most often used in the context of form submissions using:</p><pre>&lt;form action={createUser}&gt;</pre><p>Or invoked manually like:</p><pre>const handleClick = async () =&gt; {<br>  await createUser(data);<br>};</pre><p>But these are <strong>typically mutation flows</strong>, not data fetching.</p><h3><strong>Issue #4: Server Actions Are Sequential (Performance Limitation)</strong></h3><p>While Server Actions are powerful, they come with an important caveat: Server Actions are executed sequentially — not in parallel.</p><h4>What This Means</h4><p>If you trigger multiple Server Actions from the client even from unrelated components they won’t run concurrently. Next.js internally queues Server Actions and executes them one by one.</p><pre>// These won&#39;t execute in parallel<br>await createUser(formData)<br>await logAnalytics(formData)</pre><p>Or in UI:</p><pre>// Component A and B both use Server Actions<br>&lt;UserProfile /&gt;<br>&lt;Notifications /&gt;</pre><p>Even though these components are unrelated, their server actions will be executed <strong>sequentially</strong>, causing potential performance bottlenecks — especially if you’re expecting fast, parallel data fetching.</p><h4>Why Next.js Does This</h4><ul><li><strong>Security:</strong> Server Actions run server-side and often touch sensitive data — so execution is serialized for consistency and control.</li><li><strong>Form-bound execution:</strong> Actions are tied closely to user events like form submissions, where predictable sequencing matters.</li></ul><p><strong>Framework-level enforcement:</strong> This is part of how Next.js guarantees predictable behaviour across server-client boundaries.</p><h4>Recommended Workarounds</h4><p>If you need <strong>parallel data fetching</strong>, here’s how you can handle it:</p><p><strong>Use React Query for reads:<br></strong>React Query can handle parallel GET requests effortlessly with caching, background updates, and Promise.all()capabilities.</p><pre>const userQuery = useQuery([&#39;user&#39;], fetchUser)<br>const notificationsQuery = useQuery([&#39;notifications&#39;], fetchNotifications)</pre><p><strong>Use Server Actions for mutations only:<br></strong>Reserve Server Actions for writes (create/update/delete), while handling reads via React Query or traditional fetch.</p><p><strong>Combine related logic into a single Server Action:<br></strong>If multiple pieces of data are needed together, structure one Server Action that fetches and returns them in one go.</p><h3><strong>The Ideal Pattern: Server Actions + React Query</strong></h3><p>Now that we understand the limitations and why this combination is necessary, let’s see how it works in practice.</p><h4>The Workflow</h4><ol><li><strong>Server Actions</strong> handle server-side mutations (create, update, delete) and sensitive logic.</li><li><strong>React Query</strong> manages client-side data fetching, caching, and UI updates.</li></ol><h4><strong>Getting Started with React Query (Tanstack React Query)</strong></h4><p>So imagine this: You’re building a blog platform with Next.js 15, and you want to fetch some posts from an API.</p><p>But here’s the catch — you want it to:</p><ul><li>Work with server components (because Next.js encourages it now).</li><li>Avoid repeated fetching on the client.</li><li>Use <strong>React Query</strong> for caching, refetching, and state management.</li><li>Be scalable and secure on both server and client.</li></ul><p>Here’s how I built that setup, step-by-step:</p><h4><strong>Step 1: Set Up a Global Provider for React Query</strong></h4><p>Every React app needs a place to provide context globally — like theme, auth, or React Query’s client.</p><p>So in <strong>layout.tsx</strong>, I wrap my app with a Providers component:</p><pre>import Providers from &quot;./providers&quot;;<br><br>export default function RootLayout({ children }) {<br>  return (<br>    &lt;html lang=&quot;en&quot;&gt;<br>      &lt;body&gt;<br>        &lt;Providers&gt;{children}&lt;/Providers&gt;<br>      &lt;/body&gt;<br>    &lt;/html&gt;<br>  );<br>}</pre><p>This makes sure that <strong>React Query</strong> is available anywhere in the app.</p><h4><strong>Step 2: Create the Providers Component (Client Side)</strong></h4><p>Since we’re working with React Query (which runs in the browser), Providers needs to be a <strong>client component</strong>:</p><pre>&quot;use client&quot;;<br><br>import { QueryClient, QueryClientProvider } from &quot;@tanstack/react-query&quot;<br>import { ReactQueryDevtools } from &quot;@tanstack/react-query-devtools&quot;<br><br>export default function Providers({ children }: { children: React.ReactNode }) {<br>  const [queryClient] = useState(<br>    () =&gt;<br>      new QueryClient({<br>        defaultOptions: {<br>          queries: {<br>            // With SSR, we usually want to set some default staleTime<br>            // above 0 to avoid refetching immediately on the client<br>            staleTime: 4 * 1000,<br>            refetchInterval: 4 * 1000,<br>          },<br>        },<br>      })<br>  )<br><br>  return (<br>      &lt;QueryClientProvider client={queryClient}&gt;<br>        &lt;ReactQueryDevtools /&gt;<br>        {children}<br>      &lt;/QueryClientProvider&gt;<br>  )<br>}</pre><p>It grabs a QueryClient and shares it with the whole app.</p><h4><strong>Step 3: Prefetch Data in the Server Component (page.tsx)</strong></h4><p>In our posts page, we want to fetch data on the <strong>server</strong> and send it to the <strong>client</strong> hydrated (ready to use, no refetch).</p><p>Here’s what we do:</p><pre>import PostForm from &quot;@/components/post-form&quot;<br>import Posts from &quot;@/components/posts&quot;<br>import { fetchPosts } from &quot;../api&quot;<br>import {<br>  QueryClient,<br>  HydrationBoundary,<br>  dehydrate,<br>} from &quot;@tanstack/react-query&quot;<br><br>export default async function Home() {<br>  const queryClient = new QueryClient()<br><br>  await queryClient.prefetchQuery({<br>    queryKey: [&quot;posts&quot;],<br>    queryFn: fetchPosts,<br>  })<br>  return (<br>    &lt;main&gt;<br>      &lt;HydrationBoundary state={dehydrate(queryClient)}&gt;<br>        &lt;PostForm /&gt;<br>        &lt;Posts /&gt;<br>      &lt;/HydrationBoundary&gt;<br>    &lt;/main&gt;<br>  )<br>}</pre><p><strong>What’s happening here?</strong></p><ul><li>We get the QueryClient.</li><li>We <strong>prefetch</strong> the posts data on the server.</li><li>Then we <strong>dehydrate</strong> (serialize) the cache and pass it to the client with HydrationBoundary.</li></ul><p>This means: when Posts renders on the client, React Query already has the data ready in memory no extra loading spinner or request needed.</p><h4><strong>Step 4: Show the Posts with useQuery in a Client Component</strong></h4><p>Here’s the actual component that renders the posts:</p><pre>&quot;use client&quot;;<br><br>import { useQuery } from &quot;@tanstack/react-query&quot;;<br>import { getPosts } from &quot;../api&quot;;<br><br>export default function Posts() {<br>  const { data } = useQuery({<br>    queryKey: [&quot;posts&quot;],<br>    queryFn: async () =&gt; fetchPosts(),<br>  });<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Posts&lt;/h1&gt;<br>      &lt;ul&gt;<br>        {data?.map((post) =&gt; (<br>          &lt;li key={post.id}&gt;<br>            &lt;h2&gt;{post.title}&lt;/h2&gt;<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p>Since we already pre fetched and hydrated the data on the server, useQuery gets it <strong>instantly</strong> from the cache. No delay. No flashing loaders. No duplicate network requests.</p><h4><strong>Step 5: Simulate Real API with Delay</strong></h4><p>For demo purposes, we simulate a slow API using setTimeout:</p><pre>export async function fetchPosts() {<br>  await new Promise((resolve) =&gt; setTimeout(resolve, 1000));<br>  return [<br>    { id: 1, title: &quot;Post 1&quot; },<br>    { id: 2, title: &quot;Post 2&quot; },<br>  ];<br>}<br><br>export async function getComments() {<br>  await new Promise((resolve) =&gt; setTimeout(resolve, 1000));<br>  return [<br>    { id: 1, text: &quot;Great post!&quot; },<br>    { id: 2, text: &quot;Thanks for sharing&quot; },<br>  ];<br>}</pre><p>This lets us test hydration and caching more realistically.</p><h3><strong>Building Type Safe Server Actions in Next.js 15 (App Router)</strong></h3><p>With the rise of <strong>Server Actions</strong> in the Next.js App Router, it’s now easier than ever to handle form submissions on the server — securely, scalably, and with full type safety. Here’s how I built a minimal <strong>“Create Post”</strong> flow using:</p><ul><li>next-safe-action for type-safe Server Actions</li><li>react-hook-form for client-side form management</li><li>zod for validation</li><li>App Router’s built-in revalidatePath for cache revalidation</li></ul><p>Let’s break it down:</p><h4><strong>Step 1: Define a Zod Schema for Post Input</strong></h4><p>Begin by establishing a Zod schema that defines the structure and validation rules for your post input. By sharing this schema between the client and server, you ensure consistent validation across your application.</p><pre>// lib/formSchema.ts<br>import { z } from &quot;zod&quot;<br><br>export const formSchema = z.object({<br>  content: z.string().min(1, &quot;Post content is required&quot;),<br>})</pre><h4><strong>Step 2: Create the Server Action</strong></h4><p>In this step, we define a Server Action that executes on the server. The action receives validated input from the client, then calls an external API to create the post. While this example uses the native fetch API for the HTTP request, you can just as easily use an axios instance with custom interceptors for advanced scenarios such as global error handling, authentication, or logging. This flexibility allows you to integrate with any backend or third-party service without altering your client-side code.</p><pre>// server/actions/create-post.ts<br>&quot;use server&quot;<br><br>import { formSchema } from &quot;@/lib/formSchema&quot;<br>import { createSafeActionClient } from &quot;next-safe-action&quot;<br>import { revalidatePath } from &quot;next/cache&quot;<br><br>const action = createSafeActionClient()<br><br>export const createPost = action(formSchema, async ({ content }) =&gt; {<br>  try {<br>    const res = await fetch(&quot;https://api.example.com/posts&quot;, {<br>      method: &quot;POST&quot;,<br>      headers: {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        // optionally: pass auth token or session ID<br>        Authorization: `Bearer YOUR_TOKEN_HERE`,<br>      },<br>      body: JSON.stringify({ content }),<br>    })<br><br>    const data = await res.json()<br><br>    if (!res.ok) {<br>      return { error: data.message || &quot;Failed to create post&quot; }<br>    }<br><br>    revalidatePath(&quot;/&quot;) // optional cache revalidation<br><br>    return { success: &quot;Post created successfully&quot; }<br>  } catch (err) {<br>    return { error: &quot;Something went wrong&quot; }<br>  }<br>})</pre><p>This is clean, safe, and scalable. You can easily swap in another API (even third-party) without touching the client code.</p><h4><strong>Step 3: Build the Client Form</strong></h4><p>Finally, create a client-side form using react-hook-form for state management and validation. The form will invoke the server action and handle responses gracefully.</p><pre>// app/post-form.tsx<br>&quot;use client&quot;<br><br>import { useForm } from &quot;react-hook-form&quot;<br>import { zodResolver } from &quot;@hookform/resolvers/zod&quot;<br>import * as z from &quot;zod&quot;<br>import { formSchema } from &quot;@/lib/formSchema&quot;<br>import { createPost } from &quot;@/server/actions/create-post&quot;<br>import { useAction } from &quot;next-safe-action/hooks&quot;<br><br>import {<br>  Form,<br>  FormField,<br>  FormItem,<br>  FormLabel,<br>  FormControl,<br>  FormMessage,<br>} from &quot;@/components/ui/form&quot;<br>import { Input } from &quot;@/components/ui/input&quot;<br>import { Button } from &quot;@/components/ui/button&quot;<br><br>export default function PostForm() {<br>  const form = useForm&lt;z.infer&lt;typeof formSchema&gt;&gt;({<br>    resolver: zodResolver(formSchema),<br>    defaultValues: { content: &quot;&quot; },<br>  })<br><br>  const { execute, status } = useAction(createPost, {<br>    onSuccess(data) {<br>      if (data?.error) console.error(data.error)<br>      if (data?.success) console.log(data.success)<br>    },<br>    onExecute() {<br>      console.log(&quot;Creating post...&quot;)<br>    },<br>  })<br><br>  function onSubmit(values: z.infer&lt;typeof formSchema&gt;) {<br>    execute(values)<br>    form.reset()<br>  }<br><br>  return (<br>    &lt;main&gt;<br>      &lt;Form {...form}&gt;<br>        &lt;form onSubmit={form.handleSubmit(onSubmit)} className=&quot;space-y-4&quot;&gt;<br>          &lt;FormField<br>            control={form.control}<br>            name=&quot;content&quot;<br>            render={({ field }) =&gt; (<br>              &lt;FormItem&gt;<br>                &lt;FormLabel&gt;Create Post&lt;/FormLabel&gt;<br>                &lt;FormControl&gt;<br>                  &lt;Input placeholder=&quot;What&#39;s on your mind?&quot; {...field} /&gt;<br>                &lt;/FormControl&gt;<br>                &lt;FormMessage /&gt;<br>              &lt;/FormItem&gt;<br>            )}<br>          /&gt;<br>          &lt;Button disabled={status === &quot;executing&quot;} type=&quot;submit&quot;&gt;<br>            Submit<br>          &lt;/Button&gt;<br>        &lt;/form&gt;<br>      &lt;/Form&gt;<br>    &lt;/main&gt;<br>  )<br>}</pre><h3><strong>When This Pattern Might Not Be Right</strong></h3><p>This approach isn’t universal. Consider alternatives for:</p><ul><li>Apps with minimal interactivity or mostly static content.</li><li>Very small apps where React Query adds unnecessary complexity.</li><li>Apps that rely heavily on SSR with no client-side logic.</li><li>Simple CRUD operations that don’t require real-time updates.</li></ul><p>Still, for most interactive, form-heavy, or data-rich apps this combo hits a sweet spot.</p><h3><strong>Conclusion</strong></h3><p>Combining Next.js Server Actions with React Query creates a powerful pattern for<strong> </strong>large-scale React applications. Server Actions simplify mutations and form handling while maintaining security and type safety. React Query handles the complex client-side concerns of caching, background updates, and state synchronization.</p><p>This isn’t just a technical preference — it’s an architectural decision that pays dividends as your application grows. The reduced boilerplate, improved developer experience, and enhanced user experience make this pattern my default choice for serious React applications in 2025.</p><p>Have you tried combining Server Actions and React Query? I’d love to hear about your experience and any patterns you’ve discovered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2c582354010" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Handle JWTs Securely in React: Storage Strategies and Threat Analysis]]></title>
            <link>https://medium.com/@supunbandara/how-to-handle-jwts-securely-in-react-storage-strategies-and-threat-analysis-bb4f7029ee91?source=rss-8afa21e8efce------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb4f7029ee91</guid>
            <dc:creator><![CDATA[Supun Bandara]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 18:43:58 GMT</pubDate>
            <atom:updated>2025-06-06T12:59:46.415Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EKc06iWhs7RJ-rVFRcbz0A.png" /><figcaption>Image created and edited by the author</figcaption></figure><p>Authentication is the backbone of modern web applications, but implementing it securely can be surprisingly complex. If you’re building React applications that handle sensitive user data, understanding how to properly manage JSON Web Tokens (JWTs) isn’t just best practice, it’s essential for protecting your users and your business.</p><p>In this comprehensive guide, we’ll explore the landscape of token-based authentication, analyze the security implications of different storage strategies, and provide you with actionable recommendations for implementing JWT authentication securely in your React applications.</p><h3><strong>Outline</strong></h3><ol><li>What is Token-Based Authentication?</li><li>Understanding JWT Access and Refresh Tokens</li><li>Token Storage Solutions in the Browser</li><li>Browser Threats</li><li>Threat Analysis: Storage Solutions Assessment</li><li>My Recommendation: Handling JWT Tokens in React</li><li>Conclusion</li></ol><h3><strong>What is Token-Based Authentication?</strong></h3><p>Token-based authentication is a security mechanism where users receive a digital token after successful login, which they then present to access protected resources. Unlike traditional session-based authentication that relies on server-side sessions, token-based systems are stateless and highly scalable.</p><h4><strong>How does it Work?</strong></h4><p>Client sends credentials (username/password) to the authentication endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u_omUcRfg8d06OJLqYp8_w.png" /></figure><p>Server validates these credentials against the user database.</p><p>If credentials are <strong>invalid</strong>: Server responds with 422 Unprocessable Entity error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G42qlCErh0uSo7-1V6-oAQ.png" /></figure><p>If credentials are <strong>valid</strong>: Server generates a signed token and responds with 200 OK, including the token in the response body or header.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wiuRRxU_TpwELrEJhztZRA.png" /></figure><p>Client stores the received token (in local storage, cookie, or memory). For subsequent API requests, client includes this token in the request headers.</p><p>Typically sent as: Authorization: Bearer &lt;token&gt;</p><p>Server validates the token on each protected request.</p><p>If token is <strong>invalid or expired</strong>: Server responds with 401 Unauthorized.</p><p>If token is <strong>valid</strong>: Server processes the request and returns the appropriate response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0Zvq27SG0riys7ZEcC2m7w.png" /></figure><h4><strong>Examples of Token-Based Authentication Strategies</strong></h4><ul><li>SWT (Simple Web Tokens)</li><li>JWT (JSON Web Tokens)</li><li>OAuth (Open Authorization)</li><li>SAML (Security Assertions Markup Language)</li><li>OpenID</li></ul><h3><strong>Understanding JWT Access and Refresh Tokens</strong></h3><p>JWT (JSON Web Token) is a token-based authentication mechanism based on the open standard <strong>RFC 7519</strong>. It’s widely used for both <strong>authorization</strong> and <strong>secure information exchange</strong> between client and server.</p><h4>How does it Work?</h4><p>JWT works similarly to other token-based authentication methods. The key difference lies in the format and structure of the token itself.</p><p>Once a user successfully logs in with valid credentials, the server generates a <strong>pair of tokens</strong> — an <strong>access token</strong> and a <strong>refresh token</strong>. These tokens are then used by the client to authenticate future requests.</p><ul><li><strong>Access Token</strong>: A short-lived JWT that contains basic, non-sensitive user data. This token is sent with each HTTP request when accessing protected endpoints.</li><li><strong>Refresh Token</strong>: A longer-lived JWT that allows the client to request a new access token without requiring the user to log in again.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cbBMWLx-6cy-YUJtd6prcA.png" /></figure><h4><strong>Access Token Renewal</strong></h4><p>The refresh token plays a crucial role in maintaining a smooth authentication experience. In a well-designed token-based system, both tokens are meant to expire but the <strong>access token</strong> has a much <strong>shorter lifespan</strong> than the <strong>refresh token</strong>.</p><p>Without a refresh token, the user would need to log in again every time the access token expires. That would quickly become a frustrating experience, especially given how short-lived access tokens typically are.</p><p>With a refresh token, however, the client can <strong>silently renew the access token</strong> in the background whenever it expires. This ensures the user stays authenticated without being interrupted. The client automatically sends the refresh token to the server, retrieves a new access token, and retries the original request all without the user noticing.</p><p>This automated renewal process improves both <strong>security</strong> and <strong>user experience</strong> by maintaining session continuity without sacrificing token expiry best practices.</p><h3><strong>Token Storage Solutions in the Browser</strong></h3><p>When your React application receives an access token, it needs to store the token for use in subsequent API requests. There are various ways to persist data within a user’s browser, each with distinct security implications and use cases.</p><h4><strong>Understanding Browser Storage Isolation</strong></h4><p>Before exploring storage options, it’s crucial to understand how browsers isolate storage per <strong>origin</strong>. This concept directly impacts how you can store and access tokens in your application.</p><h4><strong>What is an Origin?</strong></h4><p>An <strong>origin</strong> consists of three components:</p><ul><li><strong>Scheme</strong> (protocol): http or https</li><li><strong>Hostname</strong> (domain): example.com, app.example.com, etc.</li><li><strong>Port</strong>: :80, :443, :3000, etc.</li></ul><h4><strong>Origin Examples</strong></h4><p>https://app.example.com:443 ← Origin A</p><p>https://api.example.com:443 ← Origin B (different hostname)</p><p>http://app.example.com:443 ← Origin C (different scheme)</p><p>https://app.example.com:3000 ← Origin D (different port)</p><p>Even though they all involve example.com, these are <strong>completely separate origins</strong> from the browser’s perspective.</p><h4><strong>Storage Isolation in Practice</strong></h4><p>The browser enforces the <strong>Same-Origin Policy</strong>, which means storage is completely isolated between different origins:</p><pre>// Scenario: Your React app runs on https://app.example.com<br>localStorage.setItem(&#39;accessToken&#39;, &#39;eyJ0eXAiOiJKV1Q…&#39;);</pre><pre>// Later, if code runs on https://api.example.com<br>localStorage.getItem(&#39;accessToken&#39;); // Returns null!<br>// The token is invisible to the API subdomain</pre><p><strong>Real-World Impact:</strong></p><ul><li><strong>Security benefit</strong>: If your API subdomain gets compromised, attackers can’t access tokens stored by your app subdomain.</li><li><strong>Architecture consideration</strong>: Your React app and API must share the same origin to use localStorage/sessionStorage for tokens.</li><li><strong>Common solution</strong>: Many applications serve both frontend and backend from the same domain (e.g., <a href="https://myapp.com/">https://myapp.com</a> for both).</li></ul><p>This isolation is why token storage strategy must align with your application architecture. Now let’s examine each storage option.</p><h4><strong>Local Storage</strong></h4><p>Local storage is accessed through the Web Storage API using the localStorage object in JavaScript. Data saved here remains available across browser tabs and sessions — it doesn’t expire or get removed when the browser is closed.</p><pre>// Storing token in localStorage<br>localStorage.setItem(&#39;accessToken&#39;, token);</pre><pre>// Retrieving token for API calls<br>const token = localStorage.getItem(&#39;accessToken&#39;);<br>fetch(&#39;/api/protected&#39;, {<br>  headers: { Authorization: `Bearer ${token}` }<br>});</pre><h4><strong>Why Storing Sensitive Data in localStorage Can Be a Dangerous Mistake</strong></h4><p>Cross-site scripting (XSS) attacks become much more severe when your app stores sensitive data in localStorage. Even a single XSS vulnerability can result in instant data theft. What makes these attacks especially dangerous is that they run with the same permissions as your legitimate site scripts.</p><p>What’s truly alarming is how difficult these attacks can be to detect. They:</p><ul><li>Operate with full access, just like trusted code</li><li>Can blend in as normal behaviour</li><li>May persist if malicious code is stored and reused</li><li>Often bypass security measures like CORS or CSP using tricks like image beacons</li></ul><p>That’s why saving tokens or personal information in localStorage is such a huge risk. A single XSS vulnerability anywhere in your application or its dependencies can lead to complete compromise of all stored data.</p><p>However, this doesn’t mean localStorage is useless. It has valid use cases, especially when used for non-sensitive data that won’t create security risks if exposed.</p><p>Local Storage is ideal for storing non-sensitive preferences and transient data that enhance user experience. UI preferences like theme settings, language choices, and layout configurations are ideal candidates. When a user picks dark mode or collapses their sidebar, localStorage gives you a spot to remember these choices.</p><p>Many UX features also benefit from localStorage. For example, flags for completed onboarding tutorials or “Don’t show this again” prompts can be safely stored here to avoid repeatedly showing the same UI elements.</p><h4><strong>Session Storage</strong></h4><p>Think of sessionStorage as a short-term memory bank. Unlike localStorage that keeps data indefinitely, sessionStorage enforces a strict lifetime — everything disappears when the tab closes. This automatic cleanup reduces the risk of sensitive data lingering around.</p><p>This makes sessionStorage well-suited for storing sensitive session-specific data such as multi-step form inputs, wizard progress, or transient user state during a checkout process. While it’s more secure than localStorage simply due to its shorter lifespan, it’s still vulnerable to XSS attacks within the active session. That’s why adding extra security layers, like expiration timestamps and data validation, helps create a more robust solution.</p><p>The key advantage of sessionStorage is its automatic cleanup — you don’t need to write code to clear sensitive data, the browser handles that for you. This reduces the risk of data leaks through forgotten cleanup or error conditions. However, remember that “session” means browser tab — data persists through page refreshes and survives browser crashes, so don’t treat it as truly temporary memory.</p><pre>sessionStorage.setItem(&#39;accessToken&#39;, token);<br>const token = sessionStorage.getItem(&#39;accessToken&#39;);</pre><p>SessionStorage works like localStorage but with one key difference — it only persists data for a single browser tab or window and automatically clears everything when that tab closes.</p><h4><strong>IndexedDB</strong></h4><p>IndexedDB (Indexed Database API) is designed for storing larger amounts of structured data asynchronously. However, for token storage, its advanced features are typically unnecessary overhead.</p><p>For larger datasets or offline capabilities: IndexedDB stands out, but its raw storage isn’t inherently secure. Like localStorage, any JavaScript running on your page can access it. However, IndexedDB’s architecture makes it perfect for encrypted storage of sensitive data.</p><p>IndexedDB is a low-level API for client-side storage of significant amounts of structured data, including files/blobs.</p><p>Think of IndexedDB as your app’s private database — while it offers more sophisticated storage capabilities than localStorage, it’s still bound to the same origin (domain) security model, meaning any JavaScript on your page can access it. Unlike localStorage’s simple key-value pairs, IndexedDB supports complex data structures, binary data, and most importantly — efficient storage of encrypted content. You can store several megabytes of data without impacting performance, making it ideal for offline-first applications that need to cache sensitive information.</p><h4><strong>In-Memory Token Storage</strong></h4><p>In-memory token storage represents a fundamental shift from traditional persistence-based approaches. Instead of saving tokens to localStorage, sessionStorage, or cookies, this method keeps authentication tokens exclusively in JavaScript variables, closures, or application state during the user’s active session. The tokens exist only in the browser’s RAM, never touching the file system or any persistent storage mechanism.</p><p>This approach leverages the ephemeral nature of memory to create an inherently secure environment. When implemented correctly, tokens are encapsulated within JavaScript closures or React state, accessible only through carefully controlled interfaces that you design. This controlled access pattern means that even if an attacker manages to execute malicious code on your page, they face significant barriers in accessing the stored tokens.</p><p>Successful in-memory token storage requires thoughtful implementation. In React applications, you might use useState or useContext to manage tokens at the application level. For vanilla JavaScript applications, closures provide an elegant solution, creating private scopes that external code cannot easily access.</p><p>The key is establishing a controlled interface for token access. Rather than storing tokens in global variables, encapsulate them within modules or components that expose only the necessary methods for token retrieval and updates. This creates a clear boundary between your authentication system and the rest of your application code.</p><p>Consider implementing token rotation and refresh mechanisms as part of your in-memory strategy. Since users will lose their tokens on page refresh, having a robust refresh token system becomes essential. Store refresh tokens using more persistent methods (like httpOnly cookies) while keeping access tokens in memory. This hybrid approach maximizes security while maintaining a reasonable user experience.</p><h4><strong>Cookies</strong></h4><p>Cookies have undergone a remarkable transformation since their inception. What began as a simple mechanism for maintaining state across HTTP requests has evolved into a sophisticated security tool with multiple layers of protection. The key to understanding modern cookie security lies in recognizing that cookies are not inherently insecure — they’re simply powerful tools that require proper configuration to unleash their security potential.</p><p>The HttpOnly attribute represents one of the most significant security innovations in cookie technology. When a cookie is marked as HttpOnly, it becomes completely invisible to JavaScript running in the browser. This single attribute effectively neutralizes one of the most common attack vectors in web security: JavaScript-based XSS attacks attempting to steal authentication tokens.</p><p>Consider the implications of this protection. Even if an attacker successfully injects malicious JavaScript into your application, they cannot access HttpOnly cookies through document.cookie or any other JavaScript API. This creates a fundamental barrier between client-side vulnerabilities and your authentication tokens. While XSS attacks can still manipulate the user interface or make requests on behalf of the user, they cannot extract and exfiltrate your authentication tokens for use in other contexts.</p><p>This protection is particularly valuable for refresh tokens, which typically have longer lifespans and represent high-value targets for attackers. By storing refresh tokens in HttpOnly cookies, you create a secure repository that remains accessible to your server-side code while being completely hidden from potential JavaScript-based attacks.</p><h3>Browser Threats</h3><h4>Cross-Site Scripting (XSS)</h4><p>XSS attacks occur when malicious scripts are injected into trusted websites. These scripts can:</p><ul><li>Access localStorage/sessionStorage</li><li>Read cookies (if not HTTP-only)</li><li>Steal tokens and impersonate users</li><li>Perform actions on behalf of users</li></ul><p>Web Storage (localStorage/sessionStorage) is accessible through JavaScript on the same domain. This means that any JavaScript running on your site will have access to web storage, and because of this <strong>can be vulnerable to cross-site scripting (XSS) attacks</strong>. XSS, in a nutshell, is a type of vulnerability where an attacker can inject JavaScript that will run on your page. Basic XSS attacks attempt to inject JavaScript through form inputs, where the attacker puts &lt;script&gt;alert(‘You are Hacked’);&lt;/script&gt; into a form to see if it is run by the browser and can be viewed by other users.</p><p>To prevent XSS, the common response is to escape and encode all untrusted data. React (mostly) does that for you! Here’s a great <a href="https://github.com/facebook/react/issues/3473">discussion about how much XSS vulnerability protection is React responsible for</a>.</p><p>Modern web apps include 3rd party JavaScript libraries for A/B testing, funnel/market analysis, and ads. We use package managers like Bower to import other peoples’ code into our apps.</p><p>What if only one of the scripts you use is compromised? Malicious JavaScript can be embedded on the page, and Web Storage is compromised. <strong>These types of XSS attacks can get everyone’s Web Storage that visits your site, without their knowledge.</strong> This is probably why a bunch of organizations advise not to store anything of value or trust any information in web storage. This includes session identifiers and tokens.</p><p>Therefore, my conclusion is that as a storage mechanism, Web Storage <strong>does not enforce any secure standards during transfer</strong>. Whoever reads Web Storage and uses it must do their due diligence to ensure they always send the JWT over HTTPS and never HTTP.</p><h3>Cross-Site Request Forgery (CSRF)</h3><p><strong>Cross-Site Request Forgery (CSRF)</strong> is a type of attack where a malicious website tricks a user’s browser into making unwanted requests to another site where the user is already logged in.</p><p>For example, an attacker might:</p><ul><li>Embed a crafted image or URL that triggers a <strong>GET request</strong>.</li><li>Add a hidden form that silently triggers a <strong>POST request</strong>.</li></ul><p>Because the browser automatically includes cookies (like session or SSO cookies) with these requests, the server may treat them as if they came from the legitimate user.</p><p>That’s why CSRF is also sometimes called “<strong>session riding</strong>” — the attacker rides on the back of a user’s authenticated session to perform actions the user is allowed to do.</p><p>Although attackers <strong>can’t see</strong> the response from these forged requests, they often target <strong>one-time, state-changing actions</strong>, like:</p><ul><li>Changing a user’s password</li><li>Submitting a payment</li><li>Updating profile information</li></ul><p>These kinds of attacks can cause real harm without the user even realizing it happened.</p><h3><strong>Threat Analysis: Storage Solutions Assessment</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZwpCGVi4KFBnMnsIFmgkjw.png" /></figure><h4>Key Findings:</h4><ol><li><strong>localStorage/sessionStorage</strong>: Highly vulnerable to XSS attacks, making them unsuitable for storing sensitive tokens</li><li><strong>HTTP-only Cookies</strong>: Secure against XSS but require additional CSRF protection</li><li><strong>In-Memory Storage</strong>: Most secure option, though requires handling page refreshes</li><li><strong>IndexedDB</strong>: Overkill for token storage with same XSS vulnerabilities as other persistent storage</li></ol><h4><strong>Security Best Practices</strong></h4><h4>The Stateless Nature of Token-Based Authentication And Why It Matters</h4><p>One of the biggest advantages of token-based authentication is that it’s stateless. This means the server doesn’t need to perform a database lookup for every request giving your application a noticeable performance boost. Instead, the client includes an access token with each request, and the server verifies it without storing any session data.</p><p>Both access tokens and refresh tokens are stored on the client side, but since they are essentially as powerful as passwords, they need to be handled securely.</p><p>Handling JWTs securely isn’t just about where you store them — it’s also about how you issue, validate, and protect them across your entire system. Here are essential best practices:</p><h4>1. Keep Secrets Safe</h4><p>Your JWT signing key (secret or private key) is <strong>a critical credential</strong>. It should only be accessible to trusted services (e.g., your auth server). Never expose it in frontend code or client-accessible environments.</p><h4>2. Don’t Put Sensitive Data in the Payload</h4><p>JWTs are <strong>base64-encoded, not encrypted</strong> — anyone with the token can decode the payload. Limit the data to necessary claims (e.g., sub, exp, role) and avoid exposing emails, passwords, or PII.</p><h4>3. Always Set Token Expiration</h4><p>JWTs are valid indefinitely unless you <strong>explicitly define an expiration (exp)</strong>. Use short lifetimes for access tokens (5–15 minutes) and rotate refresh tokens regularly. Implement revocation strategies for high-risk scenarios (e.g., logout, password change).</p><h4>4. Always Use HTTPS</h4><p>Never transmit tokens over <strong>insecure (HTTP) connections</strong>. Use HTTPS by default to prevent man-in-the-middle attacks that can intercept or tamper with tokens.</p><h4>5. Validate Tokens on Your Server</h4><p>Don’t just trust that a token “looks valid.” Add a secondary validation layer — e.g., verifying the token’s issuer, audience, and signature against your server’s signing key — to ensure it came from your own system and hasn’t been tampered with.</p><h3><strong>My Recommendation: Handling JWT Tokens in React</strong></h3><p>After analyzing the security implications and practical considerations, I recommend using In-Memory Token Storage With a refresh token strategy. Here’s why and how:</p><h4><strong>In-Memory Token Storage Implementation</strong></h4><p>So here’s how the flow works. When a user logs into the React app, the backend sends back two tokens: an access token and a refresh token. The access token is short-lived — usually around 15 minutes — and we just keep it in memory, like in React state. The refresh token, which lasts much longer — say 30 days — is stored in an HTTP-only cookie. That way, it’s safe from things like XSS since JavaScript can’t access it.</p><p>Now, every time the app makes a request that needs auth, it attaches the access token in the Authorization header. As long as that token’s valid, the backend processes the request as usual. But once it expires, the app doesn’t log the user out — it just silently hits a refresh endpoint. Because the refresh token is in a secure cookie, the browser sends it automatically. If it’s still valid, the server sends back a new access token, and the app continues without the user noticing anything. It’s a clean, secure way to keep users logged in without storing tokens in localStorage or sessionStorage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*67aHz1zBZf_klpqaSzAkgA.png" /></figure><p>Alright, so this file sets up a custom AuthProvider in React using context. The idea is to manage the authentication state globally and automatically handle token-based logic like attaching the token to requests and refreshing it when needed.</p><p>We start by creating a context with createContext, then we expose a useAuth() hook so components can easily access things like the token or logout() function.</p><pre>const AuthContext = createContext(undefined);<br>export const useAuth = () =&gt; {<br>  const authContext = useContext(AuthContext);<br>  if (!authContext) {<br>    throw new Error(&#39;useAuth must be used within a AuthProvider&#39;);<br>  }<br>  return authContext;<br>};</pre><p>Inside the provider component, we use useState to store the current access token. When the component mounts, we run a useEffect to hit the /api/me endpoint; this is basically a check to see if the user is already authenticated (maybe from a previous session where the refresh token is still valid). If that request works, we set the token from the response.</p><pre>useEffect(() =&gt; {<br>  const fetchMe = async () =&gt; {<br>    try {<br>      const response = await api.get(&#39;/api/me&#39;);<br>      setToken(response.data.accessToken);<br>    } catch {<br>      setToken(null);<br>    }<br>  };<br>  fetchMe();<br>}, [ ]);</pre><p>Now here’s where it gets interesting. This code uses two useLayoutEffects instead of useEffect. One is for setting up a request interceptor, and the other is for a response interceptor using Axios.</p><p>Let’s talk about the request interceptor first. We attach the access token (if available) to every outgoing request by modifying the Authorization header. This only runs if the request isn’t marked as _retry — just to avoid re-attaching tokens when we’re retrying after a refresh.</p><pre>useLayoutEffect(() =&gt; {<br>  const authInterceptor = api.interceptors.request.use((config) =&gt; {<br>    config.headers.Authorization = <br>      !config._retry &amp;&amp; token<br>        ? `Bearer ${token}`<br>        : config.headers.Authorization;<br>    return config;<br>  });<br><br>  return () =&gt; {<br>    api.interceptors.request.eject(authInterceptor);<br>  };<br>}, [token]);</pre><p>The reason we use useLayoutEffect here instead of just useEffect is timing. useLayoutEffect runs <em>synchronously after</em> all DOM mutations but before the browser actually paints. This makes sure the interceptor is already set up before any child component makes an API request during its mount lifecycle. If we used useEffect, there’s a chance an API call could fire before the interceptor is even attached — especially in SSR or fast renders — causing unauthenticated requests.</p><p>Same goes for the response interceptor. This watches for a 403 error with the message ‘Unauthorized’, which means the access token is probably expired. When that happens, it calls the /api/refreshToken endpoint to get a new access token. If it succeeds, it updates the token in state and retries the original request with the new token. If that fails, we assume the user is logged out and just clear the token.</p><pre>useLayoutEffect(() =&gt; {<br>  const refreshInterceptor = api.interceptors.response.use(<br>    (response) =&gt; response,<br>    async (error) =&gt; {<br>      const originalRequest = error.config;<br>      if (<br>        error.response.status === 403 &amp;&amp;<br>        error.response.data.message === &#39;Unauthorized&#39;<br>      ) {<br>        try {<br>          const response = await api.get(&#39;/api/refreshToken&#39;);<br>          setToken(response.data.accessToken);<br>          originalRequest.headers.Authorization = `Bearer ${response.data.accessToken}`;<br>          originalRequest._retry = true;<br>          return api(originalRequest);<br>        } catch {<br>          setToken(null);<br>        }<br>      }<br>      return Promise.reject(error);<br>    }<br>  );<br><br>  return () =&gt; {<br>    api.interceptors.response.eject(refreshInterceptor);<br>  };<br>}, []);</pre><p>Finally, we wrap everything in the context provider and pass down the token, setToken, a boolean flag isAuthenticated, and a simple logout function.</p><pre>const contextValue = {<br>  token,<br>  setToken,<br>  isAuthenticated: !!token,<br>  logout: () =&gt; setToken(null),<br>};<br><br>return (<br>  &lt;AuthContext.Provider value={contextValue}&gt;<br>    {children}<br>  &lt;/AuthContext.Provider&gt;<br>);</pre><p>Full code snippet here,</p><pre>import {<br>  createContext,<br>  useContext,<br>  useEffect,<br>  useLayoutEffect,<br>  useState,<br>} from &#39;react&#39;;<br><br>import api from &#39;@/api&#39;;<br><br>const AuthContext = createContext(undefined);<br><br>export const useAuth = () =&gt; {<br>  const authContext = useContext(AuthContext);<br><br>  if (!authContext) {<br>    throw new Error(&#39;useAuth must be used within a AuthProvider&#39;);<br>  }<br><br>  return authContext;<br>};<br><br>const AuthProvider = ({ children }) =&gt; {<br>  const [token, setToken] = useState(null);<br><br>  // Initial user data fetch<br>  useEffect(() =&gt; {<br>    const fetchMe = async () =&gt; {<br>      try {<br>        const response = await api.get(&#39;/api/me&#39;);<br>        setToken(response.data.accessToken);<br>      } catch {<br>        setToken(null);<br>      }<br>    };<br><br>    fetchMe();<br>  }, []);<br><br>  // Request interceptor to add auth header<br>  useLayoutEffect(() =&gt; {<br>    const authInterceptor = api.interceptors.request.use((config) =&gt; {<br>      config.headers.Authorization = <br>        !config._retry &amp;&amp; token<br>          ? `Bearer ${token}`<br>          : config.headers.Authorization;<br>      <br>      return config;<br>    });<br><br>    return () =&gt; {<br>      api.interceptors.request.eject(authInterceptor);<br>    };<br>  }, [token]);<br><br>  // Response interceptor for token refresh<br>  useLayoutEffect(() =&gt; {<br>    const refreshInterceptor = api.interceptors.response.use(<br>      (response) =&gt; response,<br>      async (error) =&gt; {<br>        const originalRequest = error.config;<br><br>        if (<br>          error.response.status === 403 &amp;&amp;<br>          error.response.data.message === &#39;Unauthorized&#39;<br>        ) {<br>          try {<br>            const response = await api.get(&#39;/api/refreshToken&#39;);<br>            <br>            setToken(response.data.accessToken);<br>            <br>            originalRequest.headers.Authorization = `Bearer ${response.data.accessToken}`;<br>            originalRequest._retry = true;<br>            <br>            return api(originalRequest);<br>          } catch {<br>            setToken(null);<br>          }<br>        }<br><br>        return Promise.reject(error);<br>      }<br>    );<br><br>    return () =&gt; {<br>      api.interceptors.response.eject(refreshInterceptor);<br>    };<br>  }, []);<br><br>  const contextValue = {<br>    token,<br>    setToken,<br>    isAuthenticated: !!token,<br>    logout: () =&gt; setToken(null),<br>  };<br><br>  return (<br>    &lt;AuthContext.Provider value={contextValue}&gt;<br>      {children}<br>    &lt;/AuthContext.Provider&gt;<br>  );<br>};<br><br>export default AuthProvider;</pre><p>And that’s it! With this little chunk of code, a clear mental model, and a solid understanding of the request/response flow, you now have everything you need to plug authentication into your own React application. Whether you’re working with your own backend or integrating with a third-party provider, this structure gives you the flexibility to handle token-based auth securely and efficiently.</p><p>Of course, if you’re using something like Firebase, Auth0, or Supabase, a lot of this is abstracted away through SDKs. But if you’re rolling your own system or just want to understand how things work under the hood this setup gives you full control and clarity.</p><p>So go ahead, integrate it into your workflow, make it your own, and build something robust and reliable.</p><h3><strong>Conclusion</strong></h3><p>Securing JWT tokens in React applications requires careful consideration of storage strategies, threat vectors, and user experience. While in-memory storage with HTTP-only refresh token cookies provides the best security posture, the implementation requires thoughtful handling of page refreshes and token lifecycle management.</p><p>Remember that security is not a one-time implementation but an ongoing process. Regularly review your authentication strategy, keep dependencies updated, and stay informed about emerging threats and best practices.</p><p>The approach outlined in this guide provides a solid foundation for secure JWT handling while maintaining a smooth user experience. Adapt these patterns to your specific use case, and always test your implementation thoroughly in various scenarios.</p><h4><strong>Key Takeaways:</strong></h4><ul><li>Avoid localStorage/sessionStorage for sensitive tokens</li><li>Use in-memory storage for access tokens</li><li>Store refresh tokens in HTTP-only cookies</li><li>Implement proper token refresh mechanisms</li><li>Always validate tokens server-side</li><li>Keep tokens short-lived and rotate regularly</li></ul><p>Your users trust you with their data and implement JWT security practices that honor that trust.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb4f7029ee91" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>