Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Next.js Authentication: Sessions, Cookies, and Server-Side Protection

HttpOnly cookies set only in actions, an async cookies() API, and one data-access layer. Middleware is an optimistic gate; the page that reads data is the only real check.

~5 min readNext.js
#Next.js#Authentication#Security#Cookies
3D illustration of a shield gate before server components with an HttpOnly cookie token passing through

Quick Summary

Authentication in the App Router has three layers and one rule: the session lives in an HttpOnly cookie, every read goes through one server-side data-access function, and the UI never decides access. Middleware gives a fast optimistic check, layouts render the shell, but the page or action that touches private data is the only place that can enforce it.

cookies() is now asynchronous: const store = await cookies(). It can be read anywhere on the server, but written only in a Server Action or a Route Handler — calling store.set() during a page render throws. That single constraint shapes the whole flow: sign-in posts to an action, the action sets the cookie, then redirects.

Caching is where sessions leak. Any route that reads the session must be dynamic; a page rendered statically with one user's name in it will serve that name to everyone until the next build.

Basic Syntax & Core Signatures

ts
// lib/session.ts — the single data-access layer for auth reads import "server-only"; import { cookies } from "next/headers"; import { SignJWT, jwtVerify } from "jose"; import { cache } from "react"; const key = new TextEncoder().encode(process.env.SESSION_SECRET!); const COOKIE = "session"; export type SessionPayload = { userId: string; expiresAt: number }; export async function createSession(userId: string) { const expiresAt = Date.now() + 7 * 24 * 60 * 60 * 1000; const token = await new SignJWT({ userId, expiresAt }) .setProtectedHeader({ alg: "HS256" }) .setIssuedAt() .setExpirationTime("7d") .sign(key); const store = await cookies(); store.set(COOKIE, token, { httpOnly: true, secure: process.env.NODE_ENV === "production", sameSite: "lax", path: "/", expires: new Date(expiresAt), }); } // cache() dedupes per request: layout, page, and action share one verify export const getSession = cache(async (): Promise<SessionPayload | null> => { const token = (await cookies()).get(COOKIE)?.value; if (!token) return null; try { const { payload } = await jwtVerify<SessionPayload>(token, key); return payload; } catch { return null; } }); export async function requireUser() { const session = await getSession(); if (!session) redirect("/login"); return session; }
ts
// app/login/actions.ts "use server"; import { z } from "zod"; import { redirect } from "next/navigation"; import { createSession } from "@/lib/session"; import { verifyPassword } from "@/lib/users"; const Schema = z.object({ email: z.string().email(), password: z.string().min(8) }); export async function signIn(_prev: unknown, formData: FormData) { const parsed = Schema.safeParse(Object.fromEntries(formData)); if (!parsed.success) return { error: "Invalid input" }; const user = await verifyPassword(parsed.data.email, parsed.data.password); if (!user) return { error: "Incorrect email or password" }; // same message both ways await createSession(user.id); redirect("/dashboard"); }

jose works in both Edge and Node runtimes; jsonwebtoken and bcrypt do not work on the Edge. That difference decides whether the same session helper can be used in middleware.

Key Comparison Table

LayerCan read sessionCan block renderCaching effectUse for
Middleware / proxy.tsYes (cookie value only)Redirect before routingNone; runs on EdgeFast redirect for missing cookie, coarse gating
LayoutYesredirect()Makes the subtree dynamicShell that needs identity to render
PageYesredirect(), notFound()DynamicThe real check before reading data
Server ActionYes, and can write cookiesReturn error / redirectn/aMutations, sign-in, sign-out
Route HandlerYes, and can write401/403 responseDynamicAPI consumed by clients
Client componentNo (only non-HttpOnly cookies)UI onlyn/aShowing/hiding affordances, never securing them
Cookie attributeEffectPractical value
HttpOnlyHidden from document.cookieAlways on for sessions
SecureHTTPS onlyOn in production
SameSite=LaxNot sent on cross-site POSTGood default; protects most CSRF
SameSite=StrictNot sent on cross-site navigationBreaks OAuth return and email links
SameSite=NoneSent cross-siteRequires Secure; only for embedded flows
Path=/Visible on every routeNeeded for a site-wide session
Max-Age / ExpiresPersistent vs session cookieSet explicitly; do not rely on browser session

