Part 03 · The Language of the Web

Headers, Cookies and Content Types

HeadersCookiesContentType

The metadata that rides along with every request, and how cookies remember you.

⏱ 1-2 hours · Station 30 of 153

How does a stateless server remember you logged in?

Module 1 said a good server remembers nothing between requests (stateless), and lesson 1 said HTTP is stateless by design. Yet you log in to a shop once, close the tab, come back tomorrow, and you're still logged in, with your cart still full.

Something is remembering. It's not the TCP connection (that closed hours ago) and it's not the server's memory (the request might hit a different server). It's a few bytes the browser keeps and sends back on every request: a cookie.

Cookies are just one header. The same mechanism, little Name: value lines riding along with every message, is how HTTP describes formats, compression, caching, languages, authentication and security rules. This lesson is about the headers you'll meet every day, with cookies in the spotlight because they're where most real bugs and security holes live.

The problem: the body alone can't say enough

A response body is just bytes. To use it correctly, both sides need facts about it, and about the conversation:

NeedHeaderExample
What format is the body?Content-Typeapplication/json; charset=utf-8
What formats can the client take?Acceptapplication/json
Is it compressed?Accept-Encoding / Content-Encodinggzip, br / gzip
Which language?Accept-Language / Content-Languagebn, en;q=0.8
Who is this?Cookie, Authorizationsession=abc123, Bearer eyJ...
Remember this for next timeSet-Cookiesession=abc123; HttpOnly; Secure
Can it be reused?Cache-Control, ETagmax-age=60

The hardest one is identity. HTTP has no memory, so every single request must prove who it's from. Cookies solve that by making the browser repeat the proof automatically.

Think of a cinema hand stamp

You pay at a cinema and the staff stamp your hand: "Hall 3, today".

  • You go out for popcorn. Coming back, you just show your hand. Nobody needs to remember your face.
  • The stamp only works at this cinema, and only for hall 3.
  • It washes off by tomorrow.
  • It's invisible ink: you can't easily copy it onto someone else's hand.

That's a cookie. The server "stamps" the browser with Set-Cookie. The browser shows the stamp (Cookie) on every request to that site and path, until it expires. Attributes like HttpOnly, Secure and SameSite are the invisible ink: rules about who can see and copy the stamp.

browsercookie jarshop.comevil.comPOST /loginSet-Cookie: session=abcstored: session=abcGET /cart + Cookiesame site: cookie attachedGET / (no cookie)other site: nothing attached
The browser logs in to shop.com. The response carries Set-Cookie: session=abc, and the browser stores it in its cookie jar. The next request to shop.com carries the cookie automatically, so the server knows who it is. A request to evil.com carries nothing: cookies only go back to the site that set them.

Where the analogy stops working. A hand stamp is checked by a human who might notice a fake. A cookie is just text: if someone steals the value, they are you, as far as the server knows. That's why the security attributes matter so much, and why the session ID must be long and random.

The building blocks

  1. Headers are metadata, not data. Case-insensitive names, unknown ones ignored (lesson 2). Request headers describe the request and what the client wants; response headers describe the body and give instructions.
  2. Content negotiation. The client lists what it accepts (Accept: application/json, Accept-Encoding: gzip, br, Accept-Language: bn), and the server picks and says what it picked (Content-Type, Content-Encoding, Content-Language). If a cache sits in between, the server adds Vary: Accept-Encoding so the cache stores the variants separately.
  3. Content-Type is a promise about the bytes. application/json, text/html; charset=utf-8, image/png, multipart/form-data; boundary=... for uploads. Clients decide how to parse based on it, and browsers decide whether to render or download.
  4. Cookies: the server sets, the browser returns. Response: Set-Cookie: name=value; attributes. Every later request that matches gets Cookie: name=value; other=value. The server sees only names and values, never the attributes.
  5. Attributes decide when a cookie is sent:
    • Domain / host: only to the site that set it (and its subdomains if Domain is given).
    • Path: only for URLs under that path.
    • Max-Age or Expires: until when. Without either, it's a session cookie, gone when the browser session ends.
    • Secure: only over HTTPS.
    • SameSite: Strict (never on cross-site requests), Lax (only on top-level navigations with safe methods, like clicking a link), None (always, requires Secure). Modern browsers treat a missing SameSite as Lax.
  6. And who can read it: HttpOnly hides the cookie from JavaScript (document.cookie), so an XSS bug can't steal it.
  7. Cookies are small and go everywhere. About 4 KB per cookie, and every matching request carries all of them, including requests for images. Store an ID in the cookie, and the data on the server.
