Sessions and cookies
HTTP is stateless: each request arrives on its own, with no memory of the previous one. So how does a website remember you're logged in? With a session: after login, the server stores who you are under a random session ID, and gives that ID to your browser in a cookie that comes back with every request.
How cookies work
The server sets a cookie with a Set-Cookie response header:
HTTP/1.1 200 OK
Set-Cookie: sid=hc2VjcmV0LXJhbmRvbQ; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=86400From then on, the browser automatically adds it to every request to that site:
GET /account HTTP/1.1
Cookie: sid=hc2VjcmV0LXJhbmRvbQCookie attributes
The attributes decide who can see the cookie and when it's sent. Getting them right is most of cookie security:
| Attribute | Effect | Recommended |
|---|---|---|
HttpOnly |
JavaScript can't read it (document.cookie), so an XSS bug can't steal it |
✔ always for session cookies |
Secure |
Only sent over HTTPS | ✔ always |
SameSite=Lax |
Not sent with cross-site POSTs, iframes or background requests; sent when following a link to your site | ✔ the default |
SameSite=Strict |
Never sent on cross-site requests, even links | Banking-style apps |
SameSite=None |
Always sent (requires Secure) |
Only for intentional cross-site use |
Max-Age / Expires |
When it expires; without them it's deleted when the browser closes | Match your session lifetime |
Domain |
Which hosts receive it; omitted means only this exact host | Omit unless subdomains need it |
Path |
Which URL paths receive it | / |
The __Host- name prefix (__Host-sid) makes the browser enforce Secure, Path=/ and no Domain, a cheap extra safeguard.
A session login, step by step
Notice the last request: because the session lives on the server, logging out truly ends it, even if someone kept a copy of the cookie. That's the big advantage of server-side sessions over self-contained tokens.
In real Express apps, use express-session with a store such as connect-redis. Django, Rails, Laravel and Spring all have sessions built in.
Session security rules
- Random, long IDs from a cryptographic generator (
crypto.randomBytes(32)), never user IDs or timestamps. - New session ID at login (and on privilege changes). If you keep a session ID created before login, an attacker who planted it in the victim's browser now shares their logged-in session: that's session fixation.
- Expire sessions: an idle timeout (say 30 minutes) and an absolute lifetime (say 7 days for "remember me").
- Invalidate on the server at logout and when the password changes (log out every other session).
- Store sessions in a shared store (Redis, a database) when you run several servers.
CSRF: the risk cookies bring
Browsers attach cookies automatically, even to requests started by another website. Without protection, a malicious page could contain:
<form action="https://bank.example/transfer" method="POST">
<input name="to" value="attacker"><input name="amount" value="5000">
</form>
<script>document.forms[0].submit()</script>If you're logged in to the bank, your cookie rides along and the transfer looks legitimate. This is Cross-Site Request Forgery (CSRF). Defences, from easiest:
SameSite=Laxcookies: the browser won't send the session cookie with that cross-site POST. This alone stops most CSRF.- CSRF tokens: put a random token in each form (and the session); reject state-changing requests without it. Frameworks such as Django and Rails do this automatically.
- Check
Origin/Sec-Fetch-Siteheaders on state-changing requests. - Never change state on GET requests.
The XSS, CSRF and CORS lesson covers this in depth.
Sessions or tokens?
| Server-side sessions | Self-contained tokens (JWT) | |
|---|---|---|
| Where the state lives | Server store (Redis, DB) | Inside the token |
| Instant logout / revocation | ✔ delete the session | ✖ valid until it expires (needs extra work) |
| Lookup per request | Yes (fast with Redis) | No |
| Works across many domains / services | Harder | Easier |
| Best for | Traditional and browser web apps | APIs, mobile apps, service-to-service calls |
For a website with its own backend, cookie sessions are simple and secure. Tokens shine when many independent services must verify identity. The next lesson covers JWTs.
Practice
- Add an absolute lifetime: sessions end 7 days after login, even with activity.
- Add
POST /logout-everywherethat deletes all sessions of the current user. - Rename the cookie to
__Host-sidand explain which attributes it requires.
1.What does the HttpOnly attribute protect against?
2.Why issue a new session ID right after login?
3.What stops most CSRF attacks in modern browsers with little effort?