2026-09-04 · 9 min
HTTP Caching Headers in 2026: ETag, Cache-Control, and Why Most APIs Still Get This Wrong
Most backend developers set Cache-Control: no-cache on everything and call it done. I’ve seen this pattern repeated across a dozen projects in Serpong — teams that spent weeks optimizing database queries, then shipped an API where every single request, including static product catalog data that changes twice a month, hit the origin server on every page load.
HTTP caching headers are one of the highest-leverage changes you can make to an API’s performance profile. The configuration surface is small, the semantics are well-documented, and the mistakes are predictable. Here is how to get it right.
What Cache-Control actually controls
The Cache-Control header has two audiences: private caches (the user’s browser) and shared caches (CDNs, proxies, reverse proxies). Getting the distinction wrong is where most problems start.
Cache-Control: public, max-age=3600, stale-while-revalidate=86400
public— shared caches may store this responsemax-age=3600— the response is fresh for 1 hour; no revalidation needed within that windowstale-while-revalidate=86400— after the 1-hour fresh window expires, the cache may serve the stale response for up to 24 hours while it revalidates in the background
For a product catalog API that your CDN sits in front of, this is close to the ideal configuration. Users get sub-millisecond responses from edge nodes, the CDN triggers background revalidation after an hour, and your origin server sees a fraction of the traffic.
For user-specific data — anything tied to a session or auth token — the correct directive is:
Cache-Control: private, no-store
private tells CDNs to not cache at all. no-store tells the browser not to persist the response anywhere. Both together is belt-and-suspenders, but for sensitive data, that is the right call.
The no-cache confusion
no-cache does not mean “do not cache.” It means “cache the response, but revalidate with the origin before serving it.” You are still caching; you are just requiring a conditional request every time. This is useful when you want the performance benefit of conditional requests (304 Not Modified saves bandwidth) but cannot tolerate serving stale content.
The directives you actually want when you mean “do not cache at all” are no-store (browser) and either no-store or private for CDNs.
ETag: the correct way to do conditional requests
An ETag is a token the server attaches to a response. The client sends it back on subsequent requests, and if the resource has not changed, the server returns a 304 Not Modified with no body — saving the full response payload transfer.
# First response
HTTP/1.1 200 OK
ETag: "a3f82bc"
Cache-Control: no-cache
Content-Type: application/json
{"products": [...]}
# Subsequent request from client
GET /api/products HTTP/1.1
If-None-Match: "a3f82bc"
# Server response when nothing changed
HTTP/1.1 304 Not Modified
ETag: "a3f82bc"
Generating an ETag in Node.js/Express is straightforward with the etag package (it is actually built into Express by default for static files):
import { createHash } from "crypto";
function generateETag(data: object): string {
const content = JSON.stringify(data);
return `"${createHash("sha256").update(content).digest("hex").slice(0, 16)}"`;
}
app.get("/api/products", async (req, res) => {
const products = await db.query("SELECT * FROM products WHERE active = true");
const etag = generateETag(products);
// Check If-None-Match header
if (req.headers["if-none-match"] === etag) {
return res.status(304).end();
}
res
.set("ETag", etag)
.set("Cache-Control", "public, max-age=300, stale-while-revalidate=3600")
.json({ products });
});
One detail that matters: compute the ETag from the serialized response, not from a database row’s updated_at timestamp. Timestamps drift, rows get updated with identical values, and you end up with cache invalidations that do not correspond to actual content changes. A hash of the response body is the only reliable validator.
Weak vs strong ETags
A strong ETag ("a3f82bc") means byte-for-byte identical. A weak ETag (W/"a3f82bc") means semantically equivalent — the content is the same, but maybe compression or whitespace differs. For API JSON responses, use strong ETags. For assets where gzip compression may vary by edge node, weak ETags are safer.
Cache-Control for static assets: the immutable trick
For versioned static assets — JavaScript bundles with content hashes in filenames, fonts, images — you can set extremely aggressive caching:
# nginx config for /static/ assets
location /static/ {
add_header Cache-Control "public, max-age=31536000, immutable";
expires 1y;
}
immutable tells browsers not to even attempt revalidation during the max-age window. Normally, browsers may revalidate on hard refresh even if max-age has not expired. immutable suppresses that, which matters for mobile users on flaky connections — you do not want a hard refresh to trigger 40 network requests for assets that have not changed.
This only works safely with content-addressed filenames. The moment you use immutable on a file with a static name like app.js, you have committed to serving stale assets to users until their browser cache expires, with no way to force an update short of the user clearing their cache manually.
The Vary header trap
Vary tells caches which request headers affect the response content. The most common usage is correct:
Vary: Accept-Encoding
This tells CDNs to cache separate copies for gzip, br, and identity encoding — which is what you want.
What you do not want:
Vary: Cookie
Vary: Authorization
Most CDNs — Cloudflare, Fastly, AWS CloudFront — will refuse to cache responses with Vary: Cookie or Vary: Authorization, or will cache per unique header value, effectively giving you a cache of size 1. If you need to serve different content to different authenticated users from a CDN, use surrogate keys or cache tags for explicit purging, not Vary.
The other trap is Vary: User-Agent. This creates a near-infinite cache key space (there are thousands of distinct User-Agent strings in the wild) and will silently kill your CDN hit rate. If you need to serve different responses to mobile vs desktop, use a different URL path or a normalized Vary: X-Device-Type header that you set server-side to a small enum like mobile|desktop|tablet.
Nginx configuration for a typical API setup
Here is a production-ready Nginx config for an API backend that combines these principles:
server {
listen 443 ssl http2;
server_name api.example.com;
# Static assets — aggressively cached
location ~* \.(js|css|png|jpg|webp|woff2|svg)$ {
proxy_pass http://app_upstream;
add_header Cache-Control "public, max-age=31536000, immutable";
add_header Vary "Accept-Encoding";
}
# Public API endpoints — CDN-cacheable with short TTL
location ~* ^/api/v1/(products|categories|config) {
proxy_pass http://app_upstream;
add_header Cache-Control "public, max-age=60, stale-while-revalidate=600, stale-if-error=86400";
add_header Vary "Accept-Encoding, Accept";
proxy_cache api_cache;
proxy_cache_valid 200 1m;
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
}
# Authenticated API endpoints — never cached by CDN
location /api/v1/ {
proxy_pass http://app_upstream;
add_header Cache-Control "private, no-store";
}
}
stale-if-error=86400 is one of the most underused directives. It tells caches to serve the stale cached response for up to 24 hours if the origin is returning errors (5xx, timeouts). For a product catalog, serving yesterday’s data is infinitely better than showing your users an error page because your origin had a brief outage.
Monitoring cache effectiveness
You cannot tune what you cannot measure. Two metrics to track:
Cache hit ratio at your CDN. If you are running Cloudflare, check Analytics > Cache. If it is below 70% for public endpoints, your Cache-Control headers or URL structure is probably wrong. Dynamic query parameters (e.g., ?timestamp=12345 added by some SDKs) fragment your cache keys.
Conditional request rate at your origin. If you serve ETags and no-cache directives, you should see a significant portion of requests coming in with If-None-Match headers. If your origin is returning 200 for all of them (because your ETag generation is broken or inconsistent across server instances), you are doing extra work for zero benefit. Log the ratio of 304 to 200 responses on endpoints where you expect stable content.
The state of browser support in 2026
stale-while-revalidate has had broad browser support since 2020 across Chrome, Firefox, Safari, and Edge. immutable is supported everywhere except older Safari versions, where it is safely ignored. There is no reason to avoid either directive in production today.
The one directive with incomplete CDN support is no-store for clearing existing CDN-cached content. no-store on a response does not retroactively remove previously cached copies from a CDN. For emergency cache purges — you shipped wrong data and need it gone now — use your CDN’s API to purge by URL or surrogate key. Cache headers alone are not a purge mechanism.
What to actually do tomorrow
If your API returns no Cache-Control header on public endpoints, add Cache-Control: public, max-age=60, stale-while-revalidate=300 as a starting point. Measure CDN hit rate. Adjust TTL based on how frequently the data actually changes.
If you are not generating ETags on stable but frequently accessed resources, add them. The bandwidth savings on 304 responses are real, especially for clients on mobile networks.
If you are using Vary: Cookie or Vary: Authorization anywhere near a CDN, audit those endpoints. Either move them behind a private cache directive, or rethink the caching strategy entirely.
Caching is not a one-time configuration decision — it is an ongoing trade-off between freshness, performance, and complexity. But the failure modes are well-understood, and most of them are avoidable with a handful of header values.
Ditulis oleh Reza Pradipta