3. Client and Server
3.11 How do cookies, sessions and tokens remember who you are?
In the restaurant: Two ways to remember a regular. Notebook: the restaurant gives you a token number and keeps a notebook ("token 57 = Asha, gold member"). You show the token; they look it up. Stamped card: the restaurant gives you a card with everything written on it and an official stamp nobody can fake. They read the card; no notebook needed.
In the system:
Cookies are the pocket: small values a server asks the browser to store (Set-Cookie) and send back automatically on every request to that site (Cookie). They carry either of the two approaches below.
1. Sessions (the notebook)
- On login, the server creates a random session ID, stores
session ID → userin a shared store, and sends the ID in a cookie. - Each request sends the cookie; the server looks the ID up.
- Easy to revoke: delete the entry and the user is logged out everywhere.
- Cost: a lookup in the store on every request.
2. Tokens (the stamped card)
- On login, the server creates a signed token containing who you are and when it expires. A common format is the JWT (JSON Web Token).
- The client sends it, usually in the
Authorization: Bearer <token>header (or in a cookie). - Any server checks the signature and trusts the contents. No lookup needed, which suits many services and mobile apps.
- Cost: hard to revoke. A stolen token works until it expires. So tokens are kept short-lived and paired with a longer-lived refresh token that can be revoked.
Security basics for cookies: mark them HttpOnly (JavaScript can't read them, which limits damage from cross-site scripting), Secure (only sent over HTTPS) and set SameSite (limits sending them on requests from other sites).
| Session ID | Signed token (e.g. JWT) | |
|---|---|---|
| Where the truth lives | Server-side store | Inside the token |
| Lookup per request | Yes | No, just check the signature |
| Log out / revoke | Instant | Hard; rely on short expiry |
| Good fit | Websites, admin panels | Many services, mobile apps, APIs |
Memory code: "Session: we keep the notebook. Token: you carry the stamped card." Cookies are just the pocket either one travels in.