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.

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
// 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;
}// 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
| Layer | Can read session | Can block render | Caching effect | Use for |
|---|---|---|---|---|
Middleware / proxy.ts | Yes (cookie value only) | Redirect before routing | None; runs on Edge | Fast redirect for missing cookie, coarse gating |
| Layout | Yes | redirect() | Makes the subtree dynamic | Shell that needs identity to render |
| Page | Yes | redirect(), notFound() | Dynamic | The real check before reading data |
| Server Action | Yes, and can write cookies | Return error / redirect | n/a | Mutations, sign-in, sign-out |
| Route Handler | Yes, and can write | 401/403 response | Dynamic | API consumed by clients |
| Client component | No (only non-HttpOnly cookies) | UI only | n/a | Showing/hiding affordances, never securing them |
| Cookie attribute | Effect | Practical value |
|---|---|---|
HttpOnly | Hidden from document.cookie | Always on for sessions |
Secure | HTTPS only | On in production |
SameSite=Lax | Not sent on cross-site POST | Good default; protects most CSRF |
SameSite=Strict | Not sent on cross-site navigation | Breaks OAuth return and email links |
SameSite=None | Sent cross-site | Requires Secure; only for embedded flows |
Path=/ | Visible on every route | Needed for a site-wide session |
Max-Age / Expires | Persistent vs session cookie | Set 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.
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.
// 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.
// 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:
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
| Symptom | Cause | Fix |
|---|---|---|
Cookies can only be modified… at runtime | cookies().set() called during render | Move the write into a Server Action or Route Handler |
| Signed-in user sees another user’s name | Page cached although it reads session | Read identity through cookies(), set dynamic = "force-dynamic" |
| Login redirects but stays on the form | redirect() inside try/catch | Call redirect() last, outside the block |
| Session cookie missing in production | secure: true on plain HTTP, or Path scoped | Serve HTTPS, set path: "/" |
| Middleware lets the request through | Cookie present but expired; no verification | Verify in the page or data layer |
jose/jsonwebtoken works locally, fails on deploy | Node-only crypto in an Edge route | Use jose, or set export const runtime = "nodejs" |
| Sign-out does not stick | Only client state cleared | Delete the cookie server-side, then redirect |
Try matching browser tools
All toolsSmall utilities that fit Next.js work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Next.js guides
All Next.js guidesNext.js Static Export, Standalone Output, and Docker Deployment
Export has no server, standalone has a pruned one, and the default expects a full install. The three COPY lines that decide whether a container renders CSS.
Next.js Parallel Routes and Intercepting Routes: Slot Layouts and Modals
Named slots render several pages in one layout, and (.) interception makes a click open over the page while a direct link renders the full route. Why every slot needs default.tsx.
Next.js ISR: Route Revalidate, revalidateTag, and On-Demand Invalidation
Two clocks and one trigger: route revalidate seconds, fetch-level tags, and a webhook that calls revalidateTag. A timer is a ceiling on freshness, never a guarantee.
Next.js Environment Variables: NEXT_PUBLIC_, Build-Time Inlining, and Runtime Config
The prefix decides whether a value is compiled into the browser bundle or stays on the server. One image, two environments, and the choice that follows from it.
More in Next.js
All Next.js guidesThe guides filed next to this one in Next.js, in library order.