Digital Product Engineering5.3 Sessions, Cookies & Tokens
VOL. V · CH. 5.3 · BACKEND SYSTEMS

Sessions, Cookies & Tokens

The mechanics behind how a server remembers you across an inherently stateless protocol.

DivisionBackend / Security
DifficultyAdvanced
Prerequisites5.2
Related1.8 5.14
2 min read · 353 words

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 sessionsJWT / tokens
State locationServer (database or cache, 5.9)Client (self-contained)
RevocationInstant — delete the server recordHard — must wait for expiry or maintain a blocklist
ScalingNeeds shared session storage across serversStateless — scales horizontally with no shared store
Best fitTraditional web appsAPIs, 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.
Real-World ExampleMost modern SPA-and-API architectures issue a short-lived JWT (minutes) alongside a longer-lived, HttpOnly refresh token — combining the statelessness of tokens with a workable revocation path, a pattern popularized by providers like Auth0 and Firebase Auth.