Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 39 ยท Authentication Basics

Sessions and Cookies

Learn how cookie-based sessions work: Set-Cookie attributes (HttpOnly, Secure, SameSite), session stores, login and logout, session fixation, CSRF and when sessions fit an API.

HTTP is stateless: each request stands alone. Yet after you log in to a website, the site somehow keeps recognising you. The classic mechanism is the session: the server remembers who you are, and gives your browser a small, meaningless identifier, a session id, stored in a cookie. On every later request the browser sends the cookie back automatically, and the server looks up the session.

Sessions are the oldest and still one of the best ways to authenticate browser users: the server stays in control (it can end a session at any moment) and the secret never touches JavaScript. This lesson shows exactly how they work and how to make them secure.

The session flow

sequenceDiagram
    participant B as Browser
    participant S as Server
    participant D as Session store
    B->>S: POST /login (email + password)
    S->>D: create session {userId: 7}
    S-->>B: 200 + Set-Cookie: sid=abc123; HttpOnly; Secure; SameSite=Lax
    B->>S: GET /me + Cookie: sid=abc123
    S->>D: lookup abc123
    D-->>S: {userId: 7}
    S-->>B: 200 {"name": "Ada"}
    B->>S: POST /logout + Cookie
    S->>D: delete session
    S-->>B: Set-Cookie: sid=; Max-Age=0

The cookie holds only a random id; all the data stays on the server.

Because the id is just a random key into a server-side table, the user data is never in the cookie, the user cannot tamper with it, and logging out (deleting the row) really ends the session on the server.

Cookies and their attributes

The server creates a cookie with a Set-Cookie response header; the browser returns it in a Cookie request header for matching requests.

HTTP
Set-Cookie: sid=Xk3p...; Path=/; HttpOnly; Secure; SameSite=Lax; Max-Age=3600
Attribute Purpose
HttpOnly JavaScript cannot read the cookie (document.cookie), blunting XSS-based session theft. Always set for session cookies
Secure Sent only over HTTPS
SameSite=Lax / Strict / None Controls whether the cookie is sent on cross-site requests; the main CSRF defense. Lax is a good default; None requires Secure
Max-Age / Expires Lifetime. Omit both for a session cookie that disappears when the browser closes
Path URL prefix the cookie applies to (usually /)
Domain Which hosts receive it. Leave unset to restrict to the exact host
__Host- name prefix Forces Secure, Path=/ and no Domain: __Host-sid is the safest name

Building and parsing cookies

Cookies are simple enough to handle with two small functions. Real servers use a library, but doing it once by hand clarifies what travels on the wire:

Node.js Serialise and parse cookies

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Session ids must be unguessable

If an attacker guesses or steals a session id, they are that user. The id must come from a cryptographically secure random generator and carry at least 128 bits of entropy: crypto.randomBytes(32).toString('base64url'). Never use incrementing numbers, timestamps or user ids. Store sessions server-side in memory (development only), a database or, most commonly, Redis, which also gives automatic expiry.

A complete session login API

The server below implements POST /login, GET /me, and POST /logout with an in-memory session store. fetch in Node does not keep cookies for you, so the client keeps a tiny cookie jar by hand: it saves the cookie from Set-Cookie and sends it back, exactly as a browser does. Security details to spot in the code:

  • A new session id is created at login (it never reuses an id the client sent), which prevents session fixation, where an attacker plants a known id before the victim logs in.
  • Sessions have an absolute lifetime and are deleted on logout.
  • The cookie is HttpOnly, SameSite=Lax (and Secure in production).
  • Failed logins give a generic message.
Node.js Login, session cookie and logout

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The final replay of the copied cookie fails, because logout destroyed the server-side record. This is the key advantage of sessions over self-contained tokens, which you will compare in the next chapter.

Browsers attach cookies automatically, even when the request was triggered by another site. A malicious page can make the victim's browser send POST https://bank.example/transfer, and the session cookie rides along. This is cross-site request forgery (CSRF). Defenses, in layers:

  1. SameSite=Lax (now the browser default) stops cookies on most cross-site POSTs. Use Strict for very sensitive apps.
  2. Anti-CSRF tokens: the server issues a random token bound to the session; state-changing requests must echo it in a header or form field, which another origin cannot read.
  3. Check Origin/Referer headers on unsafe methods.
  4. Never change state with GET (see HTTP methods).
  5. Require a custom header (for example X-Requested-With) on JSON APIs; cross-site forms cannot set it without a CORS preflight.

APIs that authenticate with an Authorization header (not cookies) are not vulnerable to CSRF, because the browser does not attach that header automatically. That is one reason APIs consumed by mobile apps and SPAs often prefer tokens.

Sessions versus tokens

Server-side sessions Self-contained tokens (e.g. JWT)
State On the server (store lookup per request) In the token; server may be stateless
Revocation Immediate: delete the record Hard: wait for expiry or keep a deny-list
Scaling Needs shared store (Redis) Any server can verify
Browser fit Excellent (HttpOnly cookie) Needs care where to keep the token
Mobile / third-party clients Less natural Natural

For a first-party web app talking to its own backend, sessions are usually the simplest and safest choice. For APIs used by mobile apps, other services or third parties, tokens (next chapter) fit better. Many systems use both.

Session hardening checklist

  • Random 128-bit+ ids; regenerate the id on login and on privilege change.
  • HttpOnly, Secure and SameSite set; prefer the __Host- prefix.
  • Idle timeout (for example 30 minutes) and an absolute timeout (for example 12 hours).
  • Destroy server-side on logout; offer "log out everywhere" by deleting all of a user's sessions.
  • Do not put secrets or personal data in the cookie, and never in the URL.
  • Rate-limit login, and require reauthentication for sensitive actions (change password, delete account).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the HttpOnly cookie attribute do?

    HttpOnly hides the cookie from document.cookie. The browser still sends it with requests.
  2. 2. Why create a new session id at login?

    If the server reused an id supplied before login, an attacker who planted it would share the victim's authenticated session.
  3. 3. After logout, a copied old session cookie is sent again. What should happen with server-side sessions?

    Deleting the server-side record revokes the session immediately, which is a major advantage of sessions.
  4. 4. Which attribute is the main built-in defense against CSRF?

    SameSite controls whether cookies are sent on cross-site requests. Anti-CSRF tokens add another layer.
  5. 5. Why is an API that authenticates only with an Authorization header not vulnerable to CSRF?

    CSRF abuses automatic cookie sending. A header must be added explicitly by script from an allowed origin.

Summary

  • A session stores identity on the server; the browser holds only a random session id in a cookie.
  • Set HttpOnly, Secure and SameSite (and prefer the __Host- prefix); use 128-bit random ids from crypto.randomBytes.
  • Regenerate the id at login, enforce idle and absolute timeouts and delete the server record on logout.
  • Cookies are sent automatically, so defend against CSRF with SameSite, tokens, origin checks and safe GETs.
  • Sessions suit first-party browser apps; tokens suit mobile and third-party clients, which the next chapter covers.

Next: JSON Web Tokens (JWT) Explained