{
    "componentChunkName": "component---src-pages-blog-markdown-remark-fields-slug-js",
    "path": "/blog/how-do-i-add-auth-nextjs-app",
    "result": {"data":{"markdownRemark":{"html":"<p>Authentication is a solved problem in most frameworks. In Next.js it keeps getting re-solved, because the framework splits your application across more execution contexts than almost anything else in mainstream web development. Server components, client components, middleware, and route handlers all need to know who the user is, and each one reads cookies and validates sessions differently. A session hook that works in a client component won’t run in a server component. Middleware is a moving target: Next.js 16 renamed <code class=\"language-text\">middleware.ts</code> to <code class=\"language-text\">proxy.ts</code>, which runs on Node.js, while apps still on <code class=\"language-text\">middleware.ts</code> default to the edge runtime, where plenty of Node libraries won’t load. Layer in the App Router and Pages Router split, SSR hydration, and aggressive caching on platforms like Vercel, and “add a login page” quietly becomes an architecture decision.</p>\n<p>You have three realistic paths. Build auth yourself and own token rotation, CSRF protection, and refresh logic forever. Hand it to a managed provider and accept per-user pricing and vendor lock-in. Or run an open source framework inside your own stack.</p>\n<p>SuperTokens takes the third path. It’s an open source, extensible auth framework: a core service you can self-host for free, backend and frontend SDKs that embed directly into your Next.js codebase, and prebuilt UI for login, signup, and session management. Your user data stays in your database, and recipe overrides let you customize almost any part of the flow.</p>\n<p>This guide walks through adding authentication to a Next.js app with SuperTokens: setup, login, signup, and sessions. If you’re specifically on the App Router, our companion walkthrough, <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 using the App Directory and SuperTokens</a>, goes deeper on that pattern.</p>\n<h2 id=\"what-do-i-need-before-adding-authentication-to-my-nextjs-app\" style=\"position:relative;\"><a href=\"#what-do-i-need-before-adding-authentication-to-my-nextjs-app\" aria-label=\"what do i need before adding authentication to my 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>What do I need before adding authentication to my Next.js app?</h2>\n<p>Not much. If you’ve shipped anything with Next.js before, you probably have everything on this list already.</p>\n<p><strong>Node.js and a Next.js project.</strong> Install the current LTS release of Node.js; recent Next.js versions enforce a minimum runtime and refuse to start on anything older. If you don’t have a project yet, <code class=\"language-text\">npx create-next-app@latest</code> scaffolds one in under a minute. SuperTokens supports both the App Router and the Pages Router. The examples in this guide use the App Router.</p>\n<p><strong>Working React and Next.js knowledge.</strong> You don’t need to be an expert, but you should be comfortable with components, hooks, and the difference between client and server components. Authentication in Next.js lives exactly at that boundary, so knowing which side of <code class=\"language-text\">'use client'</code> your code runs on will save you real debugging time. If you can write a route handler under <code class=\"language-text\">app/api/</code>, you know enough.</p>\n<p><strong>Environment variables for your SuperTokens config.</strong> SuperTokens needs a connection URI pointing at a core instance, an API key if your core requires one, and OAuth credentials for any social providers you add. Put them in <code class=\"language-text\">.env.local</code>, which Next.js loads automatically:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"95918911997431940000\"\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(`# .env.local\nSUPERTOKENS_CONNECTION_URI=https://try.supertokens.io\n# Only needed for the managed service or a self-hosted core with API keys enabled\nSUPERTOKENS_API_KEY=your-api-key\nGOOGLE_CLIENT_ID=your-google-client-id\nGOOGLE_CLIENT_SECRET=your-google-client-secret`, `95918911997431940000`)\"\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=\"bash\"><pre class=\"language-bash\"><code class=\"language-bash\"><span class=\"token comment\"># .env.local</span>\n<span class=\"token assign-left variable\">SUPERTOKENS_CONNECTION_URI</span><span class=\"token operator\">=</span>https://try.supertokens.io\n<span class=\"token comment\"># Only needed for the managed service or a self-hosted core with API keys enabled</span>\n<span class=\"token assign-left variable\">SUPERTOKENS_API_KEY</span><span class=\"token operator\">=</span>your-api-key\n<span class=\"token assign-left variable\">GOOGLE_CLIENT_ID</span><span class=\"token operator\">=</span>your-google-client-id\n<span class=\"token assign-left variable\">GOOGLE_CLIENT_SECRET</span><span class=\"token operator\">=</span>your-google-client-secret</code></pre></div>\n<p>The <code class=\"language-text\">try.supertokens.io</code> core is a free shared instance meant for development. It works for this guide, but swap in your own self-hosted core or a managed instance before production. One Next.js-specific warning: anything prefixed with <code class=\"language-text\">NEXT_PUBLIC_</code> gets bundled into the browser. Your API key and client secrets should never carry that prefix.</p>\n<h2 id=\"how-do-i-install-supertokens-in-my-nextjs-project\" style=\"position:relative;\"><a href=\"#how-do-i-install-supertokens-in-my-nextjs-project\" aria-label=\"how do i install supertokens in my nextjs project 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 install SuperTokens in my Next.js project?</h2>\n<p>One command covers it:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"4607273934150591000\"\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(`npm install supertokens-node supertokens-auth-react supertokens-web-js nextjs-cors`, `4607273934150591000`)\"\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=\"bash\"><pre class=\"language-bash\"><code class=\"language-bash\"><span class=\"token function\">npm</span> <span class=\"token function\">install</span> supertokens-node supertokens-auth-react supertokens-web-js nextjs-cors</code></pre></div>\n<p>Starting a project from scratch instead? <code class=\"language-text\">npx create-supertokens-app@latest</code> scaffolds a Next.js app with all of this wired up. If you’re adding auth to an existing codebase, it’s worth knowing what each package does, because the split mirrors where authentication work actually happens.</p>\n<p><strong><code class=\"language-text\">supertokens-node</code> is the backend SDK.</strong> It runs inside your route handlers under <code class=\"language-text\">app/api/</code>, exposes the auth endpoints (sign up, sign in, sign out, session refresh) so you never write them by hand, and verifies sessions in server components and protected API routes. It’s also the only piece that talks to the SuperTokens core, which means your connection URI and API key stay server-side.</p>\n<p><strong><code class=\"language-text\">supertokens-auth-react</code> is the frontend SDK.</strong> It renders the prebuilt login and signup UI, tracks session state in the browser, and refreshes tokens transparently when they expire. You’ll initialize it once in a client component and mostly forget it exists.</p>\n<p>The other two are supporting cast. <code class=\"language-text\">supertokens-web-js</code> is the lower-level browser SDK that <code class=\"language-text\">supertokens-auth-react</code> builds on: npm pulls it in automatically as a peer dependency, but yarn and pnpm want it listed explicitly, and it’s the package you’d reach for if you build a fully custom UI. <code class=\"language-text\">nextjs-cors</code> sets CORS headers on your API routes, which matters if your frontend and API ever live on different domains and costs nothing when they don’t.</p>\n<p>In most stacks the backend and frontend SDKs live in separate repositories. Next.js is the exception: everything installs into one project, because the framework serves your React code and your API routes from the same codebase. Note what that command does not install: the SuperTokens core. The core is a standalone service, not an npm dependency. During development, the shared <code class=\"language-text\">try.supertokens.io</code> instance fills that role; in production, your connection URI points at a core you run in Docker or a managed instance.</p>\n<h2 id=\"how-do-i-configure-authentication-on-the-backend\" style=\"position:relative;\"><a href=\"#how-do-i-configure-authentication-on-the-backend\" aria-label=\"how do i configure authentication on the backend 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 configure authentication on the backend?</h2>\n<p>The backend in this case is not a separate server. It’s three files inside your Next.js project, and the SuperTokens SDK does the heavy lifting in all of them.</p>\n<p><strong>First, the shared app info.</strong> Both SDKs need to agree on where things live, so this config gets its own file:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"7985018669472544000\"\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/appInfo.ts\nexport const appInfo = {\n  appName: 'my-next-app',\n  apiDomain: 'http://localhost:3000',\n  websiteDomain: 'http://localhost:3000',\n  apiBasePath: '/api/auth',\n  websiteBasePath: '/auth',\n}`, `7985018669472544000`)\"\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/appInfo.ts</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">const</span> appInfo <span class=\"token operator\">=</span> <span class=\"token punctuation\">{</span>\n  appName<span class=\"token operator\">:</span> <span class=\"token string\">'my-next-app'</span><span class=\"token punctuation\">,</span>\n  apiDomain<span class=\"token operator\">:</span> <span class=\"token string\">'http://localhost:3000'</span><span class=\"token punctuation\">,</span>\n  websiteDomain<span class=\"token operator\">:</span> <span class=\"token string\">'http://localhost:3000'</span><span class=\"token punctuation\">,</span>\n  apiBasePath<span class=\"token operator\">:</span> <span class=\"token string\">'/api/auth'</span><span class=\"token punctuation\">,</span>\n  websiteBasePath<span class=\"token operator\">:</span> <span class=\"token string\">'/auth'</span><span class=\"token punctuation\">,</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>One rule matters here: <code class=\"language-text\">apiBasePath</code> and <code class=\"language-text\">websiteBasePath</code> cannot be the same. Next.js serves your frontend and your API from one domain, and if both paths collide, routing breaks in ways that are annoying to debug.</p>\n<p><strong>Second, the backend config.</strong> This is where you pick your auth method and connect to the core:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"64958712176527335000\"\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/backend.ts\nimport SuperTokens from 'supertokens-node'\nimport EmailPassword from 'supertokens-node/recipe/emailpassword'\nimport Session from 'supertokens-node/recipe/session'\nimport { TypeInput } from 'supertokens-node/types'\nimport { appInfo } from './appInfo'\n\nexport const backendConfig = (): TypeInput => ({\n  framework: 'custom',\n  supertokens: {\n    connectionURI: process.env.SUPERTOKENS_CONNECTION_URI!,\n    apiKey: process.env.SUPERTOKENS_API_KEY,\n  },\n  appInfo,\n  recipeList: [EmailPassword.init(), Session.init()],\n  isInServerlessEnv: true,\n})\n\nlet initialized = false\nexport function ensureSuperTokensInit() {\n  if (!initialized) {\n    SuperTokens.init(backendConfig())\n    initialized = true\n  }\n}`, `64958712176527335000`)\"\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/backend.ts</span>\n<span class=\"token keyword\">import</span> SuperTokens <span class=\"token keyword\">from</span> <span class=\"token string\">'supertokens-node'</span>\n<span class=\"token keyword\">import</span> EmailPassword <span class=\"token keyword\">from</span> <span class=\"token string\">'supertokens-node/recipe/emailpassword'</span>\n<span class=\"token keyword\">import</span> Session <span class=\"token keyword\">from</span> <span class=\"token string\">'supertokens-node/recipe/session'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> TypeInput <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'supertokens-node/types'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> appInfo <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'./appInfo'</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">const</span> backendConfig <span class=\"token operator\">=</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> TypeInput <span class=\"token operator\">=></span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n  framework<span class=\"token operator\">:</span> <span class=\"token string\">'custom'</span><span class=\"token punctuation\">,</span>\n  supertokens<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span>\n    connectionURI<span class=\"token operator\">:</span> process<span class=\"token punctuation\">.</span>env<span class=\"token punctuation\">.</span><span class=\"token constant\">SUPERTOKENS_CONNECTION_URI</span><span class=\"token operator\">!</span><span class=\"token punctuation\">,</span>\n    apiKey<span class=\"token operator\">:</span> process<span class=\"token punctuation\">.</span>env<span class=\"token punctuation\">.</span><span class=\"token constant\">SUPERTOKENS_API_KEY</span><span class=\"token punctuation\">,</span>\n  <span class=\"token punctuation\">}</span><span class=\"token punctuation\">,</span>\n  appInfo<span class=\"token punctuation\">,</span>\n  recipeList<span class=\"token operator\">:</span> <span class=\"token punctuation\">[</span>EmailPassword<span class=\"token punctuation\">.</span><span class=\"token function\">init</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\">init</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">]</span><span class=\"token punctuation\">,</span>\n  isInServerlessEnv<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 punctuation\">)</span>\n\n<span class=\"token keyword\">let</span> initialized <span class=\"token operator\">=</span> <span class=\"token boolean\">false</span>\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">function</span> <span class=\"token function\">ensureSuperTokensInit</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>initialized<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    SuperTokens<span class=\"token punctuation\">.</span><span class=\"token function\">init</span><span class=\"token punctuation\">(</span><span class=\"token function\">backendConfig</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">)</span>\n    initialized <span class=\"token operator\">=</span> <span class=\"token boolean\">true</span>\n  <span class=\"token punctuation\">}</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Recipes are how SuperTokens packages auth methods. <code class=\"language-text\">EmailPassword.init()</code> gives you credential-based signup and login. Prefer magic links or OTPs instead? Swap it for <code class=\"language-text\">Passwordless.init({ contactMethod: 'EMAIL', flowType: 'MAGIC_LINK' })</code> and nothing else in this file changes. <code class=\"language-text\">Session.init()</code> stays either way: recipes prove who the user is, sessions remember it.</p>\n<p>The other flags are Next.js survival gear. <code class=\"language-text\">framework: 'custom'</code> and <code class=\"language-text\">isInServerlessEnv: true</code> tell the SDK it’s running in serverless functions rather than a long-lived Express server, and the <code class=\"language-text\">ensureSuperTokensInit</code> guard stops double initialization across cold starts and hot reloads.</p>\n<p><strong>Third, the catch-all route handler.</strong> This single file mounts every auth endpoint:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"17241306514417443000\"\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/[...path]/route.ts\nimport { getAppDirRequestHandler } from 'supertokens-node/nextjs'\nimport { NextRequest } from 'next/server'\nimport { ensureSuperTokensInit } from '../../../config/backend'\n\nensureSuperTokensInit()\n\nconst handleCall = getAppDirRequestHandler()\n\nexport async function GET(request: NextRequest) {\n  const res = await handleCall(request)\n  if (!res.headers.has('Cache-Control')) {\n    res.headers.set('Cache-Control', 'no-cache, no-store, max-age=0, must-revalidate')\n  }\n  return res\n}\n\nexport async function POST(request: NextRequest) {\n  return handleCall(request)\n}\n\n// Export DELETE, PUT, PATCH, and HEAD the same way as POST.`, `17241306514417443000`)\"\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/[...path]/route.ts</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> getAppDirRequestHandler <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> NextRequest <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> ensureSuperTokensInit <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'../../../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 keyword\">const</span> handleCall <span class=\"token operator\">=</span> <span class=\"token function\">getAppDirRequestHandler</span><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 constant\">GET</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> res <span class=\"token operator\">=</span> <span class=\"token keyword\">await</span> <span class=\"token function\">handleCall</span><span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">)</span>\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token operator\">!</span>res<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 punctuation\">{</span>\n    res<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\">'no-cache, no-store, max-age=0, must-revalidate'</span><span class=\"token punctuation\">)</span>\n  <span class=\"token punctuation\">}</span>\n  <span class=\"token keyword\">return</span> res\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 constant\">POST</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\">return</span> <span class=\"token function\">handleCall</span><span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token comment\">// Export DELETE, PUT, PATCH, and HEAD the same way as POST.</span></code></pre></div>\n<p>Sign in, sign up, sign out, session refresh: all of them now exist under <code class=\"language-text\">/api/auth</code>, and you wrote none of them. The <code class=\"language-text\">Cache-Control</code> header is not optional decoration either. Next.js route handlers and any CDN in front of your app can cache GET responses, and the SDK’s GET endpoints answer per-user questions, like whether an email is verified. Without <code class=\"language-text\">no-store</code>, a cached copy can serve one user’s stale auth state to the next request.</p>\n<p>That’s the entire backend. <code class=\"language-text\">POST /api/auth/signup</code> already works; there’s just no UI calling it yet.</p>\n<h2 id=\"how-do-i-set-up-supertokens-in-the-frontend\" style=\"position:relative;\"><a href=\"#how-do-i-set-up-supertokens-in-the-frontend\" aria-label=\"how do i set up supertokens in the frontend 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 set up SuperTokens in the frontend?</h2>\n<p>The frontend config is the mirror image of what you just wrote, with one Next.js-specific complication: <code class=\"language-text\">SuperTokens.init</code> can only run in the browser, and the App Router renders everything on the server first. Three files handle it.</p>\n<p><strong>The config function.</strong> Same <code class=\"language-text\">appInfo</code>, same recipe pairing, plus a routing bridge:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"81981830099503660000\"\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\nimport EmailPasswordReact from 'supertokens-auth-react/recipe/emailpassword'\nimport SessionReact from 'supertokens-auth-react/recipe/session'\nimport { SuperTokensConfig } from 'supertokens-auth-react/lib/build/types'\nimport { useRouter } from 'next/navigation'\nimport { appInfo } from './appInfo'\n\nconst routerInfo: { router?: ReturnType<typeof useRouter>; pathName?: string } = {}\n\nexport function setRouter(router: ReturnType<typeof useRouter>, pathName: string) {\n  routerInfo.router = router\n  routerInfo.pathName = pathName\n}\n\nexport const frontendConfig = (): SuperTokensConfig => ({\n  appInfo,\n  recipeList: [EmailPasswordReact.init(), SessionReact.init()],\n  windowHandler: (original) => ({\n    ...original,\n    location: {\n      ...original.location,\n      getPathName: () => routerInfo.pathName!,\n      assign: (url) => routerInfo.router!.push(url.toString()),\n      setHref: (url) => routerInfo.router!.push(url.toString()),\n    },\n  }),\n})`, `81981830099503660000`)\"\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/config/frontend.tsx</span>\n<span class=\"token keyword\">import</span> EmailPasswordReact <span class=\"token keyword\">from</span> <span class=\"token string\">'supertokens-auth-react/recipe/emailpassword'</span>\n<span class=\"token keyword\">import</span> SessionReact <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> SuperTokensConfig <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'supertokens-auth-react/lib/build/types'</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> appInfo <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'./appInfo'</span>\n\n<span class=\"token keyword\">const</span> routerInfo<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span> router<span class=\"token operator\">?</span><span class=\"token operator\">:</span> ReturnType<span class=\"token operator\">&lt;</span><span class=\"token keyword\">typeof</span> useRouter<span class=\"token operator\">></span><span class=\"token punctuation\">;</span> pathName<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 punctuation\">{</span><span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">function</span> <span class=\"token function\">setRouter</span><span class=\"token punctuation\">(</span>router<span class=\"token operator\">:</span> ReturnType<span class=\"token operator\">&lt;</span><span class=\"token keyword\">typeof</span> useRouter<span class=\"token operator\">></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  routerInfo<span class=\"token punctuation\">.</span>router <span class=\"token operator\">=</span> router\n  routerInfo<span class=\"token punctuation\">.</span>pathName <span class=\"token operator\">=</span> pathName\n<span class=\"token punctuation\">}</span>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">const</span> frontendConfig <span class=\"token operator\">=</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token operator\">:</span> SuperTokensConfig <span class=\"token operator\">=></span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n  appInfo<span class=\"token punctuation\">,</span>\n  recipeList<span class=\"token operator\">:</span> <span class=\"token punctuation\">[</span>EmailPasswordReact<span class=\"token punctuation\">.</span><span class=\"token function\">init</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span> SessionReact<span class=\"token punctuation\">.</span><span class=\"token function\">init</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 function-variable function\">windowHandler</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">(</span>original<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span>\n    <span class=\"token operator\">...</span>original<span class=\"token punctuation\">,</span>\n    location<span class=\"token operator\">:</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token operator\">...</span>original<span class=\"token punctuation\">.</span>location<span class=\"token punctuation\">,</span>\n      <span class=\"token function-variable function\">getPathName</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> routerInfo<span class=\"token punctuation\">.</span>pathName<span class=\"token operator\">!</span><span class=\"token punctuation\">,</span>\n      <span class=\"token function-variable function\">assign</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">(</span>url<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> routerInfo<span class=\"token punctuation\">.</span>router<span class=\"token operator\">!</span><span class=\"token punctuation\">.</span><span class=\"token function\">push</span><span class=\"token punctuation\">(</span>url<span class=\"token punctuation\">.</span><span class=\"token function\">toString</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 function-variable function\">setHref</span><span class=\"token operator\">:</span> <span class=\"token punctuation\">(</span>url<span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> routerInfo<span class=\"token punctuation\">.</span>router<span class=\"token operator\">!</span><span class=\"token punctuation\">.</span><span class=\"token function\">push</span><span class=\"token punctuation\">(</span>url<span class=\"token punctuation\">.</span><span class=\"token function\">toString</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 punctuation\">}</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>Importing the shared <code class=\"language-text\">appInfo</code> is how the frontend learns to send auth calls to <code class=\"language-text\">/api/auth</code>. The recipe list mirrors the backend: <code class=\"language-text\">EmailPasswordReact</code> renders the login UI, <code class=\"language-text\">SessionReact</code> tracks session state in the browser. Keep both sides matched. A frontend initialized with a recipe the backend never mounted will call endpoints that don’t exist, and the resulting 404s won’t explain themselves. The <code class=\"language-text\">windowHandler</code> block exists because SuperTokens redirects users after login with <code class=\"language-text\">window.location</code> by default, which triggers full page reloads. Bridging it to Next’s router keeps navigation client-side.</p>\n<p><strong>The provider.</strong> A client component that initializes the SDK exactly once, in the browser only:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"5135809669704816000\"\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/components/supertokensProvider.tsx\n'use client'\nimport React from 'react'\nimport SuperTokensReact, { SuperTokensWrapper } from 'supertokens-auth-react'\nimport { usePathname, useRouter } from 'next/navigation'\nimport { frontendConfig, setRouter } from '../config/frontend'\n\nif (typeof window !== 'undefined') {\n  SuperTokensReact.init(frontendConfig())\n}\n\nexport const SuperTokensProvider: React.FC<React.PropsWithChildren> = ({ children }) => {\n  setRouter(useRouter(), usePathname() || window.location.pathname)\n  return <SuperTokensWrapper>{children}</SuperTokensWrapper>\n}`, `5135809669704816000`)\"\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/components/supertokensProvider.tsx</span>\n<span class=\"token string\">'use client'</span>\n<span class=\"token keyword\">import</span> React <span class=\"token keyword\">from</span> <span class=\"token string\">'react'</span>\n<span class=\"token keyword\">import</span> SuperTokensReact<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> SuperTokensWrapper <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'supertokens-auth-react'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> usePathname<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> frontendConfig<span class=\"token punctuation\">,</span> setRouter <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'../config/frontend'</span>\n\n<span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span><span class=\"token keyword\">typeof</span> window <span class=\"token operator\">!==</span> <span class=\"token string\">'undefined'</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n  SuperTokensReact<span class=\"token punctuation\">.</span><span class=\"token function\">init</span><span class=\"token punctuation\">(</span><span class=\"token function\">frontendConfig</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\">export</span> <span class=\"token keyword\">const</span> SuperTokensProvider<span class=\"token operator\">:</span> React<span class=\"token punctuation\">.</span><span class=\"token constant\">FC</span><span class=\"token operator\">&lt;</span>React<span class=\"token punctuation\">.</span>PropsWithChildren<span class=\"token operator\">></span> <span class=\"token operator\">=</span> <span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> children <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">=></span> <span class=\"token punctuation\">{</span>\n  <span class=\"token function\">setRouter</span><span class=\"token punctuation\">(</span><span class=\"token function\">useRouter</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span><span class=\"token punctuation\">,</span> <span class=\"token function\">usePathname</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">||</span> window<span class=\"token punctuation\">.</span>location<span class=\"token punctuation\">.</span>pathname<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\">SuperTokensWrapper</span></span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">{</span>children<span class=\"token punctuation\">}</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span><span class=\"token class-name\">SuperTokensWrapper</span></span><span class=\"token punctuation\">></span></span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>The <code class=\"language-text\">typeof window</code> check is doing real work. This module still gets evaluated during server rendering, and without the guard, <code class=\"language-text\">init</code> would run where no browser exists. <code class=\"language-text\">SuperTokensWrapper</code> is a React context provider: everything inside it can read session state.</p>\n<p><strong>The root layout.</strong> Wrap once and every page inherits auth:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"20501219132270140000\"\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/layout.tsx\nimport { SuperTokensProvider } from './components/supertokensProvider'\n\nexport default function RootLayout({ children }: { children: React.ReactNode }) {\n  return (\n    <html lang=&quot;en&quot;>\n      <SuperTokensProvider>\n        <body>{children}</body>\n      </SuperTokensProvider>\n    </html>\n  )\n}`, `20501219132270140000`)\"\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/layout.tsx</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> SuperTokensProvider <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'./components/supertokensProvider'</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\">RootLayout</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>html</span> <span class=\"token attr-name\">lang</span><span class=\"token attr-value\"><span class=\"token punctuation attr-equals\">=</span><span class=\"token punctuation\">\"</span>en<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\">SuperTokensProvider</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>body</span><span class=\"token punctuation\">></span></span><span class=\"token punctuation\">{</span>children<span class=\"token punctuation\">}</span><span class=\"token tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;/</span>body</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\">SuperTokensProvider</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>html</span><span class=\"token punctuation\">></span></span>\n  <span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>Backend and frontend now agree on paths, recipes, and sessions. What’s missing is a page that actually renders the login form.</p>\n<h2 id=\"how-do-i-add-login-and-signup-pages-to-my-app\" style=\"position:relative;\"><a href=\"#how-do-i-add-login-and-signup-pages-to-my-app\" aria-label=\"how do i add login and signup pages to my 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>How do I add login and signup pages to my app?</h2>\n<p>You don’t build two pages. One catch-all route renders every prebuilt screen, with login and signup sharing a single form that switches between them:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"82637142149075700000\"\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/auth/[[...path]]/page.tsx\n'use client'\nimport { useEffect, useState } from 'react'\nimport { redirectToAuth } from 'supertokens-auth-react'\nimport SuperTokens from 'supertokens-auth-react/ui'\nimport { EmailPasswordPreBuiltUI } from 'supertokens-auth-react/recipe/emailpassword/prebuiltui'\n\nexport default function Auth() {\n  const [loaded, setLoaded] = useState(false)\n\n  useEffect(() => {\n    // Send paths no prebuilt screen handles (like /auth/random) back to login\n    if (SuperTokens.canHandleRoute([EmailPasswordPreBuiltUI]) === false) {\n      redirectToAuth({ redirectBack: false })\n    } else {\n      setLoaded(true)\n    }\n  }, [])\n\n  if (loaded) {\n    return SuperTokens.getRoutingComponent([EmailPasswordPreBuiltUI])\n  }\n\n  return null\n}`, `82637142149075700000`)\"\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/auth/[[...path]]/page.tsx</span>\n<span class=\"token string\">'use client'</span>\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> <span class=\"token punctuation\">{</span> redirectToAuth <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'supertokens-auth-react'</span>\n<span class=\"token keyword\">import</span> SuperTokens <span class=\"token keyword\">from</span> <span class=\"token string\">'supertokens-auth-react/ui'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> EmailPasswordPreBuiltUI <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'supertokens-auth-react/recipe/emailpassword/prebuiltui'</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\">Auth</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>loaded<span class=\"token punctuation\">,</span> setLoaded<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 comment\">// Send paths no prebuilt screen handles (like /auth/random) back to login</span>\n    <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>SuperTokens<span class=\"token punctuation\">.</span><span class=\"token function\">canHandleRoute</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">[</span>EmailPasswordPreBuiltUI<span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span> <span class=\"token operator\">===</span> <span class=\"token boolean\">false</span><span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token function\">redirectToAuth</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">{</span> redirectBack<span class=\"token operator\">:</span> <span class=\"token boolean\">false</span> <span class=\"token punctuation\">}</span><span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">}</span> <span class=\"token keyword\">else</span> <span class=\"token punctuation\">{</span>\n      <span class=\"token function\">setLoaded</span><span class=\"token punctuation\">(</span><span class=\"token boolean\">true</span><span class=\"token punctuation\">)</span>\n    <span class=\"token punctuation\">}</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\">if</span> <span class=\"token punctuation\">(</span>loaded<span class=\"token punctuation\">)</span> <span class=\"token punctuation\">{</span>\n    <span class=\"token keyword\">return</span> SuperTokens<span class=\"token punctuation\">.</span><span class=\"token function\">getRoutingComponent</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">[</span>EmailPasswordPreBuiltUI<span class=\"token punctuation\">]</span><span class=\"token punctuation\">)</span>\n  <span class=\"token punctuation\">}</span>\n\n  <span class=\"token keyword\">return</span> <span class=\"token keyword\">null</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>The <code class=\"language-text\">[[...path]]</code> folder is an optional catch-all: it matches <code class=\"language-text\">/auth</code> itself and every path beneath it, so <code class=\"language-text\">/auth/reset-password</code> and the other prebuilt screens resolve to this one file. <code class=\"language-text\">canHandleRoute</code> checks whether the current URL belongs to a prebuilt screen, and <code class=\"language-text\">getRoutingComponent</code> renders the right one. The check runs inside <code class=\"language-text\">useEffect</code>, so any redirect happens after render, in the browser.</p>\n<p>Placement is not a style choice. The route lives under <code class=\"language-text\">app/auth/</code> because <code class=\"language-text\">/auth</code> is the <code class=\"language-text\">websiteBasePath</code> you set in <code class=\"language-text\">appInfo</code>, and the SDK routes through that path on its own. When an unauthenticated user hits a protected route, SuperTokens redirects them here without you writing a redirect. The <code class=\"language-text\">'use client'</code> directive stays, too: the prebuilt UI is browser-rendered React, and the App Router needs to be told.</p>\n<p>The prebuilt UI is a starting point, not a cage. You can restyle it through theme config on the recipe init, override individual React components while keeping the form logic (swap the header, inject your own fields), or discard it entirely and build custom UI on <code class=\"language-text\">supertokens-web-js</code> against the same backend. Most teams ship the prebuilt version first and override incrementally.</p>\n<p>Run <code class=\"language-text\">npm run dev</code>, open <code class=\"language-text\">localhost:3000/auth</code>, and create an account. Signup works, login works, and a session now exists. Which raises the real question: how does the rest of your app know about it?</p>\n<h2 id=\"how-do-i-protect-pages-with-authentication\" style=\"position:relative;\"><a href=\"#how-do-i-protect-pages-with-authentication\" aria-label=\"how do i protect pages with 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>How do I protect pages with authentication?</h2>\n<p>Protection happens in two places, and they do different jobs. The client-side guard controls what renders. The backend check controls what data leaves your server. You want both, because only one of them is a security boundary.</p>\n<p><strong>Backend routes: <code class=\"language-text\">withSession</code>.</strong> Any route handler can demand a valid session before doing work. Here’s an <code class=\"language-text\">/api/dashboard</code> endpoint that only answers to logged-in users:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"51721768249749570000\"\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/dashboard/route.ts\nimport { NextRequest, NextResponse } from 'next/server'\nimport { withSession } from 'supertokens-node/nextjs'\nimport { ensureSuperTokensInit } from '../../config/backend'\n\nensureSuperTokensInit()\n\nexport function GET(request: NextRequest) {\n  return withSession(request, async (err, session) => {\n    if (err) {\n      return NextResponse.json(err, { status: 500 })\n    }\n    if (!session) {\n      return new NextResponse('Authentication required', { status: 401 })\n    }\n    return NextResponse.json({ userId: session.getUserId() })\n  })\n}`, `51721768249749570000`)\"\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/dashboard/route.ts</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> NextRequest<span class=\"token punctuation\">,</span> NextResponse <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> withSession <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\">'../../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 keyword\">export</span> <span class=\"token keyword\">function</span> <span class=\"token constant\">GET</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\">return</span> <span class=\"token function\">withSession</span><span class=\"token punctuation\">(</span>request<span class=\"token punctuation\">,</span> <span class=\"token keyword\">async</span> <span class=\"token punctuation\">(</span>err<span class=\"token punctuation\">,</span> session<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>err<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\">json</span><span class=\"token punctuation\">(</span>err<span class=\"token punctuation\">,</span> <span class=\"token punctuation\">{</span> status<span class=\"token operator\">:</span> <span class=\"token number\">500</span> <span class=\"token punctuation\">}</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>session<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\">NextResponse</span><span class=\"token punctuation\">(</span><span class=\"token string\">'Authentication required'</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 punctuation\">}</span>\n    <span class=\"token keyword\">return</span> NextResponse<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><span class=\"token function\">getUserId</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 punctuation\">}</span></code></pre></div>\n<p>Three outcomes, handled in order: an SDK error, a missing or expired session, or a verified user. By the time your callback runs, the tokens are already validated, and <code class=\"language-text\">session.getUserId()</code> hands you the identity for database queries.</p>\n<p><strong>Client pages: <code class=\"language-text\">SessionAuth</code>.</strong> For the <code class=\"language-text\">/dashboard</code> page itself, wrap the content in <code class=\"language-text\">&lt;SessionAuth></code>. It waits for session state to load, sends signed-out visitors to <code class=\"language-text\">/auth</code>, and renders its children only when a session exists:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"23111956418141300000\"\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\n'use client'\nimport { SessionAuth, useSessionContext } from 'supertokens-auth-react/recipe/session'\n\nfunction DashboardContent() {\n  const session = useSessionContext()\n\n  if (session.loading) return null\n\n  return <p>Signed in as {session.userId}</p>\n}\n\nexport default function Dashboard() {\n  return (\n    <SessionAuth>\n      <DashboardContent />\n    </SessionAuth>\n  )\n}`, `23111956418141300000`)\"\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 string\">'use client'</span>\n<span class=\"token keyword\">import</span> <span class=\"token punctuation\">{</span> SessionAuth<span class=\"token punctuation\">,</span> useSessionContext <span class=\"token punctuation\">}</span> <span class=\"token keyword\">from</span> <span class=\"token string\">'supertokens-auth-react/recipe/session'</span>\n\n<span class=\"token keyword\">function</span> <span class=\"token function\">DashboardContent</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 function\">useSessionContext</span><span class=\"token punctuation\">(</span><span class=\"token punctuation\">)</span>\n\n  <span class=\"token keyword\">if</span> <span class=\"token punctuation\">(</span>session<span class=\"token punctuation\">.</span>loading<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 tag\"><span class=\"token tag\"><span class=\"token punctuation\">&lt;</span>p</span><span class=\"token punctuation\">></span></span><span class=\"token plain-text\">Signed in as </span><span class=\"token punctuation\">{</span>session<span class=\"token punctuation\">.</span>userId<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>\n\n<span class=\"token keyword\">export</span> <span class=\"token keyword\">default</span> <span class=\"token keyword\">function</span> <span class=\"token function\">Dashboard</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><span class=\"token class-name\">SessionAuth</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\">DashboardContent</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\">SessionAuth</span></span><span class=\"token punctuation\">></span></span>\n  <span class=\"token punctuation\">)</span>\n<span class=\"token punctuation\">}</span></code></pre></div>\n<p>No redirect logic lives in your component. <code class=\"language-text\">SessionAuth</code> handles the bounce to <code class=\"language-text\">/auth</code>, and after login the user lands back on <code class=\"language-text\">/dashboard</code>. Inside it, <code class=\"language-text\">useSessionContext</code> reads the session from the <code class=\"language-text\">SuperTokensWrapper</code> you added earlier. The <code class=\"language-text\">loading</code> check is not ceremony: the hook’s type includes an unresolved state, and TypeScript will correctly refuse to let you read <code class=\"language-text\">userId</code> until you rule it out.</p>\n<p>Keep the layers straight. Anyone with dev tools open can render your dashboard shell. What they can’t do is make <code class=\"language-text\">withSession</code> hand over data without valid tokens. Guard the UI for experience; guard the API for real.</p>\n<h2 id=\"how-do-i-test-my-nextjs-app-with-authentication-enabled\" style=\"position:relative;\"><a href=\"#how-do-i-test-my-nextjs-app-with-authentication-enabled\" aria-label=\"how do i test my nextjs app with authentication enabled 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 test my Next.js app with authentication enabled?</h2>\n<p>Start the dev server and walk the whole flow, including the parts that are supposed to fail:</p>\n<div\n              class=\"gatsby-code-button-container\"\n              data-toaster-id=\"64264596802044240000\"\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(`npm run dev`, `64264596802044240000`)\"\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=\"bash\"><pre class=\"language-bash\"><code class=\"language-bash\"><span class=\"token function\">npm</span> run dev</code></pre></div>\n<ol>\n<li>\n<p><strong>Sign up.</strong> Open <code class=\"language-text\">localhost:3000/auth</code> and create an account. The prebuilt flow starts a session on signup, so you land back in the app already logged in. No separate login step needed.</p>\n</li>\n<li>\n<p><strong>Check the session exists.</strong> Open dev tools and look at the cookies for <code class=\"language-text\">localhost:3000</code>. You’ll find <code class=\"language-text\">sAccessToken</code> and <code class=\"language-text\">sRefreshToken</code>, set by the SDK without a line of cookie code on your side.</p>\n</li>\n<li>\n<p><strong>Visit the protected page.</strong> Go to <code class=\"language-text\">/dashboard</code>. It renders your user ID. Hit <code class=\"language-text\">/api/dashboard</code> too: JSON with the same ID, verified server-side by <code class=\"language-text\">withSession</code>.</p>\n</li>\n<li>\n<p><strong>Test the failure path.</strong> This is the check most people skip. Open an incognito window and go straight to <code class=\"language-text\">/dashboard</code>: you should bounce to <code class=\"language-text\">/auth</code>. Request <code class=\"language-text\">/api/dashboard</code> without cookies: 401. If either one lets you through, a guard is missing.</p>\n</li>\n<li>\n<p><strong>Confirm sessions run themselves.</strong> Reload the page: still signed in. Then let the access token expire (an hour by default) and use the app again. Nothing refreshes in the background: on the first request after expiry, the SDK calls <code class=\"language-text\">/api/auth/session/refresh</code>, gets fresh tokens, and retries the original request transparently. Your only evidence is a refresh call in the network tab.</p>\n</li>\n</ol>\n<p>To test logout, call <code class=\"language-text\">signOut()</code> from <code class=\"language-text\">supertokens-auth-react/recipe/session</code> behind a button, then confirm <code class=\"language-text\">/dashboard</code> bounces again.</p>\n<p>Five checks, all passing, and you wrote no login form, no auth endpoints, and no refresh logic.</p>\n<h2 id=\"why-should-i-use-supertokens-instead-of-other-auth-providers\" style=\"position:relative;\"><a href=\"#why-should-i-use-supertokens-instead-of-other-auth-providers\" aria-label=\"why should i use supertokens instead of other auth providers 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 should I use SuperTokens instead of other auth providers?</h2>\n<p>The fair question after any tutorial. You just wired one framework into your app; here’s why it was this one.</p>\n<p><strong>You own the stack.</strong> SuperTokens is open source under Apache 2.0, and the core runs wherever you want it: a Docker container next to your app, your Kubernetes cluster, or their managed cloud when you’d rather not operate it. User data lives in your own PostgreSQL or MySQL database, which changes the exit math entirely. Leaving a managed provider means export tickets and password reset campaigns. Leaving SuperTokens means pointing something else at tables you already own. On cost, self-hosting the open-source features is free with no MAU limits; the managed service is free up to 5,000 MAUs, then $0.02 per MAU, and paid add-ons like MFA are priced separately.</p>\n<p><strong>Recipes cover the auth methods you’ll actually ship.</strong> Email password, passwordless OTPs and magic links, social login: each is a recipe, and you’ve already seen what adopting one costs. Adding passwordless to this app is an edit to <code class=\"language-text\">recipeList</code> on each side, not a migration. Enterprise SSO and <a href=\"https://supertokens.com/blog/add-mfa-to-nextjs\" target=\"_blank\" rel=\"nofollow\">MFA</a> plug in the same way, but they’re paid add-ons rather than part of the free open-source set.</p>\n<p><strong>Extensibility is the default, not an enterprise tier.</strong> Every API the SDK exposes can be overridden, so custom signup logic or extra validation slots in without forking anything. Plugins layer on cross-cutting concerns like CAPTCHA and rate limiting as installable units.</p>\n<p>The tradeoffs are real. Self-hosting means the auth service is yours to keep healthy, and providers like Auth0 still win on enterprise feature breadth; our roundup of <a href=\"https://supertokens.com/blog/nextauth-alternatives\" target=\"_blank\" rel=\"nofollow\">NextAuth alternatives</a> compares the field side by side. But if you want auth that lives in your stack, on your terms, with core features that stay free to self-host as you grow, that’s exactly the trade SuperTokens makes.</p>\n<h2 id=\"where-can-i-learn-more-about-nextjs-authentication-with-supertokens\" style=\"position:relative;\"><a href=\"#where-can-i-learn-more-about-nextjs-authentication-with-supertokens\" aria-label=\"where can i learn more about nextjs authentication 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>Where can I learn more about Next.js authentication with SuperTokens?</h2>\n<p>A few places, depending on what you need next.</p>\n<p>For a deeper pass at the App Router specifically, read <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 using the App Directory and SuperTokens</a>. It walks the same integration with more attention to server components and session handling during SSR, which matters once your app leans hard on server rendering.</p>\n<p>To extend the app you just built, <a href=\"https://supertokens.com/blog/implement-passkeys-nextjs\" target=\"_blank\" rel=\"nofollow\">How to Implement Passkey Authentication in Next.js With SuperTokens</a> adds passkeys on the same stack, and <a href=\"https://supertokens.com/blog/enhancing-your-nextjs-application-with-middleware\" target=\"_blank\" rel=\"nofollow\">Enhancing Your Next.js Application with Middleware</a> covers checking requests before a page renders. That post predates Next.js 16, where the <code class=\"language-text\">middleware.ts</code> file it describes is now <code class=\"language-text\">proxy.ts</code>.</p>\n<p>The <a href=\"https://supertokens.com/docs\" target=\"_blank\" rel=\"nofollow\">SuperTokens docs</a> are where the recipes live. Passwordless flows, social login, MFA, UI overrides, self-hosting the core with Docker: each one builds on the config files you already have.</p>\n<p>And the <a href=\"https://github.com/supertokens/supertokens-core\" target=\"_blank\" rel=\"nofollow\">supertokens-core repo on GitHub</a> is the project itself. Read the source, file issues, or study the architecture before you self-host. Open source means the answer to “what does this actually do” lives in the code, not behind a support ticket.</p>","frontmatter":{"date":"November 11, 2026","updated":null,"title":"How do I add authentication to a Next.js app with SuperTokens?","cover":"nextjs-supertokens-auth.png","author":"Maurice Saldivar","description":"A step-by-step Next.js authentication guide: add login, signup, sessions, and protected pages to your app with SuperTokens."},"fields":{"slug":"/how-do-i-add-auth-nextjs-app/"}},"site":{"siteMetadata":{"title":"SuperTokens Blog"}}},"pageContext":{"id":"bd7436f5-b6a5-5549-a1d9-a18fb3732cde","fields__slug":"/how-do-i-add-auth-nextjs-app/","__params":{"fields__slug":"how-do-i-add-auth-nextjs-app"}}},
    "staticQueryHashes": []}