JWT
suggest changeA JSON Web Token (JWT, pronounced "jot") is a compact, URL-safe string that carries a set of claims (a JSON object) together with a cryptographic signature. A server that receives a JWT can check the signature and trust the claims without looking anything up in a database. That makes JWTs popular for stateless API authentication, for single sign-on, and for passing identity between microservices.
| Task | Tool |
|---|---|
| Sign and verify tokens (recommended) | jose package |
| Sign and verify tokens (older, very common) | jsonwebtoken package |
| Look inside a token without verifying | Buffer.from(part, 'base64url'), decodeJwt() |
| Shared secret between one issuer and verifier | HS256 (HMAC-SHA256) |
| Many verifiers, one issuer | ES256, EdDSA or RS256 with a public key / JWKS |
The examples are ES modules (save them as .mjs) and were run with Node.js 24, jose 6.2 and jsonwebtoken 9.0. Install the packages with npm install jose jsonwebtoken express.
Anatomy of a token
A JWT is three base64url-encoded parts separated by dots: header.payload.signature. The header says how the token is signed, the payload holds the claims, and the signature covers the first two parts. The first two parts are only encoded, not encrypted, so anyone who has the token can read them:
const token =
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' +
'.eyJzdWIiOiI0MiIsIm5hbWUiOiJBbGljZSIsInJvbGUiOiJhZG1pbiIsImlhdCI6MTc5MjIzNjgwMH0' +
'.jLEXKyLBaNWBpk-m6vbCdBaBvBcnoUSz8acSjQseHEw';
const [headerB64, payloadB64, signatureB64] = token.split('.');
const header = JSON.parse(Buffer.from(headerB64, 'base64url').toString('utf8'));
const payload = JSON.parse(Buffer.from(payloadB64, 'base64url').toString('utf8'));
console.log(header);
console.log(payload);
console.log('issued at:', new Date(payload.iat * 1000).toISOString());
console.log('signature bytes:', Buffer.from(signatureB64, 'base64url').length);
{ alg: 'HS256', typ: 'JWT' }
{ sub: '42', name: 'Alice', role: 'admin', iat: 1792236800 }
issued at: 2026-10-17T11:33:20.000Z
signature bytes: 32
Never put secrets (passwords, API keys, personal data you wouldn't print in a log) into a JWT payload. See Base64 and hex encoding for more about base64url.
The specification (RFC 7519) defines a set of registered claims. All are optional, but libraries know how to validate them:
| Claim | Meaning | Example |
|---|---|---|
iss |
issuer: who created the token | "https://auth.example.com" |
sub |
subject: whom the token is about, usually a user id (a string) | "42" |
aud |
audience: who the token is meant for | "example-api" |
exp |
expiration time, seconds since the epoch | 1792237700 |
nbf |
not before: token is invalid until this time | 1792236800 |
iat |
issued at | 1792236800 |
jti |
JWT ID: a unique id, useful for revocation lists | a UUID |
Time claims are in seconds, while Date.now() returns milliseconds; see Dates and time.
How signing works: HS256 by hand
You should use a library in real code, but implementing HS256 once with node:crypto shows there's no magic. The signature is an HMAC-SHA256 of the string base64url(header) + "." + base64url(payload), keyed with a secret only the server knows:
import { createHmac, timingSafeEqual } from 'node:crypto';
const b64url = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url');
function signHS256(payload, secret) {
const header = { alg: 'HS256', typ: 'JWT' };
const data = `${b64url(header)}.${b64url(payload)}`;
const sig = createHmac('sha256', secret).update(data).digest('base64url');
return `${data}.${sig}`;
}
function verifyHS256(token, secret) {
const parts = token.split('.');
if (parts.length !== 3) throw new Error('malformed token');
const [h, p, s] = parts;
const header = JSON.parse(Buffer.from(h, 'base64url').toString());
if (header.alg !== 'HS256') throw new Error(`unexpected alg ${header.alg}`);
const expected = createHmac('sha256', secret).update(`${h}.${p}`).digest();
const actual = Buffer.from(s, 'base64url');
if (actual.length !== expected.length || !timingSafeEqual(actual, expected)) {
throw new Error('invalid signature');
}
const payload = JSON.parse(Buffer.from(p, 'base64url').toString());
const now = Math.floor(Date.now() / 1000);
if (typeof payload.exp === 'number' && now >= payload.exp) throw new Error('token expired');
return payload;
}
const secret = 'a-long-random-secret-from-the-environment';
const token = signHS256({ sub: '42', name: 'Alice', role: 'admin', iat: 1792236800 }, secret);
console.log(token);
console.log(verifyHS256(token, secret));
// tamper with the payload: make ourselves superuser
const [h, , s] = token.split('.');
const forged = `${h}.${b64url({ sub: '42', name: 'Alice', role: 'superuser', iat: 1792236800 })}.${s}`;
try {
verifyHS256(forged, secret);
} catch (err) {
console.log('forged:', err.message);
}
try {
verifyHS256(token, 'wrong-secret');
} catch (err) {
console.log('wrong secret:', err.message);
}
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiI0MiIsIm5hbWUiOiJBbGljZSIsInJvbGUiOiJhZG1pbiIsImlhdCI6MTc5MjIzNjgwMH0.jLEXKyLBaNWBpk-m6vbCdBaBvBcnoUSz8acSjQseHEw
{ sub: '42', name: 'Alice', role: 'admin', iat: 1792236800 }
forged: invalid signature
wrong secret: invalid signature
Changing a single character of the payload invalidates the signature, and without the secret an attacker cannot compute a new one. Note the details a correct verifier must get right: check the alg header against the one you expect, compare signatures in constant time with timingSafeEqual() (see Cryptography), and check exp. A library also checks nbf, iss, aud, header parameters it doesn't understand, and much more, which is why you shouldn't ship your own.
Signing and verifying with jose
jose has no dependencies, is written on top of the Web Crypto API (so the same code runs in Node.js, Deno, Bun, browsers and edge runtimes), supports every JWS/JWE algorithm, and is promise-based. Keys are CryptoKey objects or, for HMAC, a Uint8Array:
import { SignJWT, jwtVerify, decodeJwt } from 'jose';
// In production: process.env.JWT_SECRET, at least 32 random bytes
const secret = new TextEncoder().encode('b6c1e0f1d0a54c7e9f3b2a8d4e6f7a1c');
const token = await new SignJWT({ role: 'admin' })
.setProtectedHeader({ alg: 'HS256' })
.setSubject('42')
.setIssuer('https://api.example.com')
.setAudience('example-web')
.setIssuedAt()
.setExpirationTime('15m')
.setJti(crypto.randomUUID())
.sign(secret);
console.log(token.split('.').length, 'parts,', token.length, 'chars');
const { payload, protectedHeader } = await jwtVerify(token, secret, {
algorithms: ['HS256'],
issuer: 'https://api.example.com',
audience: 'example-web',
});
console.log(protectedHeader);
console.log(payload.sub, payload.role, payload.exp - payload.iat, 'seconds to live');
// decodeJwt() does NOT verify anything -- only for inspecting
console.log(Object.keys(decodeJwt(token)));
3 parts, 276 chars
{ alg: 'HS256' }
42 admin 900 seconds to live
[
'role', 'sub',
'iss', 'aud',
'iat', 'exp',
'jti'
]
setExpirationTime() accepts a number (absolute seconds since the epoch), a Date, or a relative time string such as '15m', '2h' or '7d'. setIssuedAt() with no argument uses the current time.
jwtVerify() checks the signature, exp and nbf automatically. iss and aud are checked only when you pass the issuer and audience options, so always pass them when you set those claims. algorithms restricts which alg header values are accepted.
An HMAC secret must be long and random; a short or guessable one can be brute-forced offline from a single captured token. Generate one with node -e "console.log(crypto.randomBytes(32).toString('base64url'))" and load it from the environment or a secret manager.
Handling verification errors
Every failure is thrown as a subclass of errors.JOSEError with a stable code property. Map them all to an HTTP 401; you can use the class to give a more helpful message, such as telling a client that its token expired and should be refreshed:
import { SignJWT, jwtVerify, errors } from 'jose';
const secret = new TextEncoder().encode('b6c1e0f1d0a54c7e9f3b2a8d4e6f7a1c');
const now = Math.floor(Date.now() / 1000);
const make = (claims, exp) =>
new SignJWT(claims)
.setProtectedHeader({ alg: 'HS256' })
.setIssuedAt(now - 3600)
.setExpirationTime(exp)
.sign(secret);
const cases = {
expired: await make({ sub: '42', aud: 'example-web' }, now - 60),
wrongAudience: await make({ sub: '42', aud: 'mobile-app' }, '15m'),
badSignature: (await make({ sub: '42', aud: 'example-web' }, '15m')).slice(0, -4) + 'AAAA',
garbage: 'not.a.jwt',
};
for (const [name, token] of Object.entries(cases)) {
try {
await jwtVerify(token, secret, { algorithms: ['HS256'], audience: 'example-web' });
console.log(name, 'ok?!');
} catch (err) {
console.log(`${name.padEnd(14)} ${err.code}`);
console.log(` ${err.message}`);
if (err instanceof errors.JWTExpired || err instanceof errors.JWTClaimValidationFailed) {
console.log(` claim=${err.claim} reason=${err.reason} sub=${err.payload.sub}`);
}
}
}
// clock skew between servers: accept tokens up to 30 s past exp
const almost = await make({ sub: '42', aud: 'example-web' }, now - 10);
const { payload } = await jwtVerify(almost, secret, { audience: 'example-web', clockTolerance: 30 });
console.log('with clockTolerance:', payload.sub);
expired ERR_JWT_EXPIRED
"exp" claim timestamp check failed
claim=exp reason=check_failed sub=42
wrongAudience ERR_JWT_CLAIM_VALIDATION_FAILED
unexpected "aud" claim value
claim=aud reason=check_failed sub=42
badSignature ERR_JWS_SIGNATURE_VERIFICATION_FAILED
signature verification failed
garbage ERR_JWS_INVALID
JWS Protected Header is invalid
with clockTolerance: 42
err.payload on claim errors contains the decoded (and signature-verified) payload, which is handy for logging. clockTolerance (seconds, or a string like '30s') allows for small clock differences between the server that issued the token and the one verifying it.
Signing and verifying with jsonwebtoken
jsonwebtoken is the package most existing Node.js code and tutorials use. It is a CommonJS package with a synchronous API (callbacks are optional) and works only in Node.js:
import jwt from 'jsonwebtoken';
const secret = process.env.JWT_SECRET ?? 'b6c1e0f1d0a54c7e9f3b2a8d4e6f7a1c';
const token = jwt.sign({ role: 'admin' }, secret, {
algorithm: 'HS256',
subject: '42',
issuer: 'https://api.example.com',
audience: 'example-web',
expiresIn: '15m', // or a number of seconds
});
const payload = jwt.verify(token, secret, {
algorithms: ['HS256'],
issuer: 'https://api.example.com',
audience: 'example-web',
});
console.log(payload.sub, payload.role, payload.exp - payload.iat);
// decode() does not check the signature
console.log(jwt.decode(token, { complete: true }).header);
const expired = jwt.sign({ sub: '42', exp: Math.floor(Date.now() / 1000) - 60 }, secret);
for (const [t, key] of [[expired, secret], [token, 'wrong'], ['abc', secret]]) {
try {
jwt.verify(t, key, { algorithms: ['HS256'] });
} catch (err) {
console.log(err.name, '-', err.message, err.expiredAt ? '(has expiredAt)' : '');
}
}
// callback style
jwt.verify(token, secret, { algorithms: ['HS256'] }, (err, decoded) => {
console.log('callback:', err, decoded.sub);
});
42 admin 900
{ alg: 'HS256', typ: 'JWT' }
TokenExpiredError - jwt expired (has expiredAt)
JsonWebTokenError - invalid signature
JsonWebTokenError - jwt malformed
callback: null 42
Its options map to the same claims: subject, issuer, audience, expiresIn (seconds or a string like '15m'), notBefore. jwt.verify() throws TokenExpiredError (with an expiredAt date), NotBeforeError, or JsonWebTokenError for everything else. Both libraries are fine; for new code jose is the better choice because of its broader algorithm support, JWKS client and portability.
Asymmetric keys: ES256, EdDSA, RS256
With HS256 every service that verifies tokens holds the same secret, so every one of them could also forge tokens. With an asymmetric algorithm the auth server signs with a private key and other services verify with the public key, which can be shared freely.
| alg | Key | Signature size | Notes |
|---|---|---|---|
ES256 |
ECDSA P-256 | 64 bytes | widely supported, small |
EdDSA |
Ed25519 | 64 bytes | fast, deterministic, modern |
RS256 |
RSA 2048+ bits | 256+ bytes | the most compatible, large tokens |
Keys are usually stored as PEM files: PKCS#8 for private keys and SPKI for public keys. jose can generate, export and import them:
import { generateKeyPair, exportPKCS8, exportSPKI, importPKCS8, importSPKI,
exportJWK, SignJWT, jwtVerify, createLocalJWKSet } from 'jose';
// One-time: generate a key pair and store the PEMs (secret manager, files, env)
const { publicKey, privateKey } = await generateKeyPair('ES256', { extractable: true });
const privatePem = await exportPKCS8(privateKey);
const publicPem = await exportSPKI(publicKey);
console.log(publicPem.split('\n')[0], publicPem.length, 'chars');
// Auth server: loads the private key and signs
const signingKey = await importPKCS8(privatePem, 'ES256');
const token = await new SignJWT({ scope: 'orders:read' })
.setProtectedHeader({ alg: 'ES256', kid: 'key-2026-10' })
.setSubject('42')
.setIssuer('https://auth.example.com')
.setExpirationTime('10m')
.sign(signingKey);
// Any other service: needs only the public key
const verifyKey = await importSPKI(publicPem, 'ES256');
const { payload } = await jwtVerify(token, verifyKey, {
algorithms: ['ES256'],
issuer: 'https://auth.example.com',
});
console.log('verified with PEM:', payload.sub, payload.scope);
// Publishing public keys as a JWK Set (served at /.well-known/jwks.json)
const jwk = { ...(await exportJWK(publicKey)), kid: 'key-2026-10', alg: 'ES256', use: 'sig' };
const jwks = { keys: [jwk] };
console.log(JSON.stringify(jwks).slice(0, 70) + '...');
// The JWKS picks the key by the token's "kid" header
const JWKS = createLocalJWKSet(jwks);
const result = await jwtVerify(token, JWKS, { issuer: 'https://auth.example.com' });
console.log('verified with JWKS:', result.protectedHeader);
-----BEGIN PUBLIC KEY----- 177 chars
verified with PEM: 42 orders:read
{"keys":[{"kty":"EC","x":"P0ckEeHX1QCZlLahRNE1Z9mrJ17tei6n0M8FuGbI080"...
verified with JWKS: { alg: 'ES256', kid: 'key-2026-10' }
The kid (key id) header lets you rotate keys: publish the new public key next to the old one, start signing with the new key, and remove the old key once all tokens signed with it have expired.
Fetching keys from a JWKS endpoint
Identity providers (Auth0, Okta, Keycloak, Google, Microsoft Entra ID, Cognito) publish their public keys as a JWK Set at a URL such as https://issuer/.well-known/jwks.json. createRemoteJWKSet() downloads it, caches the keys, picks the right one by kid, and refetches when it sees an unknown kid. Here an http server plays the identity provider:
import http from 'node:http';
import { generateKeyPair, exportJWK, SignJWT, jwtVerify, createRemoteJWKSet } from 'jose';
// --- auth server: signs tokens and publishes its public keys ---
const { publicKey, privateKey } = await generateKeyPair('EdDSA');
const kid = 'ed-2026-10';
const jwks = { keys: [{ ...(await exportJWK(publicKey)), kid, alg: 'EdDSA', use: 'sig' }] };
let jwksRequests = 0;
const authServer = http.createServer((req, res) => {
if (req.url !== '/.well-known/jwks.json') return res.writeHead(404).end();
jwksRequests++;
res.writeHead(200, { 'Content-Type': 'application/json' }).end(JSON.stringify(jwks));
});
await new Promise((resolve) => authServer.listen(0, resolve));
const issuer = `http://localhost:${authServer.address().port}`;
const token = await new SignJWT({ scope: 'orders:read' })
.setProtectedHeader({ alg: 'EdDSA', kid })
.setIssuer(issuer)
.setSubject('42')
.setExpirationTime('5m')
.sign(privateKey);
// --- resource server: knows only the JWKS URL ---
const JWKS = createRemoteJWKSet(new URL('/.well-known/jwks.json', issuer), {
cooldownDuration: 30_000, // min time between refetches when an unknown kid shows up
cacheMaxAge: 600_000, // refetch keys at most every 10 minutes
});
for (let i = 0; i < 3; i++) {
const { payload, protectedHeader } = await jwtVerify(token, JWKS, {
issuer,
algorithms: ['EdDSA'],
});
console.log(i, protectedHeader.alg, payload.sub, payload.scope);
}
console.log('JWKS fetched', jwksRequests, 'time(s)');
authServer.close();
0 EdDSA 42 orders:read
1 EdDSA 42 orders:read
2 EdDSA 42 orders:read
JWKS fetched 1 time(s)
Create the remote JWK Set once at startup and reuse it; creating it per request would download the keys on every request. With jsonwebtoken, the jwks-rsa package fills the same role.
Protecting an Express API
The usual flow: the client posts credentials to a login endpoint, receives a short-lived access token, and sends it in the Authorization: Bearer <token> header with every request. Middleware verifies the token and attaches the user to the request. Put the token logic in its own module:
// auth.mjs
import { SignJWT, jwtVerify, errors } from 'jose';
const secret = new TextEncoder().encode(process.env.JWT_SECRET);
const ISSUER = 'https://api.example.com';
const AUDIENCE = 'example-api';
export function issueAccessToken(user) {
return new SignJWT({ role: user.role })
.setProtectedHeader({ alg: 'HS256' })
.setSubject(String(user.id))
.setIssuer(ISSUER)
.setAudience(AUDIENCE)
.setIssuedAt()
.setExpirationTime('15m')
.sign(secret);
}
export async function requireAuth(req, res, next) {
const [scheme, token] = (req.headers.authorization ?? '').split(' ');
if (scheme !== 'Bearer' || !token) {
res.set('WWW-Authenticate', 'Bearer');
return res.status(401).json({ error: 'missing bearer token' });
}
try {
const { payload } = await jwtVerify(token, secret, {
algorithms: ['HS256'],
issuer: ISSUER,
audience: AUDIENCE,
});
req.user = { id: payload.sub, role: payload.role };
next();
} catch (err) {
const error = err instanceof errors.JWTExpired ? 'token expired' : 'invalid token';
res.set('WWW-Authenticate', `Bearer error="invalid_token"`);
res.status(401).json({ error });
}
}
export function requireRole(role) {
return (req, res, next) =>
req.user?.role === role ? next() : res.status(403).json({ error: 'forbidden' });
}
// server.mjs
import express from 'express';
import { issueAccessToken, requireAuth, requireRole } from './auth.mjs';
// stand-in for a database with properly hashed passwords
const users = [
{ id: 1, name: 'alice', password: 'wonderland', role: 'admin' },
{ id: 2, name: 'bob', password: 'builder', role: 'user' },
];
const app = express();
app.use(express.json());
app.post('/login', async (req, res) => {
const { name, password } = req.body ?? {};
const user = users.find((u) => u.name === name && u.password === password);
if (!user) return res.status(401).json({ error: 'invalid credentials' });
res.json({ accessToken: await issueAccessToken(user), tokenType: 'Bearer', expiresIn: 900 });
});
app.get('/me', requireAuth, (req, res) => res.json(req.user));
app.get('/admin/stats', requireAuth, requireRole('admin'), (req, res) =>
res.json({ users: users.length }));
export default app;
The plain-text passwords are only there to keep the example short; store passwords with Password hashing. Express 5 forwards rejected promises from async handlers to the error handler, so async middleware like requireAuth needs no extra wrapper. A quick test with fetch, starting the server on a random free port:
import app from './server.mjs';
const server = app.listen(0);
await new Promise((resolve) => server.once('listening', resolve));
const base = `http://localhost:${server.address().port}`;
async function call(method, path, { token, body } = {}) {
const headers = {};
if (token) headers.Authorization = `Bearer ${token}`;
if (body) headers['Content-Type'] = 'application/json';
const res = await fetch(base + path, { method, headers, body: body && JSON.stringify(body) });
const data = await res.json();
console.log(method, path, res.status, JSON.stringify(data).slice(0, 60));
return data;
}
await call('GET', '/me');
await call('POST', '/login', { body: { name: 'bob', password: 'nope' } });
const bob = await call('POST', '/login', { body: { name: 'bob', password: 'builder' } });
await call('GET', '/me', { token: bob.accessToken });
await call('GET', '/admin/stats', { token: bob.accessToken });
const alice = await call('POST', '/login', { body: { name: 'alice', password: 'wonderland' } });
await call('GET', '/admin/stats', { token: alice.accessToken });
await call('GET', '/me', { token: alice.accessToken.slice(0, -2) + 'xx' });
server.close();
GET /me 401 {"error":"missing bearer token"}
POST /login 401 {"error":"invalid credentials"}
POST /login 200 {"accessToken":"eyJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoidXNlciIsInN
GET /me 200 {"id":"2","role":"user"}
GET /admin/stats 403 {"error":"forbidden"}
POST /login 200 {"accessToken":"eyJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiYWRtaW4iLCJ
GET /admin/stats 200 {"users":2}
GET /me 401 {"error":"invalid token"}
Run it with JWT_SECRET=... node test.mjs. Note the difference between the status codes: 401 means "we don't know who you are" (no token, bad token, expired token), 403 means "we know who you are, but you may not do this". For a gentler introduction to Express see Hello World with Express, and for session-based logins see Passport integration.
Refresh tokens
Access tokens should be short-lived (5-15 minutes), because a stolen one can't be cancelled before it expires. To avoid asking the user to log in every 15 minutes, the login endpoint also returns a long-lived refresh token, which the client exchanges for a new access token when the old one expires.
The refresh token doesn't need to be a JWT. An opaque random string stored on the server (as a hash, like a password) is simpler and can be revoked. Rotating it on every use and detecting reuse limits the damage if one is stolen:
import { randomBytes, createHash } from 'node:crypto';
const REFRESH_TTL_MS = 30 * 24 * 3600 * 1000;
const sha256 = (s) => createHash('sha256').update(s).digest('hex');
// in production: a database table keyed by token hash
const refreshTokens = new Map(); // hash -> { userId, family, expiresAt, used }
function issueRefreshToken(userId, family = randomBytes(8).toString('hex')) {
const token = randomBytes(32).toString('base64url');
refreshTokens.set(sha256(token), { userId, family, expiresAt: Date.now() + REFRESH_TTL_MS, used: false });
return token;
}
function rotateRefreshToken(token) {
const entry = refreshTokens.get(sha256(token));
if (!entry || entry.expiresAt < Date.now()) throw new Error('invalid refresh token');
if (entry.used) {
// a token was replayed: someone stole it. Kill the whole family.
for (const [hash, e] of refreshTokens) if (e.family === entry.family) refreshTokens.delete(hash);
throw new Error('refresh token reuse detected, session revoked');
}
entry.used = true;
return { userId: entry.userId, refreshToken: issueRefreshToken(entry.userId, entry.family) };
}
const first = issueRefreshToken(42);
const second = rotateRefreshToken(first);
console.log('rotated for user', second.userId, first !== second.refreshToken);
try {
rotateRefreshToken(first); // attacker replays the old token
} catch (err) {
console.log(err.message);
}
try {
rotateRefreshToken(second.refreshToken); // legitimate client is logged out too
} catch (err) {
console.log(err.message);
}
rotated for user 42 true
refresh token reuse detected, session revoked
invalid refresh token
In a browser app, send the refresh token in a cookie with HttpOnly, Secure, SameSite=Strict and a Path limited to the refresh endpoint, so JavaScript (and an XSS attack) can't read it. Keep the access token in memory rather than in localStorage. If you use cookies for authentication, protect state-changing requests against CSRF.
Revoking access tokens
A JWT is valid until it expires; that's the price of not checking a database. When you must cut access immediately (logout everywhere, password change, banned user), add a small server-side check. One cheap approach is a per-user token version stored with the user record and included in the token:
import { SignJWT, jwtVerify } from 'jose';
const secret = new TextEncoder().encode('b6c1e0f1d0a54c7e9f3b2a8d4e6f7a1c');
const users = new Map([['42', { tokenVersion: 1 }]]);
const issue = (sub) =>
new SignJWT({ ver: users.get(sub).tokenVersion })
.setProtectedHeader({ alg: 'HS256' })
.setSubject(sub)
.setExpirationTime('15m')
.sign(secret);
async function verify(token) {
const { payload } = await jwtVerify(token, secret, { algorithms: ['HS256'] });
if (payload.ver !== users.get(payload.sub)?.tokenVersion) throw new Error('token revoked');
return payload;
}
const token = await issue('42');
console.log('before:', (await verify(token)).sub);
users.get('42').tokenVersion++; // "log out everywhere" or password change
try {
await verify(token);
} catch (err) {
console.log('after:', err.message);
}
console.log('new token:', (await verify(await issue('42'))).ver);
before: 42
after: token revoked
new token: 2
Alternatives are a denylist of jti values (each entry can be dropped when the token's exp passes), or simply keeping access tokens so short that waiting for expiry is acceptable. If every request needs a database lookup anyway, consider plain server-side sessions instead of JWTs.
Security pitfalls
The most famous JWT bug is accepting "alg": "none", an unsigned token. Both libraries reject it when you verify with a key, but decode() accepts anything:
import { jwtVerify } from 'jose';
import jwt from 'jsonwebtoken';
const b64url = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url');
// attacker-made token: no signature at all
const unsigned = `${b64url({ alg: 'none', typ: 'JWT' })}.${b64url({ sub: '1', role: 'admin' })}.`;
const secret = new TextEncoder().encode('b6c1e0f1d0a54c7e9f3b2a8d4e6f7a1c');
try {
await jwtVerify(unsigned, secret);
} catch (err) {
console.log('jose:', err.code);
}
try {
jwt.verify(unsigned, 'b6c1e0f1d0a54c7e9f3b2a8d4e6f7a1c');
} catch (err) {
console.log('jsonwebtoken:', err.message);
}
console.log('decode() happily returns:', jwt.decode(unsigned));
jose: ERR_JOSE_NOT_SUPPORTED
jsonwebtoken: jwt signature is required
decode() happily returns: { sub: '1', role: 'admin' }
Checklist:
- Always verify, never just decode.
jwt.decode()anddecodeJwt()are for debugging and for reading a header before choosing a key. - Pin the algorithm. Pass
algorithms: ['HS256'](or whatever you use). This prevents algorithm-confusion attacks where a token signed with HS256 using your public RSA key as the secret is accepted by a careless verifier. - Validate
issandaud. Otherwise a token issued for one of your services (or by your identity provider for someone else's app) is accepted by another. - Use strong keys. At least 256 random bits for HS256, 2048-bit RSA or larger.
- Keep tokens short-lived and include
expin every token. - Keep payloads small. The token travels with every request, often in a header with a size limit (8-16 KB in many servers and proxies). Store an id, not the user's profile.
- Don't store secrets in the payload. It's readable by anyone; if you need confidentiality, use an encrypted JWT (JWE,
EncryptJWTinjose) or don't put the data in the token. - Send tokens only over HTTPS (see Setting up an HTTPS server), and don't log full tokens.
Summary
- A JWT is
base64url(header).base64url(payload).signature; the payload is readable by anyone, the signature makes it tamper-proof. - Use
jose(SignJWT,jwtVerify) for new code;jsonwebtoken(jwt.sign,jwt.verify) is fine in existing projects. - Always pass
algorithms,issuerandaudiencewhen verifying, and map every verification error to HTTP 401. - Use HS256 when one service issues and verifies tokens; use ES256, EdDSA or RS256 with a JWKS when other services or third parties verify them.
- Combine short-lived access tokens with rotated, revocable refresh tokens, and add a token version or
jtidenylist when you need instant revocation.