Track 01 · Lesson 7 of 9How the web works

Track 01 · How the web works

Cookies

Lesson 7 of 9· 6 min

HTTP has no memory: every request arrives as if from a stranger. Cookies fix that. The server hands your browser a small value, and the browser sends it back with every request to that site, automatically.

Follow one cookie's life

Log in, come back, wander off, log out

Step 1 of 5
https://shop.example.com

You log in

HTTP forgets you the moment a response is sent. So after checking your password, the server answers with a Set-Cookie header: a small value it wants back on every future request.

Request

POST /login HTTP/1.1Host: shop.example.comContent-Type: application/json{"email": "ana@example.com", "password": "••••••••"}

Response

HTTP/1.1 200 OKSet-Cookie: session=7f3a9c; Path=/; Max-Age=604800; HttpOnly; Secure; SameSite=LaxContent-Type: application/json{"name": "Ana"}

The browser’s cookie jar

Empty

Nothing yet. The server hasn’t asked the browser to remember anything.

Click each part of the Set-Cookie header

JavaScript on the page can’t read it, so a script injected by an attacker can’t steal it.

How it works#

  1. The server responds with a Set-Cookie header.
  2. The browser stores the cookie under that site, with an expiry date.
  3. On every later request to that site, the browser adds a Cookie header by itself.
  4. The server reads it to recognise you, usually by looking up a session ID.
  5. It expires, or the server clears it when you log out.

Why "automatically" matters#

That convenience is also the catch. The browser attaches a site's cookies to every request to that site, including requests that another website quietly starts on your behalf. And whoever gets hold of the cookie's value is you, as far as the server can tell.

That's what the flags are for. HttpOnly keeps it away from JavaScript, Secure keeps it off plain http, and SameSite stops other sites from triggering it. You'll see exactly which attacks each one blocks in Attacks and defenses, and how cookies compare to tokens in Identity and login.

Check yourself

Which cookie attribute stops JavaScript from reading a cookie?