How do you implement JWT-based auth in Next.js?

Issue a signed JWT after verifying credentials, store it in an httpOnly secure cookie (not localStorage), verify the signature and expiry with jose on each server request (in Proxy, Server Components, Route Handlers and Server Functions), and handle expiry with short-lived tokens plus refresh or rotation.

Token design

  • Claims: sub (user ID), role, iat, exp, and optionally jti for revocation.
  • Keep it small; it travels with every request.
  • Sign with HS256 (shared secret) or RS256/EdDSA (key pair, useful when other services verify it).
  • Do not put sensitive data in it; JWT payloads are only base64-encoded unless you encrypt (JWE).

Storage

  • httpOnly cookie: JavaScript cannot read it, so XSS cannot steal it, and it is sent automatically to your server.
  • sameSite: "lax" plus Next.js's built-in Server Function origin check protect against CSRF; for custom POST Route Handlers consumed by browsers, also check Origin.
  • Avoid localStorage for tokens: any XSS can exfiltrate them.

Verification

jose works in every runtime (Web Crypto). Wrap verification in a React.cache helper so it runs once per request.

Expiry and revocation

  • Access tokens of 15 minutes to a few hours, plus a refresh token (longer, rotated on use, ideally stored server-side).
  • Or a sliding session: re-issue the cookie when more than half the lifetime has passed.
  • For instant revocation, keep a denylist of jti values or a tokenVersion per user in a fast store.

For external APIs

Mobile apps and third parties can send Authorization: Bearer <jwt> to Route Handlers; verify the same way.

Code example

tsx
1// lib/jwt.ts
2import "server-only";
3import { SignJWT, jwtVerify, type JWTPayload } from "jose";
4import { cache } from "react";
5import { cookies } from "next/headers";
6
7const secret = new TextEncoder().encode(process.env.JWT_SECRET);
8type Claims = JWTPayload & { sub: string; role: "user" | "admin" };
9
10export async function issueToken(userId: string, role: Claims["role"]) {
11 return new SignJWT({ role })
12 .setProtectedHeader({ alg: "HS256" })
13 .setSubject(userId)
14 .setIssuedAt()
15 .setExpirationTime("2h")
16 .setJti(crypto.randomUUID())
17 .sign(secret);
18}
19
20export const currentUser = cache(async (): Promise<Claims | null> => {
21 const token = (await cookies()).get("token")?.value;
22 if (!token) return null;
23 try {
24 const { payload } = await jwtVerify<Claims>(token, secret, { algorithms: ["HS256"] });
25 return payload;
26 } catch {
27 return null; // invalid signature, wrong alg or expired
28 }
29});
30
31// Route Handler for mobile clients:
32// const bearer = request.headers.get("authorization")?.replace("Bearer ", "");
33// const { payload } = await jwtVerify(bearer!, secret);

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.

Open in study app