Cookies and sessions

Your login lives in one small cookie. Watch six ways to steal or misuse it, and the one rule that stops each. Then turn the rules on yourself, and compare a session cookie with a JWT kept in two different places.

Level: IntermediateWatch: 16 steps · ~80 secondsTurn rules on, attackRecall: 3 questions · 8 cardsCompare 4 places for the loginTypeScript · nginx

What you'll take away

  • Set HttpOnly, Secure, SameSite=Lax and __Host-, and say what each one stops
  • Explain why HttpOnly keeps XSS from taking the cookie but not from acting as you
  • Know why login needs a new session id and log out must delete it on the server
  • Choose a session cookie or a token, and say why localStorage is the risky place

The 1-minute version

Tap a point and the picture below plays that step.

4Compare them all
your session 
your browser
bank.example tabbank
evil.example tabevil
café Wi-FiWi-Fi
bank.example
blog.bank.exampleblog
sessions(none)
attacker
cookie(no cookie)HttpOnlySecureSameSite=Lax
POST /login → …
Step 1 / 16 · step by step
0attacks that worked
0blocked
0 / 6rules on
—the browser's cookie
0sessions on the server

The picture: your browser is the yard at the front of the city, with a tab of bank.example and a tab on evil.example (red) standing in it as houses. Every request leaves by one street, past a café's Wi-Fi on the corner, to bank.example on the back street, with its session store and its blog subdomain beside it; the attacker has a red building on a road of his own. Each step is one event, a light on the street, and a gold light rides along whenever the cookie goes too. The board over the yard is the browser's cookie and its flags; the label over the store lists the sessions the bank keeps. Each attack lands once, then meets the rule that stops it. The verdicts follow the cookie standard (RFC 6265bis), not a measurement.

Step 4 · Every option at once, on one clock

Compare them all: Where the login lives

The same six attacks, one lane at a time, in every tile. A red dot runs at your login: where a rule stands it hits a wall, where none does it gets through.

Attack 1 / 6: a script reads it
A bare cookiesid=…, no flags, log out in the browser onlyworked 0 · blocked 0

Use it when Nowhere: it's here so you can see what each rule stops

Skip it when Everywhere. Unless the browser defaults SameSite for you (Chrome and Edge treat it as Lax, not every browser does), every attack lands

A model of the browser's and server's rules from the cookie standard (RFC 6265bis), not measured in a browser. In every tile, XSS can still act as you while it runs; HttpOnly only stops it reading the cookie out. Press any tile to see it large above, with when it fits.

Six rules, six attacks

RuleStopsWhere
HttpOnlya script reading the cookie (XSS)Set-Cookie
Securesniffing on plain httpSet-Cookie
SameSite=Laxa form or fetch from another site (CSRF)Set-Cookie
a new id at logina planted id (session fixation)the server
delete at log outa copy used after log outthe server
__Host- prefixa subdomain writing over itthe cookie's name

An id, not the data

A session cookie should hold a long random id and nothing else. The user, the role and the cart stay on the server, where nobody can edit them. Give it a short life and an idle timeout, so a forgotten tab doesn't stay logged in for a week.

HttpOnly doesn't fix XSS

It stops a script from reading the cookie and taking it away. It doesn't stop the script from sending requests as you while it runs on the page, because the browser attaches the cookie anyway. Close the XSS itself as well.

Session or token?

If your pages and your API share a site, a hardened session cookie is the simple choice, and log out is instant. Tokens fit APIs that apps and other domains call. If a browser has to keep one, an HttpOnly cookie is safer than localStorage, which any script on the page can read.

In real code

session.ts
// A session cookie with every rule on: __Host- name, Secure, HttpOnly, SameSite=Lax, a short life, a new id at login,
// log out deleting the session on the server, and an idle timeout. A real node:http server on 127.0.0.1, real fetch calls.
// Run: node session.ts   (Node 23.6+; on Node 22: node --experimental-strip-types session.ts)
import assert from "node:assert/strict";
import { randomBytes } from "node:crypto";
import { createServer, type IncomingMessage } from "node:http";
import type { AddressInfo } from "node:net";

const IDLE = 30 * 60, ABSOLUTE = 8 * 3600; // seconds
let now = 1_700_000_000; // a clock the demo can move forward
const sessions = new Map<string, { user: string; created: number; seen: number }>(); // in real life: Redis or a table

const cookieOf = (req: IncomingMessage) => (req.headers.cookie ?? "").match(/(?:^|;\s*)__Host-sid=([\w-]+)/)?.[1];
const setCookie = (id: string, maxAge: number) => `__Host-sid=${id}; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=${maxAge}`;

