Intermediate · Authentication and authorization · topic 32 of 54 · 30 min
Sessions and cookies
Explanation
HTTP has no memory
HTTP is stateless: each request stands alone, and the server does not remember the one before. So after you log in, something must remind the server on every later request that you are you. The classic answer is a session.
A session is a small record on the server, such as { userId: 42, expiresAt: ... }, saved under a long random id. A cookie is a small piece of text the server asks the browser to store and send back automatically with every request to that site.
A login, step by step
- The user sends email and password to POST /api/login.
- The server checks the password hash.
- It creates a session with a new random id and saves it in the session store.
- It replies with a Set-Cookie header holding the session id.
- The browser sends Cookie: sid=... with every later request.
- The server finds the session by id and knows the user.
HTTP/1.1 200 OK
Set-Cookie: sid=9f2c4e7a1b...; Path=/; Max-Age=86400; HttpOnly; Secure; SameSite=Lax
--- next request from the browser ---
GET /api/orders HTTP/1.1
Cookie: sid=9f2c4e7a1b...Where to keep sessions
| Store | Good | Watch out |
|---|---|---|
| Server memory (a Map) | Simple, fast, fine for learning | Lost on restart; does not work with two or more servers |
| Redis | Very fast; keys can expire by themselves (TTL) | One more service to run |
| Database table | Survives restarts; easy to list and revoke | A database read on every request |
Cookie flags that keep sessions safe
| Flag | What it does |
|---|---|
| HttpOnly | JavaScript in the page cannot read the cookie, so an XSS bug cannot steal it |
| Secure | Sent only over HTTPS, never plain HTTP |
| SameSite=Lax | Not sent with most requests started by other sites; helps against CSRF |
| Max-Age=86400 | Cookie expires after this many seconds (here 1 day) |
| Path=/ | Sent for every path on the site |
// Example only: runs on a server with Node.js and Express
res.cookie('sid', sessionId, {
httpOnly: true,
secure: true,
sameSite: 'lax',
maxAge: 24 * 60 * 60 * 1000, // Express takes milliseconds here
path: '/',
});Logout, expiry and session fixation
Logout must delete the session on the server, not just the cookie in the browser; otherwise a copied session id still works. Also give sessions an idle timeout (for example 30 minutes for a bank) and an absolute limit (for example 7 days).
Session fixation is an attack where someone plants a session id they know in your browser before you log in. If the server keeps the same id after login, the attacker is now logged in as you. The fix is simple: always create a brand-new session id at login (in Express: req.session.regenerate).
Watch the lesson
Sessions and cookies · 1/6
HTTP forgets you after every request. Sessions and cookies are how a server remembers who is logged in.
Prefer a video by a teacher? Find free videos on “session vs cookie authentication explained” on YouTube ↗
In real life: Net banking that logs you out
Bank websites keep you logged in with a session cookie that is HttpOnly and Secure. If you do nothing for a few minutes, the server ends the session, and the next click sends you to the login page. When you press Logout, the bank deletes the session on its server, so even someone who copied the cookie from your laptop cannot use it any more.
Practice (0/2 done)
Write buildSetCookie(name, value, maxAgeSeconds) that returns the Set-Cookie header value with the safe flags, in exactly this order: "sid=abc; Path=/; Max-Age=3600; HttpOnly; Secure; SameSite=Lax".
Write createSessionStore(ttlMs) that returns an object with three methods. createSession(userId, now) makes a random id (at least 32 hex characters, from crypto.getRandomValues), saves { userId, expiresAt: now + ttlMs } and returns the id. getSession(id, now) returns that saved object, or null if the id is unknown or now >= expiresAt (delete expired sessions). destroySession(id) removes the session. Time is passed in as now (milliseconds) so it can be tested.
Quick quiz
Read more (free)
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.