Sessions, Cookies & Tokens
The mechanics behind how a server remembers you across an inherently stateless protocol.
5.3.1Definition
HTTP (1.8) is stateless by design — each request arrives with no memory of previous ones. Sessions, cookies, and tokens are the mechanisms that layer identity on top of that statelessness. A cookie is a small piece of data a browser stores and automatically resends with each request. A session is server-side state referenced by a cookie. A token — most commonly a JWT (JSON Web Token) — is a self-contained, cryptographically signed piece of data the client holds instead.
5.3.2Why It Exists
Without some persistence mechanism, a user would need to re-authenticate on every single request — clicking a link would log them out. This layer exists to let a server recognize a returning, already-authenticated client efficiently, at the cost of introducing an entirely new category of security surface: session hijacking, token theft, and cross-site request forgery.
5.3.3Session vs. Token Trade-off
| Server-side sessions | JWT / tokens | |
|---|---|---|
| State location | Server (database or cache, 5.9) | Client (self-contained) |
| Revocation | Instant — delete the server record | Hard — must wait for expiry or maintain a blocklist |
| Scaling | Needs shared session storage across servers | Stateless — scales horizontally with no shared store |
| Best fit | Traditional web apps | APIs, mobile clients, microservices (1.5) |
5.3.4Common Mistakes
- Storing a JWT in localStorage instead of an HttpOnly cookie. Making the token readable by any JavaScript on the page, including injected malicious scripts (XSS).
- Issuing JWTs with no expiry, or an excessively long one, removing the ability to revoke access without waiting out the token's entire lifetime.
- Missing CSRF protection on cookie-based sessions, allowing a malicious site to submit authenticated requests on the user's behalf.
5.3.5Best Practices
- Set cookies as HttpOnly, Secure, and SameSite to close off the most common cookie-based attacks.
- Keep JWT lifetimes short and pair them with a refresh-token rotation flow for renewal.
- For session-based auth, apply CSRF tokens on every state-changing request.