What's the best way to store session tokens in a Next.js app? Should I use cookies or localStorage?
Conversational Agent — Session #2840
You
claude-opus-4-7
Use HttpOnly cookies — not localStorage. Here's why:
- localStorage is accessible from JavaScript, which makes tokens vulnerable to XSS attacks.
- HttpOnly cookies cannot be read by JavaScript at all — only the browser sends them automatically.
- Pair them with
SecureandSameSite=Laxflags for CSRF protection.
For a Next.js app, the recommended pattern is to set the cookie in a Route Handler or Server Action, using a signing library like jose for JWT tokens.
You
Can you show me how to do the signing with jose? We're already using it in the project.
search_knowledge_basetool
claude-opus-4-7
Your project already has this wired up in src/auth/session.ts. Here's the relevant signing logic:
session.ts — createSessionCode
const token = await new SignJWT({ sub: userId, sid: sessionId }).setProtectedHeader({ alg: 'HS256' }).sign(getSecret());
src/auth/session.ts
The key things to note:
getSecret()readsSESSION_SECRETfrom env — never hardcode the signing key.SESSION_TTLis 7 days — adjust to your session policy.- Verification is in
verifySession()which callsjwtVerify.
You
Perfect. One more thing — how should the cookie be set in the response? We're using Route Handlers.
claude-opus-4-7
In a Route Handler, use NextResponse with .cookies.set():
app/api/session/route.tsts
const response = NextResponse.json({ ok: true });response.cookies.set("session", token, { httpOnly: true, secure: true, sameSite: "lax",});claude-opus-4-7
Cookie write flow for the implementation note
session-token-flow.svg · 18 KB
claude-opus-4-7
/commands available↵to send