Predict first

Your session cookie is set with Secure; HttpOnly; SameSite=Lax. A page on evil.com has a hidden form that POSTs to https://bank.com/transfer and submits itself with JavaScript. Does the browser attach the bank session cookie?

Behind the scenes: login, then every request after

Step through it

A session cookie's life

BrowserCookie jarServerSession store

Step 1/6 POST /login with the password

The only time the password crosses the wire for this session (over TLS).

sent
email + password

The picture to keep in your head

Headers are labels on the envelope, and cookies are a stamp the browser carries:

  • Content-Type / Accept / Encoding: what's inside and how it's packed, negotiated by both sides.
  • Set-Cookie (server → browser): "carry this stamp, under these rules".
  • Cookie (browser → server): the stamp, shown automatically on every matching request.
  • Rules on the stamp: which site and path, until when, HTTPS only, not to scripts, not on cross-site requests.

The server stays stateless; the browser carries a small ID; the real state lives in a store the ID points to.

Try it: is this cookie safe?

Try each case

Good cookie or risky?

Set-Cookie: session=9f8c...e1; Path=/; Secure; HttpOnly; SameSite=Lax
works: HTTPS only, invisible to scripts, not sent on cross-site POSTs, and a long random value. The standard for login sessions.

Code from first principles

A browser's cookie jar. setCookie parses Set-Cookie headers and stores the attributes. cookieHeader decides, for each later request, which cookies go into the Cookie header, applying the site, path, expiry, Secure and SameSite rules. scriptCookies shows what JavaScript could read. Time is passed in as seconds so the output is stable.

package main

import (
	"fmt"
	"strconv"
	"strings"
)

type cookie struct {
	name, value, domain, path, sameSite string
	expires                             int // time in seconds when it stops being sent
	secure, httpOnly                    bool
}

var jar []cookie // what the browser remembers, in the order it was set

// setCookie parses one Set-Cookie header the server sent from `domain` at time `now`.
func setCookie(header, domain string, now int) {
	parts := strings.Split(header, "; ")
	name, value, _ := strings.Cut(parts[0], "=")
	c := cookie{name: name, value: value, domain: domain, path: "/", sameSite: "Lax", expires: 1 << 30}
	for _, attr := range parts[1:] {
		k, v, _ := strings.Cut(attr, "=")
		switch strings.ToLower(k) {
		case "path":
			c.path = v
		case "max-age":
			n, _ := strconv.Atoi(v)
			c.expires = now + n
		case "secure":
			c.secure = true
		case "httponly":
			c.httpOnly = true
		case "samesite":
			c.sameSite = v
		}
	}
	jar = append(jar, c)
}

// cookieHeader is what the browser attaches to a request: only cookies that match all the rules.
func cookieHeader(now int, scheme, host, path string, crossSitePost bool) string {
	sent := []string{}
	for _, c := range jar {
		switch {
		case host != c.domain: // other sites never see it
		case !strings.HasPrefix(path, c.path): // outside its path
		case now >= c.expires: // expired
		case c.secure && scheme != "https": // Secure: never over plain HTTP
		case crossSitePost && c.sameSite != "None": // Lax/Strict: not on a POST from another site
		default:
			sent = append(sent, c.name+"="+c.value)
		}
	}
	if len(sent) == 0 {
		return "(none)"
	}
	return strings.Join(sent, "; ")
}

// scriptCookies is what JavaScript on a page at `path` can read with document.cookie.
func scriptCookies(now int, path string) string {
	seen := []string{}
	for _, c := range jar {
		if !c.httpOnly && now < c.expires && strings.HasPrefix(path, c.path) {
			seen = append(seen, c.name+"="+c.value)
		}
	}
	return strings.Join(seen, "; ")
}

