Cookies
A cookieCookieA small name-value pair a server stores in the browser with Set-Cookie, which the browser sends back on matching requests.Open in glossary → is a small name-value pair that a server asks the browser to store and send back:
HTTP/1.1 200 OK
Set-Cookie: session=8f2c91d4; Path=/; Max-Age=2592000; Secure; HttpOnly; SameSite=Lax
GET /orders HTTP/1.1
Host: shop.example
Cookie: session=8f2c91d4From then on, every request to shop.example includes Cookie: session=8f2c91d4, and the server knows who’s asking. The attributes after the value control the cookie:
| Attribute | Meaning |
|---|---|
Max-Age=2592000 or Expires=… | Keep it for 30 days. Without either, it’s deleted when the browser session ends. |
Domain=shop.example | Also send it to subdomains like api.shop.example. Without it, only the exact host that set it gets it back. |
Path=/ | Send it for every path on the site. |
Secure | Only send it over HTTPS. |
HttpOnly | JavaScript can’t read it through document.cookie, so a malicious script injected into the page can’t steal it. |
SameSite=Lax | Don’t send it on requests that other sites trigger in the background (more below). |
SameSite decides what happens when a request is caused by a different site:
Strict: never sent on cross-site requests, not even when the user clicks a link from another site to yours (they arrive logged out).Lax: sent when the user navigates to your site (clicking a link), but not on cross-site background requests (fetch, images, forms posted from another site).None: always sent; requiresSecure. Needed for cookies used inside other sites, like an embedded widget.
A cookie without SameSite is treated as Lax by modern browsers. For a login session, the safe default is Secure; HttpOnly; SameSite=Lax.
- Site vs origin: an origin is scheme + host + port (
https://api.shop.example:443); a site is scheme + registrable domain (https://shop.example, using the Public Suffix List). SameSite is about sites, soapi.shop.exampleandwww.shop.exampleare same-site; CORS is about origins, so they’re cross-origin. - Lax by default (Chrome since 2020, others followed) with a quirk: cookies set without any
SameSiteattribute in the last two minutes are still sent on top-level cross-site POST navigations (“Lax+POST”), to keep some sign-in flows working. An explicitSameSite=Laxdoesn’t get that exception. - Prefixes:
__Host-sessionmust beSecure,Path=/, and have noDomain, so a compromised or malicious subdomain can’t overwrite it;__Secure-only requiresSecure. Use__Host-for session cookies. - Third-party cookies: Safari and Firefox block them by default; Chrome still allows them: in 2025 Google dropped its plan to phase them out and retired most Privacy Sandbox APIs.
Partitioned(CHIPS) cookies are keyed by the top-level site, for embeds that need state without cross-site tracking. - Limits: about 4 KB per cookie, dozens per domain, and every cookie rides on every matching request, including static assets, so keep cookies small and serve assets from a cookieless domain or path.
- Native apps:
HTTPCookieStoragewithURLSessionon iOS handles cookies automatically; OkHttp needs aCookieJar. Most mobile APIs use tokens inAuthorizationinstead, with no cookie rules at all.
Predict the output
A page on http://127.0.0.1:8097 receives the four Set-Cookie headers below, then runs document.cookie. What does it get?
Set-Cookie: plain=1
Set-Cookie: lax=1; SameSite=Lax
Set-Cookie: none=1; SameSite=None; Secure
Set-Cookie: ho=1; HttpOnlyHttpOnly hides ho from JavaScript; it still goes to the server with every request. That's the point: an injected script can read everything else, but not the session cookie. This was run in Chrome, which treats 127.0.0.1 and localhost as secure, so the Secure cookie was accepted over plain HTTP on this local address.
// Android: OkHttp sends no cookies unless you give it a CookieJar
val client = OkHttpClient.Builder()
.cookieJar(JavaNetCookieJar(CookieManager())) // in memory; persist it for real apps
.build()// Express: a session cookie with the safe attributes
res.cookie('__Host-session', sessionId, {
httpOnly: true,
secure: true,
sameSite: 'lax',
path: '/',
maxAge: 30 * 24 * 3600 * 1000, // milliseconds in Express
});
// logging out: overwrite with the same name and attributes, already expired
res.clearCookie('__Host-session', { httpOnly: true, secure: true, sameSite: 'lax', path: '/' });The cookie any script can steal
Tap the line with the bug.
app.post('/login', async (req, res) => {
const user = await checkPassword(req.body.email, req.body.password);
if (!user) return res.status(401).end();
const sessionId = await sessions.create(user.id);
res.set('Set-Cookie', 'session=' + sessionId + '; Path=/; Max-Age=2592000');
res.redirect('/');
});Hint: Read the cookie's attributes. Who can read it, and over which connections is it sent?
The session cookie has no protective attributes:
- Without
HttpOnly, any JavaScript on the page can read it. One cross-site scripting bug (a review that contains a script, a compromised analytics library) sendsdocument.cookieto an attacker, who is then logged in as the user for 30 days. - Without
Secure, the browser also sends it over plainhttp://, for example on a hotel network before the redirect to HTTPS. - Without
SameSite, the browser appliesLax, which is a decent default, but say it explicitly so the behaviour doesn’t depend on the browser.
res.cookie('__Host-session', sessionId, {
httpOnly: true, secure: true, sameSite: 'lax', path: '/', maxAge: 30 * 24 * 3600 * 1000,
});Also regenerate the session ID at login (never reuse one that existed before), so an ID planted by an attacker before login is worthless.
Deep diveSubdomains, cookie scope and session fixationInterview favorite
“Our marketing site at blog.shop.example runs a third-party CMS. Is the shop’s session at risk?” This tests whether you know how cookies cross subdomains.
- Reading: a cookie set by
shop.examplewithDomain=shop.exampleis sent to every subdomain, includingblog.shop.example. If the CMS is compromised, or logs request headers, the session leaks. A cookie set withoutDomainis host-only and goes nowhere else. So: never setDomainon session cookies unless you need it. - Writing: any subdomain can set a cookie for the parent domain. JavaScript on
blog.shop.examplecan rundocument.cookie = "session=attacker-id; Domain=shop.example; Path=/". If the shop accepts a session ID it didn’t just issue, the user logs in to the attacker’s session (session fixation), or a shadowing cookie breaks login. The__Host-prefix stops this: the browser rejects any__Host-cookie that has aDomainattribute or lacksSecure, so subdomains can’t plant one. - SameSite doesn’t help here:
blog.shop.exampleis the same site asshop.example, so its requests carry Lax and even Strict cookies. Same-site isn’t same-trust. - Takeovers: a dangling DNS record (
old.shop.exampleCNAME to a deleted cloud bucket that someone else can claim) gives an attacker a subdomain, with all the powers above.
Recommendations: __Host- session cookies, regenerate session IDs on login and privilege changes, host untrusted content on a separate registrable domain (that’s why user content lives on domains like githubusercontent.com), and audit DNS for dangling records.
- Origin = scheme + host + port (CORS); site = scheme + registrable domain (SameSite). Subdomains are same-site.
- Session cookie:
__Host-prefix,Secure,HttpOnly,SameSite=LaxorStrict, noDomain, regenerate on login. - Default is Lax (with the 2-minute Lax+POST exception for cookies without the attribute).
NonerequiresSecure; third-party cookies blocked in Safari and Firefox;Partitionedfor embeds. - Native:
HTTPCookieStorageautomatic on iOS, OkHttp needs aCookieJar; most mobile APIs use bearer tokens.
Set-Cookie: __Host-session=8f2c91d4; Path=/; Max-Age=2592000; Secure; HttpOnly; SameSite=LaxCheck this part
Which attribute stops JavaScript on the page from reading a cookie?
A cookie has no SameSite attribute. How do modern browsers treat it?
Are api.shop.example and www.shop.example the same site? The same origin?
What does the __Host- prefix guarantee?