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 ONLY STORE THE SERVER CAN READ
Browser Server
βββ GET /orders ββββββββββββββββββββββββββΊβ
β Cookie: sid=a1b2c3; theme=dark β attached automatically
β β by the browser
βββ 200 βββββββββββββββββββββββββββββββββββ
β Set-Cookie: sid=a1b2c3; HttpOnly; β
β Secure; SameSite=Lax; β
β Max-Age=3600; Path=/ β
Every request to this origin carries it β images, API calls, all of it.
4KB of cookies Γ 60 requests = 240KB uploaded per page load.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.