Session vs Token Authentication: Which to Choose
Server sessions and stateless tokens solve the same problem differently. Learn the trade-offs and which fits your application.
By Velloreth
The core difference
Both approaches answer the same question: how does the server know which user made this request? They differ in where the answer is stored.
Session authentication stores the answer on the server. On login, the server creates a session record with the user ID and an expiry, and gives the client an opaque session ID. On each request, the client sends the ID and the server looks up the record.
Token authentication stores the answer in the client. On login, the server issues a signed token that contains the user ID and an expiry. On each request, the client sends the token and the server verifies the signature and reads the claims.
The trade-off is state. A session has state on the server, which makes it revocable and makes it a lookup. A token has no state on the server, which makes it fast and makes it irrevocable.
How a session works
// On login
app.post('/login', async (req, res) => {
const user = await verifyCredentials(req.body);
const sessionId = crypto.randomBytes(32).toString('hex');
await redis.set(`session:${sessionId}`, user.id, 'EX', 60 * 60 * 24);
res.cookie('sid', sessionId, {
httpOnly: true,
secure: true,
sameSite: 'lax',
maxAge: 86400000,
});
res.json({ ok: true });
});
// On each request
app.use(async (req, res, next) => {
const sessionId = req.cookies.sid;
const userId = await redis.get(`session:${sessionId}`);
if (!userId) return res.status(401).json({ error: 'unauthenticated' });
req.userId = userId;
next();
});
The session ID is opaque. It carries no information, so a client cannot read or forge a claim. The server is the only source of truth.
Revocation is a delete. Logging out, banning a user, or forcing a re-login is a single key removal, and it takes effect on the next request.
How a token works
// On login
app.post('/login', async (req, res) => {
const user = await verifyCredentials(req.body);
const token = jwt.sign({ sub: user.id }, privateKey, {
algorithm: 'RS256',
expiresIn: '15m',
issuer: 'https://auth.example.com',
audience: 'https://api.example.com',
});
res.json({ token });
});
// On each request
app.use((req, res, next) => {
const token = req.headers.authorization?.replace('Bearer ', '');
try {
const claims = jwt.verify(token, publicKey, {
algorithms: ['RS256'],
issuer: 'https://auth.example.com',
audience: 'https://api.example.com',
});
req.userId = claims.sub;
next();
} catch {
res.status(401).json({ error: 'unauthenticated' });
}
});
The token is self-contained. Any server with the public key can verify it, with no shared store and no lookup.
Revocation is the hard part. A signed token is valid until it expires, and the server has no record to delete. The options are a short expiry, a revocable refresh token, or a denylist.
The comparison
| Concern | Session | Token |
|---|---|---|
| Server state | Required | None |
| Revocation | Instant | Hard |
| Horizontal scale | Needs a shared store | Trivial |
| Cross-service | Needs a shared store | Natural |
| Payload readable | No (opaque) | Yes |
| Storage | Cookie | Cookie or header |
| Logout | Delete the record | Wait for expiry |
When to choose a session
A single web application. If the browser is the only client and the servers share a store, a session is simpler and gives instant revocation. This is the common case, and it is the one where a token adds complexity for no benefit.
You need instant revocation. A ban, a password change, or a forced logout must take effect immediately. A session does this in one operation; a token needs a denylist, which is a session by another name.
You want the simplest secure default. An HttpOnly cookie with a session ID is well understood, and the browser handles the storage and the sending.
When to choose a token
Multiple services verify the same identity. A gateway, an API, and a background worker can all verify a token with a public key, with no shared session store.
A non-browser client. A mobile app, a CLI, or a service-to-service call has no cookie jar, so a token in a header is the natural fit.
A third party calls your API. An access token with a scope is the standard way to grant limited access, and it is what OAuth issues.
The hybrid that most applications should use
The pattern that gets the best of both is a session cookie for the browser and a token for the API.
The browser holds a session cookie. It is HttpOnly, so a script cannot read it, and the server can revoke it instantly.
The API accepts a token. Service-to-service calls and third-party integrations use a short-lived access token, verified with a public key.
The session is backed by a short-lived token internally. The session record holds a refresh token, and the server mints a short access token for downstream calls. The browser never sees the token, and the downstream services never see the session.
Common mistakes
Storing a token in localStorage. Any script on the page can read it, so one XSS vulnerability leaks it. Use an HttpOnly cookie.
A long-lived access token with no revocation. A token that lives for a week is a week of access for an attacker. Keep it short and use a refresh token.
A session ID that is not regenerated on login. A fixed session ID allows session fixation, where an attacker sets a known ID and waits for the victim to log in. Regenerate on login.
A session cookie without HttpOnly or Secure. The cookie is then readable by a script and sendable over plain HTTP.
Assuming a token removes the need for a store. If you need revocation, you need state, and the token has not removed it; it has moved it.
A quotable summary
Session authentication keeps the identity on the server and gives the client an opaque ID, which makes revocation instant and requires a lookup. Token authentication keeps the identity in a signed token, which makes verification stateless and revocation hard. For a single web application, a session in an HttpOnly cookie is usually simpler and safer. For multiple services or non-browser clients, a token is the natural fit. The deciding question is whether you need instant revocation or horizontal scale more, and many applications should use both.
Related reading
For the token format, see jwt-explained and for the flow that issues tokens, oauth2-explained. For the broader context, cookies-explained and api-authentication-methods.