Next.jsMedium
How do you set up session management in Next.js?
Store a session token in a secure, httpOnly cookie, create it after sign-in in a Server Function or Route Handler, verify it on every server request through a cached verifySession() helper, refresh it before expiry, and delete it on sign-out. Choose stateless (signed JWT) or database sessions depending on how important instant revocation is.
Stateless sessions (JWT in a cookie)
- Sign or encrypt
{ userId, role, expiresAt }withjoseusing a secret from env vars. - Verifying needs no database, so it is fast enough for
proxy.ts. - Downside: you cannot revoke a token before it expires unless you add a denylist. Keep expiry short (hours to days) and rotate.
Database sessions
- Cookie holds a random session ID; a
sessionstable stores the user, expiry and device. - Easy to sign out everywhere or revoke a stolen session.
- One lookup per check; cache it per request with
React.cacheand consider Redis for speed.
Cookie settings
httpOnly: true, secure: true, sameSite: "lax", path: "/", an explicit expires, and ideally the __Host- prefix.
Where each step happens
- Create / delete: Server Functions or Route Handlers (
(await cookies()).set()), since Server Components cannot set cookies. - Verify: Data Access Layer, used by Server Components, Server Functions and Route Handlers.
- Optimistic redirect:
proxy.tsreads the cookie only. - Extend: update the expiry on activity in Proxy or a Server Function.
Client access
Pass a minimal user object from the server via props or context. Do not expose the token to JavaScript.
Code example
tsx
1// lib/session.ts2import "server-only";3import { SignJWT, jwtVerify } from "jose";4import { cookies } from "next/headers";56const key = new TextEncoder().encode(process.env.SESSION_SECRET);7const WEEK = 7 * 24 * 60 * 60 * 1000;89export async function createSession(userId: string) {10 const expiresAt = new Date(Date.now() + WEEK);11 const token = await new SignJWT({ userId })12 .setProtectedHeader({ alg: "HS256" })13 .setExpirationTime(expiresAt)14 .sign(key);1516 (await cookies()).set("session", token, {17 httpOnly: true, secure: true, sameSite: "lax", path: "/", expires: expiresAt,18 });19}2021export async function readSession() {22 const token = (await cookies()).get("session")?.value;23 if (!token) return null;24 try {25 return (await jwtVerify<{ userId: string }>(token, key)).payload;26 } catch {27 return null; // bad signature or expired28 }29}3031export async function deleteSession() {32 (await cookies()).delete("session");33}
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the Next.js set.