How to Implement HTTP Caching Headers for APIs
Design Cache-Control for JSON APIs: choose public versus private, set max-age and stale-while-revalidate, use validators, and avoid caching errors.
On this page
Introduction
An API that recomputes every response on every request wastes origin capacity and adds latency that a cache could remove. HTTP caching is built into the protocol, and a CDN or a browser can honor it without any client library. Yet caching an API is dangerous when done carelessly, because the wrong directive can serve one user’s data to another. The skill is to classify each response correctly and to choose directives that match who may store it and for how long.
This tutorial designs a Cache-Control policy for a JSON API. It covers public, private, and uncacheable responses, how max-age and s-maxage differ, how stale-while-revalidate improves perceived latency, how validators reduce bandwidth for data that changes, and how to keep error responses from poisoning a cache. The examples use Node.js, but the directives are protocol-level.
Classify each response before choosing directives
Start from the question of who may store the response and for how long. A public configuration endpoint that returns the same bytes to every caller can be public with a long max-age and served by a CDN. A response personalized to one user must be private and must never be stored by a shared cache. A response containing a one-time token or a secret must be no-store. Classifying first prevents the most damaging mistake, which is letting a shared cache retain per-user data.
Also consider volatility. A response that changes every second should have a short max-age or none, while a reference list that changes daily can have a long one. The classification is per endpoint and sometimes per response, such as when a header or a query parameter changes the cacheability. Make the decision once and encode it, rather than guessing at each handler.
Use the right directives
max-age sets freshness in seconds for any cache. s-maxage overrides max-age for shared caches such as a CDN, so you can allow a browser to hold a copy for a different duration than an edge. private restricts storage to the browser cache; public permits a shared cache. no-cache means the response may be stored but must be revalidated before each use, which is the correct choice for dynamic HTML with an ETag. no-store forbids any storage.
stale-while-revalidate adds a grace period during which a cache serves a stale copy while refreshing in the background. stale-if-error does the same when the origin returns an error, letting a cache keep serving a known-good copy when the backend is briefly down. Together they let you promise low latency and availability without promising perfect freshness.
function cacheHeaders(kind, maxAge, swr) {
const base = [];
if (kind === 'public') base.push('public', 'max-age=' + maxAge, 's-maxage=' + Math.min(maxAge, 300));
if (kind === 'private') base.push('private', 'max-age=' + maxAge);
if (kind === 'no-store') base.push('no-store');
if (kind === 'revalidate') base.push('no-cache');
if (swr) base.push('stale-while-revalidate=' + swr, 'stale-if-error=' + swr * 2);
return base.join(', ');
}
Add validators for changing data
For data that changes but not on every request, freshness alone is a poor fit: a long max-age serves stale data, and a short one refetches constantly. A validator solves this. Emit an ETag or a Last-Modified, set a short or zero freshness with no-cache or max-age=0, and let the client send a conditional request. The server answers 304 when nothing changed, saving the body while keeping the data current. This is the standard pattern for a frequently viewed resource that updates occasionally.
Ensure the validator is stable across replicas and computed over the final body. A per-instance or per-request validator collapses the hit rate behind a load balancer. Keep the same Cache-Control on the 304 as on the 200 so the cache refreshes its freshness clock correctly.
Keep errors and secrets uncacheable
A cache that stores a 500 and serves it for the next minute turns a transient failure into a sustained outage. Mark 5xx responses no-store, and be careful with 404: a negative cache can be useful to absorb traffic for missing resources, but it must be short and only for genuinely absent resources, not for a path that is temporarily unauthorized. Likewise, never let a response that reflects an Authorization header be stored by a shared cache.
Add Vary for any header that changes the response body, such as Accept, Accept-Encoding, Accept-Language, or a custom feature header. Missing Vary is a silent correctness bug: the shared cache stores one caller’s response and serves it to another whose request differed. Vary multiplies cache entries, so vary only on headers that truly change the body.
function respondError(res, status) {
res.writeHead(status, { 'cache-control': 'no-store', vary: 'Authorization, Accept-Encoding' });
res.end(JSON.stringify({ error: 'unavailable' }));
}
Test caching behavior explicitly
Assert the exact Cache-Control value per endpoint, because it is easy to change accidentally. Assert that a per-user endpoint is private and that an error path is no-store. Test a conditional request: fetch with the ETag, send it back, and assert 304 with no body. Test stale-while-revalidate by noting the directive presence rather than trying to simulate time in a unit test. Finally, run a header-scanner across endpoints to catch a response that is public when it reflects user identity.
curl -sD - -o /dev/null http://localhost:3000/config | grep -i -E 'cache-control|etag|vary'
curl -s -o /dev/null -w '%{http_code} %{size_download}\n' -H 'If-None-Match: "abc"' http://localhost:3000/config
Common pitfalls
Marking personalized data public, caching 5xx responses, omitting Vary for negotiated headers, using a per-request ETag that kills the hit rate, and leaving secrets in a response a shared cache can store are the recurring mistakes. Each maps to a directive or a classification rule, and a header-scanner test plus explicit Cache-Control assertions keep the policy honest.
Conclusion
An API cache policy is a classification plus a set of directives. Decide whether each response is public, private, or uncacheable, set max-age and s-maxage accordingly, add stale-while-revalidate for latency, use validators for data that changes, and keep errors and secrets out of shared caches. Self-check by asserting the Cache-Control per endpoint and by testing that a conditional request yields a 304. A correct policy cuts origin load without ever serving the wrong user’s data.
Sources: MDN: Cache-Control header, RFC 9111: HTTP Caching, MDN: HTTP caching.
FAQ
- public, private, or no-store?
- public allows a shared cache such as a CDN to store the response; private allows only the browser to store it; no-store forbids storing it at all. Use private for per-user data, public only for data that is identical for everyone, and no-store for secrets and errors.
- What is stale-while-revalidate?
- It lets a cache serve a slightly stale copy for a grace period while it refreshes in the background, trading a small amount of staleness for lower latency and fewer origin requests. It pairs well with max-age: fresh within max-age, served stale during the revalidation window.
Report a problem with this articleOpens a pre-filled issue on GitHub.