HttpOnly / SameSite Cookies
Session cookies are XSS’s ultimate prize. Set them HttpOnly, Secure, SameSite=Lax; rotate on login; bind to fingerprint when stakes are high. Done right, a compromised JS context can’t steal them.
A hardened session cookie config
EXAMPLE
// Express + cookie-session — every flag that matters
import cookieSession from 'cookie-session';
app.use(cookieSession({
name: 'sid',
keys: [process.env.SESSION_KEY_NEW, process.env.SESSION_KEY_OLD],
maxAge: 24 * 60 * 60 * 1000, // 24h absolute timeout
sameSite: 'lax', // 'strict' for high-stakes apps
secure: true, // HTTPS-only
httpOnly: true, // No JS access
path: '/',
domain: '.example.com',
}));
// On the Set-Cookie header directly
Set-Cookie: sid=<random>;
HttpOnly;
Secure;
SameSite=Lax;
Path=/;
Max-Age=86400;
Priority=High;
Partitioned; // CHIPS — third-party context
// Rotation discipline
// • Issue a fresh session ID on EVERY login
// • Rotate on privileged actions (password change, 2FA enrol)
// • Invalidate sibling sessions on password change
// • Idle timeout (e.g. 30 min) + absolute timeout (e.g. 24h)
// Token binding — optional, defence in depth
// • Bind the session to a hash of (UA + Accept-Language + accept-encoding)
// • Rebind only after deliberate flows; otherwise reject and force re-auth
// Anti-fixation — never accept a session ID the client supplied
// ALWAYS rotate on login
// NEVER trust a sid that arrived before authentication
// CSRF defence layered on top — SameSite=Lax + token + Origin check.
// XSS still leaks short-lived JWTs in localStorage — keep tokens in HttpOnly cookies.
Why it matters
HttpOnly + SameSite=Lax + Secure + rotation on login. Those four turn a session cookie from “leakable on XSS” into “survivable on XSS”.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
// XSS can't read HttpOnly cookies from JS. Set-Cookie: sid=…; HttpOnly; Secure; SameSite=Lax; Path=/Try it Yourself »
Exercise
Stop JS from reading the session cookie.
Set-Cookie: sid=…;
; Secure
PascalCase.
Discussion
Loading…