How-To Guide

Configuring Cache-Control and Stale-While-Revalidate

Combine s-maxage, stale-while-revalidate, CDN-Cache-Control, and immutable asset rules to speed up edge hits without serving stale user data.

On this page

  1. Why One-Size-Fits-All Caching Breaks Either Speed or Privacy
  2. The Four Essential Production Cache Profiles
  3. Implementing Route-Scoped Cache Middleware and ETag Validation
  4. Edge Caching Pitfalls: Cookies, Vary, and Query Strings
  5. Verifying Edge Behavior with Live Header Probes

Why One-Size-Fits-All Caching Breaks Either Speed or Privacy

Shipping an application without deliberate Cache-Control headers leaves performance and security up to browser and CDN guesswork. On one extreme, slapping Cache-Control: no-store globally forces every static script, font, and product catalog JSON request back to your origin database, driving up cloud egress and p99 latency. On the opposite extreme, setting Cache-Control: public, max-age=86400 indiscriminately across SSR routes risks caching an authenticated user’s /account/profile HTML page inside a shared CDN edge POP and serving Alice’s billing address to Bob.

Correct HTTP caching requires matching directive combinations strictly to route semantics: fingerprinted static files stay cached forever with immutable, shared public catalog pages pair crisp browser lifetimes with edge stale-while-revalidate (SWR), and authenticated endpoints declare private, no-store explicitly so shared proxies never store them.

You can compose syntactically valid header strings and catch contradictory directives (such as combining public with private or no-store with max-age) immediately in the Interactive Cache-Control Builder.

The Four Essential Production Cache Profiles

Nearly every modern web application maps cleanly onto four repeatable Cache-Control profiles:

  1. Content-hashed static assets (/_astro/app.9f4a21c.js, /fonts/ibm-plex.woff2): Cache-Control: public, max-age=31536000, immutable Because filenames embed a content hash that changes whenever code changes, browsers can cache them for a full year without sending conditional If-None-Match revalidation requests on page reloads (immutable stops F5 reloads from revalidating unchanged bundles).
  2. Un-hashed public assets (/favicon.svg, /og-default.png, /explore/resources.json): Cache-Control: public, max-age=3600, stale-while-revalidate=86400 Allows one hour of fresh reads plus instantaneous background refresh for a full day when content updates.
  3. Dynamic public HTML / JSON pages behind Cloudflare: Cache-Control: public, max-age=60, s-maxage=300, stale-while-revalidate=3600 Cloudflare-CDN-Cache-Control: max-age=600, stale-while-revalidate=3600 Browsers re-check after 60 seconds so users see fresh releases quickly, while Cloudflare edge nodes hold responses warm longer and refresh asynchronously behind the scenes via SWR without ever blocking visitors on origin cold starts.
  4. Authenticated user APIs & session endpoints (/api/me, /checkout): Cache-Control: private, no-store Forbids both shared edge caches and local disk caches from retaining any copy.

Notice the power of CDN-Cache-Control (RFC 9213) and Cloudflare-CDN-Cache-Control: they let you target CDN edge caches directly with longer max-age / stale-while-revalidate lifetimes without polluting downstream browsers’ Cache-Control headers—meaning a sudden cache purge at the CDN immediately serves fresh content to browsers whose max-age=0, must-revalidate or short max-age=60 expired cleanly!

Implementing Route-Scoped Cache Middleware and ETag Validation

Here is a clean TypeScript helper that assigns validated cache headers per route tier and supports weak/strong ETag conditional 304 Not Modified responses when no-cache or max-age expires:

import crypto from "node:crypto";
import type { IncomingMessage, ServerResponse } from "node:http";

export type CacheProfile = "immutable" | "swr-edge" | "revalidate" | "private-no-store";

const CACHE_HEADERS: Record<CacheProfile, Record<string, string>> = {
  immutable: {
    "Cache-Control": "public, max-age=31536000, immutable",
  },
  "swr-edge": {
    "Cache-Control": "public, max-age=60, s-maxage=300, stale-while-revalidate=3600",
    "Cloudflare-CDN-Cache-Control": "max-age=600, stale-while-revalidate=3600",
  },
  revalidate: {
    "Cache-Control": "public, no-cache",
  },
  "private-no-store": {
    "Cache-Control": "private, no-store",
    Pragma: "no-cache",
  },
};

export function sendWithCachePolicy(
  req: IncomingMessage,
  res: ServerResponse,
  body: string | Buffer,
  contentType: string,
  profile: CacheProfile,
): void {
  const headers = CACHE_HEADERS[profile];
  for (const [k, v] of Object.entries(headers)) {
    res.setHeader(k, v);
  }
  res.setHeader("Content-Type", contentType);

  if (profile === "private-no-store") {
    res.statusCode = 200;
    res.end(body);
    return;
  }

  // Generate strong ETag from payload hash for 304 conditional GETs
  const hash = crypto.createHash("sha256").update(body).digest("base64url").slice(0, 16);
  const etag = `"${hash}"`;
  res.setHeader("ETag", etag);

  const ifNoneMatch = req.headers["if-none-match"];
  if (ifNoneMatch && ifNoneMatch.split(",").map((t) => t.trim()).includes(etag)) {
    res.statusCode = 304;
    res.end();
    return;
  }

  res.statusCode = 200;
  res.end(body);
}

