How to Implement Static Asset Caching
Cache static assets effectively: fingerprint URLs, set immutable long max-age, differentiate HTML from assets, and test the caching policy.
On this page
Introduction
Static assets are the easiest caching win and the easiest to get wrong. A stylesheet or script that changes on every deploy cannot be cached long under a fixed URL, because a client would keep an old copy. The solution is to make the URL change with the content: a filename carrying a content hash, referenced by the page that also changes. Then the asset URL is immutable and can be cached for a year, while the HTML that references it stays fresh.
This tutorial implements a static asset caching policy: fingerprint the asset URLs and cache them immutably, keep the HTML short-lived so a deploy is seen promptly, use validators for assets you cannot fingerprint, and test the policy per response class. The examples use HTTP headers and a build step.
Fingerprint the URL and cache immutably
Give each asset a filename that includes a hash of its content, such as app.6f3a1b2c.js. Because the URL changes when the content changes, the file at any given URL never changes, and a client can cache it indefinitely. Send Cache-Control: public, max-age=31536000, immutable so the browser keeps it a year and does not revalidate even on a reload. A new deploy produces a new filename, so the old cached copy is not requested again.
This is the highest-value change in static caching: it moves the freshness question from the server to the URL. A client never asks whether the asset changed, because a changed asset has a different URL it has never seen. The only file that must be fresh is the HTML, which is small, so the whole site can be cached aggressively while a deploy is still picked up.
// build: from app.js produce app.<contenthash>.js and rewrite references in the HTML
// serve the fingerprinted file with a long immutable policy
function serveAsset(res, file) {
res.writeHead(200, {
'content-type': contentTypeFor(file),
'cache-control': 'public, max-age=31536000, immutable',
});
res.end(file); // the URL encodes the content, so it never changes
}
Keep HTML and the entry document fresh
The HTML is the one document whose content changes often, and it is the document that points at the current asset URLs. If the HTML is cached long, a deploy that changes an asset is not seen until the HTML refreshes. Serve the HTML with a short max-age, or no-cache with a validator, so the browser revalidates it frequently and picks up the new references quickly.
A common policy is Cache-Control: no-cache on HTML, which means store but revalidate every time, paired with an ETag so the revalidation usually returns a cheap 304. The HTML is small, so a conditional request costs little, and the browser always has the current asset references. Everything the HTML references can then be immutable.
// HTML: revalidate each time, but cheaply when unchanged
res.writeHead(200, {
'content-type': 'text/html; charset=utf-8',
'cache-control': 'no-cache', // store but revalidate
etag: etagFor(htmlHtmlBytes),
});
res.end(htmlHtmlBytes);
Use validators for assets you cannot fingerprint
Some assets have a fixed URL you cannot change, such as a favicon, a manifest, or a file served by a third party. For these, the best policy is a short freshness with a validator. Send an ETag and a short max-age so the client revalidates often and a conditional request returns a 304 when the content is unchanged, avoiding the body transfer in the common case.
Prefer fingerprinted URLs everywhere you can, and use validators only where you cannot. The validator path still contacts the server, so it is slower than an immutable cache hit; it is a fallback, not the primary strategy. Keep the freshness short for these files so a change is picked up within the window, and make the validator stable across replicas so the 304 rate does not collapse.
// fixed-URL asset: short freshness plus a validator
res.writeHead(200, {
'content-type': 'image/x-icon',
'cache-control': 'public, max-age=3600',
etag: etagFor(iconBytes),
});
res.end(iconBytes);
Be careful with service workers and proxies
A service worker sits between the client and the network and can cache and serve assets on its own. Its cache strategy must respect the versioning: cache fingerprinted assets indefinitely and refresh the HTML, and on activation clear caches that belong to an old version. A service worker with a stale cache can serve an old asset even after the network copy changed, so its versioning must align with the URL fingerprinting.
Shared proxies and CDNs cache static assets well, but only if Vary is right and the policy is consistent across the origin and the edge. Align the origin’s Cache-Control with the edge’s so a purge or a revalidation behaves predictably. A fingerprinted asset needs no purge, which is another reason to prefer it: the edge simply serves the old URL until it is never requested and evicted.
Test the policy per class
Test that a fingerprinted asset is served with the long immutable policy and a content hash in its URL. Test that the entry HTML is served with a revalidating policy and an ETag. Test that a second request for the HTML with its ETag gets a 304. Test that a non-fingerprinted asset gets a short freshness and a 304 when unchanged. Test that a new build produces a new asset URL and the HTML references it.
curl -sD - -o /dev/null http://localhost:3000/app.6f3a1b2c.js | grep -i cache-control # max-age=31536000, immutable
curl -sD - -o /dev/null http://localhost:3000/ | grep -i -E 'cache-control|etag' # no-cache + etag
ET=$(curl -sD - -o /dev/null http://localhost:3000/ | awk -F': ' 'tolower($1)=="etag"{print $2}')
curl -s -o /dev/null -w '%{http_code} %{size_download}\n' -H "If-None-Match: $ET" http://localhost:3000/ # 304 0
Common pitfalls
Caching HTML as long as the assets so a deploy is not seen, caching assets with a fixed URL immutably so a change is never picked up, no validator for a fixed-URL asset so it revalidates with a full body, a service worker cache that serves an old asset after a deploy, and a stale Content-Length after transforming an asset are the recurring mistakes. Fingerprinting with immutable, a revalidating HTML policy, validators for fixed URLs, a versioned service worker, and correct headers address them.
Conclusion
Static asset caching works best when the URL encodes the content. Fingerprint asset URLs and cache them immutably for a year, serve the HTML with a revalidating policy so deploys are seen promptly, and use a short freshness plus a validator for the assets you cannot fingerprint. Self-check by asserting the immutable header and hashed URL for assets, the revalidating header for HTML, and a 304 on a conditional HTML request. Then assets are cached almost forever and a deploy still takes effect immediately.
Sources: MDN: Cache-Control, web.dev: Love your cache, RFC 9111: HTTP Caching.
FAQ
- Why immutable for hashed assets?
- If the URL contains a content hash, the file at that URL will never change, so a client can keep it indefinitely without revalidating. immutable tells the browser not to revalidate even on a reload, maximizing cache use. A new build produces a new URL, so the old cached copy is simply never requested again.
- How do I cache an asset I cannot fingerprint?
- Use a validator, an ETag or Last-Modified, with a short freshness so a client revalidates cheaply. Because the URL does not change, you cannot cache it immutably, so the best you can do is a short max-age plus a conditional request that returns a 304 when the content is unchanged.
Report a problem with this articleOpens a pre-filled issue on GitHub.