100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
Node.js

Session vs Token Authentication

Compare stateful session-based authentication with stateless token-based authentication and when to use each approach.

Authentication & SecurityIntermediate11 min readJul 8, 2026
Analogies

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

javascript
// 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

javascript
// 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

Was this page helpful?

Topics covered

#NodeJs#NodeJsExpressStudyNotes#WebDevelopment#SessionVsTokenAuthentication#Session#Token#Authentication#Syntax#Security#StudyNotes#SkillVeris