Next.jsHard
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 optionallyjtifor 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
httpOnlycookie: 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 checkOrigin.- Avoid
localStoragefor 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
jtivalues or atokenVersionper 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.ts2import "server-only";3import { SignJWT, jwtVerify, type JWTPayload } from "jose";4import { cache } from "react";5import { cookies } from "next/headers";67const secret = new TextEncoder().encode(process.env.JWT_SECRET);8type Claims = JWTPayload & { sub: string; role: "user" | "admin" };910export 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}1920export 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 expired28 }29});3031// 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.