Full answer
Sessions
- Login creates a record (user id, expiry, device) in a store such as Redis or a database. The client keeps only the random session id in a cookie (HttpOnly, Secure, SameSite).
- Logging out or banning a user is immediate: delete the record.
- Cost: a store lookup per request and shared storage for many servers.
JWT
- Header.payload.signature, each part base64url encoded. Claims such as sub (user), iss, aud, exp. The server checks the signature and claims with a key, with no database call.
- Cost: you cannot cancel a token before exp unless you keep a denylist (which is state again). Payload data is readable by anyone who holds the token, so never put secrets in it. Tokens are larger than session ids, and key rotation needs care.
- Use short lifetimes (minutes) and a refresh token that is stored and revocable.
Choosing
- One web app and one backend: server sessions (simple, safe, revocable).
- Many services that must verify identity without calling an auth service, or mobile and third-party clients: short-lived access tokens (JWT), with revocable refresh tokens.
- Do not call a JWT "more secure". Security depends on storage (HttpOnly cookie vs localStorage), expiry, validation and revocation.
javascript
const crypto = require('node:crypto');
// 1. Session: opaque id, state on the server.
const sessions = new Map();
const login = (user) => { const id = crypto.randomBytes(16).toString('hex'); sessions.set(id, { user, expires: Date.now() + 3600e3 }); return id; };
const checkSession = (id) => sessions.get(id)?.user ?? null;
// 2. JWT (HS256), built by hand to show the parts.
const b64 = (obj) => Buffer.from(JSON.stringify(obj)).toString('base64url');
const SECRET = 'server-secret';
const sign = (data) => crypto.createHmac('sha256', SECRET).update(data).digest('base64url');
const issue = (claims) => { const body = `${b64({ alg: 'HS256', typ: 'JWT' })}.${b64(claims)}`; return `${body}.${sign(body)}`; };
function verify(token, now) {
const [h, p, s] = token.split('.');
if (!s || sign(`${h}.${p}`) !== s) return null;
const claims = JSON.parse(Buffer.from(p, 'base64url').toString());
return claims.exp > now ? claims : null;
}
const now = 1_800_000_000;
const sessionId = login('asha');
const token = issue({ sub: 'asha', exp: now + 900 });
console.log('session id length :', sessionId.length, '| token length:', token.length);
console.log('both valid :', checkSession(sessionId), '|', verify(token, now)?.sub);
sessions.delete(sessionId); // logout or ban
console.log('after revocation : session =', checkSession(sessionId), '| JWT still verifies =', verify(token, now + 60)?.sub);
console.log('after expiry : JWT =', verify(token, now + 901));
const tampered = token.split('.'); tampered[1] = b64({ sub: 'admin', exp: now + 900 });
console.log('tampered payload :', verify(tampered.join('.'), now));
console.log('payload is readable:', Buffer.from(token.split('.')[1], 'base64url').toString());Both mechanisms are built with Node's crypto module in a few lines. Real systems use a tested library for JWT, and a fixed timestamp keeps the output stable. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): session id length : 32 | token length: 123 both valid : asha | asha after revocation : session = null | JWT still verifies = asha after expiry : JWT = null tampered payload : null payload is readable: {"sub":"asha","exp":1800000900}
Key points
- Sessions keep state on the server; JWTs carry signed claims.
- Sessions can be revoked at once; JWTs need short expiry or a denylist.
- JWT payloads are encoded, not encrypted.
- Use short access tokens with revocable refresh tokens.
- Pick by architecture, not by fashion.
Common mistakes
- Storing JWTs in localStorage where scripts can read them.
- Long-lived JWTs that cannot be revoked.
- Putting private data in the JWT payload.
- Not validating exp, aud and iss.
- Rolling your own signing code in production.
Follow-ups
- How do you revoke a JWT before it expires?
- Where should a browser app store tokens?
- What is the benefit of a refresh token?
Tips
- Compare state location.
- Mention revocation first.
- Say that payloads are readable.