{
    "componentChunkName": "component---src-pages-blog-markdown-remark-fields-slug-js",
    "path": "/blog/nextjs-app-router-authentication",
    "result": {"data":{"markdownRemark":{"html":"<h2 id=\"tldr\" style=\"position:relative;\"><a href=\"#tldr\" aria-label=\"tldr permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>TL;DR</h2>\n<ul>\n<li><strong>Middleware, now called Proxy, is a fast first check, not a security boundary.</strong> CVE-2025-29927 let one request header skip it entirely, five more advisories in 2026 found other ways around it, and any path outside its matcher skips it too.</li>\n<li><strong>Put every read and write behind a Data Access Layer (DAL).</strong> Each function checks the session against the database, so revoking a session or removing a role takes effect on the next request. Queries filter by the signed-in user, and only the fields the UI needs leave the module.</li>\n<li><strong>Check inside every entry point, because each one is public.</strong> Pages call <code class=\"language-text\">verifySession()</code> and redirect. Server Actions are POST endpoints, so they validate their input and go through the DAL. Route Handlers answer with <code class=\"language-text\">401</code> or <code class=\"language-text\">403</code>, never a redirect.</li>\n<li><strong>Pair short-lived access tokens with single-use refresh tokens.</strong> Keep both in <code class=\"language-text\">httpOnly</code>, <code class=\"language-text\">SameSite</code> cookies, and refresh under a cross-tab lock so two tabs don’t look like token theft.</li>\n<li><strong>Streaming locks the status code at <code class=\"language-text\">200</code>.</strong> It goes out with the first Suspense fallback or Cache Components shell, so a real <code class=\"language-text\">307</code> has to come before that, from Proxy or from a page check with nothing suspended above it. Anything in the static shell reaches every visitor Proxy lets through.</li>\n<li><strong>SuperTokens replaces the token code, not the architecture.</strong> <a href=\"#implementing-this-with-supertokens\">The SuperTokens section</a> swaps in its SDK for the session lookup, Proxy’s token check, and the refresh flow, and every check stays where it is.</li>\n</ul>\n<p>Here’s the Next.js App Router authentication architecture this guide builds:</p>\n<p><span\n      class=\"gatsby-resp-image-wrapper\"\n      style=\"position: relative; display: block; margin-left: auto; margin-right: auto; max-width: 630px; \"\n    >\n      <a\n    class=\"gatsby-resp-image-link\"\n    href=\"/static/c542d4f9b58c32bbe108f1024594215c/99f37/layered-defense.png\"\n    style=\"display: block\"\n    target=\"_blank\"\n    rel=\"noopener\"\n  >\n    <span\n    class=\"gatsby-resp-image-background-image\"\n    style=\"padding-bottom: 104.43037974683544%; position: relative; bottom: 0; left: 0; background-image: url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAVCAIAAADJt1n/AAAACXBIWXMAAAsTAAALEwEAmpwYAAAEPElEQVQ4yz2S22/bZBiHfUdH0xwcn+NDHJ8/f7a/OLYTx0nsxHaOK2uZtpat7Q5o0iRuQUIgjaFNWssG5ajtliEBYuJ/4E9DywTSo9/d8+q5eLEqYdBil5V8RvRZqVcl7Srp1CivwXS3BDgb4Vy/yccEnxDCiGlPuU7BKSWnzDHFHLq9OfQLFC2gX4jqUNJGvDLklUTS0441k828A8q2mSv23HA3rDxl5dk7H9PAKJke+oNVWt4Mk32A5gAtLLQwnNLpbTRYKlauwYXmrDRnZfn7rJzRUro9kWNVwqB4l2w5FVyrNA2che/6W52I5H2c8bh2SPK9GgVJLqC4PikktDR567dnWI00+U4oG3GTtes0IFueoAxUMJH0IS0GjBh2rEnHnOCsx4t9rZ0QQkKJI2rrYzgDJa2v2SNW6lI8arKwRloN+u3WaYAzkBZ9WU+2IT1ZjMlWRPExLQwZaYI1aEs2Ey9cgm4OUG44U93JdJjqMIXdku+EZMulRUQJHtnyTbEPzTFCJQQpJwywKqGyogO8VAex6Yx1e2Q6Y9tLTWdio4wVHZw2CNZqMgbJuao8tLyl7a3bakbyMUZIMxbc4eFdxjplrDMW3GHAXcF7wIC7LLjH2fc4eF9EDzh4n1E2bSEg+Yji+wQ/IPgYkwePw6N/woM/kpt/h4d/BVv6199EH76By9/l9LWc/SZnv8rTP8XgS4FDdabXYH2cDZqtAdZCn/nrV8H6sr//k5k+V5ILO/8ezC7l+JwLnpjTSz39DuSX7eEl73+utrqWEtvWBJojng8xIXgUXns9uPYq2Lxk/Wfm9Ad38dKc/siH53x0YUx/NvOXnfGlMPylHT2WOERzPVYIWmJIcT2MAR+ro+dg+tyYfNMKnrbjC2X0Qpt8K0TPpMGFkpx3hk+l8BEfPhGch9vsbpV2axRqsD1MdfJxeeYnN1B8ozc67ibHXnxkRzdg/8hA+9bggT//arD+2i++EKwlzaIdEjZot864DQZhKD48OPpkujiZLU/z9dlsdZrObw2nx6PidjS+Nl5/mh+/ivdf9DfnD/sHt0HykZdVCLtOu3XaxRS79IeH6eIknZ+Milvp/CRdnM5WZ+n89mR+ki1uDSYfmG4G/WKGFoEx3s+uqyCtkXaNcjDVKaPxgd9fBcMN7OZur+xGS6dXSPqwY00kPemArG2+fXXJWb9HOBUa1iiwR1g10sYMb2G4M4AKu1taqADvFhW2PweocIKl7ZeymWgws7pXK01QbRoVXN8jzCphYUTLE/VU0DPRmIlGLtsL1d2Y/oHqXpXtlWCUglEIRiGaBSlElaax9z+Eie3s8Tt70pVaZ7eh79Q12cr66VG2PBukN2VrWmcQ0eo1OdRkUZ2Ge01ti77FwK5U+fdr0m5d3sXVXVwjW0g2JzqcyeaE4rt1GjYYp8FAnLFrpFnB1Qqu/ucb/wLlZfJE6ChatQAAAABJRU5ErkJggg=='); background-size: cover; display: block;\"\n  ></span>\n  <img\n        class=\"gatsby-resp-image-image\"\n        alt=\"Layered defense for Next.js App Router authentication: Proxy checks the token&#39;s signature and expiry; each page checks the session again, and each Server Action and Route Handler validates its request before calling the DAL; the Data Access Layer verifies the session and role against the database; and queries for a user&#39;s own records filter by that user&#39;s ID. A request that skips Proxy or an entry point&#39;s check is still refused by the DAL.\"\n        title=\"Four checks between a request and your data\"\n        src=\"/static/c542d4f9b58c32bbe108f1024594215c/f058b/layered-defense.png\"\n        srcset=\"/static/c542d4f9b58c32bbe108f1024594215c/c26ae/layered-defense.png 158w,\n/static/c542d4f9b58c32bbe108f1024594215c/6bdcf/layered-defense.png 315w,\n/static/c542d4f9b58c32bbe108f1024594215c/f058b/layered-defense.png 630w,\n/static/c542d4f9b58c32bbe108f1024594215c/40601/layered-defense.png 945w,\n/static/c542d4f9b58c32bbe108f1024594215c/99f37/layered-defense.png 1100w\"\n        sizes=\"(max-width: 630px) 100vw, 630px\"\n        style=\"width:100%;height:100%;margin:0;vertical-align:middle;position:absolute;top:0;left:0;\"\n        loading=\"lazy\"\n        decoding=\"async\"\n      />\n  </a>\n    </span></p>\n<h2 id=\"table-of-contents\" style=\"position:relative;\"><a href=\"#table-of-contents\" aria-label=\"table of contents permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Table of Contents</h2>\n<div class=\"table-of-contents\">\n<ul>\n<li><a href=\"#why-app-router-changes-authentication\">Why App Router Changes Authentication</a></li>\n<li><a href=\"#cve-2025-29927-what-the-middleware-bypass-actually-was\">CVE-2025-29927: What the Middleware Bypass Actually Was</a></li>\n<li><a href=\"#defense-in-depth-the-data-access-layer-pattern\">Defense in Depth: The Data Access Layer Pattern</a></li>\n<li><a href=\"#protecting-server-components\">Protecting Server Components</a></li>\n<li><a href=\"#protecting-server-actions\">Protecting Server Actions</a></li>\n<li><a href=\"#protecting-route-handlers\">Protecting Route Handlers</a></li>\n<li><a href=\"#middleware-at-the-edge-what-its-for-and-what-it-isnt\">Middleware at the Edge: What It’s For and What It Isn’t</a></li>\n<li><a href=\"#session-and-token-strategy\">Session and Token Strategy</a></li>\n<li><a href=\"#streaming-auth-with-suspense\">Streaming Auth with Suspense</a></li>\n<li><a href=\"#implementing-this-with-supertokens\">Implementing This with SuperTokens</a></li>\n<li><a href=\"#faq\">FAQ</a></li>\n</ul>\n</div>\n<h2 id=\"why-app-router-changes-authentication\" style=\"position:relative;\"><a href=\"#why-app-router-changes-authentication\" aria-label=\"why app router changes authentication permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Why App Router Changes Authentication</h2>\n<p>In March 2025, the Next.js team disclosed <a href=\"https://github.com/vercel/next.js/security/advisories/GHSA-f82v-jwr5-mffw\" target=\"_blank\" rel=\"nofollow\">CVE-2025-29927</a>, a critical (CVSS 9.1) authorization bypass in middleware. A request carrying one internal header, <code class=\"language-text\">x-middleware-subrequest</code>, set to the right value, skipped middleware entirely and went straight to the route behind it. Self-hosted apps from Next.js 11.1.4 onward were exposed until they upgraded to a fixed release.</p>\n<p>For any app that checked sessions in middleware and nowhere else, that header turned every protected route into a public one. The bug was in Next.js. How much it exposed came down to architecture.</p>\n<p>Middleware-only authentication is an easy design to fall into. One file sits in front of every route, runs before anything renders, and looks like a complete perimeter. It’s also a single point of failure, and the App Router gives that single point more ground to cover. In the Pages Router, server code lived in a short list of places, mainly <code class=\"language-text\">getServerSideProps</code> and <a href=\"https://supertokens.com/blog/mastering-nextjs-api-routes\" target=\"_blank\" rel=\"nofollow\">API routes</a>. The App Router spreads it across the component tree. That’s the real shift in Next.js App Router authentication: every place that runs server code needs its own check.</p>\n<h3 id=\"where-auth-checks-run\" style=\"position:relative;\"><a href=\"#where-auth-checks-run\" aria-label=\"where auth checks run permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Where Auth Checks Run</h3>\n<p><strong>Proxy runs first, but only where its matcher points.</strong> Next.js 16 renamed <code class=\"language-text\">middleware.ts</code> to <a href=\"https://nextjs.org/docs/app/api-reference/file-conventions/proxy\" target=\"_blank\" rel=\"nofollow\"><code class=\"language-text\">proxy.ts</code></a> without changing its job. It’s the fastest place to turn away a signed-out user and the easiest check to lose: a path outside the matcher skips it, and so does every Server Action called on that path.</p>\n<p><strong>Server Components fetch data while they render.</strong> Pages and layouts read cookies and query the database in the same function, with no API layer in between where a guard used to sit. A check at the top of a page protects that page’s output and nothing else, and a check in a layout doesn’t re-run on client-side navigation between the pages under it.</p>\n<p><strong>Server Actions are POST endpoints.</strong> Calling one sends a POST request to the current page with a <code class=\"language-text\">Next-Action</code> header that identifies the function. Anyone who can send that request can run the action, whether or not your UI shows the button. That’s why the <a href=\"https://nextjs.org/docs/app/guides/authentication\" target=\"_blank\" rel=\"nofollow\">Next.js authentication guide</a> says to treat Server Actions like public-facing API endpoints. A <a href=\"https://nextjs.org/docs/app/guides/data-security\" target=\"_blank\" rel=\"nofollow\">page-level auth check</a> doesn’t cover the actions defined on that page.</p>\n<p><strong>Route Handlers answer any client.</strong> A <code class=\"language-text\">route.ts</code> file is a plain HTTP endpoint. Mobile apps, webhooks, and other services call it directly, often with an <code class=\"language-text\">Authorization</code> header instead of a cookie, and no page or layout runs in front of it. The only check a Route Handler can count on is its own.</p>\n<h3 id=\"why-the-checks-drift-apart\" style=\"position:relative;\"><a href=\"#why-the-checks-drift-apart\" aria-label=\"why the checks drift apart permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Why the Checks Drift Apart</h3>\n<p>Each of these runs at a different moment, has different control over the response, and needs to fail in a different way. A check that’s correct in one can be wrong in the next.</p>\n<table>\n<thead>\n<tr>\n<th>Context</th>\n<th>Triggered by</th>\n<th>Can set cookies</th>\n<th>Failure response</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><strong>Proxy</strong></td>\n<td>Any request its matcher covers</td>\n<td>Yes</td>\n<td>Redirect pages to login, <code class=\"language-text\">401</code> for API paths</td>\n</tr>\n<tr>\n<td><strong>Server Component</strong></td>\n<td>Rendering a page or layout</td>\n<td>No</td>\n<td><code class=\"language-text\">redirect()</code> to login, render nothing protected</td>\n</tr>\n<tr>\n<td><strong>Server Action</strong></td>\n<td>A POST with a <code class=\"language-text\">Next-Action</code> header</td>\n<td>Yes</td>\n<td>Throw or return an error before touching data</td>\n</tr>\n<tr>\n<td><strong>Route Handler</strong></td>\n<td>Any HTTP request to its path</td>\n<td>Yes</td>\n<td><code class=\"language-text\">401</code> or <code class=\"language-text\">403</code>, not a redirect</td>\n</tr>\n</tbody>\n</table>\n<p>The last two columns are where shared helpers break. Server Components can’t set cookies, because HTTP can’t add them once a response starts streaming, so a page that finds an expired access token can’t refresh it in place. And a <code class=\"language-text\">verifySession()</code> helper that calls <code class=\"language-text\">redirect('/login')</code> is right for a page. In a Route Handler, the same helper answers a mobile client with a 307 redirect to an HTML login page instead of a 401 the client can act on.</p>\n<p>The runtime split made this worse. Until Next.js 15.2, middleware could only run on the Edge runtime, which supports a subset of Node.js APIs and rules out most traditional database drivers. A common result was a JWT signature check in middleware and a database-backed check, or none, everywhere else. Those two checks can disagree. A <a href=\"https://supertokens.com/blog/revoking-access-with-a-jwt-blacklist\" target=\"_blank\" rel=\"nofollow\">signature check can’t see revocation</a>, so a session you revoke after a password change keeps passing it until its access token expires.</p>\n<p>Proxy runs on Node.js in Next.js 16, but the Next.js authentication guide still limits it to reading the cookie, with no database calls, because it runs on every matched route, prefetches included. That split, a fast optimistic check up front and an authoritative check behind it, is the design Next.js recommends. What you control is whether every request path reaches the authoritative one.</p>\n<p>That’s the architecture this guide builds. Proxy stays as a fast first line that turns away signed-out users. A <a href=\"https://nextjs.org/blog/security-nextjs-server-components-actions\" target=\"_blank\" rel=\"nofollow\">Data Access Layer</a> becomes the one place every Server Component, Server Action, and Route Handler goes to read the session and touch data. A bypassed Proxy or a forgotten page check then doesn’t expose what’s behind it. The architecture sections stay provider-neutral, and the final section maps each layer onto SuperTokens.</p>\n<h2 id=\"cve-2025-29927-what-the-middleware-bypass-actually-was\" style=\"position:relative;\"><a href=\"#cve-2025-29927-what-the-middleware-bypass-actually-was\" aria-label=\"cve 2025 29927 what the middleware bypass actually was permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>CVE-2025-29927: What the Middleware Bypass Actually Was</h2>\n<p>Most write-ups stop at the header name. The mechanism is worth a few minutes, because it shows exactly which code held up and which didn’t.</p>\n<h3 id=\"how-the-bypass-worked\" style=\"position:relative;\"><a href=\"#how-the-bypass-worked\" aria-label=\"how the bypass worked permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>How the Bypass Worked</h3>\n<p>Middleware can make its own <code class=\"language-text\">fetch</code> calls, including to routes in the same app. Without a guard, a middleware that fetches its own app would run again on that request, and again on the next one. Next.js prevented the loop with an internal header. Every request middleware sent out carried <code class=\"language-text\">x-middleware-subrequest</code>, a colon-separated list of the middleware that had already run. When a request arrived carrying it, Next.js knew middleware had been there and skipped running it again.</p>\n<p>The flaw was in who it believed. Next.js read the header from every incoming request, including ones from the internet, and had no way to tell its own subrequests from a client that set the header itself. This is the check, trimmed, from Next.js 15.1.7:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"83662420039130370000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// packages/next/src/server/web/sandbox/sandbox.ts (Next.js 15.1.7, comments added)\nexport const run = withTaggedErrors(async function runWithTaggedErrors(params) {\n  const runtime = await getRuntimeContext(params)\n  // Read straight from the incoming request, whoever sent it\n  const subreq = params.request.headers[\\`x-middleware-subrequest\\`]\n  const subrequests = typeof subreq === 'string' ? subreq.split(':') : []\n\n  const MAX_RECURSION_DEPTH = 5\n  const depth = subrequests.reduce(\n    (acc, curr) => (curr === params.name ? acc + 1 : acc),\n    0\n  )\n\n  if (depth >= MAX_RECURSION_DEPTH) {\n    // Tell the router middleware finished, without ever running it\n    return {\n      waitUntil: Promise.resolve(),\n      response: new runtime.context.Response(null, {\n        headers: {\n          'x-middleware-next': '1',\n        },\n      }),\n    }\n  }\n  // ...the middleware function only runs past this point`, `83662420039130370000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// packages/next/src/server/web/sandbox/sandbox.ts (Next.js 15.1.7, comments added)</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">const</span> run <span class=\"token operator\">=</span> <span class=\"token function\">withTaggedErrors</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">runWithTaggedErrors</span><span class=\"token punctuation\">(</span>params<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> runtime <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">getRuntimeContext</span><span class=\"token punctuation\">(</span>params<span class=\"token punctuation\">)</span>\n  <span class=\"token comment\">// Read straight from the incoming request, whoever sent it</span>\n  <span class=\"token keyword\">const</span> subreq <span class=\"token operator\">=</span> params<span class=\"token punctuation\">.</span>request<span class=\"token punctuation\">.</span>headers<span class=\"token punctuation\">[</span><span class=\"token template-string\"><span class=\"token template-punctuation string\">`</span><span class=\"token string\">x-middleware-subrequest</span><span class=\"token template-punctuation string\">`</span></span><span class=\"token punctuation\">]</span>\n  <span class=\"token keyword\">const</span> subrequests <span class=\"token operator\">=</span> <span class=\"token keyword\">typeof</span> subreq <span class=\"token operator\">===</span> <span class=\"token string\">'string'</span> <span class=\"token operator\">?</span> subreq<span class=\"token punctuation\">.</span><span class=\"token function\">split</span><span class=\"token punctuation\">(</span><span class=\"token string\">':'</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">:</span> <span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span>\n\n  <span class=\"token keyword\">const</span> <span class=\"token constant\">MAX_RECURSION_DEPTH</span> <span class=\"token operator\">=</span> <span class=\"token number\">5</span>\n  <span class=\"token keyword\">const</span> depth <span class=\"token operator\">=</span> subrequests<span class=\"token punctuation\">.</span><span class=\"token function\">reduce</span><span class=\"token punctuation\">(</span>\n    <span class=\"token punctuation\">(</span>acc<span class=\"token punctuation\">,</span> curr<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">(</span>curr <span class=\"token operator\">===</span> params<span class=\"token punctuation\">.</span>name <span class=\"token operator\">?</span> acc <span class=\"token operator\">+</span> <span class=\"token number\">1</span> <span class=\"token operator\">:</span> acc<span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n    <span class=\"token number\">0</span>\n  <span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>depth <span class=\"token operator\">>=</span> <span class=\"token constant\">MAX_RECURSION_DEPTH</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token comment\">// Tell the router middleware finished, without ever running it</span>\n    <span class=\"token keyword\">return</span> <span class=\"token punctuation\">{</span>\n      waitUntil<span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token punctuation\">.</span><span class=\"token function\">resolve</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n      response<span class=\"token operator\">:</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">runtime</span><span class=\"token punctuation\">.</span>context<span class=\"token punctuation\">.</span><span class=\"token function\">Response</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">null</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span>\n        headers<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span>\n          <span class=\"token string-property property\">'x-middleware-next'</span><span class=\"token operator\">:</span> <span class=\"token string\">'1'</span><span class=\"token punctuation\">,</span>\n        <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n      <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">}</span>\n  <span class=\"token punctuation\">}</span>\n  <span class=\"token comment\">// ...the middleware function only runs past this point</span></code></pre></div>\n<p><code class=\"language-text\">params.name</code> is the middleware’s module path, <code class=\"language-text\">middleware</code> or <code class=\"language-text\">src/middleware</code>. Once the header named it enough times, Next.js returned <code class=\"language-text\">x-middleware-next: 1</code>, the same signal a middleware sends when it calls <code class=\"language-text\">NextResponse.next()</code>. The middleware function never executed. Its redirects, rewrites, header changes, and Content Security Policy were all skipped, and the request went on to the page as if middleware had approved it.</p>\n<p>The matching rule changed over the years. Before 12.2, middleware lived in <code class=\"language-text\">pages/_middleware</code> files. From 12.2 through 14.1, one match against the file name was enough to skip it, and 14.2 added the recursion counter above. Every version made the same mistake: it took the client’s word for it.</p>\n<h3 id=\"affected-versions-and-the-fix\" style=\"position:relative;\"><a href=\"#affected-versions-and-the-fix\" aria-label=\"affected versions and the fix permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Affected Versions and the Fix</h3>\n<p>Security researchers Rachid and Yasser Allam reported the bug on February 27, 2025. Fixed releases shipped between March 17 and March 23, and the <a href=\"https://github.com/vercel/next.js/security/advisories/GHSA-f82v-jwr5-mffw\" target=\"_blank\" rel=\"nofollow\">advisory</a> went public on March 21.</p>\n<table>\n<thead>\n<tr>\n<th>Release line</th>\n<th>Vulnerable versions</th>\n<th>Patched in</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>15.x</td>\n<td>15.0.0 to 15.2.2</td>\n<td>15.2.3</td>\n</tr>\n<tr>\n<td>14.x</td>\n<td>14.0.0 to 14.2.24</td>\n<td>14.2.25</td>\n</tr>\n<tr>\n<td>13.x</td>\n<td>13.0.0 to 13.5.8</td>\n<td>13.5.9</td>\n</tr>\n<tr>\n<td>12.x</td>\n<td>12.0.0 to 12.3.4</td>\n<td>12.3.5</td>\n</tr>\n<tr>\n<td>11.x</td>\n<td>11.1.4</td>\n<td>None. Upgrade, or strip the header</td>\n</tr>\n</tbody>\n</table>\n<p>Self-hosted apps running <code class=\"language-text\">next start</code> or <code class=\"language-text\">output: 'standalone'</code> were exposed. Apps on Vercel, Netlify, and Cloudflare Workers weren’t, because routing on those platforms runs in a separate layer in front of the app, and static exports don’t run middleware at all. Vercel’s <a href=\"https://vercel.com/blog/postmortem-on-next-js-middleware-bypass\" target=\"_blank\" rel=\"nofollow\">postmortem</a> covers the timeline in detail.</p>\n<p>The fix left the recursion check alone. It changed whether the header can be trusted. At startup, each Next.js server generates a random ID and attaches it to its own subrequests as <code class=\"language-text\">x-middleware-subrequest-id</code>. Before routing, any incoming request that doesn’t carry the matching ID has its <code class=\"language-text\">x-middleware-subrequest</code> header deleted:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"28235345040747872000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// packages/next/src/server/lib/server-ipc/utils.ts (Next.js 15.2.3)\n// If this request didn't origin from this session we filter\n// out the &quot;x-middleware-subrequest&quot; header so we don't skip\n// middleware incorrectly\nif (\n  header === 'x-middleware-subrequest' &&\n  headers['x-middleware-subrequest-id'] !==\n    (globalThis as any)[Symbol.for('@next/middleware-subrequest-id')]\n) {\n  delete headers['x-middleware-subrequest']\n}`, `28235345040747872000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// packages/next/src/server/lib/server-ipc/utils.ts (Next.js 15.2.3)</span>\n<span class=\"token comment\">// If this request didn't origin from this session we filter</span>\n<span class=\"token comment\">// out the \"x-middleware-subrequest\" header so we don't skip</span>\n<span class=\"token comment\">// middleware incorrectly</span>\n<span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>\n  header <span class=\"token operator\">===</span> <span class=\"token string\">'x-middleware-subrequest'</span> <span class=\"token operator\">&amp;&amp;</span>\n  headers<span class=\"token punctuation\">[</span><span class=\"token string\">'x-middleware-subrequest-id'</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">!==</span>\n    <span class=\"token punctuation\">(</span>globalThis <span class=\"token keyword\">as</span> <span class=\"token builtin\">any</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">[</span>Symbol<span class=\"token punctuation\">.</span><span class=\"token function\">for</span><span class=\"token punctuation\">(</span><span class=\"token string\">'@next/middleware-subrequest-id'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">]</span>\n<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">delete</span> headers<span class=\"token punctuation\">[</span><span class=\"token string\">'x-middleware-subrequest'</span><span class=\"token punctuation\">]</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>That fix needed one follow-up. <a href=\"https://github.com/vercel/next.js/security/advisories/GHSA-223j-4rm8-mrmf\" target=\"_blank\" rel=\"nofollow\">CVE-2025-30218</a>, published April 2, 2025, found that middleware sent the new ID with every outgoing <code class=\"language-text\">fetch</code>, including requests to third-party hosts, so the secret the fix depended on could end up on someone else’s server. The floor for both CVEs is 12.3.6, 13.5.10, 14.2.26, or 15.2.4.</p>\n<p>If you’re stuck on an unpatched version, the advisory’s workaround is to stop external requests carrying <code class=\"language-text\">x-middleware-subrequest</code> from reaching Next.js. On nginx, that’s one line:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"81570521682273170000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`location / {\n  # Never forward the internal header from outside traffic\n  proxy_set_header x-middleware-subrequest &quot;&quot;;\n  proxy_pass http://127.0.0.1:3000;\n}`, `81570521682273170000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"nginx\"><pre class=\"language-nginx\"><code class=\"language-nginx\"><span class=\"token directive\"><span class=\"token keyword\">location</span> /</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token comment\"># Never forward the internal header from outside traffic</span>\n  <span class=\"token directive\"><span class=\"token keyword\">proxy_set_header</span> x-middleware-subrequest <span class=\"token string\">\"\"</span></span><span class=\"token punctuation\">;</span>\n  <span class=\"token directive\"><span class=\"token keyword\">proxy_pass</span> http://127.0.0.1:3000</span><span class=\"token punctuation\">;</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<h3 id=\"it-wasnt-the-last-bypass\" style=\"position:relative;\"><a href=\"#it-wasnt-the-last-bypass\" aria-label=\"it wasnt the last bypass permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>It Wasn’t the Last Bypass</h3>\n<p>CVE-2025-29927 tends to get told as a one-off. It wasn’t. In May 2026, Next.js fixed four more ways to reach a protected route without middleware or Proxy running, and in July it fixed a fifth:</p>\n<ul>\n<li><strong><a href=\"https://github.com/vercel/next.js/security/advisories/GHSA-267c-6grr-h53f\" target=\"_blank\" rel=\"nofollow\">CVE-2026-44575</a>:</strong> <code class=\"language-text\">.rsc</code> and segment-prefetch variants of an App Router URL resolved to the same page without matching the middleware rule. Fixed in 15.5.16 and 16.2.5.</li>\n<li><strong><a href=\"https://github.com/vercel/next.js/security/advisories/GHSA-26hh-7cqf-hhc6\" target=\"_blank\" rel=\"nofollow\">CVE-2026-45109</a>:</strong> the fix for 44575 didn’t cover <code class=\"language-text\">middleware.ts</code> built with Turbopack. Fixed in 15.5.18 and 16.2.6.</li>\n<li><strong><a href=\"https://github.com/vercel/next.js/security/advisories/GHSA-492v-c6pp-mqqv\" target=\"_blank\" rel=\"nofollow\">CVE-2026-44574</a>:</strong> crafted query parameters changed the dynamic route value a page saw while the path middleware matched stayed the same. Fixed in 15.5.16 and 16.2.5.</li>\n<li><strong><a href=\"https://github.com/vercel/next.js/security/advisories/GHSA-36qx-fr4f-26g5\" target=\"_blank\" rel=\"nofollow\">CVE-2026-44573</a>:</strong> in Pages Router apps with i18n, locale-less <code class=\"language-text\">/_next/data</code> requests skipped middleware and returned protected page data. Fixed in 15.5.16 and 16.2.5.</li>\n<li><strong><a href=\"https://github.com/vercel/next.js/security/advisories/GHSA-6gpp-xcg3-4w24\" target=\"_blank\" rel=\"nofollow\">CVE-2026-64642</a>:</strong> App Router apps built with Turbopack and a single configured locale could be reached around Proxy. Fixed in 16.2.11.</li>\n</ul>\n<p>The four with published details share a shape: Proxy and the router read the same request differently. Vercel’s <a href=\"https://vercel.com/changelog/next-js-may-2026-security-release\" target=\"_blank\" rel=\"nofollow\">May 2026 release notes</a> say those advisories “cannot be reliably blocked at the WAF layer” and call patching the only complete mitigation. The workaround the advisories give is consistent: enforce authorization in the page or route itself instead of relying on middleware alone.</p>\n<h3 id=\"the-pattern-that-stayed-safe\" style=\"position:relative;\"><a href=\"#the-pattern-that-stayed-safe\" aria-label=\"the pattern that stayed safe permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>The Pattern That Stayed Safe</h3>\n<p>Here’s the difference in code. A common middleware-only setup verifies the session in Proxy and forwards the user ID to pages in a request header:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"81697217083823140000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// proxy.ts (middleware.ts before Next.js 16)\nimport { NextResponse, type NextRequest } from 'next/server'\nimport { decrypt } from '@/lib/session'\n\nexport async function proxy(request: NextRequest) {\n  const session = await decrypt(request.cookies.get('session')?.value)\n  if (!session?.userId) {\n    return NextResponse.redirect(new URL('/login', request.url))\n  }\n\n  // Forward the verified user ID to the page\n  const headers = new Headers(request.headers)\n  headers.set('x-user-id', String(session.userId))\n  return NextResponse.next({ request: { headers } })\n}\n\nexport const config = {\n  matcher: ['/dashboard/:path*'],\n}`, `81697217083823140000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// proxy.ts (middleware.ts before Next.js 16)</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> NextResponse<span class=\"token punctuation\">,</span> <span class=\"token keyword\">type</span> <span class=\"token class-name\">NextRequest</span> <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/server'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> decrypt <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/session'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">proxy</span><span class=\"token punctuation\">(</span>request<span class=\"token operator\">:</span> NextRequest<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> session <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">decrypt</span><span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">.</span>cookies<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'session'</span><span class=\"token punctuation\">)</span><span class=\"token operator\">?.</span>value<span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>session<span class=\"token operator\">?.</span>userId<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">redirect</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token constant\">URL</span></span><span class=\"token punctuation\">(</span><span class=\"token string\">'/login'</span><span class=\"token punctuation\">,</span> request<span class=\"token punctuation\">.</span>url<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n  <span class=\"token punctuation\">}</span>\n\n  <span class=\"token comment\">// Forward the verified user ID to the page</span>\n  <span class=\"token keyword\">const</span> headers <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Headers</span><span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">.</span>headers<span class=\"token punctuation\">)</span>\n  headers<span class=\"token punctuation\">.</span><span class=\"token function\">set</span><span class=\"token punctuation\">(</span><span class=\"token string\">'x-user-id'</span><span class=\"token punctuation\">,</span> <span class=\"token function\">String</span><span class=\"token punctuation\">(</span>session<span class=\"token punctuation\">.</span>userId<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">next</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> request<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> headers <span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">const</span> config <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span>\n  matcher<span class=\"token operator\">:</span> <span class=\"token punctuation\">[</span><span class=\"token string\">'/dashboard/:path*'</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">,</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>The page trusts that header:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"63366885660621720000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/dashboard/invoices/page.tsx\n// WRONG: assumes Proxy ran and set x-user-id\nimport { headers } from 'next/headers'\nimport { db } from '@/lib/db'\nimport { InvoiceList } from './invoice-list'\n\nexport default async function InvoicesPage() {\n  const userId = (await headers()).get('x-user-id')!\n  const invoices = await db.invoice.findMany({ where: { userId } })\n  return <InvoiceList invoices={invoices} />\n}`, `63366885660621720000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"tsx\"><pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token comment\">// app/dashboard/invoices/page.tsx</span>\n<span class=\"token comment\">// WRONG: assumes Proxy ran and set x-user-id</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> headers <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/headers'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> db <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/db'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> InvoiceList <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'./invoice-list'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">InvoicesPage</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> userId <span class=\"token operator\">=</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">await</span> <span class=\"token function\">headers</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'x-user-id'</span><span class=\"token punctuation\">)</span><span class=\"token operator\">!</span>\n  <span class=\"token keyword\">const</span> invoices <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> db<span class=\"token punctuation\">.</span>invoice<span class=\"token punctuation\">.</span><span class=\"token function\">findMany</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> where<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> userId <span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">InvoiceList</span></span> <span class=\"token attr-name\">invoices</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>invoices<span class=\"token punctuation\">}</span></span> <span class=\"token punctuation\">/></span></span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>With the bypass, Proxy never runs, so the page reads whatever <code class=\"language-text\">x-user-id</code> the attacker sent. That’s worse than a skipped login check: anyone can read any user’s invoices by sending that user’s ID. Stripping client-sent copies of the header inside Proxy, which some examples do, doesn’t help, because the code doing the stripping is the code that didn’t run. The same thing happens on a fully patched app the day someone adds a route the matcher doesn’t cover.</p>\n<p>The version that held up checks the session where the data is read:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"44481539854743660000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/dashboard/invoices/page.tsx\n// CORRECT: verifies the session itself, whether or not Proxy ran\nimport { verifySession } from '@/lib/dal'\nimport { db } from '@/lib/db'\nimport { InvoiceList } from './invoice-list'\n\nexport default async function InvoicesPage() {\n  // Redirects to /login when the session cookie is missing or invalid\n  const { userId } = await verifySession()\n  const invoices = await db.invoice.findMany({ where: { userId } })\n  return <InvoiceList invoices={invoices} />\n}`, `44481539854743660000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"tsx\"><pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token comment\">// app/dashboard/invoices/page.tsx</span>\n<span class=\"token comment\">// CORRECT: verifies the session itself, whether or not Proxy ran</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> verifySession <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/dal'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> db <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/db'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> InvoiceList <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'./invoice-list'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">InvoicesPage</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token comment\">// Redirects to /login when the session cookie is missing or invalid</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> userId <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">verifySession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">const</span> invoices <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> db<span class=\"token punctuation\">.</span>invoice<span class=\"token punctuation\">.</span><span class=\"token function\">findMany</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> where<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> userId <span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">InvoiceList</span></span> <span class=\"token attr-name\">invoices</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>invoices<span class=\"token punctuation\">}</span></span> <span class=\"token punctuation\">/></span></span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Under the same bypass, this page redirects to <code class=\"language-text\">/login</code>. Three things changed:</p>\n<ul>\n<li>The session check runs where the data is read, so it holds no matter how the request arrived.</li>\n<li>The user ID comes from the verified session, never from a request header.</li>\n<li>Proxy keeps its job as a fast redirect for signed-out users. It just stops being the only thing between a request and the database.</li>\n</ul>\n<p>The next section builds <code class=\"language-text\">verifySession()</code> out into a full Data Access Layer.</p>\n<p>You can test for this whole class of bug without reproducing any CVE. In a test environment, remove a protected route from your Proxy matcher, then load the page and call its Server Actions and Route Handlers directly. If anything protected comes back, a Proxy bypass would hand it out too.</p>\n<p>A bug in Proxy should cost you a redirect, not your users’ data.</p>\n<h2 id=\"defense-in-depth-the-data-access-layer-pattern\" style=\"position:relative;\"><a href=\"#defense-in-depth-the-data-access-layer-pattern\" aria-label=\"defense in depth the data access layer pattern permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Defense in Depth: The Data Access Layer Pattern</h2>\n<p>The fixed page at the end of the last section still had one weak spot. It queried the database itself, and it was safe only because someone remembered to call <code class=\"language-text\">verifySession()</code> first. The next page someone writes might not.</p>\n<p>A Data Access Layer (DAL) removes the need to remember. It’s a server-only module that owns every read and write, and every function in it checks the session before it touches data. Pages, Server Actions, and Route Handlers call the DAL instead of the database, so a check that’s missing at the edge doesn’t turn into a leak. The Next.js team <a href=\"https://nextjs.org/blog/security-nextjs-server-components-actions\" target=\"_blank\" rel=\"nofollow\">recommends this pattern</a> for new projects. This section builds the full module.</p>\n<h3 id=\"the-rules\" style=\"position:relative;\"><a href=\"#the-rules\" aria-label=\"the rules permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>The Rules</h3>\n<ul>\n<li><strong>Only the DAL touches the database.</strong> Pages and actions import functions like <code class=\"language-text\">getMyInvoices()</code>, never the database client.</li>\n<li><strong>Every exported function checks the session itself.</strong> No function assumes its caller already did.</li>\n<li><strong>Ownership lives in the query.</strong> Reads and writes filter by the signed-in user’s ID, so a guessed or leaked record ID finds nothing.</li>\n<li><strong>Only DTOs leave.</strong> Functions return the fields the UI needs and nothing else, because anything a Server Component passes to a Client Component is serialized into the payload the browser downloads.</li>\n<li><strong>The DAL decides, the caller responds.</strong> The DAL throws a typed error, and each context turns it into the right response: a redirect, an error result, or a <code class=\"language-text\">401</code>.</li>\n</ul>\n<h3 id=\"the-session-module\" style=\"position:relative;\"><a href=\"#the-session-module\" aria-label=\"the session module permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>The Session Module</h3>\n<p>The examples assume sign-in created a row in a <code class=\"language-text\">session</code> table and set a signed cookie carrying that row’s ID. The session strategy section covers that side. They use a Prisma-style client, but the structure doesn’t depend on the ORM.</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"715301288412484400\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// lib/dal/session.ts\nimport 'server-only'\nimport { cache } from 'react'\nimport { cookies } from 'next/headers'\nimport { redirect } from 'next/navigation'\nimport { jwtVerify } from 'jose'\nimport { db } from '@/lib/db'\n\nexport type Session = {\n  sessionId: string\n  userId: string\n  role: 'member' | 'admin'\n}\n\nexport class AuthError extends Error {\n  constructor(readonly status: 401 | 403) {\n    super(status === 401 ? 'Authentication required' : 'Not allowed')\n    this.name = 'AuthError'\n  }\n}\n\nfunction signingKey() {\n  const secret = process.env.SESSION_SECRET\n  if (!secret) throw new Error('SESSION_SECRET is not set')\n  return new TextEncoder().encode(secret)\n}\n\n// The only provider-specific code in the DAL. Swap this body for your auth library.\nasync function readSession(): Promise<Session | null> {\n  const token = (await cookies()).get('session')?.value\n  if (!token) return null\n\n  let sessionId: string\n  try {\n    const { payload } = await jwtVerify(token, signingKey(), { algorithms: ['HS256'] })\n    if (typeof payload.sid !== 'string') return null\n    sessionId = payload.sid\n  } catch {\n    return null // bad signature, expired token, or malformed cookie\n  }\n\n  // The signature proves we issued the cookie. The database proves it still counts.\n  const record = await db.session.findUnique({\n    where: { id: sessionId },\n    select: { userId: true, expiresAt: true, revokedAt: true, user: { select: { role: true } } },\n  })\n  if (!record || record.revokedAt || record.expiresAt <= new Date()) return null\n\n  return { sessionId, userId: record.userId, role: record.user.role }\n}\n\n// Deduplicated within a render, so ten components cost one lookup\nexport const getSession = cache(readSession)\n\n// Pages and layouts: send signed-out users to the login page\nexport async function verifySession(): Promise<Session> {\n  const session = await getSession()\n  if (!session) redirect('/login')\n  return session\n}\n\n// Data functions: fail closed with a status the caller can translate\nexport async function requireSession(): Promise<Session> {\n  const session = await getSession()\n  if (!session) throw new AuthError(401)\n  return session\n}\n\nexport async function requireRole(role: Session['role']): Promise<Session> {\n  const session = await requireSession()\n  if (session.role !== role) throw new AuthError(403)\n  return session\n}`, `715301288412484400`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// lib/dal/session.ts</span>\n<span class=\"token keyword\">import</span> <span class=\"token string\">'server-only'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> cache <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> cookies <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/headers'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> redirect <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/navigation'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> jwtVerify <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'jose'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> db <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/db'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">type</span> <span class=\"token class-name\">Session</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span>\n  sessionId<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span>\n  userId<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span>\n  role<span class=\"token operator\">:</span> <span class=\"token string\">'member'</span> <span class=\"token operator\">|</span> <span class=\"token string\">'admin'</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">class</span> <span class=\"token class-name\">AuthError</span> <span class=\"token keyword\">extends</span> <span class=\"token class-name\">Error</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token function\">constructor</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">readonly</span> status<span class=\"token operator\">:</span> <span class=\"token number\">401</span> <span class=\"token operator\">|</span> <span class=\"token number\">403</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">super</span><span class=\"token punctuation\">(</span>status <span class=\"token operator\">===</span> <span class=\"token number\">401</span> <span class=\"token operator\">?</span> <span class=\"token string\">'Authentication required'</span> <span class=\"token operator\">:</span> <span class=\"token string\">'Not allowed'</span><span class=\"token punctuation\">)</span>\n    <span class=\"token keyword\">this</span><span class=\"token punctuation\">.</span>name <span class=\"token operator\">=</span> <span class=\"token string\">'AuthError'</span>\n  <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">function</span> <span class=\"token function\">signingKey</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> secret <span class=\"token operator\">=</span> process<span class=\"token punctuation\">.</span>env<span class=\"token punctuation\">.</span><span class=\"token constant\">SESSION_SECRET</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>secret<span class=\"token punctuation\">)</span> <span class=\"token keyword\">throw</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Error</span><span class=\"token punctuation\">(</span><span class=\"token string\">'SESSION_SECRET is not set'</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">TextEncoder</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">encode</span><span class=\"token punctuation\">(</span>secret<span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token comment\">// The only provider-specific code in the DAL. Swap this body for your auth library.</span>\n<span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">readSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>Session <span class=\"token operator\">|</span> <span class=\"token keyword\">null</span><span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> token <span class=\"token operator\">=</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">await</span> <span class=\"token function\">cookies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'session'</span><span class=\"token punctuation\">)</span><span class=\"token operator\">?.</span>value\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>token<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token keyword\">null</span>\n\n  <span class=\"token keyword\">let</span> sessionId<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span>\n  <span class=\"token keyword\">try</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> payload <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">jwtVerify</span><span class=\"token punctuation\">(</span>token<span class=\"token punctuation\">,</span> <span class=\"token function\">signingKey</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> algorithms<span class=\"token operator\">:</span> <span class=\"token punctuation\">[</span><span class=\"token string\">'HS256'</span><span class=\"token punctuation\">]</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">typeof</span> payload<span class=\"token punctuation\">.</span>sid <span class=\"token operator\">!==</span> <span class=\"token string\">'string'</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token keyword\">null</span>\n    sessionId <span class=\"token operator\">=</span> payload<span class=\"token punctuation\">.</span>sid\n  <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">return</span> <span class=\"token keyword\">null</span> <span class=\"token comment\">// bad signature, expired token, or malformed cookie</span>\n  <span class=\"token punctuation\">}</span>\n\n  <span class=\"token comment\">// The signature proves we issued the cookie. The database proves it still counts.</span>\n  <span class=\"token keyword\">const</span> record <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> db<span class=\"token punctuation\">.</span>session<span class=\"token punctuation\">.</span><span class=\"token function\">findUnique</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n    where<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> id<span class=\"token operator\">:</span> sessionId <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n    select<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> userId<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span> expiresAt<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span> revokedAt<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span> user<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> select<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> role<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span> <span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>record <span class=\"token operator\">||</span> record<span class=\"token punctuation\">.</span>revokedAt <span class=\"token operator\">||</span> record<span class=\"token punctuation\">.</span>expiresAt <span class=\"token operator\">&lt;=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Date</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token keyword\">null</span>\n\n  <span class=\"token keyword\">return</span> <span class=\"token punctuation\">{</span> sessionId<span class=\"token punctuation\">,</span> userId<span class=\"token operator\">:</span> record<span class=\"token punctuation\">.</span>userId<span class=\"token punctuation\">,</span> role<span class=\"token operator\">:</span> record<span class=\"token punctuation\">.</span>user<span class=\"token punctuation\">.</span>role <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token comment\">// Deduplicated within a render, so ten components cost one lookup</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">const</span> getSession <span class=\"token operator\">=</span> <span class=\"token function\">cache</span><span class=\"token punctuation\">(</span>readSession<span class=\"token punctuation\">)</span>\n\n<span class=\"token comment\">// Pages and layouts: send signed-out users to the login page</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">verifySession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>Session<span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> session <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">getSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>session<span class=\"token punctuation\">)</span> <span class=\"token function\">redirect</span><span class=\"token punctuation\">(</span><span class=\"token string\">'/login'</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> session\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token comment\">// Data functions: fail closed with a status the caller can translate</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">requireSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>Session<span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> session <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">getSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>session<span class=\"token punctuation\">)</span> <span class=\"token keyword\">throw</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">AuthError</span><span class=\"token punctuation\">(</span><span class=\"token number\">401</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> session\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">requireRole</span><span class=\"token punctuation\">(</span>role<span class=\"token operator\">:</span> Session<span class=\"token punctuation\">[</span><span class=\"token string\">'role'</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>Session<span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> session <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">requireSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>session<span class=\"token punctuation\">.</span>role <span class=\"token operator\">!==</span> role<span class=\"token punctuation\">)</span> <span class=\"token keyword\">throw</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">AuthError</span><span class=\"token punctuation\">(</span><span class=\"token number\">403</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> session\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Key implementation decisions:</p>\n<ul>\n<li><strong><code class=\"language-text\">readSession()</code> is the authoritative check.</strong> A valid signature isn’t enough. The session row has to exist, be unexpired, and not be revoked, so signing out everywhere or banning a user takes effect on the next request. Proxy keeps its cheap signature-only check for redirects.</li>\n<li><strong>The role comes from the database, not the token.</strong> A demoted admin loses access on their next request instead of whenever a token happens to expire.</li>\n<li><strong>Only token problems mean “signed out.”</strong> A database outage throws and surfaces as a 500 instead of quietly logging everyone out.</li>\n<li><strong><code class=\"language-text\">cache()</code> only dedupes within a render.</strong> A page that makes ten DAL calls does one session lookup. Server Actions and Route Handlers aren’t part of a render pass, so each DAL call there runs its own lookup.</li>\n</ul>\n<p>The four exported helpers differ only in what happens when there’s no valid session:</p>\n<table>\n<thead>\n<tr>\n<th>Function</th>\n<th>With no valid session</th>\n<th>Use it in</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code class=\"language-text\">getSession()</code></td>\n<td>Returns <code class=\"language-text\">null</code></td>\n<td>UI that branches, like a header with a “Sign in” link</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">verifySession()</code></td>\n<td>Redirects to <code class=\"language-text\">/login</code></td>\n<td>Pages and layouts</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">requireSession()</code></td>\n<td>Throws <code class=\"language-text\">AuthError(401)</code></td>\n<td>DAL data functions</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">requireRole()</code></td>\n<td>Throws <code class=\"language-text\">AuthError(401)</code> or <code class=\"language-text\">AuthError(403)</code></td>\n<td>DAL functions that need a role</td>\n</tr>\n</tbody>\n</table>\n<h3 id=\"the-data-functions\" style=\"position:relative;\"><a href=\"#the-data-functions\" aria-label=\"the data functions permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>The Data Functions</h3>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"92536373293694810000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// lib/dal/invoices.ts\nimport 'server-only'\nimport { db } from '@/lib/db'\nimport { requireRole, requireSession } from './session'\n\n// The only invoice fields that ever leave the DAL\nconst invoiceFields = {\n  id: true,\n  number: true,\n  amountCents: true,\n  status: true,\n  dueDate: true,\n} as const\n\nexport type InvoiceDTO = {\n  id: string\n  number: string\n  amountCents: number\n  status: 'draft' | 'sent' | 'paid'\n  dueDate: Date\n}\n\nexport async function getMyInvoices(): Promise<InvoiceDTO[]> {\n  const { userId } = await requireSession()\n  return db.invoice.findMany({\n    where: { userId },\n    select: invoiceFields,\n    orderBy: { dueDate: 'desc' },\n  })\n}\n\nexport async function getInvoice(invoiceId: string): Promise<InvoiceDTO | null> {\n  const { userId } = await requireSession()\n  // Ownership lives in the query, so another user's invoice ID finds nothing\n  return db.invoice.findFirst({\n    where: { id: invoiceId, userId },\n    select: invoiceFields,\n  })\n}\n\nexport async function markInvoicePaid(invoiceId: string): Promise<boolean> {\n  const { userId } = await requireSession()\n  const { count } = await db.invoice.updateMany({\n    where: { id: invoiceId, userId, status: 'sent' },\n    data: { status: 'paid' },\n  })\n  return count === 1\n}\n\nexport async function getOverdueInvoices(): Promise<InvoiceDTO[]> {\n  await requireRole('admin')\n  return db.invoice.findMany({\n    where: { status: 'sent', dueDate: { lt: new Date() } },\n    select: invoiceFields,\n  })\n}`, `92536373293694810000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// lib/dal/invoices.ts</span>\n<span class=\"token keyword\">import</span> <span class=\"token string\">'server-only'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> db <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/db'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> requireRole<span class=\"token punctuation\">,</span> requireSession <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'./session'</span>\n\n<span class=\"token comment\">// The only invoice fields that ever leave the DAL</span>\n<span class=\"token keyword\">const</span> invoiceFields <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span>\n  id<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span>\n  <span class=\"token builtin\">number</span><span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span>\n  amountCents<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span>\n  status<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span>\n  dueDate<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span>\n<span class=\"token punctuation\">}</span> <span class=\"token keyword\">as</span> <span class=\"token keyword\">const</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">type</span> <span class=\"token class-name\">InvoiceDTO</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span>\n  id<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span>\n  <span class=\"token builtin\">number</span><span class=\"token operator\">:</span> <span class=\"token builtin\">string</span>\n  amountCents<span class=\"token operator\">:</span> <span class=\"token builtin\">number</span>\n  status<span class=\"token operator\">:</span> <span class=\"token string\">'draft'</span> <span class=\"token operator\">|</span> <span class=\"token string\">'sent'</span> <span class=\"token operator\">|</span> <span class=\"token string\">'paid'</span>\n  dueDate<span class=\"token operator\">:</span> Date\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">getMyInvoices</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>InvoiceDTO<span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span><span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> userId <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">requireSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> db<span class=\"token punctuation\">.</span>invoice<span class=\"token punctuation\">.</span><span class=\"token function\">findMany</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n    where<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> userId <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n    select<span class=\"token operator\">:</span> invoiceFields<span class=\"token punctuation\">,</span>\n    orderBy<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> dueDate<span class=\"token operator\">:</span> <span class=\"token string\">'desc'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">getInvoice</span><span class=\"token punctuation\">(</span>invoiceId<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>InvoiceDTO <span class=\"token operator\">|</span> <span class=\"token keyword\">null</span><span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> userId <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">requireSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token comment\">// Ownership lives in the query, so another user's invoice ID finds nothing</span>\n  <span class=\"token keyword\">return</span> db<span class=\"token punctuation\">.</span>invoice<span class=\"token punctuation\">.</span><span class=\"token function\">findFirst</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n    where<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> id<span class=\"token operator\">:</span> invoiceId<span class=\"token punctuation\">,</span> userId <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n    select<span class=\"token operator\">:</span> invoiceFields<span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">markInvoicePaid</span><span class=\"token punctuation\">(</span>invoiceId<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span><span class=\"token builtin\">boolean</span><span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> userId <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">requireSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> count <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> db<span class=\"token punctuation\">.</span>invoice<span class=\"token punctuation\">.</span><span class=\"token function\">updateMany</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n    where<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> id<span class=\"token operator\">:</span> invoiceId<span class=\"token punctuation\">,</span> userId<span class=\"token punctuation\">,</span> status<span class=\"token operator\">:</span> <span class=\"token string\">'sent'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n    data<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> status<span class=\"token operator\">:</span> <span class=\"token string\">'paid'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> count <span class=\"token operator\">===</span> <span class=\"token number\">1</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">getOverdueInvoices</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>InvoiceDTO<span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span><span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">await</span> <span class=\"token function\">requireRole</span><span class=\"token punctuation\">(</span><span class=\"token string\">'admin'</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> db<span class=\"token punctuation\">.</span>invoice<span class=\"token punctuation\">.</span><span class=\"token function\">findMany</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n    where<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> status<span class=\"token operator\">:</span> <span class=\"token string\">'sent'</span><span class=\"token punctuation\">,</span> dueDate<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> lt<span class=\"token operator\">:</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Date</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n    select<span class=\"token operator\">:</span> invoiceFields<span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"85485294084303340000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// lib/dal/index.ts\nexport { AuthError, getSession, verifySession, type Session } from './session'\nexport { getInvoice, getMyInvoices, getOverdueInvoices, markInvoicePaid } from './invoices'`, `85485294084303340000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// lib/dal/index.ts</span>\n<span class=\"token keyword\">export</span> <span class=\"token punctuation\">{</span> AuthError<span class=\"token punctuation\">,</span> getSession<span class=\"token punctuation\">,</span> verifySession<span class=\"token punctuation\">,</span> <span class=\"token keyword\">type</span> <span class=\"token class-name\">Session</span> <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'./session'</span>\n<span class=\"token keyword\">export</span> <span class=\"token punctuation\">{</span> getInvoice<span class=\"token punctuation\">,</span> getMyInvoices<span class=\"token punctuation\">,</span> getOverdueInvoices<span class=\"token punctuation\">,</span> markInvoicePaid <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'./invoices'</span></code></pre></div>\n<p><code class=\"language-text\">invoiceFields</code> is the DTO in practice: an allowlist of columns. Adding a <code class=\"language-text\">stripeCustomerId</code> or <code class=\"language-text\">internalNotes</code> column later doesn’t quietly ship it to the browser. <code class=\"language-text\">getInvoice()</code> returns <code class=\"language-text\">null</code> for an invoice that belongs to someone else, which tells a curious user nothing about whether it exists. And <code class=\"language-text\">requireSession()</code> and <code class=\"language-text\">requireRole()</code> stay out of the index file, so app code can only reach data through a function that already checks.</p>\n<h3 id=\"calling-the-dal-from-every-context\" style=\"position:relative;\"><a href=\"#calling-the-dal-from-every-context\" aria-label=\"calling the dal from every context permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Calling the DAL from Every Context</h3>\n<p>The same functions work in all three server contexts. What changes is how each one responds to an <code class=\"language-text\">AuthError</code>.</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"6009199904141860000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/dashboard/invoices/page.tsx\nimport { getMyInvoices, verifySession } from '@/lib/dal'\nimport { InvoiceList } from './invoice-list'\n\nexport default async function InvoicesPage() {\n  await verifySession() // signed-out users get a redirect, not an error page\n  const invoices = await getMyInvoices() // checks again, using the cached lookup\n  return <InvoiceList invoices={invoices} />\n}`, `6009199904141860000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"tsx\"><pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token comment\">// app/dashboard/invoices/page.tsx</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> getMyInvoices<span class=\"token punctuation\">,</span> verifySession <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/dal'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> InvoiceList <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'./invoice-list'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">InvoicesPage</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">await</span> <span class=\"token function\">verifySession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token comment\">// signed-out users get a redirect, not an error page</span>\n  <span class=\"token keyword\">const</span> invoices <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">getMyInvoices</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token comment\">// checks again, using the cached lookup</span>\n  <span class=\"token keyword\">return</span> <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">InvoiceList</span></span> <span class=\"token attr-name\">invoices</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>invoices<span class=\"token punctuation\">}</span></span> <span class=\"token punctuation\">/></span></span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<blockquote>\n<p><strong>Note:</strong> If Cache Components is on (the default for new apps since Next.js 16.4), this page needs a Suspense boundary to build. The next section shows how.</p>\n</blockquote>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"8018228467549626000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/dashboard/invoices/actions.ts\n'use server'\n\nimport { revalidatePath } from 'next/cache'\nimport { AuthError, markInvoicePaid } from '@/lib/dal'\n\nexport async function markPaid(invoiceId: unknown) {\n  // Arguments come from the client, whatever the call site's types say\n  if (typeof invoiceId !== 'string') return { ok: false, error: 'Invalid invoice' }\n\n  try {\n    const updated = await markInvoicePaid(invoiceId)\n    if (!updated) return { ok: false, error: 'Invoice not found' }\n  } catch (error) {\n    if (error instanceof AuthError) return { ok: false, error: error.message }\n    throw error\n  }\n\n  revalidatePath('/dashboard/invoices')\n  return { ok: true }\n}`, `8018228467549626000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// app/dashboard/invoices/actions.ts</span>\n<span class=\"token string\">'use server'</span>\n\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> revalidatePath <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/cache'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> AuthError<span class=\"token punctuation\">,</span> markInvoicePaid <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/dal'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">markPaid</span><span class=\"token punctuation\">(</span>invoiceId<span class=\"token operator\">:</span> <span class=\"token builtin\">unknown</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token comment\">// Arguments come from the client, whatever the call site's types say</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">typeof</span> invoiceId <span class=\"token operator\">!==</span> <span class=\"token string\">'string'</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token punctuation\">{</span> ok<span class=\"token operator\">:</span> <span class=\"token boolean\">false</span><span class=\"token punctuation\">,</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'Invalid invoice'</span> <span class=\"token punctuation\">}</span>\n\n  <span class=\"token keyword\">try</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">const</span> updated <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">markInvoicePaid</span><span class=\"token punctuation\">(</span>invoiceId<span class=\"token punctuation\">)</span>\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>updated<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token punctuation\">{</span> ok<span class=\"token operator\">:</span> <span class=\"token boolean\">false</span><span class=\"token punctuation\">,</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'Invoice not found'</span> <span class=\"token punctuation\">}</span>\n  <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>error <span class=\"token keyword\">instanceof</span> <span class=\"token class-name\">AuthError</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token punctuation\">{</span> ok<span class=\"token operator\">:</span> <span class=\"token boolean\">false</span><span class=\"token punctuation\">,</span> error<span class=\"token operator\">:</span> error<span class=\"token punctuation\">.</span>message <span class=\"token punctuation\">}</span>\n    <span class=\"token keyword\">throw</span> error\n  <span class=\"token punctuation\">}</span>\n\n  <span class=\"token function\">revalidatePath</span><span class=\"token punctuation\">(</span><span class=\"token string\">'/dashboard/invoices'</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> <span class=\"token punctuation\">{</span> ok<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span> <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"45531397285886640000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/api/invoices/route.ts\nimport { AuthError, getMyInvoices } from '@/lib/dal'\n\nexport async function GET() {\n  try {\n    return Response.json(await getMyInvoices())\n  } catch (error) {\n    if (error instanceof AuthError) {\n      return Response.json({ error: error.message }, { status: error.status })\n    }\n    throw error\n  }\n}`, `45531397285886640000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// app/api/invoices/route.ts</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> AuthError<span class=\"token punctuation\">,</span> getMyInvoices <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/dal'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token constant\">GET</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">try</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">return</span> Response<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">await</span> <span class=\"token function\">getMyInvoices</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n  <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>error <span class=\"token keyword\">instanceof</span> <span class=\"token class-name\">AuthError</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token keyword\">return</span> Response<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> error<span class=\"token punctuation\">.</span>message <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> status<span class=\"token operator\">:</span> error<span class=\"token punctuation\">.</span>status <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">}</span>\n    <span class=\"token keyword\">throw</span> error\n  <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>The page redirects, the action returns a result the form can display, and the Route Handler answers with a <code class=\"language-text\">401</code> instead of the 307 redirect from the first section. The allow-or-deny decision happens once, in the DAL, and none of the three call sites can skip it. The sections on each context go deeper, including bearer tokens for Route Handlers that mobile clients call.</p>\n<p>If you’ve turned on the experimental <a href=\"https://nextjs.org/docs/app/api-reference/config/next-config-js/authInterrupts\" target=\"_blank\" rel=\"nofollow\"><code class=\"language-text\">authInterrupts</code></a> flag, <code class=\"language-text\">unauthorized()</code> and <code class=\"language-text\">forbidden()</code> from <code class=\"language-text\">next/navigation</code> can replace <code class=\"language-text\">AuthError</code> in pages and Route Handlers. A typed error works today, without a flag.</p>\n<h3 id=\"keeping-the-dal-the-only-way-in\" style=\"position:relative;\"><a href=\"#keeping-the-dal-the-only-way-in\" aria-label=\"keeping the dal the only way in permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Keeping the DAL the Only Way In</h3>\n<p>Two guards turn the rules into build errors. The first is <code class=\"language-text\">import 'server-only'</code> at the top of every DAL file, which fails the build if a Client Component imports it (install it with <code class=\"language-text\">npm install server-only</code>). The second is a lint rule that stops app code from importing the database client directly:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"92136949852153050000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// eslint.config.mjs\nexport default [\n  // ...your existing config\n  {\n    files: ['app/**/*.{ts,tsx}'],\n    rules: {\n      'no-restricted-imports': ['error', {\n        patterns: [{\n          group: ['@/lib/db', '**/lib/db'],\n          message: 'Read and write data through @/lib/dal so every query checks the session.',\n        }],\n      }],\n    },\n  },\n]`, `92136949852153050000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"js\"><pre class=\"language-js\"><code class=\"language-js\"><span class=\"token comment\">// eslint.config.mjs</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> <span class=\"token punctuation\">[</span>\n  <span class=\"token comment\">// ...your existing config</span>\n  <span class=\"token punctuation\">{</span>\n    <span class=\"token literal-property property\">files</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">[</span><span class=\"token string\">'app/**/*.{ts,tsx}'</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">,</span>\n    <span class=\"token literal-property property\">rules</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token string-property property\">'no-restricted-imports'</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">[</span><span class=\"token string\">'error'</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span>\n        <span class=\"token literal-property property\">patterns</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">[</span><span class=\"token punctuation\">{</span>\n          <span class=\"token literal-property property\">group</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">[</span><span class=\"token string\">'@/lib/db'</span><span class=\"token punctuation\">,</span> <span class=\"token string\">'**/lib/db'</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">,</span>\n          <span class=\"token literal-property property\">message</span><span class=\"token operator\">:</span> <span class=\"token string\">'Read and write data through @/lib/dal so every query checks the session.'</span><span class=\"token punctuation\">,</span>\n        <span class=\"token punctuation\">}</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">,</span>\n      <span class=\"token punctuation\">}</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n<span class=\"token punctuation\">]</span></code></pre></div>\n<p>With that rule on, the fixed page from the last section fails lint, because it imports <code class=\"language-text\">db</code> directly. That’s the point. It was safe only as long as everyone remembered the check.</p>\n<p>A request for invoice data now passes four checks. Proxy turns signed-out users away early. The page redirects anyone Proxy missed. The DAL refuses anyone the page missed. The ownership filter refuses requests for someone else’s invoices. Proxy or the page can fail and the worst outcome is a confusing error page. The DAL is the layer that can’t fail, which is why every function in it checks for itself and why it’s the only code allowed near the database.</p>\n<p>Proxy decides where a request goes. The DAL decides what it gets.</p>\n<h2 id=\"protecting-server-components\" style=\"position:relative;\"><a href=\"#protecting-server-components\" aria-label=\"protecting server components permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Protecting Server Components</h2>\n<p>Server Components are where the DAL gets called most, so most of the protection is already in place. What’s left is timing. “Redirect before anything renders” only holds under specific conditions in Next.js 16, and those conditions changed when <a href=\"https://nextjs.org/blog/next-16-4\" target=\"_blank\" rel=\"nofollow\">Next.js 16.4</a> turned Cache Components on for every new app.</p>\n<h3 id=\"the-baseline-check-then-fetch\" style=\"position:relative;\"><a href=\"#the-baseline-check-then-fetch\" aria-label=\"the baseline check then fetch permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>The Baseline: Check, Then Fetch</h3>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"41326880017390756000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/dashboard/invoices/[id]/page.tsx\nimport { notFound } from 'next/navigation'\nimport { getInvoice, verifySession } from '@/lib/dal'\nimport { InvoiceDetail } from './invoice-detail'\n\nexport default async function InvoicePage({ params }: { params: Promise<{ id: string }> }) {\n  await verifySession() // first, before any data or JSX\n  const { id } = await params\n  const invoice = await getInvoice(id) // null when it isn't this user's invoice\n  if (!invoice) notFound()\n  return <InvoiceDetail invoice={invoice} />\n}`, `41326880017390756000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"tsx\"><pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token comment\">// app/dashboard/invoices/[id]/page.tsx</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> notFound <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/navigation'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> getInvoice<span class=\"token punctuation\">,</span> verifySession <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/dal'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> InvoiceDetail <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'./invoice-detail'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">InvoicePage</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> params <span class=\"token punctuation\">}</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> params<span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span><span class=\"token punctuation\">{</span> id<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span> <span class=\"token punctuation\">}</span><span class=\"token operator\">></span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">await</span> <span class=\"token function\">verifySession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token comment\">// first, before any data or JSX</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> id <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> params\n  <span class=\"token keyword\">const</span> invoice <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">getInvoice</span><span class=\"token punctuation\">(</span>id<span class=\"token punctuation\">)</span> <span class=\"token comment\">// null when it isn't this user's invoice</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>invoice<span class=\"token punctuation\">)</span> <span class=\"token function\">notFound</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">InvoiceDetail</span></span> <span class=\"token attr-name\">invoice</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>invoice<span class=\"token punctuation\">}</span></span> <span class=\"token punctuation\">/></span></span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Without Cache Components, and with no <code class=\"language-text\">loading.js</code> above it, nothing streams until this function returns. A signed-out request gets a real <code class=\"language-text\">307</code> to <code class=\"language-text\">/login</code>, and another user’s invoice ID gets a real <code class=\"language-text\">404</code>. Two habits keep it that way:</p>\n<ul>\n<li><strong>Keep <code class=\"language-text\">verifySession()</code> out of <code class=\"language-text\">try/catch</code>.</strong> <code class=\"language-text\">redirect()</code> and <code class=\"language-text\">notFound()</code> work by throwing, and a catch block swallows them. If you have to catch around them, rethrow with <code class=\"language-text\">unstable_rethrow</code>.</li>\n<li><strong>Route <code class=\"language-text\">generateMetadata</code> through the DAL too.</strong> It runs alongside the page, not after it, so a title built from a direct database query is one more unchecked read.</li>\n</ul>\n<h3 id=\"when-a-redirect-stops-being-a-redirect\" style=\"position:relative;\"><a href=\"#when-a-redirect-stops-being-a-redirect\" aria-label=\"when a redirect stops being a redirect permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>When a Redirect Stops Being a Redirect</h3>\n<p>The <a href=\"https://nextjs.org/docs/app/api-reference/file-conventions/loading#status-codes\" target=\"_blank\" rel=\"nofollow\">status code is fixed</a> the moment the response starts streaming, and streaming starts as soon as a Suspense fallback renders, including the one <code class=\"language-text\">loading.js</code> wraps around a page. Add a <code class=\"language-text\">loading.tsx</code> next to the page above and a signed-out request gets a <code class=\"language-text\">200</code>: the loading UI first, then a <code class=\"language-text\">&lt;meta http-equiv=\"refresh\"></code> tag and a client-side redirect to <code class=\"language-text\">/login</code>. <code class=\"language-text\">notFound()</code>, <code class=\"language-text\">forbidden()</code>, and <code class=\"language-text\">unauthorized()</code> downgrade the same way, to a <code class=\"language-text\">200</code> with a <code class=\"language-text\">noindex</code> tag.</p>\n<p>The data stays protected either way, because the component that reads it never renders. What changes is the status code that monitoring, crawlers, and non-browser clients see.</p>\n<h3 id=\"cache-components-move-every-check-behind-suspense\" style=\"position:relative;\"><a href=\"#cache-components-move-every-check-behind-suspense\" aria-label=\"cache components move every check behind suspense permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Cache Components Move Every Check Behind Suspense</h3>\n<p>New apps from <code class=\"language-text\">create-next-app</code> 16.4 have Cache Components on, and it becomes the default for everyone in Next.js 17. With it on, <a href=\"https://nextjs.org/docs/app/guides/authentication-with-cache-components\" target=\"_blank\" rel=\"nofollow\">reading <code class=\"language-text\">cookies()</code> outside a Suspense boundary is a build error</a>. The baseline page above, and the invoices page from the DAL section, both fail <code class=\"language-text\">next build</code> with “Next.js encountered uncached or runtime data during prerendering.”</p>\n<p>The fix is to move the check and the data into a component inside a boundary:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"44092130053708464000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/dashboard/invoices/[id]/page.tsx (Cache Components on)\nimport { Suspense } from 'react'\nimport { notFound } from 'next/navigation'\nimport { getInvoice, verifySession } from '@/lib/dal'\nimport { InvoiceDetail } from './invoice-detail'\n\nexport default function InvoicePage({ params }: { params: Promise<{ id: string }> }) {\n  return (\n    <main>\n      <Suspense fallback={<p>Loading invoice…</p>}>\n        <Invoice params={params} />\n      </Suspense>\n    </main>\n  )\n}\n\nasync function Invoice({ params }: { params: Promise<{ id: string }> }) {\n  await verifySession()\n  const { id } = await params\n  const invoice = await getInvoice(id)\n  if (!invoice) notFound()\n  return <InvoiceDetail invoice={invoice} />\n}`, `44092130053708464000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"tsx\"><pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token comment\">// app/dashboard/invoices/[id]/page.tsx (Cache Components on)</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> Suspense <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> notFound <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/navigation'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> getInvoice<span class=\"token punctuation\">,</span> verifySession <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/dal'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> InvoiceDetail <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'./invoice-detail'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> <span class=\"token keyword\">function</span> <span class=\"token function\">InvoicePage</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> params <span class=\"token punctuation\">}</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> params<span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span><span class=\"token punctuation\">{</span> id<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span> <span class=\"token punctuation\">}</span><span class=\"token operator\">></span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">return</span> <span class=\"token punctuation\">(</span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>main</span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">\n      </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">Suspense</span></span> <span class=\"token attr-name\">fallback</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>p</span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">Loading invoice…</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>p</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">}</span></span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">\n        </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">Invoice</span></span> <span class=\"token attr-name\">params</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>params<span class=\"token punctuation\">}</span></span> <span class=\"token punctuation\">/></span></span><span class=\"token plain-text\">\n      </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span><span class=\"token class-name\">Suspense</span></span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">\n    </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>main</span><span class=\"token punctuation\">></span></span>\n  <span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">Invoice</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> params <span class=\"token punctuation\">}</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> params<span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span><span class=\"token punctuation\">{</span> id<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span> <span class=\"token punctuation\">}</span><span class=\"token operator\">></span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">await</span> <span class=\"token function\">verifySession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> id <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> params\n  <span class=\"token keyword\">const</span> invoice <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">getInvoice</span><span class=\"token punctuation\">(</span>id<span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>invoice<span class=\"token punctuation\">)</span> <span class=\"token function\">notFound</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">InvoiceDetail</span></span> <span class=\"token attr-name\">invoice</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>invoice<span class=\"token punctuation\">}</span></span> <span class=\"token punctuation\">/></span></span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>That turns every Server Component check into a post-streaming check, with the <code class=\"language-text\">200</code> behavior described above. The build error also suggests <code class=\"language-text\">export const instant = false</code>, and that compiles, but the response to a signed-out visitor was still a <code class=\"language-text\">200</code>, with the redirect carried in the RSC payload. With Cache Components on, Proxy is the only layer that runs before the shell is sent, which makes it the only place that can still return a real <code class=\"language-text\">307</code>.</p>\n<h3 id=\"the-static-shell-is-public\" style=\"position:relative;\"><a href=\"#the-static-shell-is-public\" aria-label=\"the static shell is public permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>The Static Shell Is Public</h3>\n<p>With Cache Components, everything outside a Suspense boundary is prerendered into the static shell and served to every visitor before any check runs. That includes components marked <code class=\"language-text\">'use cache'</code>. A cached “members only” announcement placed above the gated section reached signed-out visitors right along with their redirect.</p>\n<p>If a signed-out visitor shouldn’t see it, it goes behind the boundary and through the DAL, or the route gets a Proxy check. The Next.js authentication guide gives the same advice for static content shared between users: protect it with Proxy.</p>\n<h3 id=\"layouts-dont-guard-pages\" style=\"position:relative;\"><a href=\"#layouts-dont-guard-pages\" aria-label=\"layouts dont guard pages permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Layouts Don’t Guard Pages</h3>\n<p>Layouts don’t re-render on client-side navigation, so a check in a layout runs once for a whole section of the app, not on every page view. The <a href=\"https://nextjs.org/docs/app/guides/authentication#layouts-and-auth-checks\" target=\"_blank\" rel=\"nofollow\">Next.js docs</a> add a second problem: a layout doesn’t control whether the route below it renders. Pages and parallel route slots render on their own, and their output still lands in the RSC payload.</p>\n<p>That’s easy to underestimate, so here’s what it looks like with Cache Components off. A layout that calls <code class=\"language-text\">verifySession()</code> returned a <code class=\"language-text\">307</code> for signed-out requests, and the body of that <code class=\"language-text\">307</code> still contained the page’s rendered output, just ahead of the redirect marker. Browsers follow the redirect and never show it. <code class=\"language-text\">curl</code> shows it fine. A layout that rendered “Please sign in” in place of <code class=\"language-text\">{children}</code> returned a <code class=\"language-text\">200</code> with the page’s output in the payload. In both cases the page function ran.</p>\n<p>Use layouts for shared UI that reads the session through <code class=\"language-text\">getSession()</code>, like a header with the user’s name, and keep the check in every page, through the DAL.</p>\n<h3 id=\"expired-access-tokens\" style=\"position:relative;\"><a href=\"#expired-access-tokens\" aria-label=\"expired access tokens permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Expired Access Tokens</h3>\n<p>Server Components can’t set cookies, so if your sessions use short-lived access tokens, a page that finds an expired one can’t refresh it in place. Redirecting to <code class=\"language-text\">/login</code> at that point signs out someone whose refresh token is still valid, and if your login page sends signed-in users back where they came from, it can start a loop. Render a small Client Component instead, one that calls your refresh endpoint and then <code class=\"language-text\">router.refresh()</code>. The session strategy section builds the endpoint, and the SuperTokens section shows the SDK’s version.</p>\n<h3 id=\"what-signed-out-visitors-actually-get\" style=\"position:relative;\"><a href=\"#what-signed-out-visitors-actually-get\" aria-label=\"what signed out visitors actually get permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>What Signed-Out Visitors Actually Get</h3>\n<p>Here’s what a test app on Next.js 16.4.2 returned for a signed-out request, depending on where the check ran:</p>\n<table>\n<thead>\n<tr>\n<th>Where the check runs</th>\n<th>Response</th>\n<th>Status</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Proxy</td>\n<td>Redirect before anything renders</td>\n<td><code class=\"language-text\">307</code></td>\n</tr>\n<tr>\n<td>Page, no Suspense above it (Cache Components off)</td>\n<td>Redirect before anything streams</td>\n<td><code class=\"language-text\">307</code></td>\n</tr>\n<tr>\n<td>Page under <code class=\"language-text\">loading.js</code> or inside <code class=\"language-text\">&lt;Suspense></code></td>\n<td>Loading UI, then a client-side redirect</td>\n<td><code class=\"language-text\">200</code></td>\n</tr>\n<tr>\n<td>Any Server Component, Cache Components on</td>\n<td>Static shell, then a client-side redirect</td>\n<td><code class=\"language-text\">200</code></td>\n</tr>\n<tr>\n<td>Layout only (Cache Components off)</td>\n<td>Redirect, with the page’s output in the body</td>\n<td><code class=\"language-text\">307</code></td>\n</tr>\n<tr>\n<td>Layout that swaps <code class=\"language-text\">{children}</code> for a sign-in prompt</td>\n<td>Prompt, with the page’s output in the payload</td>\n<td><code class=\"language-text\">200</code></td>\n</tr>\n</tbody>\n</table>\n<p>Check in the page, fetch through the DAL, and let Proxy own the status code.</p>\n<h2 id=\"protecting-server-actions\" style=\"position:relative;\"><a href=\"#protecting-server-actions\" aria-label=\"protecting server actions permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Protecting Server Actions</h2>\n<p>A Server Action reads like a function call, which makes it easy to forget that it’s also a public endpoint. The <a href=\"https://nextjs.org/docs/app/guides/server-actions#security\" target=\"_blank\" rel=\"nofollow\">Next.js docs</a> put it bluntly: “Treat every action as an untrusted entry point.”</p>\n<h3 id=\"what-a-call-looks-like\" style=\"position:relative;\"><a href=\"#what-a-call-looks-like\" aria-label=\"what a call looks like permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>What a Call Looks Like</h3>\n<p>Here’s the request behind <code class=\"language-text\">markPaid('inv_1')</code> from the DAL section:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"85865661640703900000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`POST /dashboard/invoices HTTP/1.1\nNext-Action: 7f3a9c0e…\nContent-Type: text/plain;charset=UTF-8\nCookie: session=…\n\n[&quot;inv_1&quot;]`, `85865661640703900000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"http\"><pre class=\"language-http\"><code class=\"language-http\"><span class=\"token request-line\"><span class=\"token method property\">POST</span> <span class=\"token request-target url\">/dashboard/invoices</span> <span class=\"token http-version property\">HTTP/1.1</span></span>\n<span class=\"token header\"><span class=\"token header-name keyword\">Next-Action</span><span class=\"token punctuation\">:</span> <span class=\"token header-value\">7f3a9c0e…</span></span>\n<span class=\"token header\"><span class=\"token header-name keyword\">Content-Type</span><span class=\"token punctuation\">:</span> <span class=\"token header-value\">text/plain;charset=UTF-8</span></span>\n<span class=\"token header\"><span class=\"token header-name keyword\">Cookie</span><span class=\"token punctuation\">:</span> <span class=\"token header-value\">session=…</span></span>\n\n[\"inv_1\"]</code></pre></div>\n<p>The URL is whatever page the user is on, the <code class=\"language-text\">Next-Action</code> header names the function, and the body carries its arguments. Next.js encrypts action IDs, rotates them over time, and strips unused actions from client bundles, but an ID isn’t a secret. Any action your UI can call has its ID somewhere in what the browser downloads. <a href=\"https://github.com/vercel/next.js/security/advisories/GHSA-955p-x3mx-jcvp\" target=\"_blank\" rel=\"nofollow\">CVE-2026-64643</a>, patched in July 2026, went further: IDs for actions used on signed-in pages could be read from static chunks served to anyone. Its workaround is the rule for this whole section: “Always authenticate within the boundary,” meaning inside the <code class=\"language-text\">'use server'</code> function itself.</p>\n<h3 id=\"proxy-coverage-doesnt-follow-the-action\" style=\"position:relative;\"><a href=\"#proxy-coverage-doesnt-follow-the-action\" aria-label=\"proxy coverage doesnt follow the action permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Proxy Coverage Doesn’t Follow the Action</h3>\n<p>Proxy matches URLs, and an action doesn’t have one of its own. When the POST lands on a path the matcher covers, Proxy runs and can turn it away. The <a href=\"https://nextjs.org/docs/app/api-reference/file-conventions/proxy#execution-order\" target=\"_blank\" rel=\"nofollow\">Proxy docs</a> spell out the catch: “a Proxy matcher that excludes a path will also skip Server Function calls on that path,” and “a refactor that moves a Server Function to a different route can silently remove Proxy coverage.”</p>\n<p>A shared file can do the same without moving anything. Here’s a pattern that looks safe:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"64105785599684714000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/actions.ts\n'use server'\n\nimport { db } from '@/lib/db'\n\nexport async function likePost(formData: FormData) {\n  // used by a form on the public blog page\n}\n\n// WRONG: &quot;only the admin page renders this form, and Proxy guards /admin&quot;\nexport async function deleteInvoice(formData: FormData) {\n  await db.invoice.deleteMany({ where: { id: String(formData.get('invoiceId')) } })\n}`, `64105785599684714000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// app/actions.ts</span>\n<span class=\"token string\">'use server'</span>\n\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> db <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/db'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">likePost</span><span class=\"token punctuation\">(</span>formData<span class=\"token operator\">:</span> FormData<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token comment\">// used by a form on the public blog page</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token comment\">// WRONG: \"only the admin page renders this form, and Proxy guards /admin\"</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">deleteInvoice</span><span class=\"token punctuation\">(</span>formData<span class=\"token operator\">:</span> FormData<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">await</span> db<span class=\"token punctuation\">.</span>invoice<span class=\"token punctuation\">.</span><span class=\"token function\">deleteMany</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> where<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> id<span class=\"token operator\">:</span> <span class=\"token function\">String</span><span class=\"token punctuation\">(</span>formData<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'invoiceId'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>In a test app on Next.js 16.4.2, the public blog page and an admin page both imported this file into Server Component forms. Next.js registered every action in the file for both pages, so a POST to the blog page carrying <code class=\"language-text\">deleteInvoice</code>’s ID ran the delete, with no session cookie at all. Proxy’s <code class=\"language-text\">/admin</code> rule never saw the request, because the request never went to <code class=\"language-text\">/admin</code>. When Client Components imported the same actions instead, Next.js routed the call to the admin page, where Proxy blocked it. That’s an implementation detail, not a security boundary. Don’t build on it.</p>\n<p>The lint rule from the DAL section already flags this file, because it imports the database directly.</p>\n<h3 id=\"the-auth-check-inside-every-action\" style=\"position:relative;\"><a href=\"#the-auth-check-inside-every-action\" aria-label=\"the auth check inside every action permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>The Auth Check Inside Every Action</h3>\n<p>The fix puts the check where the write happens. Add an admin-only delete to the DAL and export it from <code class=\"language-text\">lib/dal/index.ts</code>:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"26522686898785360000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// lib/dal/invoices.ts\n// Admins can delete any invoice, so there's no owner filter, which makes the role check mandatory\nexport async function deleteInvoice(invoiceId: string): Promise<boolean> {\n  await requireRole('admin')\n  const { count } = await db.invoice.deleteMany({ where: { id: invoiceId } })\n  return count === 1\n}`, `26522686898785360000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// lib/dal/invoices.ts</span>\n<span class=\"token comment\">// Admins can delete any invoice, so there's no owner filter, which makes the role check mandatory</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">deleteInvoice</span><span class=\"token punctuation\">(</span>invoiceId<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span><span class=\"token builtin\">boolean</span><span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">await</span> <span class=\"token function\">requireRole</span><span class=\"token punctuation\">(</span><span class=\"token string\">'admin'</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> count <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> db<span class=\"token punctuation\">.</span>invoice<span class=\"token punctuation\">.</span><span class=\"token function\">deleteMany</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> where<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> id<span class=\"token operator\">:</span> invoiceId <span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> count <span class=\"token operator\">===</span> <span class=\"token number\">1</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Then keep the action thin. It validates, calls the DAL, and shapes the result:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"9880733429357090000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/admin/invoices/actions.ts\n'use server'\n\nimport { z } from 'zod'\nimport { revalidatePath } from 'next/cache'\nimport { AuthError, deleteInvoice } from '@/lib/dal'\n\nexport type ActionResult = { ok: true } | { ok: false; error: string } | null\n\nconst DeleteInvoiceInput = z.object({\n  invoiceId: z.string().min(1).max(64),\n})\n\nexport async function deleteInvoiceAction(_prev: ActionResult, formData: FormData): Promise<ActionResult> {\n  // Form fields are whatever the client sent, hidden inputs included\n  const input = DeleteInvoiceInput.safeParse({ invoiceId: formData.get('invoiceId') })\n  if (!input.success) return { ok: false, error: 'Invalid invoice' }\n\n  try {\n    // The role check lives in the DAL, so it runs on every call, from any page\n    const deleted = await deleteInvoice(input.data.invoiceId)\n    if (!deleted) return { ok: false, error: 'Invoice not found' }\n  } catch (error) {\n    if (error instanceof AuthError) return { ok: false, error: error.message }\n    throw error\n  }\n\n  revalidatePath('/admin/invoices')\n  return { ok: true }\n}`, `9880733429357090000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// app/admin/invoices/actions.ts</span>\n<span class=\"token string\">'use server'</span>\n\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> z <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'zod'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> revalidatePath <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/cache'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> AuthError<span class=\"token punctuation\">,</span> deleteInvoice <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/dal'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">type</span> <span class=\"token class-name\">ActionResult</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span> ok<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span> <span class=\"token punctuation\">}</span> <span class=\"token operator\">|</span> <span class=\"token punctuation\">{</span> ok<span class=\"token operator\">:</span> <span class=\"token boolean\">false</span><span class=\"token punctuation\">;</span> error<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span> <span class=\"token punctuation\">}</span> <span class=\"token operator\">|</span> <span class=\"token keyword\">null</span>\n\n<span class=\"token keyword\">const</span> DeleteInvoiceInput <span class=\"token operator\">=</span> z<span class=\"token punctuation\">.</span><span class=\"token function\">object</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n  invoiceId<span class=\"token operator\">:</span> z<span class=\"token punctuation\">.</span><span class=\"token function\">string</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">min</span><span class=\"token punctuation\">(</span><span class=\"token number\">1</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">max</span><span class=\"token punctuation\">(</span><span class=\"token number\">64</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">deleteInvoiceAction</span><span class=\"token punctuation\">(</span>_prev<span class=\"token operator\">:</span> ActionResult<span class=\"token punctuation\">,</span> formData<span class=\"token operator\">:</span> FormData<span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>ActionResult<span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token comment\">// Form fields are whatever the client sent, hidden inputs included</span>\n  <span class=\"token keyword\">const</span> input <span class=\"token operator\">=</span> DeleteInvoiceInput<span class=\"token punctuation\">.</span><span class=\"token function\">safeParse</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> invoiceId<span class=\"token operator\">:</span> formData<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'invoiceId'</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>input<span class=\"token punctuation\">.</span>success<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token punctuation\">{</span> ok<span class=\"token operator\">:</span> <span class=\"token boolean\">false</span><span class=\"token punctuation\">,</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'Invalid invoice'</span> <span class=\"token punctuation\">}</span>\n\n  <span class=\"token keyword\">try</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token comment\">// The role check lives in the DAL, so it runs on every call, from any page</span>\n    <span class=\"token keyword\">const</span> deleted <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">deleteInvoice</span><span class=\"token punctuation\">(</span>input<span class=\"token punctuation\">.</span>data<span class=\"token punctuation\">.</span>invoiceId<span class=\"token punctuation\">)</span>\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>deleted<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token punctuation\">{</span> ok<span class=\"token operator\">:</span> <span class=\"token boolean\">false</span><span class=\"token punctuation\">,</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'Invoice not found'</span> <span class=\"token punctuation\">}</span>\n  <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>error <span class=\"token keyword\">instanceof</span> <span class=\"token class-name\">AuthError</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token punctuation\">{</span> ok<span class=\"token operator\">:</span> <span class=\"token boolean\">false</span><span class=\"token punctuation\">,</span> error<span class=\"token operator\">:</span> error<span class=\"token punctuation\">.</span>message <span class=\"token punctuation\">}</span>\n    <span class=\"token keyword\">throw</span> error\n  <span class=\"token punctuation\">}</span>\n\n  <span class=\"token function\">revalidatePath</span><span class=\"token punctuation\">(</span><span class=\"token string\">'/admin/invoices'</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> <span class=\"token punctuation\">{</span> ok<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span> <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"39260449920960135000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/admin/invoices/delete-invoice-button.tsx\n'use client'\n\nimport { useActionState } from 'react'\nimport { deleteInvoiceAction } from './actions'\n\nexport function DeleteInvoiceButton({ invoiceId }: { invoiceId: string }) {\n  const [state, formAction, pending] = useActionState(deleteInvoiceAction, null)\n\n  return (\n    <form action={formAction}>\n      <input type=&quot;hidden&quot; name=&quot;invoiceId&quot; value={invoiceId} />\n      <button disabled={pending}>Delete invoice</button>\n      {state && !state.ok && <p role=&quot;alert&quot;>{state.error}</p>}\n    </form>\n  )\n}`, `39260449920960135000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"tsx\"><pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token comment\">// app/admin/invoices/delete-invoice-button.tsx</span>\n<span class=\"token string\">'use client'</span>\n\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> useActionState <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> deleteInvoiceAction <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'./actions'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">function</span> <span class=\"token function\">DeleteInvoiceButton</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> invoiceId <span class=\"token punctuation\">}</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> invoiceId<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">[</span>state<span class=\"token punctuation\">,</span> formAction<span class=\"token punctuation\">,</span> pending<span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token function\">useActionState</span><span class=\"token punctuation\">(</span>deleteInvoiceAction<span class=\"token punctuation\">,</span> <span class=\"token keyword\">null</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">return</span> <span class=\"token punctuation\">(</span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>form</span> <span class=\"token attr-name\">action</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>formAction<span class=\"token punctuation\">}</span></span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">\n      </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>input</span> <span class=\"token attr-name\">type</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">\"</span>hidden<span class=\"token punctuation\">\"</span></span> <span class=\"token attr-name\">name</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">\"</span>invoiceId<span class=\"token punctuation\">\"</span></span> <span class=\"token attr-name\">value</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>invoiceId<span class=\"token punctuation\">}</span></span> <span class=\"token punctuation\">/></span></span><span class=\"token plain-text\">\n      </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>button</span> <span class=\"token attr-name\">disabled</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>pending<span class=\"token punctuation\">}</span></span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">Delete invoice</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>button</span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">\n      </span><span class=\"token punctuation\">{</span>state <span class=\"token operator\">&amp;&amp;</span> <span class=\"token operator\">!</span>state<span class=\"token punctuation\">.</span>ok <span class=\"token operator\">&amp;&amp;</span> <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>p</span> <span class=\"token attr-name\">role</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">\"</span>alert<span class=\"token punctuation\">\"</span></span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">{</span>state<span class=\"token punctuation\">.</span>error<span class=\"token punctuation\">}</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>p</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">}</span><span class=\"token plain-text\">\n    </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>form</span><span class=\"token punctuation\">></span></span>\n  <span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>In the shared file from the test, an action calling the same DAL function refused the request through the public blog page: “Not allowed” for a signed-in member and “Authentication required” with no cookie. An admin on the admin page could still delete. Every action needs the same three steps:</p>\n<ul>\n<li><strong>Validate first.</strong> Arguments, form fields, and hidden inputs are whatever the client sent. TypeScript types don’t exist at runtime, and a schema checks shape, not ownership.</li>\n<li><strong>Authorize through the DAL.</strong> The check runs in the action’s own call path, never in the page that rendered the form. The Next.js guide is explicit that render-time gating “is not a security boundary, because requests can be sent without going through the UI.”</li>\n<li><strong>Return only what the UI renders.</strong> Return values are serialized to the browser, so send back <code class=\"language-text\">{ ok, error }</code>, not database rows or raw error messages.</li>\n</ul>\n<h3 id=\"bound-arguments-are-input-too\" style=\"position:relative;\"><a href=\"#bound-arguments-are-input-too\" aria-label=\"bound arguments are input too permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Bound Arguments Are Input Too</h3>\n<p>The <a href=\"https://nextjs.org/docs/app/guides/forms#passing-additional-arguments\" target=\"_blank\" rel=\"nofollow\">Forms guide</a> uses <code class=\"language-text\">.bind()</code> to pass an action extra arguments, like an ID, and contrasts it with a hidden input, whose value “will not be encoded.” That makes <code class=\"language-text\">.bind()</code> sound safer than it is. Next.js encrypts variables an inline action captures from its scope, but bound arguments are only encoded: in the test app, a bound invoice ID showed up in the page’s HTML as a readable hidden field, and anyone can change it before the request goes out.</p>\n<p>Treat bound arguments like any other input. The <code class=\"language-text\">markPaid</code> action from the DAL section takes its invoice ID as an argument and already does: it checks the type, and the DAL’s ownership filter means a swapped ID finds nothing. If you run more than one instance, set <code class=\"language-text\">NEXT_SERVER_ACTIONS_ENCRYPTION_KEY</code> to one stable key so every instance can decrypt what another encrypted.</p>\n<h3 id=\"csrf-and-patching\" style=\"position:relative;\"><a href=\"#csrf-and-patching\" aria-label=\"csrf and patching permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>CSRF and Patching</h3>\n<p>Next.js only accepts actions as POST requests and compares the <code class=\"language-text\">Origin</code> header with the <code class=\"language-text\">Host</code>. A cross-site <code class=\"language-text\">Origin</code> got “Invalid Server Actions request” in the test app. If a reverse proxy or CDN serves your app from another domain, add that domain to <a href=\"https://nextjs.org/docs/app/api-reference/config/next-config-js/serverActions#allowedorigins\" target=\"_blank\" rel=\"nofollow\"><code class=\"language-text\">experimental.serverActions.allowedOrigins</code></a>. Cookies add a second layer: browsers don’t send <code class=\"language-text\">SameSite=Lax</code> or <code class=\"language-text\">Strict</code> cookies with a cross-site POST, so a forged action arrives signed out and the check inside the action refuses it. The session strategy section sets those attributes.</p>\n<p>Both layers matter, because the framework’s checks have needed fixes of their own. <a href=\"https://github.com/vercel/next.js/security/advisories/GHSA-mq59-m269-xvcx\" target=\"_blank\" rel=\"nofollow\">CVE-2026-27978</a> treated <code class=\"language-text\">Origin: null</code>, which browsers send from opaque contexts like sandboxed iframes, as a missing origin and skipped the check until 16.1.7. React2Shell (<a href=\"https://react.dev/blog/2025/12/03/critical-security-vulnerability-in-react-server-components\" target=\"_blank\" rel=\"nofollow\">CVE-2025-55182</a>), disclosed in December 2025 and rated CVSS 10.0, was worse: a crafted request to a Server Function endpoint could run code on the server while React decoded the payload, before any check inside the action ran. Keeping Next.js and React patched is part of protecting actions.</p>\n<p>The form is UI. The action is an endpoint. Check it like one.</p>\n<h2 id=\"protecting-route-handlers\" style=\"position:relative;\"><a href=\"#protecting-route-handlers\" aria-label=\"protecting route handlers permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Protecting Route Handlers</h2>\n<p>A Route Handler is an HTTP endpoint with no page attached, and the <a href=\"https://nextjs.org/docs/app/guides/backend-for-frontend#public-endpoints\" target=\"_blank\" rel=\"nofollow\">Next.js docs</a> describe it in two sentences: “Route Handlers are public HTTP endpoints. Any client can access them.” Many of those clients are mobile apps, scripts, and other services, and none of them read error pages. They read status codes. Protecting a Route Handler means refusing the request with the right one.</p>\n<h3 id=\"what-a-redirect-does-to-an-api-client\" style=\"position:relative;\"><a href=\"#what-a-redirect-does-to-an-api-client\" aria-label=\"what a redirect does to an api client permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>What a Redirect Does to an API Client</h3>\n<p>The DAL’s <code class=\"language-text\">verifySession()</code> is built for pages. It redirects when there’s no session, and in a Route Handler that redirect is all the caller gets:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"65187416745870610000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/api/account/route.ts\nimport { verifySession } from '@/lib/dal'\n\n// WRONG: verifySession() redirects when there's no session, so this 401 never runs\nexport async function GET() {\n  const session = await verifySession()\n  if (!session) return new Response(null, { status: 401 })\n  return Response.json({ userId: session.userId })\n}`, `65187416745870610000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// app/api/account/route.ts</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> verifySession <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/dal'</span>\n\n<span class=\"token comment\">// WRONG: verifySession() redirects when there's no session, so this 401 never runs</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token constant\">GET</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> session <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">verifySession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>session<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Response</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">null</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> status<span class=\"token operator\">:</span> <span class=\"token number\">401</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> Response<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> userId<span class=\"token operator\">:</span> session<span class=\"token punctuation\">.</span>userId <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>The <a href=\"https://nextjs.org/docs/app/guides/authentication#route-handlers\" target=\"_blank\" rel=\"nofollow\">Route Handler example in the Next.js authentication guide</a> has the same shape. Its <code class=\"language-text\">verifySession()</code> calls <code class=\"language-text\">redirect('/login')</code> when the session is missing or invalid, so the <code class=\"language-text\">401</code> branch after it never runs.</p>\n<p>On Next.js 16.4.2, a signed-out <code class=\"language-text\">curl</code> request to the handler above got a <code class=\"language-text\">307</code> to <code class=\"language-text\">/login</code> with an empty body. <code class=\"language-text\">fetch()</code> follows redirects by default, so a client using it never saw the 307. It got a <code class=\"language-text\">200</code> with the login page’s HTML, and <code class=\"language-text\">res.json()</code> threw <code class=\"language-text\">SyntaxError: Unexpected token '&lt;'</code>. That’s a strange way to find out you’re signed out. A POST did worse: a 307 keeps the method and body, so <code class=\"language-text\">fetch()</code> re-sent the POST to <code class=\"language-text\">/login</code> and got a <code class=\"language-text\">405</code>.</p>\n<p>Proxy causes the same failure when its matcher covers <code class=\"language-text\">/api</code> and it answers with a redirect. When Proxy turns away an API request, it should return the <code class=\"language-text\">401</code> itself, the way the <a href=\"https://nextjs.org/docs/app/api-reference/file-conventions/proxy#producing-a-response\" target=\"_blank\" rel=\"nofollow\">Proxy docs’ example</a> does. In an app built from the authentication guide, the question never comes up: its Proxy example excludes <code class=\"language-text\">api</code> from the matcher, so Route Handlers under <code class=\"language-text\">/api</code> get no Proxy check at all.</p>\n<h3 id=\"401-403-or-404\" style=\"position:relative;\"><a href=\"#401-403-or-404\" aria-label=\"401 403 or 404 permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>401, 403, or 404</h3>\n<p>Each refusal tells the client something different, and well-behaved clients act on the difference:</p>\n<table>\n<thead>\n<tr>\n<th>Status</th>\n<th>Means</th>\n<th>The client should</th>\n<th>Example</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code class=\"language-text\">401</code></td>\n<td>No valid credentials</td>\n<td>Refresh its token or sign in, then retry</td>\n<td>No session, or a revoked one</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">403</code></td>\n<td>Signed in, but not allowed</td>\n<td>Stop retrying with the same credentials</td>\n<td>A member calling an admin endpoint</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">404</code></td>\n<td>Not found, or not yours</td>\n<td>Treat the resource as missing</td>\n<td>Another user’s invoice</td>\n</tr>\n</tbody>\n</table>\n<p><a href=\"https://www.rfc-editor.org/rfc/rfc9110#section-15.5.2\" target=\"_blank\" rel=\"nofollow\">RFC 9110</a> adds two rules that are easy to miss. A server sending a <code class=\"language-text\">401</code> “MUST send a WWW-Authenticate header field” naming at least one way to authenticate. And a server that wants to hide a resource from someone who can’t access it <a href=\"https://www.rfc-editor.org/rfc/rfc9110#section-15.5.4\" target=\"_blank\" rel=\"nofollow\">“MAY instead respond with a status code of 404”</a>. The DAL makes that one free: its ownership filter returns nothing for another user’s invoice, so the handler can’t tell it apart from one that doesn’t exist.</p>\n<h3 id=\"bearer-tokens-for-non-browser-clients\" style=\"position:relative;\"><a href=\"#bearer-tokens-for-non-browser-clients\" aria-label=\"bearer tokens for non browser clients permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Bearer Tokens for Non-Browser Clients</h3>\n<p>Mobile apps and CLIs usually send an <code class=\"language-text\">Authorization: Bearer</code> header instead of a cookie. The DAL needs one small change to accept both:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"47403260843351540000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// lib/dal/session.ts\nimport { cookies, headers } from 'next/headers'\n\n// Browsers never attach a bearer token on their own, which matters for CSRF later\nexport function bearerToken(requestHeaders: Pick<Headers, 'get'>): string | undefined {\n  return requestHeaders.get('authorization')?.match(/^Bearer\\s+(\\S+)\\$/i)?.[1]\n}\n\n// The only provider-specific code in the DAL. Swap this body for your auth library.\nasync function readSession(): Promise<Session | null> {\n  // Mobile apps and CLIs send the same token in an Authorization header\n  const token = bearerToken(await headers()) ?? (await cookies()).get('session')?.value\n  if (!token) return null\n\n  // ...unchanged from here: verify the signature, then check the session row\n}`, `47403260843351540000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// lib/dal/session.ts</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> cookies<span class=\"token punctuation\">,</span> headers <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/headers'</span>\n\n<span class=\"token comment\">// Browsers never attach a bearer token on their own, which matters for CSRF later</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">function</span> <span class=\"token function\">bearerToken</span><span class=\"token punctuation\">(</span>requestHeaders<span class=\"token operator\">:</span> Pick<span class=\"token operator\">&lt;</span>Headers<span class=\"token punctuation\">,</span> <span class=\"token string\">'get'</span><span class=\"token operator\">></span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">string</span> <span class=\"token operator\">|</span> <span class=\"token keyword\">undefined</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">return</span> requestHeaders<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'authorization'</span><span class=\"token punctuation\">)</span><span class=\"token operator\">?.</span><span class=\"token function\">match</span><span class=\"token punctuation\">(</span><span class=\"token regex\"><span class=\"token regex-delimiter\">/</span><span class=\"token regex-source language-regex\">^Bearer\\s+(\\S+)$</span><span class=\"token regex-delimiter\">/</span><span class=\"token regex-flags\">i</span></span><span class=\"token punctuation\">)</span><span class=\"token operator\">?.</span><span class=\"token punctuation\">[</span><span class=\"token number\">1</span><span class=\"token punctuation\">]</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token comment\">// The only provider-specific code in the DAL. Swap this body for your auth library.</span>\n<span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">readSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>Session <span class=\"token operator\">|</span> <span class=\"token keyword\">null</span><span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token comment\">// Mobile apps and CLIs send the same token in an Authorization header</span>\n  <span class=\"token keyword\">const</span> token <span class=\"token operator\">=</span> <span class=\"token function\">bearerToken</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">await</span> <span class=\"token function\">headers</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">??</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">await</span> <span class=\"token function\">cookies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'session'</span><span class=\"token punctuation\">)</span><span class=\"token operator\">?.</span>value\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>token<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token keyword\">null</span>\n\n  <span class=\"token comment\">// ...unchanged from here: verify the signature, then check the session row</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Export <code class=\"language-text\">bearerToken</code> from <code class=\"language-text\">lib/dal/index.ts</code> too, since the wrapper below uses it. The bearer token is the same signed token the cookie carries, so the database check, revocation, and roles work the same way for both. The session strategy section covers how an app gets that token and refreshes it.</p>\n<h3 id=\"one-wrapper-for-every-handler\" style=\"position:relative;\"><a href=\"#one-wrapper-for-every-handler\" aria-label=\"one wrapper for every handler permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>One Wrapper for Every Handler</h3>\n<p>Every handler needs the same three things on top of the DAL: refusals turned into status codes, a CSRF check for cookie-authenticated writes, and a cache header for per-user responses. Server Actions get an <code class=\"language-text\">Origin</code> check from Next.js. Route Handlers don’t, and the <a href=\"https://nextjs.org/blog/security-nextjs-server-components-actions#csrf\" target=\"_blank\" rel=\"nofollow\">Next.js security post</a> says so plainly: in Route Handlers, “CSRF protection has to be done manually.”</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"65125089558391330000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// lib/api/handler.ts\nimport 'server-only'\nimport { AuthError, bearerToken } from '@/lib/dal'\n\ntype Handler<Ctx> = (request: Request, context: Ctx) => Promise<Response>\n\n// Server Actions get this check from Next.js. Route Handlers don't.\nfunction isCrossSiteCookieWrite(request: Request): boolean {\n  if (['GET', 'HEAD', 'OPTIONS'].includes(request.method)) return false\n  if (bearerToken(request.headers)) return false // a cross-site page can't attach the user's token\n  const origin = request.headers.get('origin')\n  if (origin === null) return false // not a browser: browsers send Origin on every write\n  if (!URL.canParse(origin)) return true // includes 'null' from sandboxed iframes\n  const host = request.headers.get('x-forwarded-host') ?? request.headers.get('host')\n  return new URL(origin).host !== host\n}\n\nexport function apiHandler<Ctx>(handler: Handler<Ctx>): Handler<Ctx> {\n  return async (request, context) => {\n    if (isCrossSiteCookieWrite(request)) {\n      return Response.json({ error: 'Cross-site request' }, { status: 403 })\n    }\n\n    let response: Response\n    try {\n      response = await handler(request, context)\n    } catch (error) {\n      if (!(error instanceof AuthError)) throw error // a database outage stays a 500\n      // RFC 9110 requires a challenge on every 401. RFC 6750 defines this one.\n      const challenge = bearerToken(request.headers) ? 'Bearer error=&quot;invalid_token&quot;' : 'Bearer'\n      return Response.json(\n        { error: error.message },\n        { status: error.status, headers: error.status === 401 ? { 'WWW-Authenticate': challenge } : {} },\n      )\n    }\n\n    // Next.js sets no Cache-Control on dynamic Route Handler responses, and these carry per-user data\n    if (response.headers.has('Cache-Control')) return response\n    const uncached = new Response(response.body, response) // a fetched Response has read-only headers\n    uncached.headers.set('Cache-Control', 'private, no-store')\n    return uncached\n  }\n}`, `65125089558391330000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// lib/api/handler.ts</span>\n<span class=\"token keyword\">import</span> <span class=\"token string\">'server-only'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> AuthError<span class=\"token punctuation\">,</span> bearerToken <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/dal'</span>\n\n<span class=\"token keyword\">type</span> <span class=\"token class-name\">Handler<span class=\"token operator\">&lt;</span>Ctx<span class=\"token operator\">></span></span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">(</span>request<span class=\"token operator\">:</span> Request<span class=\"token punctuation\">,</span> context<span class=\"token operator\">:</span> Ctx<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>Response<span class=\"token operator\">></span>\n\n<span class=\"token comment\">// Server Actions get this check from Next.js. Route Handlers don't.</span>\n<span class=\"token keyword\">function</span> <span class=\"token function\">isCrossSiteCookieWrite</span><span class=\"token punctuation\">(</span>request<span class=\"token operator\">:</span> Request<span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">boolean</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">[</span><span class=\"token string\">'GET'</span><span class=\"token punctuation\">,</span> <span class=\"token string\">'HEAD'</span><span class=\"token punctuation\">,</span> <span class=\"token string\">'OPTIONS'</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">.</span><span class=\"token function\">includes</span><span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">.</span>method<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token boolean\">false</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token function\">bearerToken</span><span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">.</span>headers<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token boolean\">false</span> <span class=\"token comment\">// a cross-site page can't attach the user's token</span>\n  <span class=\"token keyword\">const</span> origin <span class=\"token operator\">=</span> request<span class=\"token punctuation\">.</span>headers<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'origin'</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>origin <span class=\"token operator\">===</span> <span class=\"token keyword\">null</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token boolean\">false</span> <span class=\"token comment\">// not a browser: browsers send Origin on every write</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span><span class=\"token constant\">URL</span><span class=\"token punctuation\">.</span><span class=\"token function\">canParse</span><span class=\"token punctuation\">(</span>origin<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token boolean\">true</span> <span class=\"token comment\">// includes 'null' from sandboxed iframes</span>\n  <span class=\"token keyword\">const</span> host <span class=\"token operator\">=</span> request<span class=\"token punctuation\">.</span>headers<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'x-forwarded-host'</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">??</span> request<span class=\"token punctuation\">.</span>headers<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'host'</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token constant\">URL</span></span><span class=\"token punctuation\">(</span>origin<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span>host <span class=\"token operator\">!==</span> host\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">function</span> <span class=\"token generic-function\"><span class=\"token function\">apiHandler</span><span class=\"token generic class-name\"><span class=\"token operator\">&lt;</span>Ctx<span class=\"token operator\">></span></span></span><span class=\"token punctuation\">(</span>handler<span class=\"token operator\">:</span> Handler<span class=\"token operator\">&lt;</span>Ctx<span class=\"token operator\">></span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> Handler<span class=\"token operator\">&lt;</span>Ctx<span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">return</span> <span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">,</span> context<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token function\">isCrossSiteCookieWrite</span><span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token keyword\">return</span> Response<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'Cross-site request'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> status<span class=\"token operator\">:</span> <span class=\"token number\">403</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">}</span>\n\n    <span class=\"token keyword\">let</span> response<span class=\"token operator\">:</span> Response\n    <span class=\"token keyword\">try</span> <span class=\"token punctuation\">{</span>\n      response <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">handler</span><span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">,</span> context<span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span><span class=\"token punctuation\">(</span>error <span class=\"token keyword\">instanceof</span> <span class=\"token class-name\">AuthError</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">throw</span> error <span class=\"token comment\">// a database outage stays a 500</span>\n      <span class=\"token comment\">// RFC 9110 requires a challenge on every 401. RFC 6750 defines this one.</span>\n      <span class=\"token keyword\">const</span> challenge <span class=\"token operator\">=</span> <span class=\"token function\">bearerToken</span><span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">.</span>headers<span class=\"token punctuation\">)</span> <span class=\"token operator\">?</span> <span class=\"token string\">'Bearer error=\"invalid_token\"'</span> <span class=\"token operator\">:</span> <span class=\"token string\">'Bearer'</span>\n      <span class=\"token keyword\">return</span> Response<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span>\n        <span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> error<span class=\"token punctuation\">.</span>message <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n        <span class=\"token punctuation\">{</span> status<span class=\"token operator\">:</span> error<span class=\"token punctuation\">.</span>status<span class=\"token punctuation\">,</span> headers<span class=\"token operator\">:</span> error<span class=\"token punctuation\">.</span>status <span class=\"token operator\">===</span> <span class=\"token number\">401</span> <span class=\"token operator\">?</span> <span class=\"token punctuation\">{</span> <span class=\"token string-property property\">'WWW-Authenticate'</span><span class=\"token operator\">:</span> challenge <span class=\"token punctuation\">}</span> <span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span><span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n      <span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">}</span>\n\n    <span class=\"token comment\">// Next.js sets no Cache-Control on dynamic Route Handler responses, and these carry per-user data</span>\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>response<span class=\"token punctuation\">.</span>headers<span class=\"token punctuation\">.</span><span class=\"token function\">has</span><span class=\"token punctuation\">(</span><span class=\"token string\">'Cache-Control'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> response\n    <span class=\"token keyword\">const</span> uncached <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Response</span><span class=\"token punctuation\">(</span>response<span class=\"token punctuation\">.</span>body<span class=\"token punctuation\">,</span> response<span class=\"token punctuation\">)</span> <span class=\"token comment\">// a fetched Response has read-only headers</span>\n    uncached<span class=\"token punctuation\">.</span>headers<span class=\"token punctuation\">.</span><span class=\"token function\">set</span><span class=\"token punctuation\">(</span><span class=\"token string\">'Cache-Control'</span><span class=\"token punctuation\">,</span> <span class=\"token string\">'private, no-store'</span><span class=\"token punctuation\">)</span>\n    <span class=\"token keyword\">return</span> uncached\n  <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Here’s how the invoice endpoints use it:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"30046004943289594000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/api/invoices/[id]/route.ts\nimport { z } from 'zod'\nimport { getInvoice, markInvoicePaid } from '@/lib/dal'\nimport { apiHandler } from '@/lib/api/handler'\n\ntype Context = { params: Promise<{ id: string }> }\n\nexport const GET = apiHandler(async (_request, { params }: Context) => {\n  const invoice = await getInvoice((await params).id)\n  // Someone else's invoice gets the same 404 as one that doesn't exist\n  if (!invoice) return Response.json({ error: 'Invoice not found' }, { status: 404 })\n  return Response.json(invoice)\n})\n\nconst PatchBody = z.object({ status: z.literal('paid') })\n\n// Each exported method is its own endpoint, so PATCH goes through the DAL too\nexport const PATCH = apiHandler(async (request, { params }: Context) => {\n  const body = PatchBody.safeParse(await request.json().catch(() => null))\n  if (!body.success) return Response.json({ error: 'Invalid body' }, { status: 400 })\n\n  const updated = await markInvoicePaid((await params).id)\n  if (!updated) return Response.json({ error: 'Invoice not found' }, { status: 404 })\n  return new Response(null, { status: 204 })\n})`, `30046004943289594000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// app/api/invoices/[id]/route.ts</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> z <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'zod'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> getInvoice<span class=\"token punctuation\">,</span> markInvoicePaid <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/dal'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> apiHandler <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/api/handler'</span>\n\n<span class=\"token keyword\">type</span> <span class=\"token class-name\">Context</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span> params<span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span><span class=\"token punctuation\">{</span> id<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span> <span class=\"token punctuation\">}</span><span class=\"token operator\">></span> <span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">const</span> <span class=\"token constant\">GET</span> <span class=\"token operator\">=</span> <span class=\"token function\">apiHandler</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span>_request<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> params <span class=\"token punctuation\">}</span><span class=\"token operator\">:</span> Context<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> invoice <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">getInvoice</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">await</span> params<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span>id<span class=\"token punctuation\">)</span>\n  <span class=\"token comment\">// Someone else's invoice gets the same 404 as one that doesn't exist</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>invoice<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> Response<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'Invoice not found'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> status<span class=\"token operator\">:</span> <span class=\"token number\">404</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> Response<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span>invoice<span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n\n<span class=\"token keyword\">const</span> PatchBody <span class=\"token operator\">=</span> z<span class=\"token punctuation\">.</span><span class=\"token function\">object</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> status<span class=\"token operator\">:</span> z<span class=\"token punctuation\">.</span><span class=\"token function\">literal</span><span class=\"token punctuation\">(</span><span class=\"token string\">'paid'</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n\n<span class=\"token comment\">// Each exported method is its own endpoint, so PATCH goes through the DAL too</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">const</span> <span class=\"token constant\">PATCH</span> <span class=\"token operator\">=</span> <span class=\"token function\">apiHandler</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> params <span class=\"token punctuation\">}</span><span class=\"token operator\">:</span> Context<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> body <span class=\"token operator\">=</span> PatchBody<span class=\"token punctuation\">.</span><span class=\"token function\">safeParse</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">await</span> request<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">catch</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token keyword\">null</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>body<span class=\"token punctuation\">.</span>success<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> Response<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'Invalid body'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> status<span class=\"token operator\">:</span> <span class=\"token number\">400</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">const</span> updated <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">markInvoicePaid</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">await</span> params<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span>id<span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>updated<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> Response<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'Invoice not found'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> status<span class=\"token operator\">:</span> <span class=\"token number\">404</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Response</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">null</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> status<span class=\"token operator\">:</span> <span class=\"token number\">204</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span></code></pre></div>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"13034114756180392000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/api/admin/overdue/route.ts\nimport { getOverdueInvoices } from '@/lib/dal'\nimport { apiHandler } from '@/lib/api/handler'\n\n// requireRole('admin') inside the DAL: 401 when signed out, 403 for members\nexport const GET = apiHandler(async () => Response.json(await getOverdueInvoices()))`, `13034114756180392000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// app/api/admin/overdue/route.ts</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> getOverdueInvoices <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/dal'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> apiHandler <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/api/handler'</span>\n\n<span class=\"token comment\">// requireRole('admin') inside the DAL: 401 when signed out, 403 for members</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">const</span> <span class=\"token constant\">GET</span> <span class=\"token operator\">=</span> <span class=\"token function\">apiHandler</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> Response<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">await</span> <span class=\"token function\">getOverdueInvoices</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span></code></pre></div>\n<p>Key implementation decisions:</p>\n<ul>\n<li><strong>The wrapper doesn’t authenticate anything.</strong> The DAL does, inside <code class=\"language-text\">getInvoice()</code> and <code class=\"language-text\">markInvoicePaid()</code>. The wrapper only translates its refusals. Anything else still throws, so a database outage stays a 500 instead of becoming a 401 that sends clients into a sign-in loop.</li>\n<li><strong>Every 401 tells the client what to send.</strong> Callers without a bearer token get <code class=\"language-text\">WWW-Authenticate: Bearer</code>. A bearer caller whose token failed gets <code class=\"language-text\">error=\"invalid_token\"</code>, which <a href=\"https://datatracker.ietf.org/doc/html/rfc6750#section-3.1\" target=\"_blank\" rel=\"nofollow\">RFC 6750</a> uses for a token that’s “expired, revoked, malformed, or invalid for other reasons.” That’s the client’s cue to refresh once and retry.</li>\n<li><strong>The CSRF check only runs when a cookie is the credential.</strong> Browsers attach cookies automatically, which is what CSRF exploits, but they never attach a bearer token on their own. <code class=\"language-text\">SameSite=Lax</code> cookies already stop most cross-site writes, and the <code class=\"language-text\">Origin</code> check covers what they don’t, like a request from a sibling subdomain. A missing <code class=\"language-text\">Origin</code> means a non-browser client, since <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Origin\" target=\"_blank\" rel=\"nofollow\">browsers send one</a> with every POST, PUT, PATCH, and DELETE.</li>\n<li><strong>Per-user responses get <code class=\"language-text\">private, no-store</code>.</strong> Next.js sends a no-store header with dynamic pages, but in the test app, Route Handler responses had no <code class=\"language-text\">Cache-Control</code> at all, including 200s carrying a user’s invoice. <a href=\"https://www.rfc-editor.org/rfc/rfc9111#section-3.5\" target=\"_blank\" rel=\"nofollow\">RFC 9111</a> keeps shared caches from reusing responses to requests with an <code class=\"language-text\">Authorization</code> header, so bearer calls are covered by the spec. Cookie calls aren’t.</li>\n<li><strong>Each exported method is its own endpoint.</strong> <code class=\"language-text\">GET</code> and <code class=\"language-text\">PATCH</code> each call the DAL. A check in one doesn’t protect the other, and a method the file doesn’t export gets an automatic <code class=\"language-text\">405</code>.</li>\n</ul>\n<h3 id=\"what-the-handlers-returned\" style=\"position:relative;\"><a href=\"#what-the-handlers-returned\" aria-label=\"what the handlers returned permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>What the Handlers Returned</h3>\n<p>Here’s what the finished handlers returned on Next.js 16.4.2:</p>\n<table>\n<thead>\n<tr>\n<th>Request</th>\n<th>Response</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>No credentials, from <code class=\"language-text\">curl</code> or <code class=\"language-text\">fetch()</code></td>\n<td><code class=\"language-text\">401</code>, <code class=\"language-text\">WWW-Authenticate: Bearer</code>, nothing to follow</td>\n</tr>\n<tr>\n<td>Revoked or malformed bearer token</td>\n<td><code class=\"language-text\">401</code>, <code class=\"language-text\">WWW-Authenticate: Bearer error=\"invalid_token\"</code></td>\n</tr>\n<tr>\n<td>Member reading another user’s invoice</td>\n<td><code class=\"language-text\">404</code>, same body as a missing invoice</td>\n</tr>\n<tr>\n<td>Member calling <code class=\"language-text\">/api/admin/overdue</code></td>\n<td><code class=\"language-text\">403</code></td>\n</tr>\n<tr>\n<td>Cookie <code class=\"language-text\">PATCH</code> with a cross-site or <code class=\"language-text\">null</code> <code class=\"language-text\">Origin</code></td>\n<td><code class=\"language-text\">403</code> before the handler ran</td>\n</tr>\n<tr>\n<td>Bearer <code class=\"language-text\">PATCH</code> with a cross-site <code class=\"language-text\">Origin</code></td>\n<td><code class=\"language-text\">204</code>, since bearer calls skip the CSRF check</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">DELETE</code>, which the file doesn’t export</td>\n<td><code class=\"language-text\">405</code></td>\n</tr>\n</tbody>\n</table>\n<h3 id=\"prerendered-handlers-are-public\" style=\"position:relative;\"><a href=\"#prerendered-handlers-are-public\" aria-label=\"prerendered handlers are public permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Prerendered Handlers Are Public</h3>\n<p>Turning on Cache Components raises the cost of skipping the check. A <code class=\"language-text\">GET</code> handler that never touches request data can then be <a href=\"https://nextjs.org/docs/app/getting-started/route-handlers#with-cache-components\" target=\"_blank\" rel=\"nofollow\">prerendered at build time</a>, and <code class=\"language-text\">'use cache'</code> lets database results into that prerender. In the test app, an admin stats handler with no check of its own sat outside the Proxy matcher. It was built once and served to a signed-out request with <code class=\"language-text\">Cache-Control: s-maxage=3600</code>, an invitation for any CDN in front of it to keep a copy for an hour. A handler that calls the DAL reads cookies and headers, which stops prerendering, so it always runs per request.</p>\n<p>Redirects are for people. Status codes are for everything else.</p>\n<h2 id=\"middleware-at-the-edge-what-its-for-and-what-it-isnt\" style=\"position:relative;\"><a href=\"#middleware-at-the-edge-what-its-for-and-what-it-isnt\" aria-label=\"middleware at the edge what its for and what it isnt permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Middleware at the Edge: What It’s For and What It Isn’t</h2>\n<p>Next.js 16 moved <a href=\"https://supertokens.com/blog/enhancing-your-nextjs-application-with-middleware\" target=\"_blank\" rel=\"nofollow\">middleware</a> off the Edge runtime and renamed it Proxy. The <a href=\"https://nextjs.org/docs/app/guides/upgrading/version-16#middleware-to-proxy\" target=\"_blank\" rel=\"nofollow\">upgrade guide</a> says so in capitals: “The <code class=\"language-text\">edge</code> runtime is NOT supported in <code class=\"language-text\">proxy</code>.” Apps that still want Edge can keep the deprecated <code class=\"language-text\">middleware.ts</code>. Either way, the job is the same, and the <a href=\"https://nextjs.org/docs/app/getting-started/proxy#use-cases\" target=\"_blank\" rel=\"nofollow\">Proxy docs</a> set its limit in one line: Proxy “should not be used as a full session management or authorization solution.” This section covers what that leaves Proxy to do, and builds one that runs on both runtimes.</p>\n<h3 id=\"what-a-token-check-can-know\" style=\"position:relative;\"><a href=\"#what-a-token-check-can-know\" aria-label=\"what a token check can know permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>What a Token Check Can Know</h3>\n<p>Wherever it runs, Proxy works from what the request carries. Without a database call, that’s the token’s signature, its expiry, and the claims inside it:</p>\n<table>\n<thead>\n<tr>\n<th>Question</th>\n<th>Proxy, from the token</th>\n<th>DAL, from the database</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Did we issue this token?</td>\n<td>Yes, from the signature</td>\n<td>Yes</td>\n</tr>\n<tr>\n<td>Has it expired?</td>\n<td>Yes</td>\n<td>Yes</td>\n</tr>\n<tr>\n<td>Was the session revoked?</td>\n<td>No</td>\n<td>Yes</td>\n</tr>\n<tr>\n<td>What’s the user’s role right now?</td>\n<td>Only what the token said when it was issued</td>\n<td>Yes</td>\n</tr>\n<tr>\n<td>Does this record belong to them?</td>\n<td>No</td>\n<td>Yes, in the query</td>\n</tr>\n</tbody>\n</table>\n<p>Proxy on Node.js could make that database call now. The <a href=\"https://nextjs.org/docs/app/guides/authentication#optimistic-checks-with-proxy-optional\" target=\"_blank\" rel=\"nofollow\">authentication guide</a> still says not to, because Proxy runs on every matched route, prefetches included. On Next.js 16.4.2, one view of a page with ten links ran Proxy 15 times: once for the page and 14 times for prefetches. With Cache Components and partial prefetching on, it ran 6 times. A session lookup in Proxy would have run on every one of those. Add the matcher gaps from the Server Actions section and the bypasses from the CVE section, and Proxy is a fast first answer, never the final one.</p>\n<h3 id=\"an-edge-compatible-proxy\" style=\"position:relative;\"><a href=\"#an-edge-compatible-proxy\" aria-label=\"an edge compatible proxy permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>An Edge-Compatible Proxy</h3>\n<p>This version uses <a href=\"https://github.com/panva/jose\" target=\"_blank\" rel=\"nofollow\">jose</a>, which verifies tokens with Web Crypto, so the same file runs as <code class=\"language-text\">proxy.ts</code> on Node.js or as <code class=\"language-text\">middleware.ts</code> on the Edge runtime. It reads the token the way the DAL does, bearer header first, then cookie, and sorts every request into one of four states:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"51460587141987250000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// proxy.ts\nimport { NextResponse, type NextRequest } from 'next/server'\nimport { errors, jwtVerify } from 'jose'\n\n// Deny by default: any route not listed here needs a session\nconst PUBLIC_PATHS = ['/', '/login', '/signup', '/refresh', '/api/auth']\n\nfunction isPublic(pathname: string) {\n  return PUBLIC_PATHS.some((path) => pathname === path || (path !== '/' && pathname.startsWith(\\`\\${path}/\\`)))\n}\n\ntype TokenState = 'valid' | 'expired' | 'missing' | 'invalid'\n\n// Signature and expiry only. No database, so no revocation, roles, or ownership.\nasync function readTokenState(request: NextRequest): Promise<TokenState> {\n  const bearer = request.headers.get('authorization')?.match(/^Bearer\\s+(\\S+)\\$/i)?.[1]\n  const token = bearer ?? request.cookies.get('session')?.value // same order as the DAL\n  if (!token) return 'missing'\n\n  const secret = process.env.SESSION_SECRET\n  if (!secret) throw new Error('SESSION_SECRET is not set')\n  try {\n    await jwtVerify(token, new TextEncoder().encode(secret), { algorithms: ['HS256'] })\n    return 'valid'\n  } catch (error) {\n    if (!(error instanceof errors.JOSEError)) throw error // a broken runtime isn't a bad token\n    // jose checks the signature before the expiry, so an expired token is still one we issued\n    return error instanceof errors.JWTExpired ? 'expired' : 'invalid'\n  }\n}\n\nexport async function proxy(request: NextRequest) {\n  const { pathname, search } = request.nextUrl\n  if (isPublic(pathname)) return NextResponse.next()\n\n  const state = await readTokenState(request)\n  if (state === 'valid') return NextResponse.next()\n\n  if (pathname.startsWith('/api/')) {\n    const challenge = state === 'missing' ? 'Bearer' : 'Bearer error=&quot;invalid_token&quot;'\n    return Response.json(\n      { error: 'Authentication required' },\n      { status: 401, headers: { 'WWW-Authenticate': challenge } },\n    )\n  }\n\n  // Server Actions and other writes check for themselves, in a format their caller can read\n  if (request.method !== 'GET' && request.method !== 'HEAD') return NextResponse.next()\n\n  // An expired token isn't a signed-out user. Send them to refresh, not to sign in.\n  const destination = new URL(state === 'expired' ? '/refresh' : '/login', request.url)\n  destination.searchParams.set('next', pathname + search)\n  return NextResponse.redirect(destination)\n}\n\nexport const config = {\n  // Everything except build output, crawler files, and images, so new routes are covered by default\n  matcher: ['/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml|.*\\\\.(?:png|jpg|jpeg|gif|svg|webp|ico)\\$).*)'],\n}`, `51460587141987250000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// proxy.ts</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> NextResponse<span class=\"token punctuation\">,</span> <span class=\"token keyword\">type</span> <span class=\"token class-name\">NextRequest</span> <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/server'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> errors<span class=\"token punctuation\">,</span> jwtVerify <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'jose'</span>\n\n<span class=\"token comment\">// Deny by default: any route not listed here needs a session</span>\n<span class=\"token keyword\">const</span> <span class=\"token constant\">PUBLIC_PATHS</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">[</span><span class=\"token string\">'/'</span><span class=\"token punctuation\">,</span> <span class=\"token string\">'/login'</span><span class=\"token punctuation\">,</span> <span class=\"token string\">'/signup'</span><span class=\"token punctuation\">,</span> <span class=\"token string\">'/refresh'</span><span class=\"token punctuation\">,</span> <span class=\"token string\">'/api/auth'</span><span class=\"token punctuation\">]</span>\n\n<span class=\"token keyword\">function</span> <span class=\"token function\">isPublic</span><span class=\"token punctuation\">(</span>pathname<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">return</span> <span class=\"token constant\">PUBLIC_PATHS</span><span class=\"token punctuation\">.</span><span class=\"token function\">some</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span>path<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> pathname <span class=\"token operator\">===</span> path <span class=\"token operator\">||</span> <span class=\"token punctuation\">(</span>path <span class=\"token operator\">!==</span> <span class=\"token string\">'/'</span> <span class=\"token operator\">&amp;&amp;</span> pathname<span class=\"token punctuation\">.</span><span class=\"token function\">startsWith</span><span class=\"token punctuation\">(</span><span class=\"token template-string\"><span class=\"token template-punctuation string\">`</span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${</span>path<span class=\"token interpolation-punctuation punctuation\">}</span></span><span class=\"token string\">/</span><span class=\"token template-punctuation string\">`</span></span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">type</span> <span class=\"token class-name\">TokenState</span> <span class=\"token operator\">=</span> <span class=\"token string\">'valid'</span> <span class=\"token operator\">|</span> <span class=\"token string\">'expired'</span> <span class=\"token operator\">|</span> <span class=\"token string\">'missing'</span> <span class=\"token operator\">|</span> <span class=\"token string\">'invalid'</span>\n\n<span class=\"token comment\">// Signature and expiry only. No database, so no revocation, roles, or ownership.</span>\n<span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">readTokenState</span><span class=\"token punctuation\">(</span>request<span class=\"token operator\">:</span> NextRequest<span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>TokenState<span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> bearer <span class=\"token operator\">=</span> request<span class=\"token punctuation\">.</span>headers<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'authorization'</span><span class=\"token punctuation\">)</span><span class=\"token operator\">?.</span><span class=\"token function\">match</span><span class=\"token punctuation\">(</span><span class=\"token regex\"><span class=\"token regex-delimiter\">/</span><span class=\"token regex-source language-regex\">^Bearer\\s+(\\S+)$</span><span class=\"token regex-delimiter\">/</span><span class=\"token regex-flags\">i</span></span><span class=\"token punctuation\">)</span><span class=\"token operator\">?.</span><span class=\"token punctuation\">[</span><span class=\"token number\">1</span><span class=\"token punctuation\">]</span>\n  <span class=\"token keyword\">const</span> token <span class=\"token operator\">=</span> bearer <span class=\"token operator\">??</span> request<span class=\"token punctuation\">.</span>cookies<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'session'</span><span class=\"token punctuation\">)</span><span class=\"token operator\">?.</span>value <span class=\"token comment\">// same order as the DAL</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>token<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token string\">'missing'</span>\n\n  <span class=\"token keyword\">const</span> secret <span class=\"token operator\">=</span> process<span class=\"token punctuation\">.</span>env<span class=\"token punctuation\">.</span><span class=\"token constant\">SESSION_SECRET</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>secret<span class=\"token punctuation\">)</span> <span class=\"token keyword\">throw</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Error</span><span class=\"token punctuation\">(</span><span class=\"token string\">'SESSION_SECRET is not set'</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">try</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">await</span> <span class=\"token function\">jwtVerify</span><span class=\"token punctuation\">(</span>token<span class=\"token punctuation\">,</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">TextEncoder</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">encode</span><span class=\"token punctuation\">(</span>secret<span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> algorithms<span class=\"token operator\">:</span> <span class=\"token punctuation\">[</span><span class=\"token string\">'HS256'</span><span class=\"token punctuation\">]</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n    <span class=\"token keyword\">return</span> <span class=\"token string\">'valid'</span>\n  <span class=\"token punctuation\">}</span> <span class=\"token keyword\">catch</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span><span class=\"token punctuation\">(</span>error <span class=\"token keyword\">instanceof</span> <span class=\"token class-name\">errors</span><span class=\"token punctuation\">.</span>JOSEError<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">throw</span> error <span class=\"token comment\">// a broken runtime isn't a bad token</span>\n    <span class=\"token comment\">// jose checks the signature before the expiry, so an expired token is still one we issued</span>\n    <span class=\"token keyword\">return</span> error <span class=\"token keyword\">instanceof</span> <span class=\"token class-name\">errors</span><span class=\"token punctuation\">.</span>JWTExpired <span class=\"token operator\">?</span> <span class=\"token string\">'expired'</span> <span class=\"token operator\">:</span> <span class=\"token string\">'invalid'</span>\n  <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">proxy</span><span class=\"token punctuation\">(</span>request<span class=\"token operator\">:</span> NextRequest<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> pathname<span class=\"token punctuation\">,</span> search <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> request<span class=\"token punctuation\">.</span>nextUrl\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token function\">isPublic</span><span class=\"token punctuation\">(</span>pathname<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">next</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">const</span> state <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">readTokenState</span><span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>state <span class=\"token operator\">===</span> <span class=\"token string\">'valid'</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">next</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>pathname<span class=\"token punctuation\">.</span><span class=\"token function\">startsWith</span><span class=\"token punctuation\">(</span><span class=\"token string\">'/api/'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">const</span> challenge <span class=\"token operator\">=</span> state <span class=\"token operator\">===</span> <span class=\"token string\">'missing'</span> <span class=\"token operator\">?</span> <span class=\"token string\">'Bearer'</span> <span class=\"token operator\">:</span> <span class=\"token string\">'Bearer error=\"invalid_token\"'</span>\n    <span class=\"token keyword\">return</span> Response<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span>\n      <span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'Authentication required'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n      <span class=\"token punctuation\">{</span> status<span class=\"token operator\">:</span> <span class=\"token number\">401</span><span class=\"token punctuation\">,</span> headers<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> <span class=\"token string-property property\">'WWW-Authenticate'</span><span class=\"token operator\">:</span> challenge <span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">)</span>\n  <span class=\"token punctuation\">}</span>\n\n  <span class=\"token comment\">// Server Actions and other writes check for themselves, in a format their caller can read</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">.</span>method <span class=\"token operator\">!==</span> <span class=\"token string\">'GET'</span> <span class=\"token operator\">&amp;&amp;</span> request<span class=\"token punctuation\">.</span>method <span class=\"token operator\">!==</span> <span class=\"token string\">'HEAD'</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">next</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token comment\">// An expired token isn't a signed-out user. Send them to refresh, not to sign in.</span>\n  <span class=\"token keyword\">const</span> destination <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token constant\">URL</span></span><span class=\"token punctuation\">(</span>state <span class=\"token operator\">===</span> <span class=\"token string\">'expired'</span> <span class=\"token operator\">?</span> <span class=\"token string\">'/refresh'</span> <span class=\"token operator\">:</span> <span class=\"token string\">'/login'</span><span class=\"token punctuation\">,</span> request<span class=\"token punctuation\">.</span>url<span class=\"token punctuation\">)</span>\n  destination<span class=\"token punctuation\">.</span>searchParams<span class=\"token punctuation\">.</span><span class=\"token function\">set</span><span class=\"token punctuation\">(</span><span class=\"token string\">'next'</span><span class=\"token punctuation\">,</span> pathname <span class=\"token operator\">+</span> search<span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">redirect</span><span class=\"token punctuation\">(</span>destination<span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">const</span> config <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token comment\">// Everything except build output, crawler files, and images, so new routes are covered by default</span>\n  matcher<span class=\"token operator\">:</span> <span class=\"token punctuation\">[</span><span class=\"token string\">'/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml|.*\\\\.(?:png|jpg|jpeg|gif|svg|webp|ico)$).*)'</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">,</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Key implementation decisions:</p>\n<ul>\n<li><strong>Deny by default.</strong> Every route needs a session unless <code class=\"language-text\">PUBLIC_PATHS</code> lists it, so a page someone adds next month is covered on day one. The <a href=\"https://nextjs.org/blog/security-nextjs-server-components-actions#custom-routes-and-middleware\" target=\"_blank\" rel=\"nofollow\">Next.js security post</a> recommends the same for middleware: “an allow list rather than a deny list.” The cost is that public routes need listing too. In the test app, <code class=\"language-text\">/.well-known/security.txt</code> redirected to the login page because nobody had listed it.</li>\n<li><strong>Expired isn’t signed out.</strong> An expired token’s owner probably still has a valid refresh token, so Proxy sends them to <code class=\"language-text\">/refresh</code> instead of <code class=\"language-text\">/login</code>, and API callers get the <code class=\"language-text\">invalid_token</code> challenge from the Route Handler section. Proxy doesn’t refresh the token itself. Parallel requests and prefetches would each try to spend the same refresh token, and under <a href=\"https://www.rfc-editor.org/rfc/rfc9700#section-4.14\" target=\"_blank\" rel=\"nofollow\">refresh token rotation</a> a reused token looks like theft, so the server revokes the session. The session strategy section builds <code class=\"language-text\">/refresh</code>.</li>\n<li><strong>Only page loads get redirects.</strong> Server Actions and other writes pass through and check for themselves. In the test app, a Server Action called with an expired token returned “Authentication required” to the page. When a test version of Proxy redirected that POST instead, the action threw “An unexpected response was received from the server.”</li>\n<li><strong><code class=\"language-text\">next</code> is user input.</strong> The login and refresh pages should only follow it to a local path, the same rule the Next.js docs apply to <a href=\"https://nextjs.org/docs/app/guides/backend-for-frontend#webhooks-and-callback-urls\" target=\"_blank\" rel=\"nofollow\">callback URLs</a>. Otherwise it’s an open redirect.</li>\n</ul>\n<p>One thing is missing on purpose: Proxy forwards nothing about the user in a header. As the CVE section showed, a header is only as trustworthy as the code that set it, and that’s the code a bypass skips.</p>\n<h3 id=\"what-it-returned\" style=\"position:relative;\"><a href=\"#what-it-returned\" aria-label=\"what it returned permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>What It Returned</h3>\n<p>Here’s what the Proxy above returned on Next.js 16.4.2:</p>\n<table>\n<thead>\n<tr>\n<th>Request</th>\n<th>Proxy’s answer</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Page, no token or a forged one</td>\n<td><code class=\"language-text\">307</code> to <code class=\"language-text\">/login?next=…</code></td>\n</tr>\n<tr>\n<td>Page, expired token</td>\n<td><code class=\"language-text\">307</code> to <code class=\"language-text\">/refresh?next=…</code></td>\n</tr>\n<tr>\n<td>Page, forged token with a past expiry</td>\n<td><code class=\"language-text\">307</code> to <code class=\"language-text\">/login</code>, because the signature failed first</td>\n</tr>\n<tr>\n<td>API, no token</td>\n<td><code class=\"language-text\">401</code>, <code class=\"language-text\">WWW-Authenticate: Bearer</code></td>\n</tr>\n<tr>\n<td>API, expired or forged token</td>\n<td><code class=\"language-text\">401</code>, <code class=\"language-text\">WWW-Authenticate: Bearer error=\"invalid_token\"</code></td>\n</tr>\n<tr>\n<td>Server Action, expired token</td>\n<td>Passed through; the action returned “Authentication required”</td>\n</tr>\n<tr>\n<td>Revoked session, valid signature</td>\n<td>Passed through; the page’s DAL check redirected it to <code class=\"language-text\">/login</code></td>\n</tr>\n</tbody>\n</table>\n<p>The same file as <code class=\"language-text\">middleware.ts</code>, with the function renamed <code class=\"language-text\">middleware</code>, returned identical results on the Edge runtime. The revoked row is the first table in this section at work: the token was real, so Proxy let it in, and only the DAL knew it no longer counted.</p>\n<h3 id=\"staying-on-the-edge\" style=\"position:relative;\"><a href=\"#staying-on-the-edge\" aria-label=\"staying on the edge permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Staying on the Edge</h3>\n<p>Next.js 16.4.2 still runs <code class=\"language-text\">middleware.ts</code> on the Edge runtime, with a build warning: <code class=\"language-text\">The \"middleware\" file convention is deprecated. Please use \"proxy\" instead.</code> Keeping both files fails the build, and so does asking <code class=\"language-text\">proxy.ts</code> for Edge, with “Proxy does not support Edge runtime.” The upgrade guide’s checklist covers the migration in one line: “Edge middleware is not blindly renamed to proxy.”</p>\n<p>If you stay on Edge, the constraint that bites is libraries. The <a href=\"https://nextjs.org/docs/app/api-reference/edge\" target=\"_blank\" rel=\"nofollow\">Edge runtime</a> has Web APIs, not Node.js built-ins. In the test app, a <code class=\"language-text\">middleware.ts</code> that verified tokens with jsonwebtoken, a widely used JWT library built on Node’s <code class=\"language-text\">crypto</code> module, built with no complaint about the library. At runtime, every valid session went to <code class=\"language-text\">/login</code>: the library threw “The edge runtime does not support Node.js ‘crypto’ module,” and the middleware’s <code class=\"language-text\">catch</code> block read that as a bad token. That’s why the Proxy above uses jose and rethrows anything that isn’t one of jose’s own errors. A runtime that can’t verify tokens should fail loudly, not sign everyone out.</p>\n<p>Proxy can tell you a token is real. Only the DAL can tell you it still counts.</p>\n<h2 id=\"session-and-token-strategy\" style=\"position:relative;\"><a href=\"#session-and-token-strategy\" aria-label=\"session and token strategy permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Session and Token Strategy</h2>\n<p>The DAL section assumed sign-in had already set a signed cookie with a session ID in it. This section builds that side. A session here is <a href=\"https://supertokens.com/blog/all-you-need-to-know-about-user-session-security\" target=\"_blank\" rel=\"nofollow\">two tokens with two jobs</a>. The access token is short-lived, and Proxy and the DAL verify it on every request. The refresh token is long-lived, goes to exactly one endpoint, and works exactly once.</p>\n<h3 id=\"two-tokens-two-jobs\" style=\"position:relative;\"><a href=\"#two-tokens-two-jobs\" aria-label=\"two tokens two jobs permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Two Tokens, Two Jobs</h3>\n<table>\n<thead>\n<tr>\n<th></th>\n<th>Access token</th>\n<th>Refresh token</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>What it is</td>\n<td>Signed <a href=\"https://supertokens.com/blog/what-is-jwt\" target=\"_blank\" rel=\"nofollow\">JWT</a> holding the session ID</td>\n<td>32 random bytes, stored only as a hash</td>\n</tr>\n<tr>\n<td>Lifetime</td>\n<td>15 minutes</td>\n<td>Until the session goes idle or ends</td>\n</tr>\n<tr>\n<td>Cookie</td>\n<td><code class=\"language-text\">session</code>, <code class=\"language-text\">Path=/</code>, <code class=\"language-text\">SameSite=Lax</code></td>\n<td><code class=\"language-text\">refresh</code>, <code class=\"language-text\">Path=/api/auth/refresh</code>, <code class=\"language-text\">SameSite=Strict</code></td>\n</tr>\n<tr>\n<td>Read by</td>\n<td>Proxy and the DAL</td>\n<td>The refresh endpoint, nothing else</td>\n</tr>\n<tr>\n<td>Used</td>\n<td>On every request</td>\n<td>Once</td>\n</tr>\n</tbody>\n</table>\n<p>If the DAL checks the database on every request, why expire the access token at all? Because not every layer checks the database. Revoking a session takes effect immediately for anything that reads data through the DAL. The access token’s lifetime is how long the layers that only check signatures, like Proxy, keep waving a revoked session through. If nothing in your app verifies tokens without the database, one long-lived session ID is simpler, and the Next.js authentication guide covers that design as <a href=\"https://nextjs.org/docs/app/guides/authentication#database-sessions\" target=\"_blank\" rel=\"nofollow\">database sessions</a>.</p>\n<h3 id=\"issuing-and-rotating-tokens\" style=\"position:relative;\"><a href=\"#issuing-and-rotating-tokens\" aria-label=\"issuing and rotating tokens permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Issuing and Rotating Tokens</h3>\n<p>Sign-in creates a session row and both tokens. Every refresh spends one refresh token and issues a new pair. Export <code class=\"language-text\">signingKey()</code> from <code class=\"language-text\">lib/dal/session.ts</code> first, so both sides sign and verify with the same key:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"48341153242602280000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// lib/auth/tokens.ts\nimport 'server-only'\nimport { createHash, randomBytes } from 'node:crypto'\nimport { cookies } from 'next/headers'\nimport { SignJWT } from 'jose'\nimport { signingKey } from '@/lib/dal/session'\nimport { db } from '@/lib/db'\n\nconst ACCESS_TOKEN_TTL = 15 * 60 // seconds a revoked session can still get past Proxy\nconst IDLE_TIMEOUT = 7 * 24 * 60 * 60 // a week without a refresh means signing in again\nconst ABSOLUTE_TIMEOUT = 30 * 24 * 60 * 60 // 30 days after sign-in, however active the user is\nconst REFRESH_PATH = '/api/auth/refresh'\n\nexport type SessionTokens = { accessToken: string; refreshToken: string; expiresAt: Date }\n\n// Only a hash is stored, so a leaked table can't be replayed\nconst hash = (token: string) => createHash('sha256').update(token).digest('base64url')\n\nasync function issueTokens(sessionId: string, sessionEnds: Date): Promise<SessionTokens> {\n  const expiresAt = new Date(Math.min(Date.now() + IDLE_TIMEOUT * 1000, sessionEnds.getTime()))\n  const refreshToken = randomBytes(32).toString('base64url')\n  await db.refreshToken.create({ data: { hash: hash(refreshToken), sessionId, expiresAt } })\n\n  const accessToken = await new SignJWT({ sid: sessionId })\n    .setProtectedHeader({ alg: 'HS256' })\n    .setExpirationTime(\\`\\${ACCESS_TOKEN_TTL}s\\`)\n    .sign(signingKey())\n  return { accessToken, refreshToken, expiresAt }\n}\n\n// Call after your sign-in code has checked the user's credentials\nexport async function createSession(userId: string): Promise<SessionTokens> {\n  const expiresAt = new Date(Date.now() + ABSOLUTE_TIMEOUT * 1000)\n  const session = await db.session.create({ data: { userId, expiresAt }, select: { id: true } })\n  return issueTokens(session.id, expiresAt)\n}\n\n// A refresh token works once. A second use is a race or a theft, and either one ends the session.\nexport async function rotateRefreshToken(presented: string): Promise<SessionTokens | null> {\n  const record = await db.refreshToken.findUnique({\n    where: { hash: hash(presented) },\n    select: { id: true, sessionId: true, expiresAt: true, session: { select: { revokedAt: true, expiresAt: true } } },\n  })\n  if (!record || record.session.revokedAt || record.expiresAt <= new Date()) return null\n\n  // A conditional update, so two requests carrying the same token can't both win\n  const { count } = await db.refreshToken.updateMany({\n    where: { id: record.id, usedAt: null },\n    data: { usedAt: new Date() },\n  })\n  if (count !== 1) {\n    await db.session.update({ where: { id: record.sessionId }, data: { revokedAt: new Date() } })\n    return null\n  }\n  return issueTokens(record.sessionId, record.session.expiresAt)\n}\n\nexport async function setSessionCookies({ accessToken, refreshToken, expiresAt }: SessionTokens) {\n  const jar = await cookies()\n  // Outlives the 15-minute token inside it, so Proxy can tell &quot;expired&quot; from &quot;signed out&quot;\n  jar.set('session', accessToken, { httpOnly: true, secure: true, sameSite: 'lax', path: '/', expires: expiresAt })\n  // Sent only to the refresh endpoint, and never with a request another site started\n  jar.set('refresh', refreshToken, { httpOnly: true, secure: true, sameSite: 'strict', path: REFRESH_PATH, expires: expiresAt })\n}\n\nexport async function clearSessionCookies() {\n  const jar = await cookies()\n  jar.set('session', '', { path: '/', maxAge: 0 })\n  jar.set('refresh', '', { path: REFRESH_PATH, maxAge: 0 }) // a path-scoped cookie is cleared on its path\n}`, `48341153242602280000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// lib/auth/tokens.ts</span>\n<span class=\"token keyword\">import</span> <span class=\"token string\">'server-only'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> createHash<span class=\"token punctuation\">,</span> randomBytes <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'node:crypto'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> cookies <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/headers'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> SignJWT <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'jose'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> signingKey <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/dal/session'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> db <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/db'</span>\n\n<span class=\"token keyword\">const</span> <span class=\"token constant\">ACCESS_TOKEN_TTL</span> <span class=\"token operator\">=</span> <span class=\"token number\">15</span> <span class=\"token operator\">*</span> <span class=\"token number\">60</span> <span class=\"token comment\">// seconds a revoked session can still get past Proxy</span>\n<span class=\"token keyword\">const</span> <span class=\"token constant\">IDLE_TIMEOUT</span> <span class=\"token operator\">=</span> <span class=\"token number\">7</span> <span class=\"token operator\">*</span> <span class=\"token number\">24</span> <span class=\"token operator\">*</span> <span class=\"token number\">60</span> <span class=\"token operator\">*</span> <span class=\"token number\">60</span> <span class=\"token comment\">// a week without a refresh means signing in again</span>\n<span class=\"token keyword\">const</span> <span class=\"token constant\">ABSOLUTE_TIMEOUT</span> <span class=\"token operator\">=</span> <span class=\"token number\">30</span> <span class=\"token operator\">*</span> <span class=\"token number\">24</span> <span class=\"token operator\">*</span> <span class=\"token number\">60</span> <span class=\"token operator\">*</span> <span class=\"token number\">60</span> <span class=\"token comment\">// 30 days after sign-in, however active the user is</span>\n<span class=\"token keyword\">const</span> <span class=\"token constant\">REFRESH_PATH</span> <span class=\"token operator\">=</span> <span class=\"token string\">'/api/auth/refresh'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">type</span> <span class=\"token class-name\">SessionTokens</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span> accessToken<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">;</span> refreshToken<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">;</span> expiresAt<span class=\"token operator\">:</span> Date <span class=\"token punctuation\">}</span>\n\n<span class=\"token comment\">// Only a hash is stored, so a leaked table can't be replayed</span>\n<span class=\"token keyword\">const</span> <span class=\"token function-variable function\">hash</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">(</span>token<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token function\">createHash</span><span class=\"token punctuation\">(</span><span class=\"token string\">'sha256'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">update</span><span class=\"token punctuation\">(</span>token<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">digest</span><span class=\"token punctuation\">(</span><span class=\"token string\">'base64url'</span><span class=\"token punctuation\">)</span>\n\n<span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">issueTokens</span><span class=\"token punctuation\">(</span>sessionId<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">,</span> sessionEnds<span class=\"token operator\">:</span> Date<span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>SessionTokens<span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> expiresAt <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Date</span><span class=\"token punctuation\">(</span>Math<span class=\"token punctuation\">.</span><span class=\"token function\">min</span><span class=\"token punctuation\">(</span>Date<span class=\"token punctuation\">.</span><span class=\"token function\">now</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">+</span> <span class=\"token constant\">IDLE_TIMEOUT</span> <span class=\"token operator\">*</span> <span class=\"token number\">1000</span><span class=\"token punctuation\">,</span> sessionEnds<span class=\"token punctuation\">.</span><span class=\"token function\">getTime</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">const</span> refreshToken <span class=\"token operator\">=</span> <span class=\"token function\">randomBytes</span><span class=\"token punctuation\">(</span><span class=\"token number\">32</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">toString</span><span class=\"token punctuation\">(</span><span class=\"token string\">'base64url'</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">await</span> db<span class=\"token punctuation\">.</span>refreshToken<span class=\"token punctuation\">.</span><span class=\"token function\">create</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> data<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> hash<span class=\"token operator\">:</span> <span class=\"token function\">hash</span><span class=\"token punctuation\">(</span>refreshToken<span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span> sessionId<span class=\"token punctuation\">,</span> expiresAt <span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">const</span> accessToken <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">SignJWT</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> sid<span class=\"token operator\">:</span> sessionId <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">.</span><span class=\"token function\">setProtectedHeader</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> alg<span class=\"token operator\">:</span> <span class=\"token string\">'HS256'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">.</span><span class=\"token function\">setExpirationTime</span><span class=\"token punctuation\">(</span><span class=\"token template-string\"><span class=\"token template-punctuation string\">`</span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${</span><span class=\"token constant\">ACCESS_TOKEN_TTL</span><span class=\"token interpolation-punctuation punctuation\">}</span></span><span class=\"token string\">s</span><span class=\"token template-punctuation string\">`</span></span><span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">.</span><span class=\"token function\">sign</span><span class=\"token punctuation\">(</span><span class=\"token function\">signingKey</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> <span class=\"token punctuation\">{</span> accessToken<span class=\"token punctuation\">,</span> refreshToken<span class=\"token punctuation\">,</span> expiresAt <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token comment\">// Call after your sign-in code has checked the user's credentials</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">createSession</span><span class=\"token punctuation\">(</span>userId<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>SessionTokens<span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> expiresAt <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Date</span><span class=\"token punctuation\">(</span>Date<span class=\"token punctuation\">.</span><span class=\"token function\">now</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">+</span> <span class=\"token constant\">ABSOLUTE_TIMEOUT</span> <span class=\"token operator\">*</span> <span class=\"token number\">1000</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">const</span> session <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> db<span class=\"token punctuation\">.</span>session<span class=\"token punctuation\">.</span><span class=\"token function\">create</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> data<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> userId<span class=\"token punctuation\">,</span> expiresAt <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> select<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> id<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span> <span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> <span class=\"token function\">issueTokens</span><span class=\"token punctuation\">(</span>session<span class=\"token punctuation\">.</span>id<span class=\"token punctuation\">,</span> expiresAt<span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token comment\">// A refresh token works once. A second use is a race or a theft, and either one ends the session.</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">rotateRefreshToken</span><span class=\"token punctuation\">(</span>presented<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>SessionTokens <span class=\"token operator\">|</span> <span class=\"token keyword\">null</span><span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> record <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> db<span class=\"token punctuation\">.</span>refreshToken<span class=\"token punctuation\">.</span><span class=\"token function\">findUnique</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n    where<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> hash<span class=\"token operator\">:</span> <span class=\"token function\">hash</span><span class=\"token punctuation\">(</span>presented<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n    select<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> id<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span> sessionId<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span> expiresAt<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span> session<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> select<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> revokedAt<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span> expiresAt<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span> <span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>record <span class=\"token operator\">||</span> record<span class=\"token punctuation\">.</span>session<span class=\"token punctuation\">.</span>revokedAt <span class=\"token operator\">||</span> record<span class=\"token punctuation\">.</span>expiresAt <span class=\"token operator\">&lt;=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Date</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token keyword\">null</span>\n\n  <span class=\"token comment\">// A conditional update, so two requests carrying the same token can't both win</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> count <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> db<span class=\"token punctuation\">.</span>refreshToken<span class=\"token punctuation\">.</span><span class=\"token function\">updateMany</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n    where<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> id<span class=\"token operator\">:</span> record<span class=\"token punctuation\">.</span>id<span class=\"token punctuation\">,</span> usedAt<span class=\"token operator\">:</span> <span class=\"token keyword\">null</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n    data<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> usedAt<span class=\"token operator\">:</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Date</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>count <span class=\"token operator\">!==</span> <span class=\"token number\">1</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">await</span> db<span class=\"token punctuation\">.</span>session<span class=\"token punctuation\">.</span><span class=\"token function\">update</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> where<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> id<span class=\"token operator\">:</span> record<span class=\"token punctuation\">.</span>sessionId <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> data<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> revokedAt<span class=\"token operator\">:</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Date</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n    <span class=\"token keyword\">return</span> <span class=\"token keyword\">null</span>\n  <span class=\"token punctuation\">}</span>\n  <span class=\"token keyword\">return</span> <span class=\"token function\">issueTokens</span><span class=\"token punctuation\">(</span>record<span class=\"token punctuation\">.</span>sessionId<span class=\"token punctuation\">,</span> record<span class=\"token punctuation\">.</span>session<span class=\"token punctuation\">.</span>expiresAt<span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">setSessionCookies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> accessToken<span class=\"token punctuation\">,</span> refreshToken<span class=\"token punctuation\">,</span> expiresAt <span class=\"token punctuation\">}</span><span class=\"token operator\">:</span> SessionTokens<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> jar <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">cookies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token comment\">// Outlives the 15-minute token inside it, so Proxy can tell \"expired\" from \"signed out\"</span>\n  jar<span class=\"token punctuation\">.</span><span class=\"token function\">set</span><span class=\"token punctuation\">(</span><span class=\"token string\">'session'</span><span class=\"token punctuation\">,</span> accessToken<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> httpOnly<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span> secure<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span> sameSite<span class=\"token operator\">:</span> <span class=\"token string\">'lax'</span><span class=\"token punctuation\">,</span> path<span class=\"token operator\">:</span> <span class=\"token string\">'/'</span><span class=\"token punctuation\">,</span> expires<span class=\"token operator\">:</span> expiresAt <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n  <span class=\"token comment\">// Sent only to the refresh endpoint, and never with a request another site started</span>\n  jar<span class=\"token punctuation\">.</span><span class=\"token function\">set</span><span class=\"token punctuation\">(</span><span class=\"token string\">'refresh'</span><span class=\"token punctuation\">,</span> refreshToken<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> httpOnly<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span> secure<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span> sameSite<span class=\"token operator\">:</span> <span class=\"token string\">'strict'</span><span class=\"token punctuation\">,</span> path<span class=\"token operator\">:</span> <span class=\"token constant\">REFRESH_PATH</span><span class=\"token punctuation\">,</span> expires<span class=\"token operator\">:</span> expiresAt <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">clearSessionCookies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> jar <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">cookies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  jar<span class=\"token punctuation\">.</span><span class=\"token function\">set</span><span class=\"token punctuation\">(</span><span class=\"token string\">'session'</span><span class=\"token punctuation\">,</span> <span class=\"token string\">''</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> path<span class=\"token operator\">:</span> <span class=\"token string\">'/'</span><span class=\"token punctuation\">,</span> maxAge<span class=\"token operator\">:</span> <span class=\"token number\">0</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n  jar<span class=\"token punctuation\">.</span><span class=\"token function\">set</span><span class=\"token punctuation\">(</span><span class=\"token string\">'refresh'</span><span class=\"token punctuation\">,</span> <span class=\"token string\">''</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> path<span class=\"token operator\">:</span> <span class=\"token constant\">REFRESH_PATH</span><span class=\"token punctuation\">,</span> maxAge<span class=\"token operator\">:</span> <span class=\"token number\">0</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span> <span class=\"token comment\">// a path-scoped cookie is cleared on its path</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Your sign-in action calls <code class=\"language-text\">setSessionCookies(await createSession(user.id))</code> once the credentials check passes. Sign-out sets <code class=\"language-text\">revokedAt</code> on the session row and calls <code class=\"language-text\">clearSessionCookies()</code>. With an auth library, this whole file is the library’s job, and the SuperTokens section shows how it maps.</p>\n<p>Key implementation decisions:</p>\n<ul>\n<li><strong>Three clocks, not one.</strong> The access token lasts 15 minutes, the session ends after a week without a refresh, and it ends after 30 days no matter what. The <a href=\"https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html\" target=\"_blank\" rel=\"nofollow\">OWASP Session Management Cheat Sheet</a> calls expiration timeouts “mandatory” for every session. Its examples run much shorter, with idle timeouts of 15 to 30 minutes for low-risk apps, so treat these numbers as product decisions, not defaults to copy.</li>\n<li><strong>The cookies outlive the access token.</strong> Both cookies expire with the refresh token. Until then, the browser keeps sending an expired but genuine access token, which is how Proxy knows to send the user to <code class=\"language-text\">/refresh</code> instead of <code class=\"language-text\">/login</code>. Once the idle timeout passes, both cookies are gone, and Proxy goes straight to <code class=\"language-text\">/login</code>.</li>\n<li><strong>Refresh tokens are hashed and single-use.</strong> Only a SHA-256 hash reaches the database, and the conditional update lets exactly one request spend a token. Any second use, whether a race or a <a href=\"https://supertokens.com/blog/the-best-way-to-securely-manage-user-sessions\" target=\"_blank\" rel=\"nofollow\">stolen copy</a>, revokes the whole session. That’s the trade <a href=\"https://www.rfc-editor.org/rfc/rfc9700#section-4.14\" target=\"_blank\" rel=\"nofollow\">RFC 9700</a> describes for rotation: it “stops the attack at the cost of forcing the legitimate client to obtain a fresh authorization grant.”</li>\n<li><strong>The refresh cookie goes nowhere else.</strong> <code class=\"language-text\">Path=/api/auth/refresh</code> keeps it off page loads, API calls, and Proxy, in line with OWASP’s advice to set the path “as restrictive as possible.” <code class=\"language-text\">SameSite=Strict</code> keeps it off any request another site starts. The session cookie stays <code class=\"language-text\">Lax</code>, so a link from an email still arrives signed in. Set <code class=\"language-text\">SameSite</code> explicitly either way: <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Set-Cookie\" target=\"_blank\" rel=\"nofollow\">MDN notes</a> that browsers applying <code class=\"language-text\">Lax</code> by default still send cookies on POSTs for two minutes after they’re set.</li>\n<li><strong>Every sign-in gets a new session.</strong> <code class=\"language-text\">createSession()</code> never reuses an ID. That covers OWASP’s rule that the session ID “must be renewed or regenerated” after a privilege change like signing in, the standard defense against <a href=\"https://supertokens.com/blog/session-hijacking-fixation\" target=\"_blank\" rel=\"nofollow\">session fixation</a>.</li>\n</ul>\n<h3 id=\"the-refresh-endpoint\" style=\"position:relative;\"><a href=\"#the-refresh-endpoint\" aria-label=\"the refresh endpoint permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>The Refresh Endpoint</h3>\n<p>One endpoint serves browsers and mobile apps. A browser sends the refresh cookie and gets new cookies back. A mobile app sends the token in the body and gets JSON back. It keeps both tokens in secure storage (the Keychain on iOS, the Keystore on Android) and sends the access token as a bearer token, as in the Route Handler section.</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"13381324439984587000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/api/auth/refresh/route.ts\nimport { cookies } from 'next/headers'\nimport { AuthError } from '@/lib/dal'\nimport { apiHandler } from '@/lib/api/handler'\nimport { clearSessionCookies, rotateRefreshToken, setSessionCookies } from '@/lib/auth/tokens'\n\nexport const POST = apiHandler(async (request) => {\n  // Browsers send the refresh cookie. Mobile apps send the token in the body and get JSON back.\n  const fromCookie = (await cookies()).get('refresh')?.value\n  const fromBody = fromCookie ? undefined : (await request.json().catch(() => null))?.refreshToken\n  const presented = fromCookie ?? (typeof fromBody === 'string' ? fromBody : undefined)\n  if (!presented) throw new AuthError(401)\n\n  const tokens = await rotateRefreshToken(presented)\n  if (!tokens) {\n    if (fromCookie) await clearSessionCookies()\n    throw new AuthError(401)\n  }\n  if (!fromCookie) return Response.json({ accessToken: tokens.accessToken, refreshToken: tokens.refreshToken })\n\n  await setSessionCookies(tokens)\n  return new Response(null, { status: 204 })\n})`, `13381324439984587000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// app/api/auth/refresh/route.ts</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> cookies <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/headers'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> AuthError <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/dal'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> apiHandler <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/api/handler'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> clearSessionCookies<span class=\"token punctuation\">,</span> rotateRefreshToken<span class=\"token punctuation\">,</span> setSessionCookies <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/auth/tokens'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">const</span> <span class=\"token constant\">POST</span> <span class=\"token operator\">=</span> <span class=\"token function\">apiHandler</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token comment\">// Browsers send the refresh cookie. Mobile apps send the token in the body and get JSON back.</span>\n  <span class=\"token keyword\">const</span> fromCookie <span class=\"token operator\">=</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">await</span> <span class=\"token function\">cookies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'refresh'</span><span class=\"token punctuation\">)</span><span class=\"token operator\">?.</span>value\n  <span class=\"token keyword\">const</span> fromBody <span class=\"token operator\">=</span> fromCookie <span class=\"token operator\">?</span> <span class=\"token keyword\">undefined</span> <span class=\"token operator\">:</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">await</span> request<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">catch</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token keyword\">null</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token operator\">?.</span>refreshToken\n  <span class=\"token keyword\">const</span> presented <span class=\"token operator\">=</span> fromCookie <span class=\"token operator\">??</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">typeof</span> fromBody <span class=\"token operator\">===</span> <span class=\"token string\">'string'</span> <span class=\"token operator\">?</span> fromBody <span class=\"token operator\">:</span> <span class=\"token keyword\">undefined</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>presented<span class=\"token punctuation\">)</span> <span class=\"token keyword\">throw</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">AuthError</span><span class=\"token punctuation\">(</span><span class=\"token number\">401</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">const</span> tokens <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">rotateRefreshToken</span><span class=\"token punctuation\">(</span>presented<span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>tokens<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>fromCookie<span class=\"token punctuation\">)</span> <span class=\"token keyword\">await</span> <span class=\"token function\">clearSessionCookies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n    <span class=\"token keyword\">throw</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">AuthError</span><span class=\"token punctuation\">(</span><span class=\"token number\">401</span><span class=\"token punctuation\">)</span>\n  <span class=\"token punctuation\">}</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>fromCookie<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> Response<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> accessToken<span class=\"token operator\">:</span> tokens<span class=\"token punctuation\">.</span>accessToken<span class=\"token punctuation\">,</span> refreshToken<span class=\"token operator\">:</span> tokens<span class=\"token punctuation\">.</span>refreshToken <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">await</span> <span class=\"token function\">setSessionCookies</span><span class=\"token punctuation\">(</span>tokens<span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Response</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">null</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> status<span class=\"token operator\">:</span> <span class=\"token number\">204</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span></code></pre></div>\n<p>It runs through <code class=\"language-text\">apiHandler()</code> from the Route Handler section, so cross-site cookie POSTs get a <code class=\"language-text\">403</code> and every response gets <code class=\"language-text\">Cache-Control: private, no-store</code>. A failed refresh returns the same <code class=\"language-text\">401</code> as every other handler. In the test app, a replayed refresh token got that <code class=\"language-text\">401</code>, cleared both cookies, and revoked the session, so the legitimate token issued after it failed too.</p>\n<h3 id=\"refreshing-without-racing\" style=\"position:relative;\"><a href=\"#refreshing-without-racing\" aria-label=\"refreshing without racing permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Refreshing Without Racing</h3>\n<p>Proxy sends a page load with an expired access token to <code class=\"language-text\">/refresh</code>. That page has one job: spend the refresh token once and go back. The hard part is “once.” Restoring a browser with three tabs open sends all three to <code class=\"language-text\">/refresh</code> together, and each tab holds the same refresh cookie. In the test app, three tabs refreshing at the same time got <code class=\"language-text\">401</code>, <code class=\"language-text\">204</code>, <code class=\"language-text\">401</code>, and the session was revoked. Five parallel requests with one token got one <code class=\"language-text\">204</code> and four <code class=\"language-text\">401</code>s. Rotation did its job, and everyone got signed out anyway.</p>\n<p>The fix is to make refreshes take turns. The <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Web_Locks_API\" target=\"_blank\" rel=\"nofollow\">Web Locks API</a>, available in every major browser since March 2022, gives every tab of an origin one shared queue:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"6062809658067448000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// lib/client/session.ts\nlet pending: Promise<boolean> | null = null\n\n// navigator.locks queues callers from every tab of this origin, so one refresh runs at a time\nasync function refreshWithLock(): Promise<boolean> {\n  return navigator.locks.request('session-refresh', async () => {\n    const response = await fetch('/api/auth/refresh', { method: 'POST' })\n    return response.ok\n  })\n}\n\n// Two tabs spending the same refresh token at once would look like theft and end the session\nexport function refreshSession(): Promise<boolean> {\n  const current = pending ?? refreshWithLock().finally(() => (pending = null))\n  pending = current\n  return current\n}\n\n// For your own API calls: on an expired token, refresh once and retry once\nexport async function apiFetch(input: string, init?: RequestInit): Promise<Response> {\n  const response = await fetch(input, init)\n  const expired = response.status === 401 && response.headers.get('WWW-Authenticate')?.includes('invalid_token')\n  if (!expired || !(await refreshSession())) return response\n  return fetch(input, init)\n}`, `6062809658067448000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// lib/client/session.ts</span>\n<span class=\"token keyword\">let</span> pending<span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span><span class=\"token builtin\">boolean</span><span class=\"token operator\">></span> <span class=\"token operator\">|</span> <span class=\"token keyword\">null</span> <span class=\"token operator\">=</span> <span class=\"token keyword\">null</span>\n\n<span class=\"token comment\">// navigator.locks queues callers from every tab of this origin, so one refresh runs at a time</span>\n<span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">refreshWithLock</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span><span class=\"token builtin\">boolean</span><span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">return</span> navigator<span class=\"token punctuation\">.</span>locks<span class=\"token punctuation\">.</span><span class=\"token function\">request</span><span class=\"token punctuation\">(</span><span class=\"token string\">'session-refresh'</span><span class=\"token punctuation\">,</span> <span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">const</span> response <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">fetch</span><span class=\"token punctuation\">(</span><span class=\"token string\">'/api/auth/refresh'</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> method<span class=\"token operator\">:</span> <span class=\"token string\">'POST'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n    <span class=\"token keyword\">return</span> response<span class=\"token punctuation\">.</span>ok\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token comment\">// Two tabs spending the same refresh token at once would look like theft and end the session</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">function</span> <span class=\"token function\">refreshSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span><span class=\"token builtin\">boolean</span><span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> current <span class=\"token operator\">=</span> pending <span class=\"token operator\">??</span> <span class=\"token function\">refreshWithLock</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">finally</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">(</span>pending <span class=\"token operator\">=</span> <span class=\"token keyword\">null</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n  pending <span class=\"token operator\">=</span> current\n  <span class=\"token keyword\">return</span> current\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token comment\">// For your own API calls: on an expired token, refresh once and retry once</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">apiFetch</span><span class=\"token punctuation\">(</span>input<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">,</span> init<span class=\"token operator\">?</span><span class=\"token operator\">:</span> RequestInit<span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>Response<span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> response <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">fetch</span><span class=\"token punctuation\">(</span>input<span class=\"token punctuation\">,</span> init<span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">const</span> expired <span class=\"token operator\">=</span> response<span class=\"token punctuation\">.</span>status <span class=\"token operator\">===</span> <span class=\"token number\">401</span> <span class=\"token operator\">&amp;&amp;</span> response<span class=\"token punctuation\">.</span>headers<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'WWW-Authenticate'</span><span class=\"token punctuation\">)</span><span class=\"token operator\">?.</span><span class=\"token function\">includes</span><span class=\"token punctuation\">(</span><span class=\"token string\">'invalid_token'</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>expired <span class=\"token operator\">||</span> <span class=\"token operator\">!</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">await</span> <span class=\"token function\">refreshSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> response\n  <span class=\"token keyword\">return</span> <span class=\"token function\">fetch</span><span class=\"token punctuation\">(</span>input<span class=\"token punctuation\">,</span> init<span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"3420557315510342000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/refresh/refresh-session.tsx\n'use client'\n\nimport { useEffect } from 'react'\nimport { useRouter } from 'next/navigation'\nimport { refreshSession } from '@/lib/client/session'\n\n// \\`next\\` comes from the URL, so only follow it to a path on this site\nfunction localPath(next: string | null): string {\n  const origin = window.location.origin\n  if (!next || !URL.canParse(next, origin)) return '/'\n  const url = new URL(next, origin)\n  return url.origin === origin ? url.pathname + url.search : '/'\n}\n\nexport function RefreshSession() {\n  const router = useRouter()\n\n  useEffect(() => {\n    const next = localPath(new URLSearchParams(window.location.search).get('next'))\n    refreshSession().then((ok) => router.replace(ok ? next : \\`/login?next=\\${encodeURIComponent(next)}\\`))\n  }, [router])\n\n  return <p>Refreshing your session…</p>\n}`, `3420557315510342000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"tsx\"><pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token comment\">// app/refresh/refresh-session.tsx</span>\n<span class=\"token string\">'use client'</span>\n\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> useEffect <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> useRouter <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/navigation'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> refreshSession <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/client/session'</span>\n\n<span class=\"token comment\">// `next` comes from the URL, so only follow it to a path on this site</span>\n<span class=\"token keyword\">function</span> <span class=\"token function\">localPath</span><span class=\"token punctuation\">(</span>next<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span> <span class=\"token operator\">|</span> <span class=\"token keyword\">null</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">string</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> origin <span class=\"token operator\">=</span> window<span class=\"token punctuation\">.</span>location<span class=\"token punctuation\">.</span>origin\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>next <span class=\"token operator\">||</span> <span class=\"token operator\">!</span><span class=\"token constant\">URL</span><span class=\"token punctuation\">.</span><span class=\"token function\">canParse</span><span class=\"token punctuation\">(</span>next<span class=\"token punctuation\">,</span> origin<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token string\">'/'</span>\n  <span class=\"token keyword\">const</span> url <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token constant\">URL</span></span><span class=\"token punctuation\">(</span>next<span class=\"token punctuation\">,</span> origin<span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> url<span class=\"token punctuation\">.</span>origin <span class=\"token operator\">===</span> origin <span class=\"token operator\">?</span> url<span class=\"token punctuation\">.</span>pathname <span class=\"token operator\">+</span> url<span class=\"token punctuation\">.</span>search <span class=\"token operator\">:</span> <span class=\"token string\">'/'</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">function</span> <span class=\"token function\">RefreshSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> router <span class=\"token operator\">=</span> <span class=\"token function\">useRouter</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token function\">useEffect</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">const</span> next <span class=\"token operator\">=</span> <span class=\"token function\">localPath</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">new</span> <span class=\"token class-name\">URLSearchParams</span><span class=\"token punctuation\">(</span>window<span class=\"token punctuation\">.</span>location<span class=\"token punctuation\">.</span>search<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'next'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n    <span class=\"token function\">refreshSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">then</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span>ok<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> router<span class=\"token punctuation\">.</span><span class=\"token function\">replace</span><span class=\"token punctuation\">(</span>ok <span class=\"token operator\">?</span> next <span class=\"token operator\">:</span> <span class=\"token template-string\"><span class=\"token template-punctuation string\">`</span><span class=\"token string\">/login?next=</span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${</span><span class=\"token function\">encodeURIComponent</span><span class=\"token punctuation\">(</span>next<span class=\"token punctuation\">)</span><span class=\"token interpolation-punctuation punctuation\">}</span></span><span class=\"token template-punctuation string\">`</span></span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">[</span>router<span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">return</span> <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>p</span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">Refreshing your session…</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>p</span><span class=\"token punctuation\">></span></span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p><code class=\"language-text\">app/refresh/page.tsx</code> just renders <code class=\"language-text\">&lt;RefreshSession /></code>. With the lock in place, the same three tabs refreshed one after another, <code class=\"language-text\">204</code>, <code class=\"language-text\">204</code>, <code class=\"language-text\">204</code>. Each tab waited its turn, then spent the token the tab before it had just received, and all three landed back on the invoices page still signed in. The <code class=\"language-text\">next</code> check sent <code class=\"language-text\">//evil.example/steal</code> and <code class=\"language-text\">https://evil.example/x</code> to <code class=\"language-text\">/</code>, and a page load with no refresh cookie ended at <code class=\"language-text\">/login?next=%2Fdashboard%2Finvoices</code>.</p>\n<p><code class=\"language-text\">apiFetch()</code> handles API calls the same way: the <code class=\"language-text\">invalid_token</code> challenge that Proxy and the Route Handlers send for an expired token triggers one refresh and one retry. A page that needs to refresh in place, the case from the Server Components section, can call <code class=\"language-text\">refreshSession()</code> and then <code class=\"language-text\">router.refresh()</code>.</p>\n<blockquote>\n<p><strong>Rather not maintain the token code?</strong> Rotation, reuse detection, the refresh endpoint, and the cross-tab lock are the parts of this section that are easiest to get subtly wrong. <a href=\"https://supertokens.com/docs/post-authentication/session-management/introduction\" target=\"_blank\" rel=\"nofollow\">SuperTokens session management</a> covers all four, and it’s open source, so you can self-host the core or use the managed service. The <a href=\"#implementing-this-with-supertokens\">SuperTokens section</a> shows what changes: <code class=\"language-text\">readSession()</code> and Proxy’s token check get new bodies, and <code class=\"language-text\">lib/auth/tokens.ts</code>, the refresh endpoint, and most of the client refresh code go away.</p>\n</blockquote>\n<p>An expired token should cost a round trip, not a sign-in.</p>\n<h2 id=\"streaming-auth-with-suspense\" style=\"position:relative;\"><a href=\"#streaming-auth-with-suspense\" aria-label=\"streaming auth with suspense permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Streaming Auth with Suspense</h2>\n<p>Streaming changes what an auth check costs. On a blocking page, the session lookup and every query behind it run before the first byte leaves the server. With Suspense, the page’s shell goes out immediately and each check runs next to the data it protects. This guide calls that <strong>shell-first auth</strong>, and it comes down to three rules:</p>\n<ol>\n<li><strong>The shell holds nothing that depends on who’s asking.</strong> It’s sent before any check runs, and with Cache Components it’s prerendered once for everyone.</li>\n<li><strong>Every boundary that does depend on the viewer checks for itself, through the DAL.</strong> React’s <code class=\"language-text\">cache()</code> turns those checks into a single session lookup per render.</li>\n<li><strong>Proxy decides who gets the shell at all.</strong> Once the first chunk is sent, the <a href=\"https://nextjs.org/docs/app/guides/streaming#the-http-contract\" target=\"_blank\" rel=\"nofollow\">status code is fixed at <code class=\"language-text\">200</code></a>, so a real redirect for signed-out visitors has to come from Proxy.</li>\n</ol>\n<h3 id=\"the-pattern-in-code\" style=\"position:relative;\"><a href=\"#the-pattern-in-code\" aria-label=\"the pattern in code permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>The Pattern in Code</h3>\n<p>The header needs the viewer’s name, so the DAL gets one more function, exported from <code class=\"language-text\">lib/dal/index.ts</code> with the others:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"62637849483635960000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// lib/dal/users.ts\nimport 'server-only'\nimport { cache } from 'react'\nimport { db } from '@/lib/db'\nimport { getSession } from './session'\n\nexport type CurrentUser = { name: string; role: 'member' | 'admin' }\n\n// For UI that changes with the viewer: null when signed out, never a redirect\nexport const getCurrentUser = cache(async (): Promise<CurrentUser | null> => {\n  const session = await getSession()\n  if (!session) return null\n  const user = await db.user.findUnique({ where: { id: session.userId }, select: { name: true } })\n  return user ? { name: user.name, role: session.role } : null\n})`, `62637849483635960000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// lib/dal/users.ts</span>\n<span class=\"token keyword\">import</span> <span class=\"token string\">'server-only'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> cache <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> db <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/db'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> getSession <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'./session'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">type</span> <span class=\"token class-name\">CurrentUser</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span> name<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">;</span> role<span class=\"token operator\">:</span> <span class=\"token string\">'member'</span> <span class=\"token operator\">|</span> <span class=\"token string\">'admin'</span> <span class=\"token punctuation\">}</span>\n\n<span class=\"token comment\">// For UI that changes with the viewer: null when signed out, never a redirect</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">const</span> getCurrentUser <span class=\"token operator\">=</span> <span class=\"token function\">cache</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>CurrentUser <span class=\"token operator\">|</span> <span class=\"token keyword\">null</span><span class=\"token operator\">></span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> session <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">getSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>session<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token keyword\">null</span>\n  <span class=\"token keyword\">const</span> user <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> db<span class=\"token punctuation\">.</span>user<span class=\"token punctuation\">.</span><span class=\"token function\">findUnique</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> where<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> id<span class=\"token operator\">:</span> session<span class=\"token punctuation\">.</span>userId <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> select<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> name<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span> <span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> user <span class=\"token operator\">?</span> <span class=\"token punctuation\">{</span> name<span class=\"token operator\">:</span> user<span class=\"token punctuation\">.</span>name<span class=\"token punctuation\">,</span> role<span class=\"token operator\">:</span> session<span class=\"token punctuation\">.</span>role <span class=\"token punctuation\">}</span> <span class=\"token operator\">:</span> <span class=\"token keyword\">null</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span></code></pre></div>\n<p>The layout puts the only viewer-dependent part of the header in its own boundary:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"55644919299951680000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/dashboard/layout.tsx\nimport { Suspense } from 'react'\nimport Link from 'next/link'\nimport { getCurrentUser } from '@/lib/dal'\n\nexport default function DashboardLayout({ children }: { children: React.ReactNode }) {\n  return (\n    <>\n      <header>\n        <Link href=&quot;/dashboard&quot;>Invoices</Link>\n        {/* The only part of the header that depends on who's asking */}\n        <Suspense fallback={<span className=&quot;avatar-placeholder&quot; />}>\n          <UserMenu />\n        </Suspense>\n      </header>\n      {children}\n    </>\n  )\n}\n\nasync function UserMenu() {\n  const user = await getCurrentUser()\n  if (!user) return <Link href=&quot;/login&quot;>Sign in</Link>\n  return <span>{user.name}</span>\n}`, `55644919299951680000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"tsx\"><pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token comment\">// app/dashboard/layout.tsx</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> Suspense <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span>\n<span class=\"token keyword\">import</span> Link <span class=\"token keyword\">from</span> <span class=\"token string\">'next/link'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> getCurrentUser <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/dal'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> <span class=\"token keyword\">function</span> <span class=\"token function\">DashboardLayout</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> children <span class=\"token punctuation\">}</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> children<span class=\"token operator\">:</span> React<span class=\"token punctuation\">.</span>ReactNode <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">return</span> <span class=\"token punctuation\">(</span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span></span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">\n      </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>header</span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">\n        </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">Link</span></span> <span class=\"token attr-name\">href</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">\"</span>/dashboard<span class=\"token punctuation\">\"</span></span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">Invoices</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span><span class=\"token class-name\">Link</span></span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">\n        </span><span class=\"token punctuation\">{</span><span class=\"token comment\">/* The only part of the header that depends on who's asking */</span><span class=\"token punctuation\">}</span><span class=\"token plain-text\">\n        </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">Suspense</span></span> <span class=\"token attr-name\">fallback</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>span</span> <span class=\"token attr-name\">className</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">\"</span>avatar-placeholder<span class=\"token punctuation\">\"</span></span> <span class=\"token punctuation\">/></span></span><span class=\"token punctuation\">}</span></span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">\n          </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">UserMenu</span></span> <span class=\"token punctuation\">/></span></span><span class=\"token plain-text\">\n        </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span><span class=\"token class-name\">Suspense</span></span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">\n      </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>header</span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">\n      </span><span class=\"token punctuation\">{</span>children<span class=\"token punctuation\">}</span><span class=\"token plain-text\">\n    </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span></span><span class=\"token punctuation\">></span></span>\n  <span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">UserMenu</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> user <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">getCurrentUser</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>user<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">Link</span></span> <span class=\"token attr-name\">href</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">\"</span>/login<span class=\"token punctuation\">\"</span></span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">Sign in</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span><span class=\"token class-name\">Link</span></span><span class=\"token punctuation\">></span></span>\n  <span class=\"token keyword\">return</span> <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>span</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">{</span>user<span class=\"token punctuation\">.</span>name<span class=\"token punctuation\">}</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>span</span><span class=\"token punctuation\">></span></span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>The page does the same with its two data sections, one for every member and one only admins see:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"49973527424949220000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/dashboard/page.tsx\nimport { Suspense } from 'react'\nimport { getCurrentUser, getMyInvoices, getOverdueInvoices, verifySession } from '@/lib/dal'\nimport { InvoiceList } from './invoices/invoice-list'\n\nexport default function DashboardPage() {\n  return (\n    <main>\n      <h1>Dashboard</h1>\n      <Suspense fallback={<p>Loading your invoices…</p>}>\n        <MyInvoices />\n      </Suspense>\n      <Suspense fallback={null}>\n        <OverdueSummary />\n      </Suspense>\n    </main>\n  )\n}\n\nasync function MyInvoices() {\n  await verifySession() // Proxy turned signed-out visitors away; this catches revoked sessions\n  return <InvoiceList invoices={await getMyInvoices()} />\n}\n\nasync function OverdueSummary() {\n  const user = await getCurrentUser()\n  if (user?.role !== 'admin') return null // a UI decision: getOverdueInvoices() checks the role again\n  const overdue = await getOverdueInvoices()\n  return <p>{overdue.length} overdue invoices across all customers</p>\n}`, `49973527424949220000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"tsx\"><pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token comment\">// app/dashboard/page.tsx</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> Suspense <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> getCurrentUser<span class=\"token punctuation\">,</span> getMyInvoices<span class=\"token punctuation\">,</span> getOverdueInvoices<span class=\"token punctuation\">,</span> verifySession <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/dal'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> InvoiceList <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'./invoices/invoice-list'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> <span class=\"token keyword\">function</span> <span class=\"token function\">DashboardPage</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">return</span> <span class=\"token punctuation\">(</span>\n    <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>main</span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">\n      </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>h1</span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">Dashboard</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>h1</span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">\n      </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">Suspense</span></span> <span class=\"token attr-name\">fallback</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>p</span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">Loading your invoices…</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>p</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">}</span></span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">\n        </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">MyInvoices</span></span> <span class=\"token punctuation\">/></span></span><span class=\"token plain-text\">\n      </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span><span class=\"token class-name\">Suspense</span></span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">\n      </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">Suspense</span></span> <span class=\"token attr-name\">fallback</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span><span class=\"token keyword\">null</span><span class=\"token punctuation\">}</span></span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">\n        </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">OverdueSummary</span></span> <span class=\"token punctuation\">/></span></span><span class=\"token plain-text\">\n      </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span><span class=\"token class-name\">Suspense</span></span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">\n    </span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>main</span><span class=\"token punctuation\">></span></span>\n  <span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">MyInvoices</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">await</span> <span class=\"token function\">verifySession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token comment\">// Proxy turned signed-out visitors away; this catches revoked sessions</span>\n  <span class=\"token keyword\">return</span> <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">InvoiceList</span></span> <span class=\"token attr-name\">invoices</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span><span class=\"token keyword\">await</span> <span class=\"token function\">getMyInvoices</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">}</span></span> <span class=\"token punctuation\">/></span></span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">OverdueSummary</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> user <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">getCurrentUser</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>user<span class=\"token operator\">?.</span>role <span class=\"token operator\">!==</span> <span class=\"token string\">'admin'</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token keyword\">null</span> <span class=\"token comment\">// a UI decision: getOverdueInvoices() checks the role again</span>\n  <span class=\"token keyword\">const</span> overdue <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">getOverdueInvoices</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>p</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">{</span>overdue<span class=\"token punctuation\">.</span>length<span class=\"token punctuation\">}</span><span class=\"token plain-text\"> overdue invoices across all customers</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>p</span><span class=\"token punctuation\">></span></span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Key implementation decisions:</p>\n<ul>\n<li><strong>Nothing awaits at the top.</strong> Neither the layout nor the page reads the session itself. Each boundary does its own reading, which the Next.js streaming guide calls <a href=\"https://nextjs.org/docs/app/guides/streaming#push-dynamic-access-down\" target=\"_blank\" rel=\"nofollow\">pushing dynamic access down</a>. One <code class=\"language-text\">await</code> at the top of the layout would hold the whole page behind it.</li>\n<li><strong>The header never decides the page.</strong> <code class=\"language-text\">getCurrentUser()</code> returns <code class=\"language-text\">null</code> instead of redirecting, because a layout doesn’t guard the page below it. The page’s own boundary calls <code class=\"language-text\">verifySession()</code>.</li>\n<li><strong>The admin check is a UI decision, and only that.</strong> <code class=\"language-text\">OverdueSummary</code> skips rendering for members, and <code class=\"language-text\">getOverdueInvoices()</code> still calls <code class=\"language-text\">requireRole('admin')</code> inside the DAL.</li>\n<li><strong>Repeated checks are cheap.</strong> In the test app, one render of this page ran one session lookup and one user lookup, shared by all three components that needed the viewer.</li>\n</ul>\n<p>If you cache per-user data inside a boundary, the DAL’s rule still holds. The exported function reads the session and passes the user ID to an unexported <code class=\"language-text\">'use cache'</code> function, which is the pattern the Next.js <a href=\"https://nextjs.org/docs/app/guides/authentication-with-cache-components#step-4-cache-session-derived-data\" target=\"_blank\" rel=\"nofollow\">Cache Components authentication guide</a> uses so no caller can ask for someone else’s cached data.</p>\n<h3 id=\"what-streaming-changed\" style=\"position:relative;\"><a href=\"#what-streaming-changed\" aria-label=\"what streaming changed permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>What Streaming Changed</h3>\n<p>To make the difference visible, the test app delayed every database call by 200 ms and compared this page with a version that awaits the same data before rendering anything:</p>\n<table>\n<thead>\n<tr>\n<th>Next.js 16.4.2, 200 ms per query</th>\n<th>First byte</th>\n<th>Last byte</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Blocking page, member</td>\n<td>417 ms</td>\n<td>417 ms</td>\n</tr>\n<tr>\n<td>Shell-first page, member</td>\n<td>15 ms</td>\n<td>417 ms</td>\n</tr>\n<tr>\n<td>Blocking page, admin</td>\n<td>614 ms</td>\n<td>615 ms</td>\n</tr>\n<tr>\n<td>Shell-first page, admin</td>\n<td>12 ms</td>\n<td>615 ms</td>\n</tr>\n</tbody>\n</table>\n<p>Streaming didn’t make the data any faster. The admin still waited 600 ms for the overdue count. What changed is that nothing else waited for it: the header, the heading, and the fallbacks arrived in the first chunk. With Cache Components on, the same page built as a partial prerender and sent its first byte in 10 to 12 ms.</p>\n<p>The responses held up too. A member’s page contained no overdue data at all, not even an empty panel. A revoked session passes Proxy, because its signature is valid. It got the shell, a “Sign in” link in the header, and a client-side redirect, with no invoice and no name anywhere in the response. A signed-out visitor never got the shell: Proxy answered with a <code class=\"language-text\">307</code>.</p>\n<h3 id=\"refusals-inside-a-boundary\" style=\"position:relative;\"><a href=\"#refusals-inside-a-boundary\" aria-label=\"refusals inside a boundary permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Refusals Inside a Boundary</h3>\n<p>A boundary that might be refused needs to handle the refusal itself. In the test app, a page whose second boundary called <code class=\"language-text\">getOverdueInvoices()</code> as a member, with nothing to catch the <code class=\"language-text\">AuthError</code>, didn’t lose one section. It lost all of them: the browser showed Next.js’s “This page couldn’t load” screen, with a <code class=\"language-text\">200</code>. Adding an <code class=\"language-text\">error.tsx</code> kept the layout, but its error UI still replaced the whole page, including the boundary that had loaded fine.</p>\n<p>So decide inside the component. For a section the viewer can’t see, check first and return <code class=\"language-text\">null</code>, the way <code class=\"language-text\">OverdueSummary</code> does. For a page the viewer shouldn’t be on, call <code class=\"language-text\">verifySession()</code>, which redirects instead of throwing an error. Save <code class=\"language-text\">error.tsx</code> for real failures, like a database outage, which the DAL deliberately lets throw.</p>\n<p>The shell is for everyone. Each boundary decides who gets the rest.</p>\n<h2 id=\"implementing-this-with-supertokens\" style=\"position:relative;\"><a href=\"#implementing-this-with-supertokens\" aria-label=\"implementing this with supertokens permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Implementing This with SuperTokens</h2>\n<p>The architecture so far kept provider-specific code in three places. <code class=\"language-text\">readSession()</code> was the only part of the DAL that knew where sessions come from, <code class=\"language-text\">readTokenState()</code> was the only part of Proxy, and <code class=\"language-text\">lib/auth/tokens.ts</code> was the whole token system. With SuperTokens, the first two get new bodies and the third goes away, along with the refresh endpoint and most of the client refresh code. Server Actions, Route Handlers, and the streaming pages don’t change.</p>\n<p>Here’s how the session strategy section’s pieces map:</p>\n<table>\n<thead>\n<tr>\n<th>Hand-built</th>\n<th>SuperTokens</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><code class=\"language-text\">lib/auth/tokens.ts</code> issues and rotates tokens</td>\n<td>The SuperTokens core, behind the SDK’s sign-in and refresh APIs</td>\n</tr>\n<tr>\n<td>15-minute HS256 access token</td>\n<td>RS256 token signed by the core, one hour by default (<a href=\"https://github.com/supertokens/supertokens-core/blob/master/config.yaml\" target=\"_blank\" rel=\"nofollow\"><code class=\"language-text\">access_token_validity</code></a>)</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">session</code> cookie, <code class=\"language-text\">Path=/</code>, <code class=\"language-text\">SameSite=Lax</code></td>\n<td><code class=\"language-text\">sAccessToken</code>, <code class=\"language-text\">Path=/</code>, <code class=\"language-text\">SameSite=Lax</code>, a one-year cookie</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">refresh</code> cookie, <code class=\"language-text\">Path=/api/auth/refresh</code>, <code class=\"language-text\">SameSite=Strict</code></td>\n<td><code class=\"language-text\">sRefreshToken</code>, <code class=\"language-text\">Path=/api/auth/session/refresh</code>, <code class=\"language-text\">SameSite=Lax</code></td>\n</tr>\n<tr>\n<td>7-day idle timeout</td>\n<td><a href=\"https://github.com/supertokens/supertokens-core/blob/master/config.yaml\" target=\"_blank\" rel=\"nofollow\"><code class=\"language-text\">refresh_token_validity</code></a>, 100 days by default, extended as the session is used</td>\n</tr>\n<tr>\n<td>30-day absolute timeout</td>\n<td>No setting. <code class=\"language-text\">Session.getSessionInformation()</code> returns <code class=\"language-text\">timeCreated</code> if you need one</td>\n</tr>\n<tr>\n<td>Single-use refresh tokens</td>\n<td>Rotated on every refresh, and reusing a retired token counts as theft</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">navigator.locks</code> and <code class=\"language-text\">apiFetch()</code></td>\n<td>The frontend SDK’s cross-tab lock and fetch interceptor</td>\n</tr>\n<tr>\n<td>Mobile refresh with a JSON body</td>\n<td>Header mode, with <code class=\"language-text\">st-auth-mode: header</code></td>\n</tr>\n<tr>\n<td>Sign-out revokes the row and clears both cookies</td>\n<td><code class=\"language-text\">Session.signOut()</code> in the browser does both. <code class=\"language-text\">revokeAllSessionsForUser()</code> ends every session a user has</td>\n</tr>\n</tbody>\n</table>\n<p>One cell looks weaker than it is. SuperTokens sets both cookies from one <code class=\"language-text\">cookieSameSite</code> value, <code class=\"language-text\">Lax</code> by default when the site and API share a domain, so the refresh cookie isn’t <code class=\"language-text\">Strict</code>. But its refresh API only answers <code class=\"language-text\">POST</code>, and browsers don’t send a <code class=\"language-text\">Lax</code> cookie with a POST another site starts.</p>\n<p>The setup comes from SuperTokens’ <a href=\"https://supertokens.com/docs/integrations/nextjs/app-directory/about\" target=\"_blank\" rel=\"nofollow\">App Router guide</a>: config files, a provider in the root layout, the sign-in UI at <code class=\"language-text\">/auth</code>, and the auth API at <code class=\"language-text\">app/api/auth/[[...path]]/route.ts</code>. <a href=\"https://supertokens.com/blog/adding-login-to-your-nextjs-app-using-the-app-directory-and-supertokens\" target=\"_blank\" rel=\"nofollow\">Adding login to your Next.js app with SuperTokens</a> walks through an earlier version of this setup one file at a time. It was written for older SDKs, so take the recipe imports from SuperTokens’ current guide. Two settings tie the setup to this architecture. Set <code class=\"language-text\">apiBasePath: '/api/auth'</code> in <code class=\"language-text\">appInfo</code> to match that route, which also keeps every SuperTokens API under the prefix Proxy already treats as public. And add <code class=\"language-text\">UserRoles.init()</code> to the backend recipe list, because the DAL reads roles from the core. The code below ran on supertokens-node 24.0.3 and supertokens-auth-react 0.51.3 against a self-hosted core 12.3.1, with access tokens cut to 20 seconds so they’d expire mid-test.</p>\n<h3 id=\"a-new-body-for-readsession\" style=\"position:relative;\"><a href=\"#a-new-body-for-readsession\" aria-label=\"a new body for readsession permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>A New Body for readSession()</h3>\n<p>Everything else in <code class=\"language-text\">lib/dal/session.ts</code> stays, except that <code class=\"language-text\">signingKey()</code> goes away and <code class=\"language-text\">verifySession()</code> now redirects to <code class=\"language-text\">/auth</code>:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"71766510891993600000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// lib/dal/session.ts\nimport 'server-only'\nimport { cache } from 'react'\nimport { cookies, headers } from 'next/headers'\nimport { redirect } from 'next/navigation'\nimport SuperTokensSession from 'supertokens-node/recipe/session'\nimport UserRoles from 'supertokens-node/recipe/userroles'\nimport { ensureSuperTokensInit } from '@/app/config/backend'\n\nensureSuperTokensInit()\n\n// Session, AuthError, and bearerToken() are unchanged\n\n// Expired or forged tokens, and sessions the core no longer has\nconst SIGNED_OUT = new Set<string>([SuperTokensSession.Error.TRY_REFRESH_TOKEN, SuperTokensSession.Error.UNAUTHORISED])\n\n// The only provider-specific code in the DAL\nasync function readSession(): Promise<Session | null> {\n  const token = bearerToken(await headers()) ?? (await cookies()).get('sAccessToken')?.value\n  if (!token) return null\n\n  const session = await SuperTokensSession.getSessionWithoutRequestResponse(token, undefined, {\n    checkDatabase: true, // asks the core, so a revoked session fails on its next request\n    antiCsrfCheck: false, // Next.js checks Server Actions, and apiHandler() checks Route Handlers\n  }).catch((error) => {\n    // Anything else, like an unreachable core, stays a 500\n    if (SuperTokensSession.Error.isErrorFromSuperTokens(error) && SIGNED_OUT.has(error.type)) return null\n    throw error\n  })\n  if (!session) return null\n\n  // Roles from the core, not the copy in the token, so a demotion counts on the next request\n  const { roles } = await UserRoles.getRolesForUser(session.getTenantId(), session.getUserId())\n  return {\n    sessionId: session.getHandle(),\n    userId: session.getUserId(),\n    role: roles.includes('admin') ? 'admin' : 'member',\n  }\n}`, `71766510891993600000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// lib/dal/session.ts</span>\n<span class=\"token keyword\">import</span> <span class=\"token string\">'server-only'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> cache <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> cookies<span class=\"token punctuation\">,</span> headers <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/headers'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> redirect <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/navigation'</span>\n<span class=\"token keyword\">import</span> SuperTokensSession <span class=\"token keyword\">from</span> <span class=\"token string\">'supertokens-node/recipe/session'</span>\n<span class=\"token keyword\">import</span> UserRoles <span class=\"token keyword\">from</span> <span class=\"token string\">'supertokens-node/recipe/userroles'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> ensureSuperTokensInit <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/app/config/backend'</span>\n\n<span class=\"token function\">ensureSuperTokensInit</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n<span class=\"token comment\">// Session, AuthError, and bearerToken() are unchanged</span>\n\n<span class=\"token comment\">// Expired or forged tokens, and sessions the core no longer has</span>\n<span class=\"token keyword\">const</span> <span class=\"token constant\">SIGNED_OUT</span> <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\">Set<span class=\"token operator\">&lt;</span><span class=\"token builtin\">string</span><span class=\"token operator\">></span></span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">[</span>SuperTokensSession<span class=\"token punctuation\">.</span>Error<span class=\"token punctuation\">.</span><span class=\"token constant\">TRY_REFRESH_TOKEN</span><span class=\"token punctuation\">,</span> SuperTokensSession<span class=\"token punctuation\">.</span>Error<span class=\"token punctuation\">.</span><span class=\"token constant\">UNAUTHORISED</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span>\n\n<span class=\"token comment\">// The only provider-specific code in the DAL</span>\n<span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">readSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>Session <span class=\"token operator\">|</span> <span class=\"token keyword\">null</span><span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> token <span class=\"token operator\">=</span> <span class=\"token function\">bearerToken</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">await</span> <span class=\"token function\">headers</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">??</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">await</span> <span class=\"token function\">cookies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'sAccessToken'</span><span class=\"token punctuation\">)</span><span class=\"token operator\">?.</span>value\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>token<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token keyword\">null</span>\n\n  <span class=\"token keyword\">const</span> session <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> SuperTokensSession<span class=\"token punctuation\">.</span><span class=\"token function\">getSessionWithoutRequestResponse</span><span class=\"token punctuation\">(</span>token<span class=\"token punctuation\">,</span> <span class=\"token keyword\">undefined</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span>\n    checkDatabase<span class=\"token operator\">:</span> <span class=\"token boolean\">true</span><span class=\"token punctuation\">,</span> <span class=\"token comment\">// asks the core, so a revoked session fails on its next request</span>\n    antiCsrfCheck<span class=\"token operator\">:</span> <span class=\"token boolean\">false</span><span class=\"token punctuation\">,</span> <span class=\"token comment\">// Next.js checks Server Actions, and apiHandler() checks Route Handlers</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">catch</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n    <span class=\"token comment\">// Anything else, like an unreachable core, stays a 500</span>\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>SuperTokensSession<span class=\"token punctuation\">.</span>Error<span class=\"token punctuation\">.</span><span class=\"token function\">isErrorFromSuperTokens</span><span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token operator\">&amp;&amp;</span> <span class=\"token constant\">SIGNED_OUT</span><span class=\"token punctuation\">.</span><span class=\"token function\">has</span><span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">.</span>type<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token keyword\">null</span>\n    <span class=\"token keyword\">throw</span> error\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>session<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token keyword\">null</span>\n\n  <span class=\"token comment\">// Roles from the core, not the copy in the token, so a demotion counts on the next request</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> roles <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> UserRoles<span class=\"token punctuation\">.</span><span class=\"token function\">getRolesForUser</span><span class=\"token punctuation\">(</span>session<span class=\"token punctuation\">.</span><span class=\"token function\">getTenantId</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span> session<span class=\"token punctuation\">.</span><span class=\"token function\">getUserId</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> <span class=\"token punctuation\">{</span>\n    sessionId<span class=\"token operator\">:</span> session<span class=\"token punctuation\">.</span><span class=\"token function\">getHandle</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n    userId<span class=\"token operator\">:</span> session<span class=\"token punctuation\">.</span><span class=\"token function\">getUserId</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span>\n    role<span class=\"token operator\">:</span> roles<span class=\"token punctuation\">.</span><span class=\"token function\">includes</span><span class=\"token punctuation\">(</span><span class=\"token string\">'admin'</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">?</span> <span class=\"token string\">'admin'</span> <span class=\"token operator\">:</span> <span class=\"token string\">'member'</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Key implementation decisions:</p>\n<ul>\n<li><strong><code class=\"language-text\">checkDatabase: true</code> is the revocation check.</strong> SuperTokens <a href=\"https://supertokens.com/docs/post-authentication/session-management/advanced-workflows/access-token-blacklisting\" target=\"_blank\" rel=\"nofollow\">verifies sessions statelessly by default</a>, so a revoked session works until its access token expires. With the core consulted, <code class=\"language-text\">revokeAllSessionsForUser()</code> took effect on the next request. <code class=\"language-text\">getSSRSession()</code>, which SuperTokens’ guide uses in Server Components, skips this check, and SuperTokens’ own <a href=\"https://supertokens.com/docs/additional-verification/session-verification/ssr\" target=\"_blank\" rel=\"nofollow\">SSR docs</a> say to verify against the database before rendering sensitive data.</li>\n<li><strong>Roles come from the core, not the token.</strong> The UserRoles recipe copies a user’s roles into the access token as <code class=\"language-text\">st-role</code> at sign-in, and refreshes carry that copy forward unchanged. In the test app, an admin whose role was removed still had <code class=\"language-text\">admin</code> in a freshly refreshed token, and their next request got a <code class=\"language-text\">403</code> anyway.</li>\n<li><strong>Each render makes two calls to the core.</strong> <code class=\"language-text\">cache()</code> holds it at two however many components ask, and shell-first streaming keeps them out of the first byte. On the managed service, they count toward a <a href=\"https://supertokens.com/docs/deployment/rate-limits\" target=\"_blank\" rel=\"nofollow\">rate limit</a> per app and IP address: 50 requests per second on the free tier, or about 25 renders per second from one server. Paid plans start at 100, and a self-hosted core has no limit.</li>\n<li><strong>The replacement token gets dropped.</strong> With supertokens-node 24.0.3, each verify after a refresh returns a replacement access token that the SDK expects you to write to the response, and a Server Component can’t set cookies. In the test app, ignoring it cost only work on the core: verification, later refreshes, and theft detection all behaved normally.</li>\n<li><strong>An unreachable core is a <code class=\"language-text\">500</code>, with one gap.</strong> Once the SDK has the core’s signing keys, a failed verify call throws and the page fails, instead of signing everyone out. But the SDK caches those keys for four hours and reports a failure to fetch them as <code class=\"language-text\">TRY_REFRESH_TOKEN</code>. A test server started while the core was down treated every valid token as expired, in Proxy and the DAL alike.</li>\n</ul>\n<h3 id=\"proxy-on-the-sdk\" style=\"position:relative;\"><a href=\"#proxy-on-the-sdk\" aria-label=\"proxy on the sdk permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Proxy on the SDK</h3>\n<p>Proxy keeps its job: signature and expiry, no database. The SDK’s <code class=\"language-text\">getSSRSession()</code> checks both against the core’s public keys, so it replaces the jose call and the shared secret:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"50420645311084450000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// proxy.ts\nimport { NextResponse, type NextRequest } from 'next/server'\nimport { getSSRSession } from 'supertokens-node/nextjs'\nimport { ensureSuperTokensInit } from '@/app/config/backend'\n\nensureSuperTokensInit()\n\n// Deny by default. /auth is the SuperTokens sign-in UI and /api/auth its API.\nconst PUBLIC_PATHS = ['/', '/auth', '/refresh', '/api/auth']\n\nfunction isPublic(pathname: string) {\n  return PUBLIC_PATHS.some((path) => pathname === path || (path !== '/' && pathname.startsWith(\\`\\${path}/\\`)))\n}\n\ntype TokenState = 'valid' | 'expired' | 'missing'\n\n// Signature and expiry only, against the core's public keys. No revocation, roles, or ownership.\nasync function readTokenState(request: NextRequest): Promise<TokenState> {\n  const bearer = request.headers.get('authorization')?.match(/^Bearer\\s+(\\S+)\\$/i)?.[1]\n  // getSSRSession() looks for sAccessToken in a cookie list, so a bearer token goes in as one\n  const cookies = bearer ? [{ name: 'sAccessToken', value: bearer }] : request.cookies.getAll()\n  const { accessTokenPayload, hasToken, error } = await getSSRSession(cookies)\n  if (error) throw error // SuperTokens isn't initialized, which isn't a bad token\n  if (!hasToken) return 'missing'\n  // Expired and forged tokens look the same here. Both go to /refresh, and a forged one fails there.\n  return accessTokenPayload ? 'valid' : 'expired'\n}\n\nexport async function proxy(request: NextRequest) {\n  const { pathname, search } = request.nextUrl\n  if (isPublic(pathname)) return NextResponse.next()\n\n  const state = await readTokenState(request)\n  if (state === 'valid') return NextResponse.next()\n\n  if (pathname.startsWith('/api/')) {\n    const challenge = state === 'missing' ? 'Bearer' : 'Bearer error=&quot;invalid_token&quot;'\n    return Response.json(\n      { error: 'Authentication required' },\n      { status: 401, headers: { 'WWW-Authenticate': challenge } },\n    )\n  }\n\n  // Server Actions and other writes check for themselves, in a format their caller can read\n  if (request.method !== 'GET' && request.method !== 'HEAD') return NextResponse.next()\n\n  // An expired token isn't a signed-out user. Send them to refresh, not to sign in.\n  const destination = new URL(state === 'expired' ? '/refresh' : '/auth', request.url)\n  destination.searchParams.set('redirectToPath', pathname + search) // the name SuperTokens' sign-in page reads\n  return NextResponse.redirect(destination)\n}\n\nexport const config = {\n  // Everything except build output, crawler files, and images, so new routes are covered by default\n  matcher: ['/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml|.*\\\\.(?:png|jpg|jpeg|gif|svg|webp|ico)\\$).*)'],\n}`, `50420645311084450000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// proxy.ts</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> NextResponse<span class=\"token punctuation\">,</span> <span class=\"token keyword\">type</span> <span class=\"token class-name\">NextRequest</span> <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'next/server'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> getSSRSession <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'supertokens-node/nextjs'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> ensureSuperTokensInit <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/app/config/backend'</span>\n\n<span class=\"token function\">ensureSuperTokensInit</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n<span class=\"token comment\">// Deny by default. /auth is the SuperTokens sign-in UI and /api/auth its API.</span>\n<span class=\"token keyword\">const</span> <span class=\"token constant\">PUBLIC_PATHS</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">[</span><span class=\"token string\">'/'</span><span class=\"token punctuation\">,</span> <span class=\"token string\">'/auth'</span><span class=\"token punctuation\">,</span> <span class=\"token string\">'/refresh'</span><span class=\"token punctuation\">,</span> <span class=\"token string\">'/api/auth'</span><span class=\"token punctuation\">]</span>\n\n<span class=\"token keyword\">function</span> <span class=\"token function\">isPublic</span><span class=\"token punctuation\">(</span>pathname<span class=\"token operator\">:</span> <span class=\"token builtin\">string</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">return</span> <span class=\"token constant\">PUBLIC_PATHS</span><span class=\"token punctuation\">.</span><span class=\"token function\">some</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span>path<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> pathname <span class=\"token operator\">===</span> path <span class=\"token operator\">||</span> <span class=\"token punctuation\">(</span>path <span class=\"token operator\">!==</span> <span class=\"token string\">'/'</span> <span class=\"token operator\">&amp;&amp;</span> pathname<span class=\"token punctuation\">.</span><span class=\"token function\">startsWith</span><span class=\"token punctuation\">(</span><span class=\"token template-string\"><span class=\"token template-punctuation string\">`</span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${</span>path<span class=\"token interpolation-punctuation punctuation\">}</span></span><span class=\"token string\">/</span><span class=\"token template-punctuation string\">`</span></span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">type</span> <span class=\"token class-name\">TokenState</span> <span class=\"token operator\">=</span> <span class=\"token string\">'valid'</span> <span class=\"token operator\">|</span> <span class=\"token string\">'expired'</span> <span class=\"token operator\">|</span> <span class=\"token string\">'missing'</span>\n\n<span class=\"token comment\">// Signature and expiry only, against the core's public keys. No revocation, roles, or ownership.</span>\n<span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">readTokenState</span><span class=\"token punctuation\">(</span>request<span class=\"token operator\">:</span> NextRequest<span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span>TokenState<span class=\"token operator\">></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> bearer <span class=\"token operator\">=</span> request<span class=\"token punctuation\">.</span>headers<span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'authorization'</span><span class=\"token punctuation\">)</span><span class=\"token operator\">?.</span><span class=\"token function\">match</span><span class=\"token punctuation\">(</span><span class=\"token regex\"><span class=\"token regex-delimiter\">/</span><span class=\"token regex-source language-regex\">^Bearer\\s+(\\S+)$</span><span class=\"token regex-delimiter\">/</span><span class=\"token regex-flags\">i</span></span><span class=\"token punctuation\">)</span><span class=\"token operator\">?.</span><span class=\"token punctuation\">[</span><span class=\"token number\">1</span><span class=\"token punctuation\">]</span>\n  <span class=\"token comment\">// getSSRSession() looks for sAccessToken in a cookie list, so a bearer token goes in as one</span>\n  <span class=\"token keyword\">const</span> cookies <span class=\"token operator\">=</span> bearer <span class=\"token operator\">?</span> <span class=\"token punctuation\">[</span><span class=\"token punctuation\">{</span> name<span class=\"token operator\">:</span> <span class=\"token string\">'sAccessToken'</span><span class=\"token punctuation\">,</span> value<span class=\"token operator\">:</span> bearer <span class=\"token punctuation\">}</span><span class=\"token punctuation\">]</span> <span class=\"token operator\">:</span> request<span class=\"token punctuation\">.</span>cookies<span class=\"token punctuation\">.</span><span class=\"token function\">getAll</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> accessTokenPayload<span class=\"token punctuation\">,</span> hasToken<span class=\"token punctuation\">,</span> error <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">getSSRSession</span><span class=\"token punctuation\">(</span>cookies<span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>error<span class=\"token punctuation\">)</span> <span class=\"token keyword\">throw</span> error <span class=\"token comment\">// SuperTokens isn't initialized, which isn't a bad token</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>hasToken<span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token string\">'missing'</span>\n  <span class=\"token comment\">// Expired and forged tokens look the same here. Both go to /refresh, and a forged one fails there.</span>\n  <span class=\"token keyword\">return</span> accessTokenPayload <span class=\"token operator\">?</span> <span class=\"token string\">'valid'</span> <span class=\"token operator\">:</span> <span class=\"token string\">'expired'</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">async</span> <span class=\"token keyword\">function</span> <span class=\"token function\">proxy</span><span class=\"token punctuation\">(</span>request<span class=\"token operator\">:</span> NextRequest<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">{</span> pathname<span class=\"token punctuation\">,</span> search <span class=\"token punctuation\">}</span> <span class=\"token operator\">=</span> request<span class=\"token punctuation\">.</span>nextUrl\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token function\">isPublic</span><span class=\"token punctuation\">(</span>pathname<span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">next</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">const</span> state <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">readTokenState</span><span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>state <span class=\"token operator\">===</span> <span class=\"token string\">'valid'</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">next</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>pathname<span class=\"token punctuation\">.</span><span class=\"token function\">startsWith</span><span class=\"token punctuation\">(</span><span class=\"token string\">'/api/'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">const</span> challenge <span class=\"token operator\">=</span> state <span class=\"token operator\">===</span> <span class=\"token string\">'missing'</span> <span class=\"token operator\">?</span> <span class=\"token string\">'Bearer'</span> <span class=\"token operator\">:</span> <span class=\"token string\">'Bearer error=\"invalid_token\"'</span>\n    <span class=\"token keyword\">return</span> Response<span class=\"token punctuation\">.</span><span class=\"token function\">json</span><span class=\"token punctuation\">(</span>\n      <span class=\"token punctuation\">{</span> error<span class=\"token operator\">:</span> <span class=\"token string\">'Authentication required'</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n      <span class=\"token punctuation\">{</span> status<span class=\"token operator\">:</span> <span class=\"token number\">401</span><span class=\"token punctuation\">,</span> headers<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> <span class=\"token string-property property\">'WWW-Authenticate'</span><span class=\"token operator\">:</span> challenge <span class=\"token punctuation\">}</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n    <span class=\"token punctuation\">)</span>\n  <span class=\"token punctuation\">}</span>\n\n  <span class=\"token comment\">// Server Actions and other writes check for themselves, in a format their caller can read</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">.</span>method <span class=\"token operator\">!==</span> <span class=\"token string\">'GET'</span> <span class=\"token operator\">&amp;&amp;</span> request<span class=\"token punctuation\">.</span>method <span class=\"token operator\">!==</span> <span class=\"token string\">'HEAD'</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">next</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token comment\">// An expired token isn't a signed-out user. Send them to refresh, not to sign in.</span>\n  <span class=\"token keyword\">const</span> destination <span class=\"token operator\">=</span> <span class=\"token keyword\">new</span> <span class=\"token class-name\"><span class=\"token constant\">URL</span></span><span class=\"token punctuation\">(</span>state <span class=\"token operator\">===</span> <span class=\"token string\">'expired'</span> <span class=\"token operator\">?</span> <span class=\"token string\">'/refresh'</span> <span class=\"token operator\">:</span> <span class=\"token string\">'/auth'</span><span class=\"token punctuation\">,</span> request<span class=\"token punctuation\">.</span>url<span class=\"token punctuation\">)</span>\n  destination<span class=\"token punctuation\">.</span>searchParams<span class=\"token punctuation\">.</span><span class=\"token function\">set</span><span class=\"token punctuation\">(</span><span class=\"token string\">'redirectToPath'</span><span class=\"token punctuation\">,</span> pathname <span class=\"token operator\">+</span> search<span class=\"token punctuation\">)</span> <span class=\"token comment\">// the name SuperTokens' sign-in page reads</span>\n  <span class=\"token keyword\">return</span> NextResponse<span class=\"token punctuation\">.</span><span class=\"token function\">redirect</span><span class=\"token punctuation\">(</span>destination<span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">const</span> config <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token comment\">// Everything except build output, crawler files, and images, so new routes are covered by default</span>\n  matcher<span class=\"token operator\">:</span> <span class=\"token punctuation\">[</span><span class=\"token string\">'/((?!_next/static|_next/image|favicon.ico|robots.txt|sitemap.xml|.*\\\\.(?:png|jpg|jpeg|gif|svg|webp|ico)$).*)'</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">,</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Key implementation decisions:</p>\n<ul>\n<li><strong>Three states instead of four.</strong> <code class=\"language-text\">getSSRSession()</code> doesn’t say why a token failed, so an expired token and a forged one both go to <code class=\"language-text\">/refresh</code>. Without a valid refresh token behind it, the forged one ends up at sign-in. SuperTokens’ SSR docs route invalid and expired tokens through a refresh page the same way.</li>\n<li><strong>It still runs on the Edge.</strong> The same file as <code class=\"language-text\">middleware.ts</code>, with the function renamed, ran on the Edge runtime in Next.js 16.4.2 and gave the same answers for valid, missing, expired, and forged tokens.</li>\n<li><strong>No user ID in a header.</strong> SuperTokens’ guide also offers a <a href=\"https://supertokens.com/docs/integrations/nextjs/app-directory/protecting-backend/session-verification-middleware\" target=\"_blank\" rel=\"nofollow\">Proxy that forwards <code class=\"language-text\">x-user-id</code></a> to Route Handlers. It deletes any copy the client sent, but as the CVE section showed, that deletion only happens when Proxy runs. The DAL reads the session itself.</li>\n</ul>\n<h3 id=\"refresh-rotation-and-the-lock\" style=\"position:relative;\"><a href=\"#refresh-rotation-and-the-lock\" aria-label=\"refresh rotation and the lock permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Refresh, Rotation, and the Lock</h3>\n<p>The SDK replaces <code class=\"language-text\">lib/auth/tokens.ts</code>, the refresh Route Handler, and <code class=\"language-text\">lib/client/session.ts</code>. Its fetch interceptor watches every request to your API domain, and on a <code class=\"language-text\">401</code> it refreshes under a cross-tab lock and retries, which covers Route Handlers without any code. Proxy still sends expired page loads to <code class=\"language-text\">/refresh</code>, which now calls the SDK:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"17156948021269125000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/refresh/refresh-session.tsx\n'use client'\n\nimport { useEffect, useState } from 'react'\nimport Session from 'supertokens-auth-react/recipe/session'\nimport { localPath } from '@/lib/client/local-path'\n\nexport function RefreshSession() {\n  const [failed, setFailed] = useState(false)\n\n  useEffect(() => {\n    const next = localPath(new URLSearchParams(window.location.search).get('redirectToPath'))\n    // Takes the same cross-tab lock as the SDK's fetch interceptor\n    Session.attemptRefreshingSession()\n      // A full page load, so nothing the router fetched with the expired token gets reused\n      .then((ok) => window.location.replace(ok ? next : \\`/auth?redirectToPath=\\${encodeURIComponent(next)}\\`))\n      .catch(() => setFailed(true)) // the refresh call itself failed, which isn't the same as signed out\n  }, [])\n\n  return <p>{failed ? 'Something went wrong. Reload to try again.' : 'Refreshing your session…'}</p>\n}`, `17156948021269125000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"tsx\"><pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token comment\">// app/refresh/refresh-session.tsx</span>\n<span class=\"token string\">'use client'</span>\n\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> useEffect<span class=\"token punctuation\">,</span> useState <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span>\n<span class=\"token keyword\">import</span> Session <span class=\"token keyword\">from</span> <span class=\"token string\">'supertokens-auth-react/recipe/session'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> localPath <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'@/lib/client/local-path'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">function</span> <span class=\"token function\">RefreshSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">const</span> <span class=\"token punctuation\">[</span>failed<span class=\"token punctuation\">,</span> setFailed<span class=\"token punctuation\">]</span> <span class=\"token operator\">=</span> <span class=\"token function\">useState</span><span class=\"token punctuation\">(</span><span class=\"token boolean\">false</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token function\">useEffect</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">const</span> next <span class=\"token operator\">=</span> <span class=\"token function\">localPath</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">new</span> <span class=\"token class-name\">URLSearchParams</span><span class=\"token punctuation\">(</span>window<span class=\"token punctuation\">.</span>location<span class=\"token punctuation\">.</span>search<span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">get</span><span class=\"token punctuation\">(</span><span class=\"token string\">'redirectToPath'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n    <span class=\"token comment\">// Takes the same cross-tab lock as the SDK's fetch interceptor</span>\n    Session<span class=\"token punctuation\">.</span><span class=\"token function\">attemptRefreshingSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n      <span class=\"token comment\">// A full page load, so nothing the router fetched with the expired token gets reused</span>\n      <span class=\"token punctuation\">.</span><span class=\"token function\">then</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span>ok<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> window<span class=\"token punctuation\">.</span>location<span class=\"token punctuation\">.</span><span class=\"token function\">replace</span><span class=\"token punctuation\">(</span>ok <span class=\"token operator\">?</span> next <span class=\"token operator\">:</span> <span class=\"token template-string\"><span class=\"token template-punctuation string\">`</span><span class=\"token string\">/auth?redirectToPath=</span><span class=\"token interpolation\"><span class=\"token interpolation-punctuation punctuation\">${</span><span class=\"token function\">encodeURIComponent</span><span class=\"token punctuation\">(</span>next<span class=\"token punctuation\">)</span><span class=\"token interpolation-punctuation punctuation\">}</span></span><span class=\"token template-punctuation string\">`</span></span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n      <span class=\"token punctuation\">.</span><span class=\"token function\">catch</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token function\">setFailed</span><span class=\"token punctuation\">(</span><span class=\"token boolean\">true</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token comment\">// the refresh call itself failed, which isn't the same as signed out</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span> <span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">return</span> <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>p</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">{</span>failed <span class=\"token operator\">?</span> <span class=\"token string\">'Something went wrong. Reload to try again.'</span> <span class=\"token operator\">:</span> <span class=\"token string\">'Refreshing your session…'</span><span class=\"token punctuation\">}</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>p</span><span class=\"token punctuation\">></span></span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p><code class=\"language-text\">localPath()</code> moves, unchanged, from the session strategy section into <code class=\"language-text\">lib/client/local-path.ts</code>, because the sign-in page needs it too. Proxy sends signed-out users to <code class=\"language-text\">/auth?redirectToPath=…</code>, and the Proxy section’s rule applies there as well: only follow it to a path on this site. Add the check to the frontend config from SuperTokens’ guide:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"80098586155039490000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// app/config/frontend.tsx, in the object frontendConfig() returns\ngetRedirectionURL: async (context) => {\n  // After sign-in, follow redirectToPath only to a path on this site\n  if (context.action === 'SUCCESS') return localPath(context.redirectToPath ?? null)\n  return undefined // SuperTokens' default for everything else\n},`, `80098586155039490000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// app/config/frontend.tsx, in the object frontendConfig() returns</span>\n<span class=\"token function-variable function\">getRedirectionURL</span><span class=\"token operator\">:</span> <span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span>context<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token comment\">// After sign-in, follow redirectToPath only to a path on this site</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>context<span class=\"token punctuation\">.</span>action <span class=\"token operator\">===</span> <span class=\"token string\">'SUCCESS'</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token function\">localPath</span><span class=\"token punctuation\">(</span>context<span class=\"token punctuation\">.</span>redirectToPath <span class=\"token operator\">??</span> <span class=\"token keyword\">null</span><span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">return</span> <span class=\"token keyword\">undefined</span> <span class=\"token comment\">// SuperTokens' default for everything else</span>\n<span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span></code></pre></div>\n<p>In the test app, no <code class=\"language-text\">redirectToPath</code> value left the site after sign-in, and local paths kept their query strings.</p>\n<p>Rotation keeps the hand-built rule on a different schedule. Replaying a refresh token after the tokens that replaced it had been used got a <code class=\"language-text\">401</code> with “token theft detected,” cleared both cookies, and revoked the session, the SDK’s <a href=\"https://supertokens.com/docs/post-authentication/session-management/advanced-workflows/customize-error-handling\" target=\"_blank\" rel=\"nofollow\">default response</a> to theft. But with supertokens-node 24.0.3, the core retires a refresh token when its replacement is first used, not when it’s spent, so two refreshes sent at once with the same token both succeeded. The race from the session strategy section is survivable until two requests use different token pairs: when one went out with the first pair’s access token while the cookie jar kept the second, the next refresh tripped theft detection. The cross-tab lock keeps the pairs from splitting: three tabs refreshing together made one or two refresh calls between them, never three, and all three landed back on the invoices page signed in. Core 12.1 added rotation at refresh time, with a 30-second grace period for the old token, for SDKs on its newer driver interface, and supertokens-node 24.0.3 isn’t one of them.</p>\n<p>The page-level refresh from the Server Components section has an SDK version too: the guide’s <a href=\"https://supertokens.com/docs/integrations/nextjs/app-directory/protecting-route\" target=\"_blank\" rel=\"nofollow\"><code class=\"language-text\">TryRefreshComponent</code></a> calls <code class=\"language-text\">Session.attemptRefreshingSession()</code>, then <code class=\"language-text\">router.refresh()</code>, or <code class=\"language-text\">redirectToAuth()</code> if the refresh fails. For a page Proxy doesn’t cover, render it when the DAL rejects a token the request still carries:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"23412905495388283000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// Inside a page that Proxy doesn't cover\nconst session = await getSession()\nif (!session) {\n  // A token the DAL couldn't use: expired, revoked, or forged. The refresh endpoint sorts them out.\n  if ((await cookies()).has('sAccessToken')) return <TryRefreshComponent key={Date.now()} />\n  redirect('/auth')\n}`, `23412905495388283000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"tsx\"><pre class=\"language-tsx\"><code class=\"language-tsx\"><span class=\"token comment\">// Inside a page that Proxy doesn't cover</span>\n<span class=\"token keyword\">const</span> session <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">getSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n<span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>session<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token comment\">// A token the DAL couldn't use: expired, revoked, or forged. The refresh endpoint sorts them out.</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">(</span><span class=\"token keyword\">await</span> <span class=\"token function\">cookies</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">.</span><span class=\"token function\">has</span><span class=\"token punctuation\">(</span><span class=\"token string\">'sAccessToken'</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> <span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span><span class=\"token class-name\">TryRefreshComponent</span></span> <span class=\"token attr-name\">key</span><span class=\"token script language-javascript\"><span class=\"token script-punctuation punctuation\">=</span><span class=\"token punctuation\">{</span>Date<span class=\"token punctuation\">.</span><span class=\"token function\">now</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">}</span></span> <span class=\"token punctuation\">/></span></span>\n  <span class=\"token function\">redirect</span><span class=\"token punctuation\">(</span><span class=\"token string\">'/auth'</span><span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>In the test app, that page refreshed once and rendered with the new token.</p>\n<p>Mobile apps use <a href=\"https://supertokens.com/docs/post-authentication/session-management/switch-between-cookies-and-header-authentication\" target=\"_blank\" rel=\"nofollow\">header mode</a>, the default in SuperTokens’ mobile SDKs. A sign-in request with <code class=\"language-text\">st-auth-mode: header</code> gets its tokens back in <code class=\"language-text\">st-access-token</code> and <code class=\"language-text\">st-refresh-token</code> response headers instead of cookies. The app sends the access token as a bearer token, which the DAL and Proxy already read, and refreshes by sending the refresh token as the bearer token to <code class=\"language-text\">/api/auth/session/refresh</code>.</p>\n<h3 id=\"server-actions-after-an-expiry\" style=\"position:relative;\"><a href=\"#server-actions-after-an-expiry\" aria-label=\"server actions after an expiry permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Server Actions After an Expiry</h3>\n<p>The fetch interceptor refreshes on a <code class=\"language-text\">401</code>, and the actions in this guide never return one. They answer an expired token with <code class=\"language-text\">{ ok: false, error: 'Authentication required' }</code> and a <code class=\"language-text\">200</code>, and that’s exactly what the test app got, with no refresh attempt. With a one-hour access token, that’s anyone who leaves a tab open over lunch. Wrap the action on the client:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"15654610048220041000\"\n              data-toaster-class=\"gatsby-code-button-toaster\"\n              data-toaster-text-class=\"gatsby-code-button-toaster-text\"\n              data-toaster-text=\"Copied!\"\n              data-toaster-duration=\"3500\"\n              onClick=\"copyToClipboard(`// lib/client/with-refresh.ts\nimport Session from 'supertokens-auth-react/recipe/session'\n\ntype Result = { ok: boolean; error?: string } | null\n\n// Server Actions answer 200 even when the DAL refuses, so the SDK's fetch interceptor never sees a 401\nexport function withRefresh<Args extends unknown[], R extends Result>(action: (...args: Args) => Promise<R>) {\n  return async (...args: Args): Promise<R> => {\n    const result = await action(...args)\n    if (result === null || result.ok || result.error !== 'Authentication required') return result\n    // Most likely an expired access token: refresh once, then retry once\n    return (await Session.attemptRefreshingSession()) ? action(...args) : result\n  }\n}`, `15654610048220041000`)\"\n            >\n              <div\n                class=\"gatsby-code-button\"\n                data-tooltip=\"\"\n              >\n                <svg class=\"gatsby-code-button-icon\" xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M16 1H2v16h2V3h12V1zm-1 4l6 6v12H6V5h9zm-1 7h5.5L14 6.5V12z\"/></svg>\n              </div>\n            </div>\n<div class=\"gatsby-highlight\" data-language=\"ts\"><pre class=\"language-ts\"><code class=\"language-ts\"><span class=\"token comment\">// lib/client/with-refresh.ts</span>\n<span class=\"token keyword\">import</span> Session <span class=\"token keyword\">from</span> <span class=\"token string\">'supertokens-auth-react/recipe/session'</span>\n\n<span class=\"token keyword\">type</span> <span class=\"token class-name\">Result</span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span> ok<span class=\"token operator\">:</span> <span class=\"token builtin\">boolean</span><span class=\"token punctuation\">;</span> error<span class=\"token operator\">?</span><span class=\"token operator\">:</span> <span class=\"token builtin\">string</span> <span class=\"token punctuation\">}</span> <span class=\"token operator\">|</span> <span class=\"token keyword\">null</span>\n\n<span class=\"token comment\">// Server Actions answer 200 even when the DAL refuses, so the SDK's fetch interceptor never sees a 401</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">function</span> <span class=\"token generic-function\"><span class=\"token function\">withRefresh</span><span class=\"token generic class-name\"><span class=\"token operator\">&lt;</span>Args <span class=\"token keyword\">extends</span> <span class=\"token builtin\">unknown</span><span class=\"token punctuation\">[</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">,</span> <span class=\"token constant\">R</span> <span class=\"token keyword\">extends</span> Result<span class=\"token operator\">></span></span></span><span class=\"token punctuation\">(</span><span class=\"token function-variable function\">action</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">...</span>args<span class=\"token operator\">:</span> Args<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span><span class=\"token constant\">R</span><span class=\"token operator\">></span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  <span class=\"token keyword\">return</span> <span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">...</span>args<span class=\"token operator\">:</span> Args<span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> <span class=\"token builtin\">Promise</span><span class=\"token operator\">&lt;</span><span class=\"token constant\">R</span><span class=\"token operator\">></span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">const</span> result <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">action</span><span class=\"token punctuation\">(</span><span class=\"token operator\">...</span>args<span class=\"token punctuation\">)</span>\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>result <span class=\"token operator\">===</span> <span class=\"token keyword\">null</span> <span class=\"token operator\">||</span> result<span class=\"token punctuation\">.</span>ok <span class=\"token operator\">||</span> result<span class=\"token punctuation\">.</span>error <span class=\"token operator\">!==</span> <span class=\"token string\">'Authentication required'</span><span class=\"token punctuation\">)</span> <span class=\"token keyword\">return</span> result\n    <span class=\"token comment\">// Most likely an expired access token: refresh once, then retry once</span>\n    <span class=\"token keyword\">return</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">await</span> Session<span class=\"token punctuation\">.</span><span class=\"token function\">attemptRefreshingSession</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">?</span> <span class=\"token function\">action</span><span class=\"token punctuation\">(</span><span class=\"token operator\">...</span>args<span class=\"token punctuation\">)</span> <span class=\"token operator\">:</span> result\n  <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>The delete button then calls <code class=\"language-text\">useActionState(withRefresh(deleteInvoiceAction), null)</code>. Retrying is safe because the DAL refused before anything was written.</p>\n<h3 id=\"what-it-returned-1\" style=\"position:relative;\"><a href=\"#what-it-returned-1\" aria-label=\"what it returned 1 permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>What It Returned</h3>\n<table>\n<thead>\n<tr>\n<th>Request</th>\n<th>Result</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Page, no session</td>\n<td><code class=\"language-text\">307</code> to <code class=\"language-text\">/auth?redirectToPath=…</code></td>\n</tr>\n<tr>\n<td>Page load or client-side navigation, expired token</td>\n<td><code class=\"language-text\">/refresh</code>, one refresh, then the page</td>\n</tr>\n<tr>\n<td><code class=\"language-text\">fetch()</code> to a Route Handler, expired token</td>\n<td><code class=\"language-text\">401</code>, one refresh, an automatic retry, <code class=\"language-text\">200</code></td>\n</tr>\n<tr>\n<td>Server Action, expired token</td>\n<td>“Authentication required”, or <code class=\"language-text\">{ ok: true }</code> through <code class=\"language-text\">withRefresh()</code></td>\n</tr>\n<tr>\n<td>Session revoked with <code class=\"language-text\">revokeAllSessionsForUser()</code></td>\n<td>Passed Proxy; pages redirected to <code class=\"language-text\">/auth</code>, Route Handlers returned <code class=\"language-text\">401</code></td>\n</tr>\n<tr>\n<td>Admin role removed mid-session</td>\n<td><code class=\"language-text\">403</code> on the next request</td>\n</tr>\n<tr>\n<td>Old refresh token replayed</td>\n<td><code class=\"language-text\">401</code>, “token theft detected”, session revoked</td>\n</tr>\n<tr>\n<td>Member and admin on the streaming dashboard</td>\n<td>Same as before: the overdue count for the admin only</td>\n</tr>\n</tbody>\n</table>\n<p>To put this in your own app, start with SuperTokens’ <a href=\"https://supertokens.com/docs/integrations/nextjs/app-directory/about\" target=\"_blank\" rel=\"nofollow\">Next.js App Router integration guide</a> for the config files and auth routes, and add <code class=\"language-text\">UserRoles.init()</code> to the backend recipe list. Then work through this section’s code: the new <code class=\"language-text\">readSession()</code> body, Proxy’s token check, the <code class=\"language-text\">/refresh</code> page, the <code class=\"language-text\">redirectToPath</code> check, and <code class=\"language-text\">withRefresh()</code> for Server Actions. To run the core yourself, follow the <a href=\"https://supertokens.com/docs/deployment/self-host-supertokens\" target=\"_blank\" rel=\"nofollow\">self-hosting guide</a>. For a second factor, see <a href=\"https://supertokens.com/blog/add-mfa-to-nextjs\" target=\"_blank\" rel=\"nofollow\">how to add MFA to Next.js with SuperTokens</a>.</p>\n<p>Let SuperTokens own the tokens. Keep the checks in your DAL.</p>\n<h2 id=\"faq\" style=\"position:relative;\"><a href=\"#faq\" aria-label=\"faq permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>FAQ</h2>\n<h3 id=\"is-middleware-enough-to-protect-a-nextjs-app\" style=\"position:relative;\"><a href=\"#is-middleware-enough-to-protect-a-nextjs-app\" aria-label=\"is middleware enough to protect a nextjs app permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Is Middleware Enough to Protect a Next.js App?</h3>\n<p>No. Proxy, the Next.js 16 name for middleware, runs before the route does, which makes it the fastest check and the easiest one to skip. A path outside its matcher never reaches it, a Server Action is covered only if the page it posts to is, and CVE-2025-29927 plus five advisories in 2026 all let requests reach protected routes without it running. The <a href=\"https://nextjs.org/docs/app/getting-started/proxy#use-cases\" target=\"_blank\" rel=\"nofollow\">Next.js docs</a> say Proxy “should not be used as a full session management or authorization solution.” Keep it as a fast first check, and make the DAL the one every page, action, and handler goes through.</p>\n<h3 id=\"was-my-app-affected-by-cve-2025-29927-and-is-upgrading-enough\" style=\"position:relative;\"><a href=\"#was-my-app-affected-by-cve-2025-29927-and-is-upgrading-enough\" aria-label=\"was my app affected by cve 2025 29927 and is upgrading enough permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Was My App Affected by CVE-2025-29927, and Is Upgrading Enough?</h3>\n<p>If you self-hosted with <code class=\"language-text\">next start</code> or <code class=\"language-text\">output: 'standalone'</code>, you were exposed from 11.1.4 until your release line’s fix: 15.2.3, 14.2.25, 13.5.9, or 12.3.5. The 11.x line never got one. Apps on Vercel, Netlify, and Cloudflare Workers weren’t exposed, and static exports don’t run middleware. A follow-up, <a href=\"https://github.com/vercel/next.js/security/advisories/GHSA-223j-4rm8-mrmf\" target=\"_blank\" rel=\"nofollow\">CVE-2025-30218</a>, moved the floor to 15.2.4, 14.2.26, 13.5.10, and 12.3.6. Upgrading closes that bypass, not the pattern: the 2026 advisories found new ways around a patched Proxy. Patch, and keep the authorization check in the DAL.</p>\n<h3 id=\"what-is-a-data-access-layer-in-nextjs\" style=\"position:relative;\"><a href=\"#what-is-a-data-access-layer-in-nextjs\" aria-label=\"what is a data access layer in nextjs permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>What Is a Data Access Layer in Next.js?</h3>\n<p>A server-only module that owns every database read and write, where every exported function checks the session before it touches data. Pages, Server Actions, and Route Handlers call functions like <code class=\"language-text\">getMyInvoices()</code> instead of the database, so a check that’s missing somewhere else doesn’t become a leak. Ownership lives in the query, and only the fields the UI needs leave the module. The <a href=\"https://nextjs.org/blog/security-nextjs-server-components-actions\" target=\"_blank\" rel=\"nofollow\">Next.js team recommends</a> it for new projects, and the DAL section builds a complete one.</p>\n<h3 id=\"do-i-need-proxy-at-all\" style=\"position:relative;\"><a href=\"#do-i-need-proxy-at-all\" aria-label=\"do i need proxy at all permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Do I Need Proxy at All?</h3>\n<p>Not to protect your data. The DAL covers everything fetched at request time, and the Next.js authentication guide marks Proxy as <a href=\"https://nextjs.org/docs/app/guides/authentication#optimistic-checks-with-proxy-optional\" target=\"_blank\" rel=\"nofollow\">optional</a>. Proxy still earns its place in three ways. It’s the only layer that can still return a real <code class=\"language-text\">307</code> for a page that streams. It’s the only protection for static routes that share data between users, where nothing runs per request. And it can send expired tokens to <code class=\"language-text\">/refresh</code> before anything renders. The cost is that it runs on every matched request, prefetches included: in the test app, one view of a page with ten links ran it 15 times.</p>\n<h3 id=\"should-proxy-run-on-the-edge-or-nodejs-runtime\" style=\"position:relative;\"><a href=\"#should-proxy-run-on-the-edge-or-nodejs-runtime\" aria-label=\"should proxy run on the edge or nodejs runtime permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Should Proxy Run on the Edge or Node.js Runtime?</h3>\n<p>On Next.js 16, <code class=\"language-text\">proxy.ts</code> only runs on Node.js, and asking it for Edge fails the build with “Proxy does not support Edge runtime.” The deprecated <code class=\"language-text\">middleware.ts</code> still runs on the Edge, and an app can’t have both. Node.js is the simpler choice, since any library works there, though Proxy still shouldn’t query the database. If you stay on the Edge, verify tokens with a library built on Web Crypto, like <a href=\"https://github.com/panva/jose\" target=\"_blank\" rel=\"nofollow\">jose</a>. In the test app, a JWT library that depends on Node’s <code class=\"language-text\">crypto</code> module compiled without complaint in Edge middleware, then sent every valid session to the login page.</p>\n<h3 id=\"how-do-i-protect-server-actions\" style=\"position:relative;\"><a href=\"#how-do-i-protect-server-actions\" aria-label=\"how do i protect server actions permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>How Do I Protect Server Actions?</h3>\n<p>Check inside every action, through the DAL. A Server Action is a POST to whatever page the user is on, with a header naming the function, so a page-level check doesn’t cover it, and Proxy covers it only when that page’s path is in the matcher. Validate the input first, hidden fields and bound arguments included, let the DAL decide who’s allowed, and return only what the UI renders. The <a href=\"https://nextjs.org/docs/app/guides/server-actions#security\" target=\"_blank\" rel=\"nofollow\">Next.js docs</a> put it in one line: “Treat every action as an untrusted entry point.”</p>\n<h3 id=\"why-does-my-server-component-get-a-401-from-my-own-route-handler\" style=\"position:relative;\"><a href=\"#why-does-my-server-component-get-a-401-from-my-own-route-handler\" aria-label=\"why does my server component get a 401 from my own route handler permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Why Does My Server Component Get a 401 from My Own Route Handler?</h3>\n<p>A <code class=\"language-text\">fetch</code> from the server doesn’t carry the browser’s cookies, so the handler sees a signed-out request. In the test app, a page’s plain <code class=\"language-text\">fetch</code> to its own <code class=\"language-text\">/api/invoices/inv_1</code> got a <code class=\"language-text\">401</code>. Forwarding the cookie header got a <code class=\"language-text\">200</code>, at the cost of an HTTP round trip to its own server. The <a href=\"https://nextjs.org/docs/app/guides/backend-for-frontend#server-components\" target=\"_blank\" rel=\"nofollow\">Next.js docs</a> say to fetch data in Server Components “directly from its source, not via Route Handlers.” With a DAL, that means calling <code class=\"language-text\">getInvoice()</code> instead of the endpoint that wraps it.</p>\n<h3 id=\"why-does-my-auth-redirect-return-a-200\" style=\"position:relative;\"><a href=\"#why-does-my-auth-redirect-return-a-200\" aria-label=\"why does my auth redirect return a 200 permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Why Does My Auth Redirect Return a 200?</h3>\n<p>Because the response had already started streaming. Once a <code class=\"language-text\">loading.js</code> fallback, a Suspense boundary, or a Cache Components shell goes out, the <a href=\"https://nextjs.org/docs/app/api-reference/file-conventions/loading#status-codes\" target=\"_blank\" rel=\"nofollow\">status code is fixed</a> at <code class=\"language-text\">200</code>, and <code class=\"language-text\">redirect()</code> turns into a meta refresh and a client-side redirect. The protected data still never renders. What changes is what crawlers, monitors, and API clients see. For a real <code class=\"language-text\">307</code>, the check has to run before anything streams: in Proxy, or, with Cache Components off, at the top of a page with nothing suspended above it.</p>\n<h3 id=\"does-cache-components-change-how-authentication-works\" style=\"position:relative;\"><a href=\"#does-cache-components-change-how-authentication-works\" aria-label=\"does cache components change how authentication works permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Does Cache Components Change How Authentication Works?</h3>\n<p>It changes where checks can run. With it on, reading cookies outside a Suspense boundary <a href=\"https://nextjs.org/docs/app/guides/authentication-with-cache-components\" target=\"_blank\" rel=\"nofollow\">fails the build</a>, so checks move into components inside boundaries, and everything outside them becomes a static shell that every visitor gets, signed in or not. GET Route Handlers that never read the request can be prerendered too. In the test app, one with no check of its own was served to a signed-out request with <code class=\"language-text\">s-maxage=3600</code>. Keep anything viewer-specific behind a boundary and the DAL, and use Proxy for anything the shell itself shouldn’t show.</p>\n<h3 id=\"should-session-tokens-go-in-cookies-or-localstorage\" style=\"position:relative;\"><a href=\"#should-session-tokens-go-in-cookies-or-localstorage\" aria-label=\"should session tokens go in cookies or localstorage permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Should Session Tokens Go in Cookies or localStorage?</h3>\n<p>In a browser, <a href=\"https://supertokens.com/blog/cookies-vs-localstorage-for-sessions-everything-you-need-to-know\" target=\"_blank\" rel=\"nofollow\"><code class=\"language-text\">httpOnly</code> cookies</a>. Anything in <code class=\"language-text\">localStorage</code> is readable by every script on the page, so one XSS bug hands over the session. OWASP’s <a href=\"https://cheatsheetseries.owasp.org/cheatsheets/HTML5_Security_Cheat_Sheet.html\" target=\"_blank\" rel=\"nofollow\">HTML5 Security Cheat Sheet</a> is direct about it: “Do not store session identifiers in local storage as the data is always accessible by JavaScript.” Cookies bring CSRF into play, which <code class=\"language-text\">SameSite</code>, Next.js’s <code class=\"language-text\">Origin</code> check on Server Actions, and the <code class=\"language-text\">Origin</code> check from the Route Handler section cover. Mobile apps are the exception: they keep tokens in the Keychain or Keystore and send them as bearer tokens.</p>\n<h3 id=\"how-long-should-access-tokens-live\" style=\"position:relative;\"><a href=\"#how-long-should-access-tokens-live\" aria-label=\"how long should access tokens live permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>How Long Should Access Tokens Live?</h3>\n<p>As long as you’re willing to let a revoked session through the checks that skip the database. When the DAL checks the session store on every request, revocation is immediate for data, and the access token’s lifetime only limits what Proxy lets through. This guide used 15 minutes. SuperTokens defaults to an hour, set by <code class=\"language-text\">access_token_validity</code>. Shorter tokens mean more refreshes and more chances for the refresh race from the session strategy section, which is what the cross-tab lock is for.</p>\n<h3 id=\"do-i-need-supertokens-for-nextjs-app-router-authentication\" style=\"position:relative;\"><a href=\"#do-i-need-supertokens-for-nextjs-app-router-authentication\" aria-label=\"do i need supertokens for nextjs app router authentication permalink\" class=\"anchor before\"><svg aria-hidden=\"true\" focusable=\"false\" height=\"16\" version=\"1.1\" viewBox=\"0 0 16 16\" width=\"16\"><path fill-rule=\"evenodd\" d=\"M4 9h1v1H4c-1.5 0-3-1.69-3-3.5S2.55 3 4 3h4c1.45 0 3 1.69 3 3.5 0 1.41-.91 2.72-2 3.25V8.59c.58-.45 1-1.27 1-2.09C10 5.22 8.98 4 8 4H4c-.98 0-2 1.22-2 2.5S3 9 4 9zm9-3h-1v1h1c1 0 2 1.22 2 2.5S13.98 12 13 12H9c-.98 0-2-1.22-2-2.5 0-.83.42-1.64 1-2.09V6.25c-1.09.53-2 1.84-2 3.25C6 11.31 7.55 13 9 13h4c1.45 0 3-1.69 3-3.5S14.5 6 13 6z\"></path></svg></a>Do I Need SuperTokens for Next.js App Router Authentication?</h3>\n<p>No. Everything before the SuperTokens section is provider-neutral, and the provider lives in three places: <code class=\"language-text\">readSession()</code>, Proxy’s <code class=\"language-text\">readTokenState()</code>, and the token code. Any auth library that can verify a session on the server, revocation included, fits there. SuperTokens fills all three with an <a href=\"https://github.com/supertokens/supertokens-core\" target=\"_blank\" rel=\"nofollow\">open-source core</a> you can self-host or run on its managed service, plus the refresh handling and cross-tab lock you’d otherwise build. The trade-off is two calls to the core for each render that reads data, which count against the managed service’s rate limit.</p>\n<p>Check where the data is. Everything else is a fast first answer.</p>","frontmatter":{"date":"November 11, 2026","updated":null,"title":"Next.js App Router Authentication: The Complete Guide (2026)","cover":"nextjs-app-router-auth-cover.png","author":"Maurice Saldivar","description":"Learn how to secure Next.js App Router authentication after CVE-2025-29927, across Server Components, Server Actions, and Route Handlers, using SuperTokens."},"fields":{"slug":"/nextjs-app-router-authentication/"}},"site":{"siteMetadata":{"title":"SuperTokens Blog"}}},"pageContext":{"id":"f09d7d27-c5fc-5867-a105-7e93debdd4f0","fields__slug":"/nextjs-app-router-authentication/","__params":{"fields__slug":"nextjs-app-router-authentication"}}},
    "staticQueryHashes": []}