Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 79 ยท Application Layer: Names and Web

Caching, Cookies and State

Learn how Cache-Control, ETag and conditional requests avoid repeated downloads, how proxies and CDNs share caches, and how cookies add state to stateless HTTP.

The fastest request is the one that never leaves your computer, and the cheapest response is the one a server does not have to build again. HTTP has a detailed caching system for exactly this: copies of responses can be kept by the browser, by proxies and CDNs, and each copy comes with rules about how long it is good and how to check that it is still correct.

HTTP is also stateless: the server treats every request as a stranger, as you saw in HTTP Fundamentals. Real sites need to remember who you are, what is in your cart and whether you are logged in. Cookies are the mechanism that adds state on top. In this lesson you learn both halves, because they interact: a cache that serves one user's personalized page to another user is a serious bug.

Why cache, and what can be cached

A cache stores a response and reuses it for later identical requests. That saves bandwidth, reduces server load and, most visibly, removes latency (no round trip at all if the copy is fresh). Not everything should be cached: usually only responses to GET (and HEAD) with certain status codes (200, 301, 404 and a few more) are stored, and a response to a POST generally is not.

There are two kinds of caches:

  • A private cache belongs to one user: the browser's cache. It may hold personalized content.
  • A shared cache serves many users: a company proxy, an ISP cache, or a CDN edge server. It must never keep or hand out content meant for one user only.
flowchart LR
    B["Browser<br/>(private cache)"] --> P["CDN / proxy<br/>(shared cache)"] --> O["Origin server"]
    O -. "response + caching rules" .-> P
    P -. "stored copy" .-> B

A request is answered by the first cache on the path that holds a usable copy.

Freshness: Cache-Control and max-age

The server controls caching with the Cache-Control response header, a comma-separated list of directives:

Directive Meaning
max-age=N The response is fresh for N seconds after it was generated. During that time a cache can reuse it without asking the server.
s-maxage=N Like max-age, but only for shared caches. It overrides max-age there.
public / private public allows shared caches to store it. private means only the user's own browser may store it (use it for personalized pages).
no-cache Despite the name, the response may be stored, but it must be revalidated with the server before every reuse.
no-store Do not keep it anywhere. Use it for sensitive data such as banking pages.
immutable The content will never change at this URL, so do not even revalidate on reload.
stale-while-revalidate=N A stale copy may be served for N more seconds while a fresh one is fetched in the background.

no-cache and no-store are the most confused pair. no-cache is about checking first; no-store is about never saving.

A cache keeps track of the response's age: the time since the origin generated it (the Age header adds the time spent in upstream caches). While age < max-age the copy is fresh. When it is stale, the cache does not simply throw it away. It asks the server whether it is still valid, which brings us to revalidation. First, a small decision function you can play with.

Node.js Is this cached copy fresh?

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.

Real caches also use heuristics when a response has no explicit lifetime (often a fraction of the time since Last-Modified), so you should always state your intent explicitly.

Cache busting for static files

A year-long max-age is great for speed but terrible if the file changes. The standard solution is to put a version or content hash in the file name (app.3f9c2a.js). A new build produces a new URL, so the old cached copy is simply never asked for again. The HTML page that references it is served with a short lifetime or no-cache, so users always find the new file names.

Revalidation: conditional requests

When a copy is stale, downloading the whole thing again would be wasteful if nothing changed. HTTP uses validators so a cache can ask "is my copy still current?" and get a tiny answer.

  • ETag is an opaque identifier for one version of the content (often a hash). Example: ETag: "a1b2c3".
  • Last-Modified is a timestamp, a weaker validator.

The cache then sends a conditional request:

HTTP
GET /news.json HTTP/1.1
Host: example.org
If-None-Match: "a1b2c3"

If the version on the server still has that ETag, the server answers 304 Not Modified with no body, and the cache uses its stored copy (updating the freshness information). If the content changed, the server replies 200 OK with the new body and a new ETag. If-Modified-Since works the same way with Last-Modified.

sequenceDiagram
    participant C as Cache
    participant S as Server
    C->>S: GET /news.json
    S-->>C: 200 OK, ETag "v1", body
    Note over C: later, the copy is stale
    C->>S: GET /news.json, If-None-Match "v1"
    S-->>C: 304 Not Modified (no body)
    Note over C: content changed on the server
    C->>S: GET /news.json, If-None-Match "v1"
    S-->>C: 200 OK, ETag "v2", new body

A 304 costs one round trip and a few hundred bytes instead of the full resource.

Below, a real server on loopback computes an ETag from the content and answers conditional requests. The client keeps its own small cache.

Node.js ETag and 304 Not Modified

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.

All four requests reached the server, but only two carried a body. That is the trade-off of no-cache revalidation: it keeps content correct at the cost of a round trip. A fresh max-age copy would have avoided the round trip entirely.

