JWT Auth in Node.js & Express: Access + Refresh Tokens
Add JWT auth to Node.js and Express the safe way: 15-minute access tokens, rotating refresh tokens in httpOnly cookies and a logout that works.
On this page 13 sections
Most JWT tutorials stop at jwt.sign() and jwt.verify(). That part takes ten minutes. The questions that come up in code review are the other ones: where does the refresh token live, what happens when someone steals it and how do you log a user out of a token you can’t delete?

This post builds the whole flow in Express 5 with TypeScript and Mongoose: login, a route guard, role checks, refresh token rotation with reuse detection, logout and the client-side retry. Every snippet is meant to be copied.
How JWT authentication works
A JWT is three base64url strings joined by dots: header.payload.signature. The server signs the header and payload with a secret. Anyone can read the payload, but nobody can change it without breaking the signature.
{
"sub": "665f1c2a9b1e8a0012ab34cd",
"role": "admin",
"iss": "api.example.com",
"iat": 1763337600,
"exp": 1763338500
}Base64 is encoding, not encryption. Paste any token into jwt.io and you’ll see this JSON. Never put passwords, emails you don’t need or internal flags in it.
A production setup uses two tokens:
| Access token | Refresh token | |
|---|---|---|
| Lifetime | 15 minutes | 7 days |
| Sent to | Every API route | /auth/refresh only |
| Client storage | JavaScript memory | httpOnly cookie |
| Server state | None | One row per session |
The access token is stateless, so verifying it costs no database call. The refresh token is the one you track, which is what makes logout and theft detection possible.
Project setup
npm install express jsonwebtoken cookie-parser bcrypt mongoose
npm install -D @types/express @types/jsonwebtoken @types/cookie-parser @types/bcrypt
# Two different secrets, 32 random bytes each
echo "JWT_ACCESS_SECRET=$(openssl rand -base64 32)" >> .env
echo "JWT_REFRESH_SECRET=$(openssl rand -base64 32)" >> .envUse separate secrets. With one shared secret, a refresh token passes access token verification and the 15-minute limit means nothing. On Node 24 you can load the file with node --env-file=.env and skip dotenv (more on that here).
Signing and verifying tokens
// src/auth/token.service.ts
import jwt from "jsonwebtoken";
import { randomUUID } from "node:crypto";
const ACCESS_SECRET = process.env.JWT_ACCESS_SECRET!;
const REFRESH_SECRET = process.env.JWT_REFRESH_SECRET!;
const ISSUER = "api.example.com";
export type Role = "user" | "admin";
type AccessClaims = jwt.JwtPayload & { sub: string; role: Role; jti: string; exp: number };
type RefreshClaims = jwt.JwtPayload & { sub: string; jti: string };
export function signAccessToken(userId: string, role: Role) {
return jwt.sign({ role }, ACCESS_SECRET, {
algorithm: "HS256",
subject: userId,
issuer: ISSUER,
jwtid: randomUUID(),
expiresIn: "15m",
});
}
export function signRefreshToken(userId: string) {
const jti = randomUUID();
const token = jwt.sign({}, REFRESH_SECRET, {
algorithm: "HS256",
subject: userId,
jwtid: jti,
expiresIn: "7d",
});
return { token, jti };
}
export function verifyAccessToken(token: string) {
return jwt.verify(token, ACCESS_SECRET, {
algorithms: ["HS256"],
issuer: ISSUER,
}) as AccessClaims;
}
export function verifyRefreshToken(token: string) {
return jwt.verify(token, REFRESH_SECRET, { algorithms: ["HS256"] }) as RefreshClaims;
}The algorithms option matters most here. Without it, older libraries accepted alg: "none" or let an attacker switch RS256 to HS256 and sign with your public key. Pin it on every call.
Storing refresh sessions
The refresh token is a bearer credential, so I don’t store it. I store its jti, a random ID nobody can forge without the secret.
// src/auth/refresh-session.model.ts
import { Schema, model } from "mongoose";
const refreshSessionSchema = new Schema({
_id: { type: String }, // the token's jti
userId: { type: Schema.Types.ObjectId, ref: "User", required: true, index: true },
revokedAt: { type: Date, default: null },
expiresAt: { type: Date, required: true },
});
// MongoDB removes the row once the token would have expired anyway
refreshSessionSchema.index({ expiresAt: 1 }, { expireAfterSeconds: 0 });
export const RefreshSession = model("RefreshSession", refreshSessionSchema);The TTL index keeps the collection from growing forever. In Redis, the same thing is a key with EX set to seven days.
Login endpoint
// src/auth/auth.controller.ts
import type { Request, Response, CookieOptions } from "express";
import bcrypt from "bcrypt";
import { User } from "../users/user.model.js";
import { RefreshSession } from "./refresh-session.model.js";
import { signAccessToken, signRefreshToken, verifyRefreshToken, type Role } from "./token.service.js";
const SEVEN_DAYS = 7 * 24 * 60 * 60 * 1000;
const refreshCookie: CookieOptions = {
httpOnly: true, // invisible to JavaScript, so XSS can't read it
secure: process.env.NODE_ENV === "production",
sameSite: "strict", // not sent on cross-site requests
path: "/auth", // not sent to the rest of the API
maxAge: SEVEN_DAYS,
};
async function issueTokens(res: Response, userId: string, role: Role) {
const { token, jti } = signRefreshToken(userId);
await RefreshSession.create({ _id: jti, userId, expiresAt: new Date(Date.now() + SEVEN_DAYS) });
res.cookie("refresh_token", token, refreshCookie);
return signAccessToken(userId, role);
}
export async function login(req: Request, res: Response) {
const { email, password } = req.body;
const user = await User.findOne({ email }).select("+passwordHash");
// One message for both failures, so the endpoint can't be used to find valid emails
if (!user || !(await bcrypt.compare(password, user.passwordHash))) {
return res.status(401).json({ code: "INVALID_CREDENTIALS" });
}
const accessToken = await issueTokens(res, user.id, user.role);
res.json({ accessToken });
}Validate email and password before they reach this handler. Input validation with Zod or Joi covers that, and the login route should sit behind a rate limiter too.
Protecting routes with middleware
TypeScript doesn’t know about req.user until you tell it. Declaration merging fixes the “Property ‘user’ does not exist on type Request” error without casting to any:
// src/types/express.d.ts
import type { Role } from "../auth/token.service.js";
declare global {
namespace Express {
interface Request {
user?: { id: string; role: Role };
}
}
}
export {};// src/middleware/authenticate.ts
import type { Request, Response, NextFunction } from "express";
import jwt from "jsonwebtoken";
import { verifyAccessToken } from "../auth/token.service.js";
export function authenticate(req: Request, res: Response, next: NextFunction) {
const header = req.headers.authorization;
if (!header?.startsWith("Bearer ")) {
return res.status(401).json({ code: "TOKEN_MISSING" });
}
try {
const claims = verifyAccessToken(header.slice(7));
req.user = { id: claims.sub, role: claims.role };
next();
} catch (err) {
const code = err instanceof jwt.TokenExpiredError ? "TOKEN_EXPIRED" : "TOKEN_INVALID";
res.status(401).json({ code });
}
}jwt.verify throws TokenExpiredError, JsonWebTokenError or NotBeforeError. Returning a distinct TOKEN_EXPIRED code tells the client to refresh instead of sending the user to the login page.
Authorization is a second, smaller middleware:
// src/middleware/authorize.ts
import type { Request, Response, NextFunction } from "express";
import type { Role } from "../auth/token.service.js";
export const authorize =
(...roles: Role[]) =>
(req: Request, res: Response, next: NextFunction) => {
if (!req.user || !roles.includes(req.user.role)) {
return res.status(403).json({ code: "FORBIDDEN" });
}
next();
};
// Usage
router.delete("/users/:id", authenticate, authorize("admin"), deleteUser);401 means “who are you?” and 403 means “I know who you are, and no”. For more ways to compose these, see Express middleware patterns.
Refresh token rotation with reuse detection
Every refresh revokes the old token and issues a new one. If a revoked token shows up again, two parties hold copies of it. One of them is an attacker, and the server can’t tell which, so it ends every session for that user.
// src/auth/auth.controller.ts (continued)
export async function refresh(req: Request, res: Response) {
let claims;
try {
claims = verifyRefreshToken(req.cookies.refresh_token);
} catch {
return res.status(401).json({ code: "TOKEN_INVALID" });
}
// Revoke atomically: null means this jti was already used or never existed
const session = await RefreshSession.findOneAndUpdate(
{ _id: claims.jti, revokedAt: null },
{ revokedAt: new Date() },
);
if (!session) {
await RefreshSession.updateMany({ userId: claims.sub }, { revokedAt: new Date() });
res.clearCookie("refresh_token", refreshCookie);
return res.status(401).json({ code: "TOKEN_REUSED" });
}
// Read the role fresh, so a demotion takes effect within one access token lifetime
const user = await User.findById(claims.sub);
if (!user) return res.status(401).json({ code: "TOKEN_INVALID" });
const accessToken = await issueTokens(res, user.id, user.role);
res.json({ accessToken });
}The atomic findOneAndUpdate stops two parallel requests from both rotating the same token. It also means two browser tabs refreshing at the same moment will trip reuse detection. If that bites you, allow a grace window of a few seconds on revokedAt before treating reuse as theft.
Logout: you can’t delete a JWT
A signed token stays valid until exp. Logout therefore revokes the refresh session and clears the cookie; the access token dies on its own within 15 minutes.
export async function logout(req: Request, res: Response) {
try {
const { jti } = verifyRefreshToken(req.cookies.refresh_token);
await RefreshSession.updateOne({ _id: jti }, { revokedAt: new Date() });
} catch {
// Missing or expired cookie: nothing to revoke
}
res.clearCookie("refresh_token", refreshCookie);
res.sendStatus(204);
}If 15 minutes is too long (banking, admin panels), deny the access token’s jti in Redis until it expires:
// On logout, using the access token from the Authorization header
const { jti, exp } = verifyAccessToken(accessToken);
await redis.set(`deny:${jti}`, "1", { EX: Math.max(1, exp - Math.floor(Date.now() / 1000)) });
// In authenticate, after verifyAccessToken
if (await redis.exists(`deny:${claims.jti}`)) {
return res.status(401).json({ code: "TOKEN_REVOKED" });
}That adds a Redis lookup to every request, which is the state JWTs were meant to avoid. Use it when you need it, not by default.
Wire the routes up:
// src/app.ts
import express from "express";
import cookieParser from "cookie-parser";
import { login, refresh, logout } from "./auth/auth.controller.js";
const app = express();
app.use(express.json());
app.use(cookieParser());
app.post("/auth/login", login);
app.post("/auth/refresh", refresh);
app.post("/auth/logout", logout);Express 5 forwards rejected promises from async handlers to your error middleware, so a database outage in login returns a 500 instead of hanging. Error handling patterns covers that handler.
The client side
Keep the access token in a variable. Retry once when the API says it expired:
let accessToken: string | null = null;
export async function api(path: string, init: RequestInit = {}) {
const send = () =>
fetch(path, { ...init, headers: { ...init.headers, Authorization: `Bearer ${accessToken}` } });
let res = await send();
if (res.status === 401 && (await res.clone().json()).code === "TOKEN_EXPIRED") {
const r = await fetch("/auth/refresh", { method: "POST", credentials: "include" });
if (!r.ok) throw new Error("Session ended, log in again");
accessToken = (await r.json()).accessToken;
res = await send();
}
return res;
}On page reload the variable is empty, so call /auth/refresh once at startup. The cookie gets you a fresh access token without a login screen.
Why not localStorage? Any script on the page can read it, including one injected through an XSS bug or a compromised npm package. An httpOnly cookie can’t be read by JavaScript at all. Cookies bring CSRF risk instead, which SameSite=Strict and the narrow /auth path mostly remove. Pair this with the security headers and HTTPS setup from this series, since secure: true cookies need TLS.
HS256 or RS256?
HS256 uses one shared secret to sign and verify. That’s fine when a single service does both. Once other services verify tokens, every one of them holds a secret that can also mint tokens. RS256 or ES256 fixes this: the auth service signs with a private key and everyone else gets the public key.
import { readFileSync } from "node:fs";
const privateKey = readFileSync("keys/private.pem");
const publicKey = readFileSync("keys/public.pem");
jwt.sign({ role }, privateKey, { algorithm: "RS256", subject: userId, expiresIn: "15m" });
jwt.verify(token, publicKey, { algorithms: ["RS256"] });Mistakes I keep finding
- No
algorithmsoption onjwt.verify. - One secret for both token types, or a short one like
"secret123". - Access tokens that last 24 hours or never expire.
- Refresh tokens stored in plain text with no rotation, so a stolen one works for a week.
- User data in the payload that changes, like role, with no refresh path to pick up the change.
Frequently Asked Questions
Should I use JWT or sessions? For a single server-rendered app, a session cookie is simpler and easier to revoke. JWTs pay off when several services or a mobile app need to verify identity without a shared session store.
How long should access and refresh tokens last? 5 to 15 minutes for access tokens and 7 to 30 days for refresh tokens are common. Shorter access tokens mean faster revocation and more refresh calls.
Can I invalidate a JWT before it expires?
Not without server state. Either keep access tokens short and revoke refresh sessions, or keep a denylist of jti values until each token expires.
Do mobile apps need cookies? No. Native apps can keep the refresh token in the iOS Keychain or Android Keystore and send it in the request body. Rotation and reuse detection work the same way.
Related reading
- Advanced Authentication Patterns in Node.js & Express.js. Next in this series: passkeys, magic links, OAuth and MFA.
- Master Input Validation & Sanitization in Node.js. Validate the login body before it reaches bcrypt.
- Node.js Security Checklist. Rate limiting, Helmet and dependency audits around your auth routes.
- Understanding TTL Indexes in MongoDB. How the refresh session cleanup above works.
- Node.js with TypeScript: Best Practices Guide. Project layout for the files in this post.