Introduction
There are two dominant approaches to keeping a user 'logged in' across requests: session-based authentication, which is stateful, and token-based authentication (typically JWT), which is stateless. Session-based auth stores session data on the server and gives the client only a small session ID (usually in a cookie). Token-based auth encodes the user's identity and claims directly into a signed token that the client holds and presents on every request, so the server does not need to remember anything between requests. Choosing between them affects scalability, revocation, and where trust and storage responsibilities live.
Cricket analogy: Session auth is like the scorer's table keeping the full scorecard and only handing each player a numbered wristband, while token auth is like printing every player's stats directly onto their own wristband so any ground official can verify it without checking the scorer's table.
Syntax
// Session-based (stateful) with express-session
const session = require('express-session');
app.use(session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: false,
cookie: { httpOnly: true, secure: true, maxAge: 1000 * 60 * 60 }
}));
app.post('/login', (req, res) => {
// ...validate credentials...
req.session.userId = user.id; // stored server-side, cookie holds only the session ID
res.json({ message: 'Logged in' });
});
// Token-based (stateless) with JWT
app.post('/login', (req, res) => {
// ...validate credentials...
const token = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '1h' });
res.json({ token }); // client stores and resends this on every request
});Explanation
With sessions, the server (or a shared store like Redis) keeps a record mapping a session ID to user data; the browser only holds an opaque, HttpOnly cookie containing that ID. This makes revocation trivial — deleting the server-side session immediately logs the user out everywhere. The tradeoff is that every request requires a lookup in the session store, and scaling across multiple servers requires a shared, centralized session store. With JWTs, all the claims the server needs are embedded in the signed token itself, so any server instance can verify it independently without a shared database, which scales horizontally very well. The tradeoff is that a JWT remains valid until it expires — there is no built-in way to instantly revoke a single token without adding extra infrastructure like a token blocklist.
Cricket analogy: With sessions, the scoring office (or a shared ledger like Redis) holds the full record and the spectator only carries a wristband number; revoking entry is as simple as erasing that wristband from the ledger, but every gate check requires a lookup, and multiple stadium gates need one shared ledger. With tokens, the wristband itself lists the seat and access level, so any gate can verify it instantly, but once printed it stays valid until it expires -- there's no easy way to revoke just one wristband without a blocklist.
Example
// A hybrid approach: short-lived JWT access token + server-tracked refresh token
app.post('/login', async (req, res) => {
const accessToken = jwt.sign({ userId: user.id }, process.env.JWT_SECRET, { expiresIn: '15m' });
const refreshToken = crypto.randomUUID();
await RefreshToken.create({ token: refreshToken, userId: user.id }); // stored server-side
res.cookie('refreshToken', refreshToken, { httpOnly: true, secure: true });
res.json({ accessToken });
});
app.post('/logout', async (req, res) => {
await RefreshToken.deleteOne({ token: req.cookies.refreshToken });
res.clearCookie('refreshToken');
res.json({ message: 'Logged out' });
});Output
In a pure session setup, logging out means the server deletes req.session, and the next request with that cookie finds no matching session, so the user is treated as unauthenticated immediately. In a pure JWT setup, logging out on the client (discarding the token) does not invalidate the token on the server — it simply remains valid until its exp claim passes, which is why many production systems use the hybrid pattern above: a short-lived access token combined with a revocable, server-tracked refresh token.
Cricket analogy: In a pure session setup, once the scorer erases a player's wristband record, the next gate check finds no match and the player is turned away immediately; in a pure token setup, tearing up your own wristband doesn't stop it from working at other gates until its printed expiry -- which is why top tournaments issue a short-lived match pass alongside a revocable season pass.
Key Takeaways
- Sessions are stateful (server stores session data); tokens like JWT are stateless (server verifies without storage).
- Sessions offer instant revocation but require a shared store to scale across multiple servers.
- JWTs scale easily across servers but cannot be instantly revoked without extra infrastructure (e.g., a blocklist or short expiry).
- A common production pattern combines short-lived JWT access tokens with longer-lived, revocable refresh tokens stored server-side.
Practice what you learned
1. In session-based authentication, what does the client's cookie typically contain?
2. Why is JWT-based authentication considered easier to scale horizontally than session-based authentication?
3. What is the main drawback of pure JWT-based authentication regarding logout?
4. What is a common hybrid pattern used to combine the benefits of both approaches?
Was this page helpful?
You May Also Like
Authentication Basics and JWT
Learn how authentication works in web APIs and how JSON Web Tokens (JWT) provide a stateless way to verify user identity.
Securing Express Apps (Helmet, CORS, Rate Limiting)
Harden Express applications with secure HTTP headers, controlled cross-origin access, and rate limiting to mitigate common attacks.
Middleware in Express
Master the Express middleware chain, the next() function, and the special error-handling middleware signature.
Related Reading
Related Study Notes in Web Development
Browse all study notesWebSockets Study Notes
Web Development · 30 topics
Web DevelopmentWebAssembly Study Notes
WebAssembly · 30 topics
Web DevelopmentgRPC Study Notes
Protocol Buffers · 30 topics
Web DevelopmentSpring Boot Study Notes
Java · 30 topics
Web DevelopmentFlask Study Notes
Python · 30 topics
Web DevelopmentDjango Study Notes
Python · 30 topics