1st Principles

Web · 30 min read

Cookies and Sessions

How the web layers state onto a largely stateless protocol: cookies as client-stored tokens, sessions as server-side memory keyed by those tokens.

Why this exists

HTTP's core model is stateless: each request stands alone. But users need login continuity, shopping carts, and preferences across page loads.

Cookies and sessions are the dominant pattern for attaching just enough memory to a conversation without turning HTTP into a permanent circuit.

Getting scope and security attributes wrong is how accounts get stolen. This lesson treats state as a deliberate design, not a browser quirk.

Axioms & primitives

  1. 01A cookie is data the server asks the browser to store and resend on later requests to a scope.
  2. 02A session is server-side state indexed by an identifier, often carried in a cookie.
  3. 03Scope rules (Domain, Path, Secure, HttpOnly, SameSite) define when cookies are sent.
  4. 04Bearer tokens in headers are an alternative pattern with different tradeoffs.
  5. 05State on the client can be stolen or forged if integrity and scope are weak.
  6. 06HTTPS matters: Secure cookies should not ride cleartext HTTP.

Learning objectives

After this lesson you should be able to:

  • Explain how a session cookie turns a sequence of HTTP requests into a logged-in experience.
  • Choose Secure, HttpOnly, and SameSite attributes for a login cookie and justify each.
  • Contrast server-side sessions with storing all state in a signed client cookie.
  • Describe a CSRF attack path at a high level and which cookie attribute mitigates the classic form case.
  • Predict when a cookie will not be sent on a cross-site request.

Progressive depth

Read the layers in order for a full explanation. Or open the layer you need.

01

Intuition

You log in once. Later clicks still know who you are. Under the hood, the server set a cookie: a small token your browser stores and resends. The server looks up that token and restores your session.

Without something like this, every request would need to re-send username and password, or the server would have to recognize your TCP connection forever (it will not).

The danger is obvious: whoever holds the token is you, as far as the server can tell.

02

Formal shape

Set-Cookie in a response installs a cookie. Cookie request headers send matching cookies back. Attributes control lifetime (Max-Age/Expires), Domain/Path scope, Secure, HttpOnly, SameSite, and Priority in some browsers.

Server-side sessions store data keyed by an opaque ID. Client-side sessions store signed/encrypted payloads in the cookie itself; size and revocation tradeoffs differ.

SameSite=Lax/Strict/None changes cross-site sending behavior. None requires Secure. CSRF defenses also include anti-CSRF tokens and Fetch metadata checks.

Logout should invalidate server session state, not only ask the browser to delete a cookie.

Login session cookie path

Click a stage to follow the login flow this page's worked examples spell out.

Loading diagram...

Select a stage to read the boundary detail.

03

Worked examples

Login flow: POST credentials -> server creates session -> Set-Cookie: session=...; HttpOnly; Secure; SameSite=Lax -> subsequent GETs include Cookie header.

Shopping cart without login: cookie holds a cart ID referencing server state, or a signed cart blob. Clearing cookies empties the cart from the user's point of view.

CSRF sketch: evil page triggers a POST to bank.example while the browser attaches bank cookies. SameSite and CSRF tokens break that pattern.

API alternative: Authorization: Bearer <token> stored by a careful client. Mobile apps often prefer this over cookie jars; browsers still often use cookies for first-party web apps.

04

Edge cases

Third-party cookie deprecation changes advertising and some embed auth flows; first-party session cookies remain central.

Subdomain cookie scope mistakes can leak sessions across apps. Prefer host-only cookies when possible.

Session fixation: issue a fresh session ID after privilege changes like login.

Clock skew and Max-Age versus Expires quirks still appear in the wild. Prefer Max-Age for simplicity when you can.

Mental models

  • Coat check ticket

    The cookie is the ticket. The coat (session data) stays behind the counter (server). Losing the ticket loses access; stealing the ticket steals access.

  • Sticker on every form

    Browsers automatically attach matching cookies to requests. That convenience is also why CSRF exists.

  • Passport with visas

    Attributes are visas: Secure, Domain, Path, SameSite restrict where the passport is shown.

Common misconceptions

  • Myth

    Cookies are only for ads.

    Reality

    Ads use them, but so do logins, preferences, and CSRF tokens. The mechanism is general.

  • Myth

    HttpOnly cookies cannot be stolen.

    Reality

    HttpOnly blocks JavaScript access; network attackers on HTTP, malware, and XSS into other storage still matter. It is necessary, not sufficient.

  • Myth

    LocalStorage is a safer place for session tokens than cookies.

    Reality

    LocalStorage is available to JS and often worse for XSS. Prefer well-scoped HttpOnly cookies for session IDs unless you have a deliberate token design.

  • Myth

    Clearing cookies 'logs everyone out of the server.'

    Reality

    It removes the client's key to the session. Server sessions may linger until expiry or revocation.

Exercises

Work these without looking up answers first. Check yourself against the intent notes.

  1. Exercise 01

    Design attributes for a session cookie on https://app.example.com that should not be readable by JavaScript or sent on cross-site POSTs from other sites.

    What good looks like

    Secure; HttpOnly; SameSite=Strict or Lax with CSRF tokens; host-only domain; sensible Path.

  2. Exercise 02

    A user clicks Log out but an old session ID still works from another computer. What did the server fail to do?

    What good looks like

    Did not invalidate server-side session; only cleared one browser's cookie.

  3. Exercise 03

    Why is putting a long-lived access token in LocalStorage risky on an XSS-prone SPA?

    What good looks like

    Any script can read it; XSS becomes instant account theft. Prefer HttpOnly cookies or tighter token design + strong XSS defense.

Sources & further reading

External references. Prefer primary documents and clear explainers.

Go deeper on your own

These picks go past the foundation in this lesson. Use them when you want a primary spec, official docs, or a longer walkthrough.