Skip to content

Intermediate · Authentication and authorization · topic 32 of 54 · 30 min

Sessions and cookies

Explanation

HTTP forgets you after every request, so after login the server creates a session and gives the browser a random session id in a cookie. The browser sends the cookie back with each request, and the server looks up who you are. Safe cookies use HttpOnly, Secure and SameSite, and logout destroys the session on the server.

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.

Think of it like this: A session is like the shoe stand outside a temple. You hand over your shoes and get a token with a number. The token alone is worthless; the stand keeps the shoes. Show the token and you get your shoes back. The session id is the token, the session store is the rack.

A login, step by step

  1. The user sends email and password to POST /api/login.
  2. The server checks the password hash.
  3. It creates a session with a new random id and saves it in the session store.
  4. It replies with a Set-Cookie header holding the session id.
  5. The browser sends Cookie: sid=... with every later request.
  6. The server finds the session by id and knows the user.
output
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...
The server sets the cookie once; the browser sends it back every time.

Where to keep sessions

StoreGoodWatch out
Server memory (a Map)Simple, fast, fine for learningLost on restart; does not work with two or more servers
RedisVery fast; keys can expire by themselves (TTL)One more service to run
Database tableSurvives restarts; easy to list and revokeA database read on every request

Cookie flags that keep sessions safe

FlagWhat it does
HttpOnlyJavaScript in the page cannot read the cookie, so an XSS bug cannot steal it
SecureSent only over HTTPS, never plain HTTP
SameSite=LaxNot sent with most requests started by other sites; helps against CSRF
Max-Age=86400Cookie expires after this many seconds (here 1 day)
Path=/Sent for every path on the site
javascript
// 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: '/',
});
Setting a session cookie with the safe flags in Express.

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).

Careful: Session ids must be long and random (at least 128 bits from crypto.getRandomValues or crypto.randomBytes). Never use the user id, a counter or Math.random as a session id.
Tip: Name your cookie with the __Host- prefix (for example __Host-sid). Browsers then insist on Secure, Path=/ and no Domain, which blocks some subdomain tricks.

Watch the lesson

Sessions and cookies · 1/6

Sessions and cookies

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)

Task 1 · Code · Javascript

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".

Task 2 · Code · Javascript

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

Question 1

1.What does "HTTP is stateless" mean?

Question 2

2.Which cookie flag stops page JavaScript from reading the cookie?

Question 3

3.What must the server do when a user logs out?

Question 4

4.How do you stop session fixation?

Question 5

5.Your app runs on three servers. Where should sessions be stored?

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.

← Previous: Storing passwords safely