JSON Web Tokens remain the most consistently misconfigured piece of application security I encounter during production code reviews. Nearly every vulnerable setup traces back to the same five-minute quickstart: issue a JWT valid for 30 days, return it inside the login JSON body, persist it in localStorage, and verify the signature in route middleware.
In live software, that shortcut fails in two severe ways: you cannot invalidate a stolen token before day 30, and any XSS payload or compromised third-party tag manager can read localStorage silently.
When your architecture genuinely calls for JWTs—across decoupled mobile clients, cross-origin APIs, or distributed microservices—you must combine short-lived stateless access tokens with stateful, single-use refresh tokens.
Step One: Verify That You Actually Need JWTs
Before writing rotation tables and lock logic, confirm whether classic server-side sessions (backed by Redis or PostgreSQL behind an HttpOnly cookie) serve your product more cleanly.
When your web frontend and API share one registrable domain (app.acme.test and api.acme.test), opaque session cookies offer instant revocation, zero client-side refresh races, and straightforward permission invalidation. Reach for Access JWT + Refresh Token specifically when:
- Native iOS or Android clients authenticate alongside a browser app.
- Separate backend microservices verify identity locally using public keys (JWKS) without calling a central session database on every request.
- Third-party API consumers require scoped short-lived bearer credentials.
Access vs. Refresh Responsibilities and Storage
Splitting credentials into two distinct tokens balances stateless verification speed against real session control:
- Access JWT: Expires in 5–15 minutes, signed asymmetrically (
EdDSAorRS256), kept strictly in memory (or a short-livedHttpOnlycookie), never persisted inlocalStorage. - Refresh Token (Opaque Secret): A 256-bit cryptographically random string—never a JWT—hashed via SHA-256 before database storage, valid for 7–30 days, and accepted once at
/auth/refresh.
Client Transport Security Matrix
| Runtime Target | Access Token Placement | Refresh Token Placement | Cross-Site Request Protection |
|---|---|---|---|
| Browser SPA | JS memory or HttpOnly cookie |
HttpOnly, Secure, SameSite=Lax cookie (Path=/auth/refresh) |
SameSite policy + Origin verification |
| iOS / Android App | In-memory state store | Keychain (iOS) / EncryptedSharedPreferences (Android) | Not needed (Authorization: Bearer header) |
| Anti-Pattern | localStorage / sessionStorage |
localStorage |
Exposed to any inline or third-party script |
Scoping the browser cookie with Path=/auth/refresh ensures the refresh credential never rides along on ordinary /api/* calls, minimizing exposure in proxy logs.
Schema Design for Rotation and Reuse Detection
To revoke sessions cleanly and catch token replay attacks, store SHA-256 digests in auth_refresh_tokens grouped under a chain_id representing one device login:
CREATE TABLE auth_refresh_tokens (
token_id UUID PRIMARY KEY,
account_id UUID NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
chain_id UUID NOT NULL,
sha256_digest CHAR(64) NOT NULL UNIQUE,
superseded_by UUID NULL REFERENCES auth_refresh_tokens(token_id),
invalidated_at TIMESTAMP WITH TIME ZONE NULL,
valid_until TIMESTAMP WITH TIME ZONE NOT NULL,
issued_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX idx_auth_refresh_chain ON auth_refresh_tokens (chain_id);
Because only sha256_digest hits disk, even a leaked database snapshot cannot be replayed directly against your refresh endpoint.
Atomic Rotation and Automatic Reuse Detection
Each call to /auth/refresh locks the matching token row, marks it superseded, and mints a fresh (accessToken, refreshToken) pair inside the same chain_id.
If an attacker steals an older refresh token and submits it after the legitimate user has already rotated forward—or vice versa—the server spots that superseded_by or invalidated_at is already populated and revokes the entire chain_id immediately:
import crypto from "node:crypto";
export async function rotateSessionTokens(db: Database, rawRefresh: string) {
const digest = crypto.createHash("sha256").update(rawRefresh).digest("hex");
return db.transaction(async (tx) => {
// Row lock serializes parallel tab refresh requests
const current = await tx.queryOne(
`SELECT * FROM auth_refresh_tokens WHERE sha256_digest = $1 FOR UPDATE`,
[digest]
);
if (!current || current.valid_until < new Date()) {
throw new AuthError("TOKEN_EXPIRED_OR_UNKNOWN");
}
// Reuse detected: invalidate entire login chain
if (current.superseded_by !== null || current.invalidated_at !== null) {
await tx.execute(
`UPDATE auth_refresh_tokens SET invalidated_at = NOW() WHERE chain_id = $1 AND invalidated_at IS NULL`,
[current.chain_id]
);
throw new AuthError("REFRESH_TOKEN_REUSE_DETECTED");
}
const nextSecret = crypto.randomBytes(32).toString("base64url");
const nextDigest = crypto.createHash("sha256").update(nextSecret).digest("hex");
const nextTokenId = crypto.randomUUID();
await tx.execute(
`INSERT INTO auth_refresh_tokens (token_id, account_id, chain_id, sha256_digest, valid_until)
VALUES ($1, $2, $3, $4, NOW() + INTERVAL '14 days')`,
[nextTokenId, current.account_id, current.chain_id, nextDigest]
);
await tx.execute(
`UPDATE auth_refresh_tokens SET superseded_by = $1 WHERE token_id = $2`,
[nextTokenId, current.token_id]
);
const accessJwt = issueShortAccessJwt({
sub: current.account_id,
jti: crypto.randomUUID(),
expiresInSeconds: 600,
});
return { accessJwt, refreshToken: nextSecret };
});
}
Preventing Multi-Tab False Positives in Browsers
When a user leaves three tabs open and returns after 15 minutes, all three tabs hit 401 and call /auth/refresh simultaneously with the identical cookie. Without coordination, tab #2 trips reuse detection and forces a logout.
Prevent false alarms cleanly:
- Single-flight refresh lock: Deduplicate concurrent refresh promises inside your frontend HTTP client and coordinate across tabs via
navigator.locksorBroadcastChannel(patterns frequently covered on Vercel's engineering blog). - Row-level serialization (
FOR UPDATE): Ensures the server processes overlapping requests sequentially rather than racing two inserts.
Verification Hardening and Key Rotation Pitfalls
Even solid refresh flows break if JWT signature verification skips basic guardrails:
- Explicit algorithm allow-lists: Never trust the incoming
algheader blindly (which enablesalg: noneor asymmetric-to-HMAC downgrade attacks). Passalgorithms: ['EdDSA']or['RS256']explicitly to your verifier. - Strict
iss,aud, and minimal clock leeway: Cap clock skew tolerance under 30 seconds and enforce environment-specific audience strings so staging tokens cannot hit production APIs. - Lean claims only: Include
sub,tid(for multi-tenant isolation),exp,iat, andjti. Avoid stuffing huge RBAC arrays or sensitive PII into Base64-encoded payloads visible in browser devtools or logs. - Zero-downtime signing key rotation via
kid: Serve active public keys from/.well-known/jwks.jsonkeyed bykidso key rotations never invalidate live 10-minute access tokens.
For broader guidance on isolating identity boundaries from domain logic, review Martin Fowler's architecture patterns, or read how we extract coupled session logic when modularizing older PHP codebases.
Shipping Hardened Auth Layers With SmitDev
Authentication leaves zero margin for guesswork—one missing cookie attribute, unvalidated alg header, or race-prone refresh handler compromises user trust overnight. Across 170+ shipped systems since 2017, I regularly build and audit HttpOnly cookie BFF proxies, rotating refresh pipelines, OAuth2/SSO flows, and tenant-scoped RBAC.
Engage SmitDev directly via dedicated engineering retainers or full-stack development services at $55/day (8–9 hours of daily engineering) or $1,999/month for continuous delivery. Share your current auth flow or stack constraints on our contact page for a concrete hardening plan.