Skip to the content

Lesson 198 of 296

HTTP caching: ETag and Cache-Control

What you will learn

  • Where HTTP responses can be cached
  • The Cache-Control header and its directives
  • ETags and conditional requests (304 Not Modified)
  • Last-Modified
  • Caching rules for different kinds of content
  • Cache busting with hashed file names
On this page

Where caching happens

An HTTP response can be stored and reused at several places between the server and the user:

CacheWhereShared?
Browser cacheThe user's browserPrivate to that user
CDN / proxy cacheServers close to users (Cloudflare, CloudFront, Fastly)Shared by many users
Reverse proxy cachenginx or Varnish in front of your appShared

The server controls caching with response headers.

Cache-Control

DirectiveMeaning
max-age=3600Fresh for 3600 seconds; reuse without asking the server
s-maxage=600Like max-age, but only for shared caches (CDNs)
publicAny cache, including CDNs, may store it
privateOnly the user's browser may store it (personal data)
no-cacheMay store, but must revalidate with the server before each use
no-storeNever store anywhere (sensitive data: bank pages, tokens)
must-revalidateOnce stale, must not be used without checking the server
immutableWill never change; do not even revalidate
stale-while-revalidate=60After it expires, may serve the stale copy for 60 more seconds while fetching a fresh one in the background

Trick question: no-cache does not mean "do not cache"; it means "always check first". no-store means do not cache.

ETag and conditional requests

An ETag (entity tag) is an identifier for a version of a resource, often a hash of the body:

HTTP/1.1 200 OK
ETag: "a1b2c3"
Cache-Control: no-cache

Next time, the browser asks: "I have version a1b2c3; has it changed?"

GET /api/products/42
If-None-Match: "a1b2c3"
  • Not changed: the server replies 304 Not Modified with no body. The browser uses its copy. Bandwidth saved.
  • Changed: normal 200 with the new body and new ETag.
TypeScript
import { createHash } from "node:crypto";
import type { Request, Response } from "express";

export function sendWithEtag(req: Request, res: Response, data: unknown): void {
  const body = JSON.stringify(data);
  const etag = `"${createHash("sha1").update(body).digest("base64url")}"`;
  res.setHeader("ETag", etag);
  res.setHeader("Cache-Control", "private, no-cache");
  if (req.header("If-None-Match") === etag) {
    res.status(304).end();
    return;
  }
  res.type("application/json").send(body);
}

(Express can generate weak ETags automatically for res.send; this example shows the mechanism.) The server still builds the response to compute the hash, so ETags mainly save bandwidth. Storing a version number or updated_at per record lets you answer 304 without building the body.

ETags for safe updates: a client can send If-Match: "a1b2c3" with a PUT or PATCH. If someone else changed the resource meanwhile, the ETag differs and the server returns 412 Precondition Failed instead of overwriting their change. This is optimistic concurrency control over HTTP (Lesson 225).

Last-Modified

The older alternative: Last-Modified: Mon, 23 Nov 2026 10:00:00 GMT and the browser sends If-Modified-Since. Only accurate to one second; ETags are more precise.

Choosing caching rules

ContentHeaderWhy
Built JS and CSS with a hash in the name (app.3f9c2a.js)public, max-age=31536000, immutableThe name changes whenever the content changes
HTML pagesno-cache (or a short s-maxage on the CDN)Must pick up new deployments quickly
Public API data (product list)public, max-age=60, stale-while-revalidate=300Slightly stale is acceptable
User-specific API dataprivate, no-cache with ETagNever cached by a CDN; revalidated
Sensitive data (account balance, tokens)no-storeNever stored

Cache busting: build tools put a content hash in file names. When the file changes, its name changes, so the HTML refers to a new URL and the old cached file is simply never requested again. This is what makes year-long caching safe.

Danger: putting user-specific data in a public response cached by a CDN can show one user's data to another. Mark personal responses private or no-store, and be careful with CDN cache keys (Vary header: Vary: Accept-Encoding, Authorization tells caches that responses differ by those headers).

How to say it in an interview

"Responses can be cached by the browser, CDNs and reverse proxies, controlled by Cache-Control: max-age and s-maxage for freshness, public or private for who may store it, no-cache to always revalidate, no-store to never store, immutable for hashed assets, and stale-while-revalidate to serve stale content while refreshing. ETags identify a version; the client sends If-None-Match and gets 304 Not Modified with no body if unchanged, and If-Match on updates gives optimistic concurrency with 412. I use immutable year-long caching for content-hashed assets, no-cache for HTML, short public caching for public data, private for user data and no-store for sensitive data."

Key words

WordMeaning
Cache-ControlThe header that controls caching
no-cache vs no-storeRevalidate before use vs never store
ETagAn identifier for a version of a resource
Conditional requestA request with If-None-Match or If-Match
304 Not ModifiedYour cached copy is still valid
Cache bustingChanging file names when content changes
VaryTells caches which request headers change the response

Now prove it

This lesson is complete when you pass the quiz and all three practice levels.