const server = createServer((req, res) => {
  const id = cookieOf(req);
  if (req.method === "POST" && req.url === "/login") {
    if (id) sessions.delete(id); // whatever id came in (maybe planted) is never the logged-in one
    const fresh = randomBytes(32).toString("base64url"); // 256 random bits: nothing to guess
    sessions.set(fresh, { user: "mai", created: now, seen: now });
    res.writeHead(204, { "set-cookie": setCookie(fresh, IDLE) });
    return res.end();
  }
  if (req.method === "POST" && req.url === "/logout") {
    if (id) sessions.delete(id); // on the server, not just in the browser
    res.writeHead(204, { "set-cookie": setCookie("", 0) });
    return res.end();
  }
  const s = id ? sessions.get(id) : undefined;
  if (!s || now - s.seen > IDLE || now - s.created > ABSOLUTE) { if (id) sessions.delete(id); res.writeHead(401); return res.end(); }
  s.seen = now;
  res.writeHead(200, { "content-type": "application/json" });
  res.end(JSON.stringify({ user: s.user }));
});

await new Promise<void>((ok) => server.listen(0, "127.0.0.1", ok));
const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
const as = (sid?: string): Record<string, string> => (sid ? { cookie: `__Host-sid=${sid}` } : {});
const login = async (sid?: string) => (await fetch(`${base}/login`, { method: "POST", headers: as(sid) })).headers.getSetCookie()[0];
const me = async (sid: string) => (await fetch(`${base}/me`, { headers: as(sid) })).status;
const idOf = (header: string) => header.match(/__Host-sid=([\w-]+)/)![1];

const planted = "KNOWN1"; // an attacker got the browser to carry this before login
const header = await login(planted);
const sid = idOf(header);
const fixation = [sid !== planted, await me(planted)];
const mine = await me(sid);
const copy = sid; // someone copied the cookie
await fetch(`${base}/logout`, { method: "POST", headers: as(sid) });
const afterLogout = await me(copy);
const again = idOf(await login());
now += 31 * 60; // away from the keyboard for 31 minutes
const idle = await me(again);
server.close();

assert.equal(header.replace(sid, "…"), "__Host-sid=…; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=1800");
assert.deepEqual([fixation, mine, afterLogout, idle], [[true, 401], 200, 401, 401]);
console.log(`Set-Cookie: ${header.replace(sid, "…")} · planted id: a new one at login, the planted one 401 · /me 200 · the copy after log out 401 · idle 31 min 401`);
Run: node session.ts (Node 23.6+ · on Node 22 add --experimental-strip-types)It printed: Set-Cookie: __Host-sid=…; Path=/; Secure; HttpOnly; SameSite=Lax; Max-Age=1800 · planted id: a new one at login, the planted one 401 · /me 200 · the copy after log out 401 · idle 31 min 401

A real node:http server on 127.0.0.1: the __Host- cookie with Secure, HttpOnly and SameSite=Lax, 256 random bits for the id, a new id at login (a planted one gets 401), log out deleting the session on the server, and an idle timeout. Then real fetch calls to it.

Common questions

What do HttpOnly, Secure and SameSite each stop?

HttpOnly: scripts on the page can't read it. Secure: it's sent over https only, so nobody on the Wi-Fi can sniff it. SameSite=Lax: requests another site starts, like a POST or a fetch, go without it, which stops most CSRF.

Table: six rules, six attacks

Does HttpOnly stop XSS?

No. It stops a script from reading the cookie and taking it away. While the script runs on the page it can still send requests as you, because the browser attaches the cookie itself. Close the XSS too, with escaping and a CSP.

Read: HttpOnly doesn't fix XSS

What's the difference between SameSite=Lax and Strict?

Lax still sends the cookie when you follow a plain link to the site (a top-level GET), but not with a POST, fetch or iframe from another site. Strict sends nothing for anything another site starts, so following a link from another site opens the first page logged out.

Why issue a new session id at login?

To stop session fixation: the attacker gets your browser to use an id they know, then waits for you to log in with it. A new id at login makes theirs worthless. Do the same whenever privileges change.

After log out, does a copied cookie still work?

It depends on the server. If log out only clears the browser's cookie, a leaked copy still works. Delete the session on the server and it dies at once. A JWT has nothing to delete: it works until it expires, unless you keep a denylist.

What does the __Host- prefix on a cookie's name do?

The browser accepts a cookie with that name only with Secure, Path=/ and no Domain, so only that exact host can set it. A hacked subdomain like blog.bank.example can't write over it.

Session cookie or JWT: which one?

If your pages and your API share a site, a hardened session cookie: simple, and log out is instant. For an API that mobile apps or other domains call, a short-lived token plus a refresh token.

Read: session or token?

Is it OK to keep a JWT in localStorage?

You can, but any script on the page can read it: one XSS and the token is gone. The upside is no CSRF, since the browser never attaches it for you. If the browser has to hold one, an HttpOnly cookie is safer.

Next lesson

API securityLevel: Intermediate

Your login is safe in its cookie or token; next, what an API checks on every call: who you are, what you may do, how often.