func main() {
	for _, h := range []string{
		"session=abc123; Path=/; Max-Age=3600; Secure; HttpOnly; SameSite=Lax",
		"theme=dark; Path=/; Max-Age=31536000",
		"cart=7; Path=/cart; Max-Age=600",
		"promo=EID; Path=/; Max-Age=60",
	} {
		setCookie(h, "shop.com", 0)
		fmt.Println("Set-Cookie: " + h)
	}
	reqs := []struct {
		now                int
		scheme, host, path string
		crossSitePost      bool
		label              string
	}{
		{10, "https", "shop.com", "/", false, "t=10s   GET https://shop.com/"},
		{10, "https", "shop.com", "/cart/items", false, "t=10s   GET https://shop.com/cart/items"},
		{10, "http", "shop.com", "/", false, "t=10s   GET http://shop.com/ (plain HTTP)"},
		{10, "https", "evil.com", "/", false, "t=10s   GET https://evil.com/"},
		{10, "https", "shop.com", "/transfer", true, "t=10s   POST https://shop.com/transfer from a form on evil.com"},
		{120, "https", "shop.com", "/", false, "t=120s  GET https://shop.com/"},
		{4000, "https", "shop.com", "/", false, "t=4000s GET https://shop.com/"},
	}
	for _, r := range reqs {
		fmt.Printf("%s\n  Cookie: %s\n", r.label, cookieHeader(r.now, r.scheme, r.host, r.path, r.crossSitePost))
	}
	fmt.Println("document.cookie on https://shop.com/ at t=10s: " + scriptCookies(10, "/"))
}

Output (the same in all five languages):

Set-Cookie: session=abc123; Path=/; Max-Age=3600; Secure; HttpOnly; SameSite=Lax
Set-Cookie: theme=dark; Path=/; Max-Age=31536000
Set-Cookie: cart=7; Path=/cart; Max-Age=600
Set-Cookie: promo=EID; Path=/; Max-Age=60
t=10s   GET https://shop.com/
  Cookie: session=abc123; theme=dark; promo=EID
t=10s   GET https://shop.com/cart/items
  Cookie: session=abc123; theme=dark; cart=7; promo=EID
t=10s   GET http://shop.com/ (plain HTTP)
  Cookie: theme=dark; promo=EID
t=10s   GET https://evil.com/
  Cookie: (none)
t=10s   POST https://shop.com/transfer from a form on evil.com
  Cookie: (none)
t=120s  GET https://shop.com/
  Cookie: session=abc123; theme=dark
t=4000s GET https://shop.com/
  Cookie: theme=dark
document.cookie on https://shop.com/ at t=10s: theme=dark; promo=EID

Reading the output:

  • / vs /cart/items: cart has Path=/cart, so it only rides along with cart URLs. The others go everywhere on the site.
  • Plain HTTP: session is Secure, so it's held back. Anyone sniffing a plain HTTP request sees only theme and promo.
  • evil.com: nothing. Cookies never go to other sites.
  • Cross-site POST: nothing, not even theme. Every cookie here is Lax (explicitly, or by the modern default), so a form on another site can't carry them.
  • t=120s: promo had Max-Age=60, so it's gone. t=4000s: session expired after an hour, and cart after 10 minutes. Only the year-long theme is left.
  • document.cookie: JavaScript sees theme and promo, but never session (HttpOnly) and not cart (wrong path for this page).

Real servers, real headers:

$ curl -s -D - -o /dev/null https://github.com/ | tr -d '\r' | grep -i "^set-cookie" | sed -E 's/^(set-cookie: _gh_sess=)[^;]*/\1.../'
set-cookie: _gh_sess=...; path=/; HttpOnly; secure; SameSite=Lax
set-cookie: _octo=GH1.1.1051490817.1795139962; expires=Sat, 20 Nov 2027 01:59:22 GMT; domain=.github.com; path=/; secure; SameSite=Lax
set-cookie: logged_in=no; expires=Sat, 20 Nov 2027 01:59:22 GMT; domain=.github.com; path=/; HttpOnly; secure; SameSite=Lax
$ curl -s -D - -o /dev/null -H 'Accept-Encoding: gzip' https://example.com/ | tr -d '\r' | grep -iE "^(content-encoding|content-type|vary)"
content-type: text/html; charset=utf-8
content-encoding: gzip
  • _gh_sess has no expires: a session cookie, gone when the browser closes. It's HttpOnly, secure and SameSite=Lax, exactly the flags from this lesson (the long value is hidden here with sed).
  • domain=.github.com makes _octo and logged_in go to subdomains too (like gist.github.com).
  • Content negotiation: the request said "I accept gzip", and the server answered with content-encoding: gzip, so the body bytes are compressed and the client must unzip them.

