Full answer
Sessions
- Login creates a record in a store (memory for demos, Redis or a database in production) and sends Set-Cookie with a random session id (HttpOnly, Secure, SameSite).
- Each request carries the cookie, the server looks up the record. Logout, password change or admin action deletes the record, and access ends immediately.
- Cost: a store lookup per request, and a shared store when you run several instances.
JWT (JSON Web Token)
- Three base64url parts: header, payload (claims such as sub and exp), signature. The server verifies the signature and the expiry, no lookup needed.
- Good for stateless APIs, service to service calls and short-lived access tokens.
- Problems: you cannot revoke a token before exp without extra state (a deny list or a token version number), the payload is readable by anyone (do not store secrets), tokens in localStorage are exposed to XSS, and a leaked token works anywhere until it expires.
How to choose
- Traditional web app with a browser: server sessions in an HttpOnly cookie are simpler and safer.
- Mobile or third-party API clients, microservices: short-lived JWT access token (5 to 15 minutes) plus a refresh token that the server can revoke.
- Avoid using JWT only because it feels modern. Stateless tokens trade revocation for scalability.
In both cases: use HTTPS, rotate secrets, set short lifetimes, and protect cookies against CSRF.
javascript
const express = require('express');
const session = require('express-session');
const jwt = require('jsonwebtoken');
const SECRET = 'demo-secret-change-me';
const app = express();
app.use(express.json());
app.use(session({ secret: SECRET, resave: false, saveUninitialized: false, cookie: { httpOnly: true, sameSite: 'lax' } }));
// Session login and a protected route
app.post('/session/login', (req, res) => { req.session.user = 'asha'; res.json({ ok: true }); });
app.get('/session/me', (req, res) => (req.session.user ? res.json({ user: req.session.user }) : res.status(401).json({ error: 'not logged in' })));
app.post('/session/logout', (req, res) => req.session.destroy(() => res.json({ ok: true })));
// JWT login and a protected route
app.post('/jwt/login', (req, res) => res.json({ token: jwt.sign({ sub: 'asha' }, SECRET, { expiresIn: '15m' }) }));
app.get('/jwt/me', (req, res) => {
try { res.json({ user: jwt.verify((req.get('authorization') || '').replace('Bearer ', ''), SECRET).sub }); }
catch { res.status(401).json({ error: 'invalid token' }); }
});
app.post('/jwt/logout', (req, res) => res.json({ ok: true, note: 'the server has nothing to delete' }));
const server = app.listen(0, '127.0.0.1', async () => {
const base = 'http://127.0.0.1:' + server.address().port;
const call = async (path, headers = {}, method = 'GET') => { const r = await fetch(base + path, { method, headers }); return r; };
const login = await call('/session/login', {}, 'POST');
const cookie = login.headers.get('set-cookie').split(';')[0];
console.log('session cookie flags:', /HttpOnly/i.test(login.headers.get('set-cookie')), /SameSite=Lax/i.test(login.headers.get('set-cookie')));
console.log('session /me before logout:', (await call('/session/me', { cookie })).status);
await call('/session/logout', { cookie }, 'POST');
console.log('session /me after logout :', (await call('/session/me', { cookie })).status, '(revoked at once)');
const { token } = await (await call('/jwt/login', {}, 'POST')).json();
console.log('jwt payload is readable by anyone:', JSON.parse(Buffer.from(token.split('.')[1], 'base64url')).sub);
console.log('jwt /me before logout :', (await call('/jwt/me', { authorization: 'Bearer ' + token })).status);
await call('/jwt/logout', {}, 'POST');
console.log('jwt /me after logout :', (await call('/jwt/me', { authorization: 'Bearer ' + token })).status, '(still valid until it expires)');
server.close();
});The same user logs in with a session and with a JWT and then logs out. The session stops working at once, the JWT keeps working. Install first with npm install express express-session jsonwebtoken (run here with express 5.3.0, express-session 1.19.0, jsonwebtoken 9.0.3). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): session cookie flags: true true session /me before logout: 200 session /me after logout : 401 (revoked at once) jwt payload is readable by anyone: asha jwt /me before logout : 200 jwt /me after logout : 200 (still valid until it expires)
Key points
- A session stores state on the server; a JWT carries signed claims.
- Deleting the session revokes access at once.
- A JWT is valid until it expires unless extra state is kept.
- Use HttpOnly, Secure, SameSite cookies for browser sessions.
- Short access tokens plus revocable refresh tokens suit APIs.
Common mistakes
- Choosing JWT for a simple browser app and then needing revocation.
- Storing a JWT in localStorage where XSS can read it.
- Putting secrets in the JWT payload.
- Long-lived access tokens with no refresh strategy.
- Using MemoryStore for sessions in production.
Follow-ups
- How do you revoke a JWT before it expires?
- Where should a browser app keep a token?
- Why do sessions need a shared store when you scale out?
Tips
- Define both in one sentence each.
- Say 'revocation' as the key difference.
- Give a rule of thumb for choosing.