Notice two critical behaviors in sendWithCachePolicy: first, private-no-store skips generating ETag altogether so browsers cannot infer cached resource equality across auth changes; second, ifNoneMatch checks comma-separated tokens because proxies or browsers occasionally send multiple candidate tags inside If-None-Match. Also remember that on Cloudflare, enabling automatic email obfuscation or server-side compression can transform strong ETag tags into weak tags (W/"..."), so handle weak-tag stripping (tag.replace(/^W\//, "")) if your origin relies strictly on byte-identical comparisons.

Edge Caching Pitfalls: Cookies, Vary, and Query Strings

Watch out for five edge-cache pitfalls before enabling CDN caching on dynamic routes:

  • Set-Cookie silently bypassing or leaking caches: Most CDNs refuse to cache responses carrying Set-Cookie, yet misconfigured rules ignoring cookies can leak session cookies across users! Never attach Set-Cookie on any route emitting public or s-maxage.
  • Caching 500 or 404 origin hiccups: If an upstream glitch returns 502 or 500 without Cache-Control: no-store, some aggressive CDN page rules cache the error page briefly, keeping an outage visible after recovery! Always explicitly set Cache-Control: no-store on 5xx error handlers (and short or zero stale-if-error unless intentional).
  • Missing Vary: Accept-Encoding or Vary: Origin: Returning compressed vs uncompressed bodies—or CORS headers varying by Origin—without matching Vary keys poisons edge cache buckets.
  • Unbounded cache-busting query strings: Attackers or tracking UTMs (?fbclid=...&utm_source=...) split cache keys into millions of cold misses unless your CDN strips marketing query params before cache key lookup.
  • HTML referencing stale hashed JS chunks after a deploy: During atomic static deploys, keep previous hashed /_astro/* asset files online for at least 24 hours (or serve an edge grace buffer) so a browser reading a cached SWR HTML document referencing old chunk app.oldhash.js never hits 404 mid-navigation.

Verifying Edge Behavior with Live Header Probes

After drafting policies with the Interactive Cache-Control Builder and deploying to staging behind Cloudflare, inspect live CF-Cache-Status, Age, ETag, and Cache-Control headers across consecutive curl -I probes:

# 1. Verify immutable static asset headers
curl -sI "https://staging.example.com/fonts/ibm-plex-sans-latin.woff2" | grep -iE "cache-control|cf-cache-status|age"

# 2. Probe dynamic SWR route twice to observe MISS -> HIT transition
curl -sI "https://staging.example.com/explore/" | grep -iE "cache-control|cf-cache-status|age|etag"
sleep 2
curl -sI "https://staging.example.com/explore/" | grep -iE "cache-control|cf-cache-status|age|etag"

# 3. Confirm authenticated/private endpoint stays uncacheable
curl -sI "https://staging.example.com/api/me" | grep -iE "cache-control|cf-cache-status"

Verify four concrete checks: static assets return HIT with immutable, the second probe on your SWR endpoint returns CF-Cache-Status: HIT (or UPDATING/REVALIDATED post-TTL) with incrementing Age, conditional requests sending If-None-Match receive 304 Not Modified with zero body bytes, and private user routes strictly show CF-Cache-Status: DYNAMIC or BYPASS alongside private, no-store. Also inspect Vary headers explicitly on every negotiated route to verify Accept-Encoding and Origin cache keys stay cleanly isolated across client types.

FAQ

What is the difference between no-cache and no-store in Cache-Control?
no-store forbids browsers and CDNs from persisting any copy of the response on disk or memory, mandatory for banking or personal tokens. no-cache permits storing the cached response locally but forces revalidation with the origin (via ETag or Last-Modified) before every use.
Does Cloudflare cache HTML pages automatically if I return Cache-Control: public, max-age=3600?
Not by default unless Cache Everything rules or CDN-Cache-Control / CloudFlare-CDN-Cache-Control rules apply. Cloudflare's default policy caches static asset extensions (.js, .css, .woff2) while bypassing HTML unless configured explicitly.
How does stale-while-revalidate prevent thundering herds when an edge cache expires?
When a cached entry passes its max-age/s-maxage yet stays inside its stale-while-revalidate window, the CDN edge serves the slightly stale copy immediately to thousands of concurrent visitors while dispatching a single asynchronous background revalidation request to the origin.

Related Examples

Interactive Tools for This Topic