Real engineering

  • Session cookies: Secure; HttpOnly; SameSite=Lax (or Strict for admin panels), a long random value (128 bits or more), and a server-side expiry. Rotate the session ID on login to prevent session fixation.
  • Keep cookies tiny. They're sent with every request, including images and API calls. Big cookies slow every request and can hit header limits (431).
  • Log out properly. Delete the session on the server and clear the cookie (Max-Age=0). Clearing only the cookie leaves a stolen copy valid.
  • Cookies vs Authorization headers. Browsers send cookies automatically (convenient, but exposed to CSRF without SameSite). Mobile apps and service-to-service calls usually send Authorization: Bearer <token> explicitly. Module 9 compares them in depth.
  • Always set Content-Type and compress text. gzip or brotli for JSON and HTML; skip compression for images and videos that are already compressed.
  • Cookie consent is a legal topic, not just technical. Tracking cookies need user consent in many countries; strictly necessary ones (session, CSRF) usually don't.

When it breaks

Try each case

Pick a failure

cookie set, but never sent back
breaks: Often Secure on a site still served over http, or a Domain attribute that doesn't match the real host. Check the browser's dev tools: blocked cookies show a reason.

Think before you read on

A cookie is sent with every request to the site, automatically, even when the request is started by another website (for example an <img src="https://shop.com/api/cart/clear"> on a forum). Before SameSite existed, what attack did this make possible, and what are the defences today?

Reveal

Cross-site request forgery (CSRF): another site makes your browser send a request to shop.com, the browser attaches your session cookie, and shop.com thinks you did it. Defences today: SameSite=Lax or Strict on session cookies (cross-site POSTs and subresource requests no longer carry them), never changing state on GET (lesson 4, so the <img> trick does nothing), CSRF tokens in forms (a secret value the other site can't read), and checking the Origin header on state-changing requests.

Check yourself

1. What's the difference between Set-Cookie and Cookie?

Answer

Set-Cookie is a response header: the server tells the browser to store a cookie, with attributes. Cookie is a request header: the browser sends back the names and values of all matching cookies, without the attributes.

2. What do HttpOnly, Secure and SameSite=Lax each protect against?

Answer

HttpOnly: scripts (including XSS) can't read the cookie. Secure: the cookie never travels over plain HTTP where it could be sniffed. SameSite=Lax: other sites can't make cross-site POSTs (and most subresource requests) carry it, which blocks most CSRF.

3. Why should a cookie hold a session ID rather than the user's data?

Answer

The client controls cookies and can change them, and every byte is sent on every request. An unguessable ID reveals nothing and can't be edited into something useful; the real data stays on the server.

4. What does Vary: Accept-Encoding tell a cache?

Answer

That the response depends on the request's Accept-Encoding header, so the cache must store and serve separate versions (for example gzip and uncompressed) instead of giving everyone the same bytes.

Your challenge: SameSite=Strict and top-level links

Extend the jar's rules:

  • Add a parameter for the kind of cross-site request: "none" (same site), "link" (a top-level GET navigation, like clicking a link from another site), or "post" (a cross-site form POST).
  • Rules: Strict cookies go only on same-site requests. Lax cookies also go on cross-site link navigations, but not on post. None cookies (which must be Secure) go on everything over HTTPS.
  • Add a fifth cookie, admin=1; Path=/; Secure; HttpOnly; SameSite=Strict, and test a link click from evil.com to https://shop.com/.

Before you run it, predict which cookies arrive with the link click.

You've succeeded when the link click carries session, theme and promo but not admin, the cross-site POST still carries nothing, and same-site requests carry admin too.

The mental model

Headers are labels on every HTTP message: what the body is (Content-Type), how it's packed (Content-Encoding), what the client accepts, and instructions like caching. Cookies add memory to a stateless protocol: the server sends Set-Cookie once, and the browser shows the value on every matching request, by site, path and expiry. Keep only a random ID in it, keep the data on the server, and lock it down with Secure, HttpOnly and SameSite.

Station stamp

Finish the chapter

Done reading? Press Complete to save your progress. XP is Pro-only — on Pro this chapter is worth +10 XP.

Go Pro to earn XP →