Card 05/ 12

ComparisonDifficulty: Intermediate2 min

Sessions vs Tokens

A session keeps the state on the server and hands the browser a pointer; a token carries what the server needs.

A session and a token both let a caller authenticate once and prove it on later requests, and they differ in where the state lives. A session keeps the signed-in user's state on the server and gives the browser a random id in a cookie. A token is handed to the client and sent in a header, and a self-contained token carries the user's details itself. The table answers the four questions for each.

Sessions and tokens against the four questions
QuestionSessionToken
What proves the callerA random session id pointing at server-side stateThe token, opaque or self-contained
Where it travelsA cookie the browser sends automaticallyThe Authorization header, added by the client's code
Which client it suitsThe API's own web front end, on the same siteMobile apps, third parties and other services
How access is cut offDelete the session, effective at onceWait for expiry, or revoke at the issuer

Sessions in the browser. A cookie marked HttpOnly, Secure and SameSite cannot be read by page scripts, is sent only over HTTPS, and is not sent with most cross-site requests. That makes a session the safer choice for a site calling its own API. Because the browser sends the cookie automatically, the API also needs protection against cross-site request forgery, which SameSite mostly provides.

Tokens beyond the browser. A mobile app or a partner has no shared cookie jar, and a different domain cannot receive the API's cookies, so tokens in a header are the natural fit. A self-contained token also lets many services verify the caller without each reaching a session store.

Choose a session for the API's own browser front end. Choose tokens for every other caller. A system may use both, with a session for its web app and tokens for its public API.