Cookies over HTTP
Follow the cookie round trip
Trace Set-Cookie from a response into the browser cookie jar and back through matching Cookie request headers.
A cookie is the one kind of browser storage that travels with HTTP. That is its whole point, and it explains every rule about it.
The round trip
The server creates a cookie by adding a Set-Cookie header to a response. The browser stores it in its cookie jar. On every later request that matches the cookie’s scope, the browser adds the value to the Cookie request header. Your frontend code never sets that request header by hand.
Here is one full round trip. The server sets a theme, and the next request carries it back:
HTTP/1.1 200 OK
Set-Cookie: theme=dark; Path=/; Max-Age=2592000; Secure; SameSite=Lax
GET /notes HTTP/1.1
Cookie: theme=dark
The attributes after the value are instructions for the browser, not data. Path=/ says “send this on every path”. Max-Age=2592000 is thirty days in seconds. Secure means HTTPS only. SameSite=Lax limits cross-site delivery, which we’ll cover in a later lesson. Notice that the request only carries theme=dark. The attributes stay in the browser.
Why cookies stay small
The browser repeats this on every matching request. Every image, every API call, every navigation. That’s why cookies are meant for a compact identifier or a tiny preference, not a profile, a document, or a cached response.
Browsers cap a single cookie around 4 KB and limit how many cookies a domain can hold. Long before you hit those limits, a fat cookie already made every request slower.
Watching it in DevTools
Page JavaScript can’t see the Set-Cookie response header. The browser hides it on purpose. So the place to watch the round trip is the Network panel.
Click the response that set the cookie and read its headers. Then open the Application panel, find the cookie under your domain, and check the stored attributes. Finally click the next request to /notes and confirm Cookie: theme=dark is there.
Then change something. Request /api/notes instead of /notes. With Path=/ the cookie still travels. If the server had set Path=/notes, the /api/notes request would carry nothing. Seeing that once teaches more than any diagram.
Reading cookies from JavaScript
For a script-visible preference like the theme, document.cookie works but it’s awkward. It’s synchronous and gives you one long string you have to split yourself:
document.cookie //'theme=dark; editor=compact'
The newer Cookie Store API is promise-based and returns objects:
const cookie = await cookieStore.get('theme')
console.log(cookie.value) //'dark'
Use it where your supported browsers have it, and fall back to document.cookie elsewhere. Either way, authentication cookies should be HttpOnly, so neither API can read them. The next lessons build that cookie.
To practice, set one harmless preference cookie from a local server, capture the response and the next request, then narrow the Path until the cookie stops matching.
Lesson completed