Sessions and cookies: keeping users logged in safely
After login, a session cookie is the user's identity. Which cookie flags protect it from XSS, network sniffing and cross-site requests, and the session lifecycle rules that stop fixation and hijacking.
In one sentence
A session cookie is as good as a password while it's valid. Ship it as HttpOnly; Secure; SameSite=Lax, keep it short-lived, and rotate it on login and privilege changes.
The flags
HTTP is stateless, so after you log in the server gives your browser a random session ID in a cookie and looks it up on every request. Whoever has that value is you. The cookie's attributes decide who can read it and when the browser sends it.
| Attribute | Protects against |
|---|---|
| HttpOnly | JavaScript (and so XSS) reading the cookie |
| Secure | Sending it over plain http:// where it can be sniffed |
| SameSite=Lax / Strict | Other sites making requests with it (CSRF) |
| Max-Age / Expires | A stolen cookie staying valid forever |
| __Host- prefix | Subdomains overwriting it; forces Secure, Path=/ and no Domain |
Session lifecycle
- Rotate the ID on login (and on role changes). Otherwise an attacker who planted a session ID before login gets a logged-in one after: session fixation.
- Idle and absolute timeouts: expire after 30 minutes of inactivity and after N days regardless.
- Logout means server-side delete, not just clearing the cookie.
- Re-authenticate for sensitive actions: changing email, password or payout details asks for the password or MFA again.
- Show active sessions so users can sign out of devices they don't recognize.
Set-Cookie: __Host-session=8f3a2c…; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=3600Key takeaways
- 01Whoever holds a valid session cookie is the user.
- 02Use HttpOnly, Secure, SameSite=Lax and a __Host- prefix.
- 03Rotate the session ID on login and privilege changes.
- 04Expire sessions, delete them on logout and re-authenticate for sensitive actions.
Check your understanding
1 of 3
Who is the user, as far as the server knows?
Related concepts
CSRF
Cookies prove which browser sent a request, not which site asked for it. SameSite cookies and CSRF tokens tell your server the request really came from your own pages.
6 min read →XSS
XSS is injection into HTML instead of SQL. Escape output by default, never inject raw HTML, and add a Content Security Policy as the safety net.
8 min read →JWT
A JWT is base64, not encryption: anyone can read it. Its signature only proves the server issued it, and only if you verify it with a fixed algorithm and check the expiry.
8 min read →