HTTP, cookies and sessions

How the web remembers who you are, and how to configure session cookies so they stay safe.

Beginner30 min

Learning objectives

  • Explain why HTTP is stateless and how sessions solve that
  • Set cookie attributes that reduce XSS and CSRF risk
  • Generate and manage session identifiers correctly

HTTP is stateless

Every HTTP request is independent. The server does not remember the previous request unless the client sends something that links them. Sessions provide that link.

How a session works

  1. The user logs in with their credentials.
  2. The server creates a random session identifier and stores the user’s state on the server side.
  3. The server sends the identifier to the browser in a Set-Cookie header.
  4. The browser sends the cookie back automatically with every later request to that site.
HTTP/1.1 200 OK
Set-Cookie: sid=9f2c4e...b1; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=3600
Attribute What it does Protects against
HttpOnly Hides the cookie from document.cookie Session theft through XSS
Secure Sends the cookie only over HTTPS Interception on plain HTTP
SameSite=Lax or Strict Limits when the cookie is sent cross-site CSRF
Path / Domain Restricts where the cookie is sent Overly broad exposure
Max-Age / Expires Sets a lifetime Long-lived stolen sessions

Setting a cookie in Node with Express:

import { randomBytes } from 'node:crypto';

const sid = randomBytes(32).toString('base64url');

res.cookie('sid', sid, {
  httpOnly: true,
  secure: true,
  sameSite: 'lax',
  maxAge: 60 * 60 * 1000, // one hour, in milliseconds
});

Session identifier rules

  • Make them unguessable. Use at least 128 bits from a cryptographically secure random source such as crypto.randomBytes. Never use sequential IDs or timestamps.
  • Regenerate on login. Issue a new identifier after authentication to prevent session fixation, where an attacker plants a known ID in the victim’s browser.
  • Invalidate on logout on the server. Clearing the cookie in the browser is not enough, because a copied cookie would still work.
  • Use timeouts. Apply both an idle timeout and an absolute maximum lifetime.

Lab: inspect the cookies

Open a site you own or a local app you are running, then open DevTools → Application → Cookies. For each cookie, check:

  1. Is HttpOnly set on session cookies?
  2. Is Secure set?
  3. What is the SameSite value?
  4. How long does the cookie live?

Repeat the check on a public website and compare.

Key takeaways

  • Sessions are only as strong as their identifier and their cookie settings.
  • HttpOnly, Secure and SameSite are free protections. Use them on every session cookie.
  • Always invalidate sessions on the server.