Part 0 · 2 chapters · ~12 min

Sessions vs Tokens

Opaque server sessions and cookie flags, bearer tokens and self-contained claims, access and refresh tokens, where tokens should live in browsers and apps, CSRF and XSS implications, the backend-for-frontend pattern, and session management (timeouts, concurrent sessions, logout everywhere).

1

Two models

code
// a secure session cookie (Express)
res.cookie('__Host-sid', sessionId, { httpOnly: true, secure: true, sameSite: 'lax', path: '/', maxAge: 30 * 60 * 1000 });

// session store record
{ sid: '8f3c…', userId: 7, createdAt, lastSeenAt, ip, userAgent, mfa: true, stepUpUntil: null }
SESSIONS VS TOKENS
a reference the server looks up, or a signed statement the server verifies
browsercookie: sid=8f3...APIsession storeRedis: sid → user, expirymobile appAuthorization: Bearer eyJ...APIpublic keysverify signature, no lookup
swipe the figure sideways, or tap expand for full screen
1/5
server sessions
The browser holds an opaque random session id in an HttpOnly, Secure, SameSite cookie; the server looks it up in a store. Logout and revocation are instant: delete the row.
opaque id, server lookupinstant revocation
2

Session management that holds up

concernpractice
idle timeoutshort for money apps (5-15 min), sliding on activity
absolute lifetimere-authenticate after hours or days regardless of activity
session fixationissue a new session id at login and at privilege change
logout everywherelist sessions per user, revoke all; revoke refresh token families
device listshow active sessions and devices to the user, with revoke buttons
tokens in the browseravoid localStorage for long-lived tokens (XSS steals them); prefer a BFF and cookies