Card 05/ 12
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.
| Question | Session | Token |
|---|---|---|
| What proves the caller | A random session id pointing at server-side state | The token, opaque or self-contained |
| Where it travels | A cookie the browser sends automatically | The Authorization header, added by the client's code |
| Which client it suits | The API's own web front end, on the same site | Mobile apps, third parties and other services |
| How access is cut off | Delete the session, effective at once | Wait 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.
← → move through sections and cards