Part III — The Speed · Lesson 6.4
Cookie Storage
In one lineFour kilobytes that ride along on every single request — which is both the feature and the cost.
Where you've seen itStaying logged in after a hard refresh. No JavaScript ran; the cookie did the work.
Diagram
THE ATTRIBUTE MATRIX — each one closes a specific hole
HttpOnly JS cannot read it ← blocks XSS token theft (3.2)
Secure HTTPS only ← blocks network sniffing
SameSite=Lax not sent on cross- ← blocks most CSRF (3.15)
site POST
SameSite=Strict not sent cross-site ← strongest, worse UX
at all
SameSite=None always sent ← requires Secure
Max-Age / Expires lifetime ← session cookie if omitted
Domain / Path scope ← narrower is saferSESSION COOKIE vs TOKEN — where the state lives
COOKIE + SERVER SESSION JWT IN COOKIE
sid → lookup in Redis claims signed inside the cookie
✓ revoke instantly ✗ revocation needs a denylist
✗ server-side store needed ✓ stateless, scales horizontallyHow it works
- The server sets a cookie with
Set-Cookie; the browser stores it and re-sends it on every matching request. - Attribute defaults are unsafe — always set
HttpOnly,Secure, andSameSiteexplicitly for anything auth-related. - Scope tightly:
Path=/apiand an exactDomainlimit where it travels. A cookie on.example.comgoes to every subdomain, including that old marketing site. - Keep them small. Cookies are uploaded on every request, and upload bandwidth is far scarcer than download on mobile.
- Non-sensitive UI preferences belong in
localStorage, not cookies — unless the server needs them for SSR (e.g. rendering the correct theme on first paint).
Trade-offs
| Cookie | Web storage |
|---|---|
| Server can read it | JS only |
Can be HttpOnly — XSS-proof | Always JS-readable |
| 4KB, sent every request | 5MB, never sent |
CSRF exposure (needs SameSite) | No CSRF exposure |
Interview angle
"Where do you store the session, and why?"
HttpOnly; Secure; SameSite=Laxcookie: XSS can't read it and most CSRF is closed by default.- Short-lived access token with server-side refresh rotation, so a stolen cookie has a small window.
- Keep everything else out of cookies — each byte is uploaded on every request for the life of the session.
Recap
- The only client store the server sees, and the only one with an XSS-proof mode.
HttpOnly+Secure+SameSiteis the non-negotiable trio for auth.- Size matters: cookies are upload cost on every single request.