Node.js JWT Authentication: Verify and Refresh Tokens
Implement JWT authentication in Node.js: access and refresh tokens, rotation with reuse detection, and Express middleware
Overview
JWT gives a Node.js API stateless authentication: the server signs a token carrying the user’s claims, and each request presents it in the Authorization header — there’s no session store to query on every call. This recipe builds the complete flow in Express with jsonwebtoken: issuing access and refresh tokens, protecting routes with middleware, rotating refresh tokens, and detecting reuse. For the multi-language version that also covers Python and Java, see the JWT Authentication recipe.
When to Use
- You’re building a stateless Express API and need auth without server-side sessions
- You want short-lived access tokens backed by long-lived refresh tokens
- You need refresh token rotation to contain the damage of a stolen token
- Your microservices verify tokens independently with a shared secret or a public key
Avoid it when:
- A server-side session already does the job — a monolith with a single web frontend is usually simpler with cookie sessions
- You delegate authentication to an OAuth provider; in that case go to Node.js OAuth2 GitHub Login with Express
- You need instant per-request revocation — a JWT stays valid until it expires unless you keep a server-side blocklist
Solution
Basic JWT generation and verification
const jwt = require("jsonwebtoken");
const ACCESS_TOKEN_SECRET = process.env.JWT_ACCESS_SECRET || "access-secret-change-me";
const REFRESH_TOKEN_SECRET = process.env.JWT_REFRESH_SECRET || "refresh-secret-change-me";
function generateAccessToken(payload) {
return jwt.sign(payload, ACCESS_TOKEN_SECRET, {
expiresIn: "15m",
issuer: "my-api",
audience: "my-api-users"
});
}
function generateRefreshToken(payload) {
return jwt.sign(payload, REFRESH_TOKEN_SECRET, {
expiresIn: "7d",
issuer: "my-api",
audience: "my-api-users"
});
}
function verifyAccessToken(token) {
try {
return jwt.verify(token, ACCESS_TOKEN_SECRET, {
issuer: "my-api",
audience: "my-api-users"
});
} catch (err) {
if (err.name === "TokenExpiredError") {
return { error: "token_expired" };
}
return { error: "invalid_token" };
}
}
// Usage
const user = { userId: 123, role: "admin" };
const accessToken = generateAccessToken(user);
const decoded = verifyAccessToken(accessToken);
console.log(decoded);
Express middleware for JWT authentication
const express = require("express");
const jwt = require("jsonwebtoken");
const app = express();
app.use(express.json());
const ACCESS_TOKEN_SECRET = process.env.JWT_ACCESS_SECRET || "access-secret";
function authMiddleware(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith("Bearer ")) {
return res.status(401).json({ error: "Missing or invalid authorization header" });
}
const token = authHeader.split(" ")[1];
try {
const decoded = jwt.verify(token, ACCESS_TOKEN_SECRET, {
issuer: "my-api",
audience: "my-api-users"
});
req.user = decoded;
next();
} catch (err) {
if (err.name === "TokenExpiredError") {
return res.status(401).json({ error: "Token expired", code: "token_expired" });
}
return res.status(401).json({ error: "Invalid token", code: "invalid_token" });
}
}
function requireRole(role) {
return (req, res, next) => {
if (!req.user || req.user.role !== role) {
return res.status(403).json({ error: "Insufficient permissions" });
}
next();
};
}
app.get("/api/public", (req, res) => {
res.json({ message: "public endpoint" });
});
app.get("/api/profile", authMiddleware, (req, res) => {
res.json({ user: req.user });
});
app.get("/api/admin", authMiddleware, requireRole("admin"), (req, res) => {
res.json({ message: "admin only" });
});
app.listen(3000, () => console.log("Server running on port 3000"));
Login and refresh token flow
const express = require("express");
const jwt = require("jsonwebtoken");
const crypto = require("crypto");
const bcrypt = require("bcrypt");
const app = express();
app.use(express.json());
const ACCESS_TOKEN_SECRET = process.env.JWT_ACCESS_SECRET || "access-secret";
const REFRESH_TOKEN_SECRET = process.env.JWT_REFRESH_SECRET || "refresh-secret";
// In-memory refresh token store keyed by token hash — O(1) lookup (use Redis in production)
const refreshTokens = new Map();
const tokenKey = (token) => crypto.createHash("sha256").update(token).digest("hex");
// Mock user database — generate the hash with bcrypt.hashSync("admin123", 12)
const users = [
{ id: 1, username: "admin", password: "$2b$12$REPLACE_WITH_REAL_BCRYPT_HASH", role: "admin" }
];
app.post("/auth/login", async (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username);
if (!user || !(await bcrypt.compare(password, user.password))) {
return res.status(401).json({ error: "Invalid credentials" });
}
const payload = { userId: user.id, role: user.role };
const accessToken = jwt.sign(payload, ACCESS_TOKEN_SECRET, { expiresIn: "15m" });
const refreshToken = jwt.sign(payload, REFRESH_TOKEN_SECRET, { expiresIn: "7d" });
refreshTokens.set(tokenKey(refreshToken), { userId: user.id });
res.json({
accessToken,
refreshToken,
expiresIn: 900
});
});
app.post("/auth/refresh", (req, res) => {
const { refreshToken } = req.body;
if (!refreshToken) {
return res.status(400).json({ error: "Refresh token required" });
}
try {
const decoded = jwt.verify(refreshToken, REFRESH_TOKEN_SECRET);
// Check if token is in store (not revoked)
if (!refreshTokens.has(tokenKey(refreshToken))) {
return res.status(401).json({ error: "Token revoked" });
}
// Generate new access token
const newAccessToken = jwt.sign(
{ userId: decoded.userId, role: decoded.role },
ACCESS_TOKEN_SECRET,
{ expiresIn: "15m" }
);
res.json({ accessToken: newAccessToken, expiresIn: 900 });
} catch (err) {
return res.status(401).json({ error: "Invalid refresh token" });
}
});
app.post("/auth/logout", (req, res) => {
refreshTokens.delete(tokenKey(req.body.refreshToken));
res.json({ message: "Logged out" });
});
app.listen(3000);
Token rotation with refresh token reuse detection
This example continues from the Express setup above — app is the same instance and both secrets come from env vars.
const jwt = require("jsonwebtoken");
const crypto = require("crypto");
const ACCESS_TOKEN_SECRET = process.env.JWT_ACCESS_SECRET || "access-secret";
const REFRESH_TOKEN_SECRET = process.env.JWT_REFRESH_SECRET || "refresh-secret";
// Store: { jti: { userId, token, family, createdAt } }
const tokenStore = new Map();
function generateRotatedRefreshToken(userId, family) {
const jti = crypto.randomUUID();
const token = jwt.sign({ userId, jti, family }, REFRESH_TOKEN_SECRET, { expiresIn: "7d" });
tokenStore.set(jti, { userId, token, family, createdAt: Date.now() });
return token;
}
function rotateRefreshToken(oldToken) {
let decoded;
try {
decoded = jwt.verify(oldToken, REFRESH_TOKEN_SECRET);
} catch (err) {
throw new Error("invalid_token");
}
const stored = tokenStore.get(decoded.jti);
if (!stored) {
// Token was already used — possible reuse attack
// Revoke entire family
for (const [jti, data] of tokenStore.entries()) {
if (data.family === decoded.family) {
tokenStore.delete(jti);
}
}
throw new Error("reuse_detected");
}
if (stored.token !== oldToken) {
throw new Error("invalid_token");
}
// Delete old token
tokenStore.delete(decoded.jti);
// Issue new token in same family
return generateRotatedRefreshToken(decoded.userId, decoded.family);
}
// Usage in Express route
app.post("/auth/refresh", (req, res) => {
try {
const newRefreshToken = rotateRefreshToken(req.body.refreshToken);
const decoded = jwt.verify(newRefreshToken, REFRESH_TOKEN_SECRET);
const accessToken = jwt.sign(
{ userId: decoded.userId },
ACCESS_TOKEN_SECRET,
{ expiresIn: "15m" }
);
res.json({ accessToken, refreshToken: newRefreshToken });
} catch (err) {
if (err.message === "reuse_detected") {
return res.status(401).json({
error: "Token reuse detected. All sessions revoked.",
code: "reuse_detected"
});
}
return res.status(401).json({ error: "Invalid refresh token" });
}
});
RS256 asymmetric tokens
const fs = require("fs");
const jwt = require("jsonwebtoken");
const privateKey = fs.readFileSync("private.key", "utf8");
const publicKey = fs.readFileSync("public.key", "utf8");
function signToken(payload) {
return jwt.sign(payload, privateKey, {
algorithm: "RS256",
expiresIn: "15m"
});
}
function verifyToken(token) {
try {
return jwt.verify(token, publicKey, { algorithms: ["RS256"] });
} catch (err) {
return { error: err.message };
}
}
Explanation
A JWT has three dot-separated parts: header (the algorithm), payload (claims like userId, role, exp, iat, iss, aud), and signature. jwt.verify recomputes the signature and rejects the token if anything was tampered with — that’s why you never need a database lookup to authenticate a request.
Key concepts:
- Access tokens: short-lived on purpose (15 minutes here). The client sends one on every API request and the server verifies it statelessly — no store lookup.
- Refresh tokens: long-lived (7 days here) and only ever exchanged for new access tokens. Since they can mint new sessions, they live in a server-side store so you can revoke them.
- Token rotation: every refresh burns the old token and issues a new one. If a burned token shows up again, treat it as theft — the whole token family gets revoked and the user logs in again.
- HS256 vs RS256: HS256 shares one secret between signer and verifier. RS256 signs with a private key and verifies with a public key, so a compromised read-only service can’t forge tokens.
How rotation with reuse detection works
Production notes
- Secrets: the
|| "access-secret"fallbacks exist so the snippet runs locally. In production, load both secrets from env vars or a secret manager and fail fast on startup if they’re missing — a deployed fallback secret is a known string anyone can sign with. - Refresh store: the
Maphere dies with the process and doesn’t scale past one instance. Move it to Redis keyed by the token hash (same astokenKeyabove) with a TTL equal to the token lifetime; the revocation logic stays identical. - Transport: for browser clients, send the refresh token as an
httpOnly,Secure,SameSite=Strictcookie instead of a JSON field — JavaScript can’t read it and CSRF risk stays low. The access token can live in memory and never touchlocalStorage. - Library choice:
jsonwebtokenstill ships in most Express codebases, which is why the examples use it. On ESM, edge runtimes, or anywhere you wantWebCrypto,josecovers the same flows with a more modern API.
Variants
| Approach | Algorithm | Storage | Use When |
|---|---|---|---|
| HS256 | Symmetric | Shared secret | Single server, simple setup |
| RS256 | Asymmetric | Key pair | Microservices, public-key verifiers |
| ES256 | Asymmetric | EC key pair | Mobile apps, constrained devices |
| Redis-backed | HS256 | Redis | Refresh store shared across several app instances |
| Database-backed | HS256 | SQL | When Redis is unavailable |
Best Practices
- Sign access and refresh tokens with different secrets — a leak of one stays contained.
- Keep access tokens at 15 minutes or less and let the refresh token carry the long session.
- Store refresh tokens server-side; a purely stateless refresh token can’t be revoked.
- Rotate refresh tokens and detect reuse — it’s the cheapest signal that a token was stolen.
- Use RS256 in microservices so verifiers hold only the public key and can never sign.
- Set
issuerandaudienceclaims so a token minted for one service is rejected by another. - Never store tokens in localStorage for browser apps. Use httpOnly cookies.
Common Mistakes
- Using the same secret for access and refresh tokens — one leak and an attacker can mint both.
- Skipping
issuerandaudiencevalidation, which lets a token minted for a different service walk through your middleware. - Putting tokens in localStorage, where any XSS payload can read them. httpOnly cookies are out of JavaScript’s reach.
- Keeping refresh tokens purely stateless — with no server-side record there’s nothing to revoke, so logout does nothing.
- Long-lived access tokens. A stolen one-hour token is an hour of free access; fifteen minutes shrinks that window to something an attacker can barely use.
Further Reading
- RFC 7519 — JSON Web Token (JWT) — the spec behind
iss,aud,expand JWS signatures - OWASP JSON Web Token cheat sheet — hardening checklist: algorithm checks, storage, revocation
- jose — JWT for modern runtimes — the ESM/WebCrypto alternative mentioned above
- Companion repo — runnable Express server plus a flow test covering rotation and reuse detection
Frequently Asked Questions
Should I use JWT or server-side sessions?
Reach for JWT when the API must scale horizontally without a shared session store — each service verifies the token on its own. For a single monolith, server-side sessions are simpler to revoke and easier to reason about.
How do I revoke a JWT before it expires?
An access token stays valid until it expires — there's no way to kill it early without checking a server-side denylist of jti claims. That's why this recipe keeps them at 15 minutes. Refresh tokens are different: they live in a server-side store anyway, so revoke them the moment the user logs out or a reuse attempt shows up.
What is the difference between HS256 and RS256?
With HS256, every service that verifies a token also holds the signing secret — leak it once and an attacker can mint tokens. RS256 splits the duties: the auth service signs with a private key, everyone else verifies with the public key, which can't sign anything.
How do I handle token expiration gracefully?
Return a distinct token_expired code so the client can tell an expired token apart from a bad signature, then refresh and retry the request once:
if (error.response.status === 401 && error.response.data.code === "token_expired") {
const newToken = await refreshToken();
retryOriginalRequest(newToken);
}
Related Resources
JWT Authentication
Sign, verify, and refresh JWTs in Python, JavaScript, and Java — access/refresh flows, RS256 key pairs, and token revocation done right.
RecipeNode.js OAuth2 GitHub Login with Express
Implement GitHub OAuth2 login flow in Node.js with Express and Passport
DocEndpoint Device Security Checklist Template
A checklist template for hardening laptops, workstations, and mobile devices that access corporate data and systems.
RecipeSecure JWT Refresh Token Rotation with Python
Implement secure JWT access and refresh token rotation in Python with blacklist, reuse detection, and automatic access token renewal for stateless auth