Skip to content
Velloreth
Cybersecurity 5 min read

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

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

ConcernSessionToken
Server stateRequiredNone
RevocationInstantHard
Horizontal scaleNeeds a shared storeTrivial
Cross-serviceNeeds a shared storeNatural
Payload readableNo (opaque)Yes
StorageCookieCookie or header
LogoutDelete the recordWait 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.

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.

Frequently asked questions

What is the difference between session and token authentication?
With session authentication, the server creates a session record and gives the client an opaque session ID. The server looks up the session on each request. With token authentication, the server issues a signed token that carries the claims, and the server verifies the signature without a lookup. The first keeps state on the server; the second keeps it in the token.
Are tokens more secure than sessions?
Neither is inherently more secure. A session ID is opaque and can be revoked instantly, which is a security advantage. A token is self-contained and cannot be revoked without extra state, which is a security disadvantage. The security of either depends on how it is stored and transmitted, not on the format.
Why do people say tokens scale better?
A token can be verified with a key the server already has, so any server in a fleet can handle any request without a shared session store. A session requires a lookup, which means either a shared store such as Redis or sticky sessions. The scaling advantage is real, but it only matters at a scale where a shared store is a bottleneck.
Can I use both sessions and tokens?
Yes, and many applications do. A common pattern is a session cookie for the browser, which gives instant revocation, and a token for the API, which gives stateless verification for service-to-service calls. The two are not mutually exclusive.
What is the safest way to store a session ID?
In an HttpOnly, Secure, SameSite cookie. HttpOnly stops a script from reading it, Secure keeps it off plain HTTP, and SameSite limits cross-site sending. The session ID should be long and random, and it should be regenerated on login to prevent session fixation.
How do I log a user out with token authentication?
You cannot invalidate a signed token by itself. The practical options are a short expiry so the token dies quickly, a refresh token that you revoke, or a denylist of token IDs checked on each request. The last option adds the server state that the token was meant to avoid.