Headers and cookies

Reading · 6 min · Module 6, lesson 3 of 411 min left in this module

Module 6 · HTTP and HTTPSLesson 3 of 4

Goal: Read the headers of a real request and response, and explain how a cookie keeps you logged in.

Key idea

Headers are name-and-value lines that describe a request or response: what type the body is, where to go next, who's asking. A cookie is a header the server asks the browser to keep and send back with every later request to that site, which is how a site remembers you.

Try it: read a real exchange

curl -v prints both halves of an exchange.

curl -v https://example.com

Among the output, you'll find lines like these (yours may say HTTP/1.1; the parts are the same):

> GET / HTTP/2
> Host: example.com
> User-Agent: curl/8.7.1
> Accept: */*
>
< HTTP/2 200
< content-type: text/html

Lines starting with > are what curl sent, < is what came back, and * lines are curl's notes about the connection and TLS. The empty > line ends the request's headers. Header names ignore case, and HTTP/2 writes them in lower case.

Headers worth knowing

  • Host: which site you want (lesson 1.6.1).
  • Content-Type: what the body is, like text/html or application/json. A wrong one makes a browser mishandle a perfectly good body.
  • Location: where a 301 or other redirect sends you.
  • Cache-Control: whether and how long browsers and caches may keep the response.
  • Authorization: credentials, like an API token, sent with a request.
  • Set-Cookie and Cookie: next.

How cookies work

  1. You log in. The response includes Set-Cookie: session=7f3a; Secure; HttpOnly.
  2. The browser stores it for that site.
  3. Every later request to that site carries Cookie: session=7f3a, so the server knows it's you.

The attributes after the value are instructions for the browser:

  • Secure: only send it over HTTPS.
  • HttpOnly: the page's JavaScript can't read it, so an injected script can't steal it.
  • SameSite: whether requests started by other sites carry it.
  • Max-Age or Expires: when to delete it. Without one, it usually goes when the browser closes.

Anyone holding a session cookie is logged in as you, so treat it like a password. Never log it or paste it into a support ticket.

example.com sets no cookies. To see cookies on a site you use, open the browser's developer tools: they're under Application in Chrome and Edge, and Storage in Firefox and Safari.

Check yourself

A site sets 'Set-Cookie: session=7f3a; HttpOnly'. What does HttpOnly do?
In curl -v output, which lines are the response?