Part 03 · The Language of the Web
Headers, Cookies and Content Types
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:
| Need | Header | Example |
|---|---|---|
| What format is the body? | Content-Type | application/json; charset=utf-8 |
| What formats can the client take? | Accept | application/json |
| Is it compressed? | Accept-Encoding / Content-Encoding | gzip, br / gzip |
| Which language? | Accept-Language / Content-Language | bn, en;q=0.8 |
| Who is this? | Cookie, Authorization | session=abc123, Bearer eyJ... |
| Remember this for next time | Set-Cookie | session=abc123; HttpOnly; Secure |
| Can it be reused? | Cache-Control, ETag | max-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.
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
- 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.
- 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 addsVary: Accept-Encodingso the cache stores the variants separately. - 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. - Cookies: the server sets, the browser returns. Response:
Set-Cookie: name=value; attributes. Every later request that matches getsCookie: name=value; other=value. The server sees only names and values, never the attributes. - Attributes decide when a cookie is sent:
Domain/ host: only to the site that set it (and its subdomains ifDomainis given).Path: only for URLs under that path.Max-AgeorExpires: 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, requiresSecure). Modern browsers treat a missing SameSite asLax.
- And who can read it:
HttpOnlyhides the cookie from JavaScript (document.cookie), so an XSS bug can't steal it. - 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.
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
A session cookie's life
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?
Good cookie or risky?
Set-Cookie: session=9f8c...e1; Path=/; Secure; HttpOnly; SameSite=Lax
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, "/"))
}const jar = []; // what the browser remembers, in the order it was set
// setCookie parses one Set-Cookie header the server sent from `domain` at time `now`.
function setCookie(header, domain, now) {
const [first, ...attrs] = header.split("; ");
const eq = first.indexOf("=");
const c = { name: first.slice(0, eq), value: first.slice(eq + 1), domain, path: "/", sameSite: "Lax",
expires: 2 ** 30, secure: false, httpOnly: false };
for (const attr of attrs) {
const [k, v] = attr.split("=");
switch (k.toLowerCase()) {
case "path": c.path = v; break;
case "max-age": c.expires = now + Number(v); break;
case "secure": c.secure = true; break;
case "httponly": c.httpOnly = true; break;
case "samesite": c.sameSite = v; break;
}
}
jar.push(c);
}
// cookieHeader is what the browser attaches to a request: only cookies that match all the rules.
function cookieHeader(now, scheme, host, path, crossSitePost) {
const sent = jar.filter(
(c) =>
host === c.domain && // other sites never see it
path.startsWith(c.path) && // inside its path
now < c.expires && // not expired
!(c.secure && scheme !== "https") && // Secure: never over plain HTTP
!(crossSitePost && c.sameSite !== "None"), // Lax/Strict: not on a POST from another site
);
return sent.length ? sent.map((c) => `${c.name}=${c.value}`).join("; ") : "(none)";
}
// scriptCookies is what JavaScript on a page at `path` can read with document.cookie.
const scriptCookies = (now, path) =>
jar.filter((c) => !c.httpOnly && now < c.expires && path.startsWith(c.path)).map((c) => `${c.name}=${c.value}`).join("; ");
for (const h of [
"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);
console.log("Set-Cookie: " + h);
}
const reqs = [
[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 (const [now, scheme, host, path, cross, label] of reqs) {
console.log(`${label}\n Cookie: ${cookieHeader(now, scheme, host, path, cross)}`);
}
console.log("document.cookie on https://shop.com/ at t=10s: " + scriptCookies(10, "/"));struct Cookie {
name: String,
value: String,
domain: String,
path: String,
same_site: String,
expires: u32, // time in seconds when it stops being sent
secure: bool,
http_only: bool,
}
// set_cookie parses one Set-Cookie header the server sent from `domain` at time `now`.
fn set_cookie(jar: &mut Vec<Cookie>, header: &str, domain: &str, now: u32) {
let mut parts = header.split("; ");
let (name, value) = parts.next().unwrap().split_once('=').unwrap();
let mut c = Cookie {
name: name.into(),
value: value.into(),
domain: domain.into(),
path: "/".into(),
same_site: "Lax".into(),
expires: 1 << 30,
secure: false,
http_only: false,
};
for attr in parts {
let (k, v) = attr.split_once('=').unwrap_or((attr, ""));
match k.to_lowercase().as_str() {
"path" => c.path = v.into(),
"max-age" => c.expires = now + v.parse::<u32>().unwrap(),
"secure" => c.secure = true,
"httponly" => c.http_only = true,
"samesite" => c.same_site = v.into(),
_ => {}
}
}
jar.push(c);
}
// cookie_header is what the browser attaches to a request: only cookies that match all the rules.
fn cookie_header(jar: &[Cookie], now: u32, scheme: &str, host: &str, path: &str, cross_site_post: bool) -> String {
let sent: Vec<String> = jar
.iter()
.filter(|c| {
host == c.domain // other sites never see it
&& path.starts_with(&c.path) // inside its path
&& now < c.expires // not expired
&& !(c.secure && scheme != "https") // Secure: never over plain HTTP
&& !(cross_site_post && c.same_site != "None") // Lax/Strict: not on a POST from another site
})
.map(|c| format!("{}={}", c.name, c.value))
.collect();
if sent.is_empty() { "(none)".into() } else { sent.join("; ") }
}
// script_cookies is what JavaScript on a page at `path` can read with document.cookie.
fn script_cookies(jar: &[Cookie], now: u32, path: &str) -> String {
let seen: Vec<String> = jar
.iter()
.filter(|c| !c.http_only && now < c.expires && path.starts_with(&c.path))
.map(|c| format!("{}={}", c.name, c.value))
.collect();
seen.join("; ")
}
fn main() {
let mut jar = Vec::new(); // what the browser remembers, in the order it was set
for h in [
"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",
] {
set_cookie(&mut jar, h, "shop.com", 0);
println!("Set-Cookie: {h}");
}
let reqs = [
(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 (now, scheme, host, path, cross, label) in reqs {
println!("{label}\n Cookie: {}", cookie_header(&jar, now, scheme, host, path, cross));
}
println!("document.cookie on https://shop.com/ at t=10s: {}", script_cookies(&jar, 10, "/"));
}jar = [] # what the browser remembers, in the order it was set
def set_cookie(header, domain, now):
"""Parse one Set-Cookie header the server sent from `domain` at time `now`."""
first, *attrs = header.split("; ")
name, _, value = first.partition("=")
c = {"name": name, "value": value, "domain": domain, "path": "/", "same_site": "Lax",
"expires": 2**30, "secure": False, "http_only": False}
for attr in attrs:
k, _, v = attr.partition("=")
k = k.lower()
if k == "path":
c["path"] = v
elif k == "max-age":
c["expires"] = now + int(v)
elif k == "secure":
c["secure"] = True
elif k == "httponly":
c["http_only"] = True
elif k == "samesite":
c["same_site"] = v
jar.append(c)
def cookie_header(now, scheme, host, path, cross_site_post):
"""What the browser attaches to a request: only cookies that match all the rules."""
sent = [
f"{c['name']}={c['value']}"
for c in jar
if host == c["domain"] # other sites never see it
and path.startswith(c["path"]) # inside its path
and now < c["expires"] # not expired
and not (c["secure"] and scheme != "https") # Secure: never over plain HTTP
and not (cross_site_post and c["same_site"] != "None") # Lax/Strict: not on a POST from another site
]
return "; ".join(sent) if sent else "(none)"
def script_cookies(now, path):
"""What JavaScript on a page at `path` can read with document.cookie."""
return "; ".join(
f"{c['name']}={c['value']}" for c in jar if not c["http_only"] and now < c["expires"] and path.startswith(c["path"])
)
for h in [
"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",
]:
set_cookie(h, "shop.com", 0)
print("Set-Cookie: " + h)
reqs = [
(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 now, scheme, host, path, cross, label in reqs:
print(f"{label}\n Cookie: {cookie_header(now, scheme, host, path, cross)}")
print("document.cookie on https://shop.com/ at t=10s: " + script_cookies(10, "/"))import java.util.*;
public class Main {
static class Cookie {
String name, value, domain, path = "/", sameSite = "Lax";
int expires = 1 << 30; // time in seconds when it stops being sent
boolean secure, httpOnly;
}
static List<Cookie> jar = new ArrayList<>(); // what the browser remembers, in the order it was set
// setCookie parses one Set-Cookie header the server sent from `domain` at time `now`.
static void setCookie(String header, String domain, int now) {
String[] parts = header.split("; ");
Cookie c = new Cookie();
int eq = parts[0].indexOf('=');
c.name = parts[0].substring(0, eq);
c.value = parts[0].substring(eq + 1);
c.domain = domain;
for (int i = 1; i < parts.length; i++) {
String[] kv = parts[i].split("=", 2);
String v = kv.length > 1 ? kv[1] : "";
switch (kv[0].toLowerCase()) {
case "path" -> c.path = v;
case "max-age" -> c.expires = now + Integer.parseInt(v);
case "secure" -> c.secure = true;
case "httponly" -> c.httpOnly = true;
case "samesite" -> c.sameSite = v;
default -> {}
}
}
jar.add(c);
}
// cookieHeader is what the browser attaches to a request: only cookies that match all the rules.
static String cookieHeader(int now, String scheme, String host, String path, boolean crossSitePost) {
StringJoiner sent = new StringJoiner("; ");
for (Cookie c : jar) {
if (!host.equals(c.domain)) continue; // other sites never see it
if (!path.startsWith(c.path)) continue; // outside its path
if (now >= c.expires) continue; // expired
if (c.secure && !scheme.equals("https")) continue; // Secure: never over plain HTTP
if (crossSitePost && !c.sameSite.equals("None")) continue; // Lax/Strict: not on a POST from another site
sent.add(c.name + "=" + c.value);
}
return sent.length() == 0 ? "(none)" : sent.toString();
}
// scriptCookies is what JavaScript on a page at `path` can read with document.cookie.
static String scriptCookies(int now, String path) {
StringJoiner seen = new StringJoiner("; ");
for (Cookie c : jar) if (!c.httpOnly && now < c.expires && path.startsWith(c.path)) seen.add(c.name + "=" + c.value);
return seen.toString();
}
public static void main(String[] args) {
for (String h : new 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);
System.out.println("Set-Cookie: " + h);
}
Object[][] reqs = {
{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 (Object[] r : reqs) {
System.out.println(r[5] + "\n Cookie: " + cookieHeader((Integer) r[0], (String) r[1], (String) r[2], (String) r[3], (Boolean) r[4]));
}
System.out.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:carthasPath=/cart, so it only rides along with cart URLs. The others go everywhere on the site.- Plain HTTP:
sessionisSecure, so it's held back. Anyone sniffing a plain HTTP request sees onlythemeandpromo. - evil.com: nothing. Cookies never go to other sites.
- Cross-site POST: nothing, not even
theme. Every cookie here isLax(explicitly, or by the modern default), so a form on another site can't carry them. - t=120s:
promohadMax-Age=60, so it's gone. t=4000s:sessionexpired after an hour, andcartafter 10 minutes. Only the year-longthemeis left. - document.cookie: JavaScript sees
themeandpromo, but neversession(HttpOnly) and notcart(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_sesshas noexpires: a session cookie, gone when the browser closes. It'sHttpOnly,secureandSameSite=Lax, exactly the flags from this lesson (the long value is hidden here withsed).domain=.github.commakes_octoandlogged_ingo to subdomains too (likegist.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(orStrictfor 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
Authorizationheaders. Browsers send cookies automatically (convenient, but exposed to CSRF without SameSite). Mobile apps and service-to-service calls usually sendAuthorization: Bearer <token>explicitly. Module 9 compares them in depth. - Always set
Content-Typeand 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
Pick a failure
cookie set, but never sent back
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:
Strictcookies go only on same-site requests.Laxcookies also go on cross-sitelinknavigations, but not onpost.Nonecookies (which must beSecure) go on everything over HTTPS. - Add a fifth cookie,
admin=1; Path=/; Secure; HttpOnly; SameSite=Strict, and test a link click from evil.com tohttps://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 →