Course outline · 0% complete

0/25 lessons0%

Course overview →

Cookies: HTTP has no memory

lesson 6-1 · ~10 min · 18/25

Quiz

Warm-up from unit 4: where does extra information like Content-Type travel in an HTTP message?

Every request is a stranger

HTTP is stateless: the server handles each request on its own and remembers nothing afterwards. Request #2 does not know request #1 happened. So how does a site keep you logged in across hundreds of requests?

Cookies. A cookie is a small piece of text the server asks the browser to remember, using the Set-Cookie response header:

HTTP/1.1 200 OK
Set-Cookie: session=abc123; Path=/; HttpOnly; Max-Age=3600

The part before the first ; is the actual cookie: a name (session) and a value (abc123). Everything after are attributes, instructions about how to handle it:

  • Path=/: send it with requests to every path on this site
  • HttpOnly: page JavaScript cannot read it (protects it from scripts)
  • Max-Age=3600: forget it after 3600 seconds

From then on, the browser automatically attaches the cookie to every request to that site, in the Cookie request header:

GET /inbox HTTP/1.1
Host: example.com
Cookie: session=abc123

Code exercise · bash

Run this. It parses a raw Set-Cookie header into the cookie's name and value using the trimming patterns you have used since lesson 1-2: cut off the header name, keep what is before the first semicolon, then split on =.

Code exercise · bash

Your turn. Now list the cookie's attributes, one per line. Strip everything through the first '; ' to get the attribute list, turn the remaining semicolons into newlines with tr ';' '\n', and print each one prefixed with 'attribute: '.

Quiz

After a server sends Set-Cookie: session=abc123, how does that value get back to the server on the user's next click?