You signed a token, and now the user logged out, changed their password, or you just watched someone replay it from a stolen laptop. The token is still perfectly valid until its exp. "Just delete it" doesn't work, because what your server verifies is a self-contained signed string, not a row in a database.
This guide covers four ways to revoke JWTs without adding a database query to every request, when each one is the right pick, what each one costs, and Node.js code for each (written for jsonwebtoken and node-redis v4). It also covers logout, choosing an expiration time, and the clock errors that look like revocation bugs but aren't.
Short answer: to revoke a JWT before it expires, keep access tokens short-lived and kill the refresh token on logout. Add a denylist or a token-version check if you need immediate revocation.
Why Deleting the Token on the Client Is Not Revocation
A stateless JWT check verifies exactly two things: the signature and the exp claim. The server keeps no memory of what it issued, which is the whole point of JWTs. So when a user "logs out" by removing the token from localStorage, what disappears is the browser's copy. Anyone else holding the token can keep using it:
# after "logout": still works until exp
curl https://api.example.com/me -H "Authorization: Bearer <deleted-token>"
Revocation never means deleting a token. It means making the verifier reject it. The four strategies below differ in one dimension: who pays for that check, and how often.
The Four Strategies, Ranked
1. Short TTL + Refresh Token Rotation (the default)
Give access tokens a 5 to 15 minute lifetime and keep long-lived state in a refresh token stored server-side. To remove a user (logout, password change, ban), delete their refresh token. Every access token already in the wild dies on its own within one TTL, with no per-request cost.
The exposure window is bounded by the TTL. With a 5-minute access token, the worst case after "kill everything" is 5 minutes of lingering validity. That is why this is the default: bounded damage with no lookup at all.
const jwt = require('jsonwebtoken');
const { randomUUID } = require('crypto');
// access token: short TTL, carries a jti and the user's token version
const accessToken = jwt.sign(
{ sub: user.id, ver: user.tokenVersion },
process.env.JWT_SECRET,
{ algorithm: 'HS256', expiresIn: '5m', jwtid: randomUUID() }
);
// refresh token: opaque random value; store only its hash server-side
const refreshToken = randomUUID();
Pick this if you can tolerate a bounded exposure window and your refresh flow is solid. The rotation side is covered in refresh token reuse detection.
2. Token Versioning, Cached (kill every token for one user, now)
Versioning moves the decision into a claim the token already carries. Embed ver at signing time, compare it to the user's current token_version, and reject mismatches. Bump the version once and every older token for that user dies at its next request.
The catch is where the current version comes from. Reading the users table on every request is a database lookup, whatever you call it. The fix is to cache the integer in Redis (or in-process memory) and only touch the database on a cache miss:
async function getTokenVersion(userId) {
const cached = await redis.get(`tv:${userId}`);
if (cached !== null) return Number(cached);
const { rows } = await db.query('SELECT token_version FROM users WHERE id = $1', [userId]);
if (!rows[0]) return null;
await redis.set(`tv:${userId}`, String(rows[0].token_version), { EX: 60 });
return rows[0].token_version;
}
// on password change / ban / suspected theft
async function bumpTokenVersion(userId) {
const { rows } = await db.query(
'UPDATE users SET token_version = token_version + 1 WHERE id = $1 RETURNING token_version',
[userId]
);
// write the new value through so every node sees it immediately
await redis.set(`tv:${userId}`, String(rows[0].token_version), { EX: 60 });
}
async function authenticate(req, res, next) {
try {
const token = (req.headers.authorization || '').replace(/^Bearer /, '');
// throws on bad signature or expired token
const claims = jwt.verify(token, process.env.JWT_SECRET, { algorithms: ['HS256'] });
const current = await getTokenVersion(claims.sub);
if (current === null || claims.ver !== current) {
return res.status(401).json({ error: 'token revoked' });
}
req.auth = { token, claims };
next();
} catch (err) {
res.status(401).json({ error: 'invalid or expired token' });
}
}
With the write-through in bumpTokenVersion, revocation is immediate for every server sharing that Redis. If you cache in each process's memory instead, revocation takes up to the cache TTL to reach every instance, so keep that TTL short. If Redis is unreachable, getTokenVersion throws and the middleware above fails closed (401). Decide that on purpose: failing open means falling back to the database or skipping the check.
This is not stateless. You still hold one integer per user, but it is the cheapest state you can have: one cached read per request, and a database read only after a miss or a bump.
Pick this if password changes, bans, or "log out everywhere" must take effect now and per-user granularity is enough, which it usually is.
3. A jti Denylist in Redis (kill one specific token)
Versioning is all-or-nothing per user. To kill one token (a stolen session on one device, without logging the user out elsewhere) you need per-token state, and jti is the claim for that. Write the jti to a denylist whose TTL equals the token's remaining life. The entry removes itself, so there is no cleanup job.
const { createClient } = require('redis'); // node-redis v4
const redis = createClient({ url: process.env.REDIS_URL });
redis.on('error', (err) => console.error('redis error', err));
await redis.connect(); // call inside an async init function if you are not using ESM
async function revokeAccessToken(claims) {
const ttl = claims.exp - Math.floor(Date.now() / 1000);
if (ttl > 0) {
await redis.set(`revoked:${claims.jti}`, '1', { EX: ttl });
}
}
// inside authenticate(), right after the version check:
if (await redis.exists(`revoked:${claims.jti}`)) {
return res.status(401).json({ error: 'token revoked' });
}
The per-request cost is one O(1) Redis call, typically well under a millisecond inside the same region. Always mint tokens with a unique jwtid: a denylist keyed on jti does nothing if the claim is missing or shared. Store the jti, never the token string itself.
Pick this if individual sessions must be revocable instantly (shared devices, reported stolen sessions) and you already run Redis. The same per-request Redis pattern appears in distributed rate limiting with Redis.
4. A jti Allowlist (strongest, but now you run sessions)
Invert the denylist: store the valid jti values per session and reject anything not in the set. Logout deletes the entry, replays outside the set are detectable, and you can answer "which sessions exist right now". Entries can carry the token's TTL too, so storage is bounded by active sessions times token lifetime rather than growing forever.
Be clear about what this is: an allowlist turns "stateless JWT" into server-side sessions that carry a signed identity payload. That is not a failure, and for audit-heavy systems it is often the right design. Just don't build it while still believing you have stateless auth.
Last Resort: Rotate the Signing Key
Rotating the signing secret invalidates every token signed with the old key, for every user. It is for suspected key compromise, not for logout. In that case the old key must stop verifying immediately, and you accept a mass re-login. For planned, routine rotation, put a kid in the token header and let the verifier accept both keys for up to one access-token TTL. Never leave a possibly leaked key verifying "for a while".
What Each Strategy Costs
The real question is not "database or not". It is who pays, per request, and what exposure window you are buying.
| Strategy | Per-request cost | Instant? | Kills one token? | Kills all for a user? | State |
|---|---|---|---|---|---|
| 1. Short TTL + refresh rotation | none | no (up to one TTL) | only via the refresh token | via refresh delete | refresh sessions |
| 2. Token versioning (cached) | one cached integer read | yes | no | yes | one integer per user |
3. jti denylist | one Redis call | yes | yes | no | self-expiring |
4. jti allowlist | one Redis call | yes | yes | yes (delete all) | bounded by active sessions |
Assumptions for the numbers that follow (measure your own): 1,000 requests per second, a 5-minute access TTL, a Redis GET of about 0.5 ms in the same region, and a typical request taking about 100 ms. Under those assumptions a Redis check adds roughly 0.5% to request time and no queries on your primary database. After revoking a refresh token, the worst-case exposure is 5 minutes, and a specific stolen access token dies the moment its jti is denylisted. A 14-day access token with no denylist has a worst case of two weeks per leaked token. Shortening the TTL is free, so every other strategy is an upgrade you add for a concrete requirement.
A compact rule: start at 1. Move to 2 as soon as "log out everywhere" or password-change urgency exists. Add 3 when you must kill individual sessions. Accept 4 when audit or compliance requires knowing which sessions are alive.
How to Expire a JWT Token (TTL Best Practices)
There is no universal number, but these are common starting points:
| Token | Typical lifetime | Notes |
|---|---|---|
| Access token | 5 to 15 minutes | Shorter means a smaller damage window and more refresh traffic |
| Refresh token | 7 to 30 days | Rotate on every use; store server-side, hashed |
| Password reset / email link token | 15 to 60 minutes | Single use |
To change the expiration time, change expiresIn where you sign the token:
jwt.sign(payload, secret, { expiresIn: '10m' }); // minutes
jwt.sign(payload, secret, { expiresIn: 600 }); // a number means seconds
Two details trip people up. With jsonwebtoken, a string without a unit such as '600' is read as milliseconds, so always include the unit or pass a number of seconds. And changing expiresIn only affects tokens issued afterwards: tokens already in circulation keep the exp they were signed with. To cut those off early, bump the user's token_version.
Logout Done Right: Kill the Refresh Token and the Access Token
The refresh token holds the real power. A logout that only removes the access token from the client revokes nothing, because the attacker's client can mint new access tokens from the still-valid refresh token. A correct logout does three things:
const crypto = require('crypto');
const sha256 = (s) => crypto.createHash('sha256').update(s).digest('hex');
app.post('/logout', authenticate, async (req, res) => {
const { jti, exp, sub } = req.auth.claims;
const refreshToken = req.cookies.refresh_token; // requires cookie-parser
// 1. kill the refresh session server-side (the actual revocation)
if (refreshToken) {
await db.query(
'DELETE FROM sessions WHERE user_id = $1 AND token_hash = $2',
[sub, sha256(refreshToken)]
);
}
// 2. block the current access token for its remaining life
const ttl = exp - Math.floor(Date.now() / 1000);
if (ttl > 0) await redis.set(`revoked:${jti}`, '1', { EX: ttl });
// 3. clear the cookie (options must match how it was set)
res.clearCookie('refresh_token', { httpOnly: true, secure: true, sameSite: 'strict', path: '/token' });
res.status(204).end();
});
With 5-minute access tokens, step 2 is belt and suspenders. With longer lifetimes it is required. If your refresh tokens rotate, turn on reuse detection: see refresh token reuse detection.
Clock Skew: "Token Used Before Issued" and "JWT Not Before"
These errors come from clock differences, not revocation logic. The token's nbf or iat is in the future relative to the verifying server's clock, usually because one machine is seconds or minutes off after a container restart or VM reschedule. Error wording depends on the library: jsonwebtoken reports a failed nbf check as "jwt not active", while other libraries use different messages (Go's golang-jwt has an error for tokens used before they were issued, and PyJWT raises an immature-signature error). Check your library's documentation for the exact behavior.
Every major library has a leeway option for small skew:
// Node (jsonwebtoken), seconds
jwt.verify(token, secret, { clockTolerance: 30 });
// Go (golang-jwt v5)
parser := jwt.NewParser(jwt.WithLeeway(30 * time.Second))
# Python (PyJWT), seconds
jwt.decode(token, key, algorithms=["HS256"], leeway=30)
Use leeway to absorb small drift and NTP sync on every machine that signs or verifies tokens to remove it. If skew is consistently measured in minutes, treat it as an infrastructure incident.
Common Mistakes
- Deleting the token client-side and calling it revocation. The token still verifies until
exp. - Long access-token lifetimes "for convenience". That is your maximum damage window per leaked token.
- Revoking the access token but not the refresh token, so the session mints a new one within seconds.
- Denylist entries without a TTL, so the list grows forever.
- Minting tokens without a
jti, or with duplicated IDs. - Calling it "no database" while running a
SELECTon the users table for every request. Cache the version instead.
Worked Scenarios
| Situation | Move | Why |
|---|---|---|
| User changes password | bump token_version + delete all refresh sessions | instant, per user, no per-token bookkeeping |
| Logout on a shared computer | delete that session's refresh token; denylist the access jti if the TTL is long | kills exactly that session |
| Stolen refresh token detected (reuse alarm) | delete the session, denylist its access jti, force re-login; bump the version if theft is suspected | per-session first, escalate on evidence |
| Ban a user | bump token_version + delete all refresh sessions | every token dies at its next request |
| Suspected signing-key leak | rotate the key, old key stops verifying immediately | the only fix for arbitrary already-signed tokens |
| Compliance needs "list active sessions" | allowlist (strategy 4) | you cannot list what you don't store |
Verifying It Works
Test the revocation itself, not the intention:
- Mint a token, revoke it through your real flow (logout, version bump, or denylist write), then call a protected endpoint with it. Expect a 401 before
exp, not after. - With the access token still valid, try to refresh using a deleted refresh token. Expect rejection and, with reuse detection on, an alert.
- After deploying, watch the 401 rate (a spike means version bumps or denylist writes are misfiring), the number of denylist keys (bounded by active revocations times TTL), and login latency.
- Log rejection reasons separately: expired, version mismatch, and revoked
jtiare different incidents.
Try It Yourself
The Redis logic above is simplified for explanation. A fuller runnable Express service with login, rotation, reuse detection and family revocation is open source:
github.com/polasamy-eng/devsaas-devops-examples (see refresh-token-reuse-detection/)
Clone it, run docker compose up, and hit the endpoints with curl to watch reuse detection trigger.
The snippets here are illustrative and written for jsonwebtoken and node-redis v4, so check them against the library versions you run before relying on them.
Frequently Asked Questions
Does logging out invalidate a JWT?
Not by itself. Logout removes the client's copy and, done correctly, the server-side refresh token. The access token stays cryptographically valid until its exp claim passes, unless you denylist its jti or the user's token version changes. That is why the access token lifetime matters: it caps how long a logged-out token can still be used.
Can you revoke a JWT without a database?
You can revoke without a database query on every request. Short lifetimes bound the exposure, a cached token version handles per-user revocation, and a Redis denylist handles single tokens. Instant revocation of a specific token always needs some shared state, so "no database" really means "no extra query on your primary database", not "no state".
How long should a JWT access token live?
Five to fifteen minutes is a common range for browser and mobile clients. Longer lifetimes widen the damage window for every leaked token, and shorter ones increase refresh traffic. The long-lived credential should be the refresh token, stored server-side, not the access token.
How do I change the JWT expiration time?
Change the expiresIn option where you sign the token, for example expiresIn set to 10m. It only affects tokens issued after the change. Existing tokens keep their original exp, so bump the user's token version if they must stop working earlier. With jsonwebtoken, include a unit in string values, because a bare string is read as milliseconds.
Why do I get "jwt not before" or "token used before issued"?
The token's nbf or iat claim is in the future relative to the verifying server's clock, which means the clocks differ. Allow a small leeway, such as 30 seconds, and sync every machine with NTP. Consistently large skew points to an infrastructure problem rather than a JWT configuration issue.
What is the difference between revoking, invalidating and expiring a JWT?
Expiring happens automatically when the exp timestamp passes. Revoking is proactive: making the verifier reject a token before exp through versioning, a denylist or key rotation. Invalidating is the umbrella term people use for both. In every case the token string itself never changes, only the verifier's decision about it.