Vary: caching more than one version

The same URL can return different content depending on a request header, such as Accept-Encoding (gzip or Brotli) or Accept-Language. The server lists those headers in Vary: Accept-Encoding, and a cache then stores a separate copy per distinct value. Vary: * effectively disables sharing. A missing Vary is a classic cause of users receiving the wrong language or a compressed body they cannot read.

Cookies: adding state to HTTP

A cookie is a small piece of data that the server asks the browser to store and send back with later requests to the same site. The server sets it with a response header:

HTTP
HTTP/1.1 200 OK
Set-Cookie: sid=x7Kp29; Path=/; Max-Age=3600; HttpOnly; Secure; SameSite=Lax

On every following request to a matching URL the browser adds:

HTTP
GET /cart HTTP/1.1
Host: shop.example
Cookie: sid=x7Kp29

The cookie almost always holds just an opaque session ID. The real data (user, cart, login state) lives on the server in a session store, and the ID is the key. This is how a stateless protocol supports logins: each request carries the proof of which session it belongs to. Other uses are preferences and, controversially, tracking across sites.

The attributes decide where and for how long a cookie works:

Attribute Effect
Domain / Path Which hosts and URL paths the browser sends the cookie to. Without Domain it is limited to the exact host.
Max-Age / Expires Lifetime. Without either, it is a session cookie that disappears when the browser closes.
Secure Only sent over HTTPS.
HttpOnly Not readable from JavaScript (document.cookie), which limits theft through cross-site scripting.
SameSite Whether the cookie is sent on cross-site requests (see below).

The demo below shows the full round trip with a real loopback server: the first request gets a Set-Cookie, and the client stores it and sends it back.

Node.js A session cookie round trip

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.

SameSite and cross-site requests

By default, a browser attaches a site's cookies to any request to that site, even one triggered by a different site's page (an image, a form post, a link). Attackers abused this for cross-site request forgery (CSRF): a malicious page makes your browser submit a transfer form to your bank, and your bank cookie goes along. SameSite controls this:

  • SameSite=Strict: the cookie is sent only when the request starts from the same site. Even clicking a link to the site from elsewhere arrives without it, so the user may appear logged out for that first page.
  • SameSite=Lax: also sent on top-level navigations with safe methods (clicking a link), but not on cross-site subrequests or POST forms. Modern browsers treat a cookie without the attribute as Lax.
  • SameSite=None: always sent, but only allowed together with Secure. Needed for embedded third-party content and cross-site APIs.

"Same site" means the same registrable domain (such as example.org), so app.example.org and www.example.org are same-site, while example.org and example.com are not. A good default for a login cookie is HttpOnly; Secure; SameSite=Lax.

Caching and cookies together

Caches must not mix up users. Rules of thumb:

  • Pages that depend on the logged-in user should be Cache-Control: private (or no-store if sensitive), so a CDN does not store one user's page and serve it to another.
  • Many CDNs refuse to cache or bypass the cache when a request carries a session cookie, or they include the cookie in the cache key, which defeats sharing. Serve static assets from a cookie-free path or domain.
  • A Set-Cookie header in a response that is cached publicly is dangerous, because the cache could hand the same session ID to many users.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A response has Cache-Control: no-cache. What does a cache do?

    no-cache means 'check first'. The copy can be stored, and a 304 answer makes reuse cheap. no-store is the directive that forbids storing.
  2. 2. A cache sends If-None-Match with a stored ETag and gets 304. What happens next?

    A 304 response has no body. It tells the cache that its stored version is still valid.
  3. 3. What is the best way to let users get a new version of app.js quickly while keeping a year-long max-age?

    A new name is a new URL, so no cached copy can be reused by accident. The HTML that points to it is kept short-lived.
  4. 4. Why is the HttpOnly attribute useful on a session cookie?

    HttpOnly cookies are still sent with requests but cannot be read through document.cookie.
  5. 5. Which SameSite value is sent on a normal cross-site form POST?

    Strict and Lax withhold the cookie on cross-site POST subrequests. Only SameSite=None allows it, and it requires Secure.

Summary

  • Caches (private in browsers, shared in proxies and CDNs) reuse responses to save latency, bandwidth and server load.
  • Cache-Control sets freshness: max-age, s-maxage, public/private, no-cache (revalidate first) and no-store (never keep).
  • Stale copies are revalidated with ETag + If-None-Match (or Last-Modified + If-Modified-Since); a 304 Not Modified has no body. Vary makes caches store one copy per header value.
  • Version static file names to combine long lifetimes with instant updates.
  • Cookies add state to stateless HTTP, usually as a session ID. Use HttpOnly, Secure and SameSite to limit theft and CSRF.
  • Never let a shared cache store personalized responses.

Next, see the servers that sit in the middle of all this traffic in Proxies, Load Balancers and CDNs.