Practical Edge Cases & Deep Dives

1. cookies().set outside an action throws

Setting a cookie during render raises Cookies can only be modified in a Server Action or Route Handler. Two consequences: sign-in cannot be a plain form POST to a page, and refresh-token rotation cannot happen inside getSession. Do the write in the action, and if the read path must rotate, return the new token from the route handler that owns the request.

2. Redirect in an action versus returning an error

redirect() inside a Server Action works by throwing a special error; code after it does not run and try/catch around it will swallow the redirect. Keep the redirect last, outside any try block, and validate before redirecting so the user never lands on a page they cannot see.

ts
export async function signOut() { (await cookies()).delete("session"); redirect("/"); }

If you must catch, rethrow when the error is a redirect: if (isRedirectError(e)) throw e; from next/dist/client/components/redirect-error — but relying on internals is fragile, so ordering is the better fix.

3. Preventing a cached page from leaking another user’s data

Any page that calls getSession() becomes dynamic automatically because cookies() is a dynamic API. The leak happens when identity enters through a fetch that is cached, or through a layout that was rendered at build time while the page reads the session. The practical defence is a data-access layer that always awaits the session and a test that loads the same page as two users in one session.

tsx
// app/dashboard/page.tsx import { requireUser } from "@/lib/session"; export const dynamic = "force-dynamic"; // explicit, even though cookies() implies it export default async function Dashboard() { const session = await requireUser(); const invoices = await db.invoice.findMany({ where: { userId: session.userId } }); return <InvoiceList invoices={invoices} />; }

4. Optimistic checks in middleware, real checks in the page

Middleware can see whether a cookie exists, not whether the token is still valid, unless it verifies the signature there. A common split is: middleware redirects when the cookie is absent (cheap, saves a render), the page verifies the token and role (authoritative). Never put a role check only in middleware — a request that reaches the route another way, such as a Server Action call, bypasses the path matcher entirely.

ts
// middleware.ts — coarse gate only export function middleware(req: NextRequest) { const hasSession = req.cookies.has("session"); if (!hasSession && req.nextUrl.pathname.startsWith("/dashboard")) { const url = req.nextUrl.clone(); url.pathname = "/login"; url.searchParams.set("next", req.nextUrl.pathname); return NextResponse.redirect(url); } } export const config = { matcher: ["/dashboard/:path*", "/settings/:path*"] };

5. CSRF, Server Actions, and the Origin header

Server Actions are POST requests to the current route. Next.js compares Origin with Host and rejects mismatches for actions, which covers the common case. Your own route handlers get no such protection. For those, require a same-site cookie and check Origin explicitly, or use a double-submit token:

ts
export async function POST(req: NextRequest) { const origin = req.headers.get("origin"); if (origin !== process.env.APP_ORIGIN) { return new Response("Bad origin", { status: 403 }); } // ...mutate }

SameSite=Lax already blocks cross-site POST cookies in modern browsers, so the Origin check is defence in depth rather than the only line.

6. Token expiry, refresh, and the silent 401

A JWT with an exp claim that passes verification returns null after expiry, which looks identical to "never logged in". Distinguish the cases for the user: expired sessions should land on /login?expired=1 with a message, not a generic redirect that loses their place. Sliding sessions need a real refresh token in a second HttpOnly cookie, and the refresh must happen in a route handler or action, per the write constraint above.

Common Runtime & Configuration Mistakes

SymptomCauseFix
Cookies can only be modified… at runtimecookies().set() called during renderMove the write into a Server Action or Route Handler
Signed-in user sees another user’s namePage cached although it reads sessionRead identity through cookies(), set dynamic = "force-dynamic"
Login redirects but stays on the formredirect() inside try/catchCall redirect() last, outside the block
Session cookie missing in productionsecure: true on plain HTTP, or Path scopedServe HTTPS, set path: "/"
Middleware lets the request throughCookie present but expired; no verificationVerify in the page or data layer
jose/jsonwebtoken works locally, fails on deployNode-only crypto in an Edge routeUse jose, or set export const runtime = "nodejs"
Sign-out does not stickOnly client state clearedDelete the cookie server-side, then redirect

Try matching browser tools

All tools

Small utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Next.js guides

More in Next.js

All Next.js guides

The guides filed next to this one in Next.js, in library order.