Cache Busting with Content-Hashed Filenames
The fastest request is one the browser never makes. For a static site, that means serving CSS, JavaScript, fonts and images with a Cache-Control lifetime of a year and the immutable directive, so a returning reader's browser uses its copy without even revalidating. The catch is obvious: if the file changes, readers keep the old one for a year. Content-hashed filenames resolve that tension. The URL contains a hash of the file's bytes; when the bytes change, the URL changes, and the new HTML points at a URL no cache has seen.
This guide sets up fingerprinting across every asset type in Astro, Hugo and Eleventy, pairs it with the two-tier cache policy, and measures the effect on repeat visits. It is part of CDN Caching Rules for SSGs.
Prerequisites
- A static site with a build step that can rename assets.
- Control over response headers at the host — see Setting Cache-Control Headers on Cloudflare Pages or Setting Up Proper Cache Headers on Netlify.
- An atomic deploy, or a plan for keeping old assets around briefly.
The Two-Tier Policy
Hashing only works together with the right headers. Two tiers cover every file on a static site:
| Tier | Files | Cache-Control |
|---|---|---|
| Immutable | anything with a content hash in its name | public, max-age=31536000, immutable |
| Revalidating | HTML, sitemap.xml, robots.txt, feeds, unhashed entry files | public, max-age=0, must-revalidate (or a short max-age with stale-while-revalidate) |
HTML is the pointer file: it is always fetched fresh (or revalidated cheaply with an ETag), and it names the current hashed assets. Everything the HTML points to can then be immutable. The immutable directive matters beyond a long max-age: without it, some browsers still revalidate cached subresources when the reader presses reload, sending a conditional request for every asset on the page.
Fingerprinting in Each Generator
Astro (Vite) hashes bundled CSS and JavaScript into /_astro/ automatically, and images processed through astro:assets get hashed names too. Files in public/ are copied as-is and are not hashed — anything placed there needs the revalidating tier, or should move into src/ and be imported.
Hugo fingerprints anything passed through Hugo Pipes:
{{ $css := resources.Get "css/main.css" | minify | fingerprint "sha256" }}
<link rel="stylesheet" href="{{ $css.RelPermalink }}" integrity="{{ $css.Data.Integrity }}">
{{ $hero := (.Resources.Get "hero.jpg").Resize "1200x webp q78" }}
<img src="{{ $hero.RelPermalink }}" width="{{ $hero.Width }}" height="{{ $hero.Height }}" alt="">
Processed images get a hash in their generated filename. Files under static/ are copied unchanged and unhashed.
Eleventy has no bundler by default. Options: the eleventy-plugin-bundle or @11ty/eleventy-img for images (which hashes output filenames), a small addFilter('hash', …) that reads a file, hashes it and returns a renamed copy's URL, or a Vite/esbuild step that emits a manifest the templates read.
// eleventy.config.js — minimal content-hash filter
import { createHash } from 'node:crypto';
import { readFileSync, copyFileSync } from 'node:fs';
eleventyConfig.addFilter('hashed', (path) => {
const buf = readFileSync(`src${path}`);
const h = createHash('sha256').update(buf).digest('hex').slice(0, 10);
const out = path.replace(/(\.\w+)$/, `.${h}$1`);
copyFileSync(`src${path}`, `_site${out}`);
return out;
});
Fonts, Images and Everything Referenced From CSS
The subtle cases are files referenced from inside other files. A font URL inside CSS, a background image inside CSS, a chunk imported by JavaScript: when they change, the referencing file's contents change too, so its hash must change as well. Bundlers handle this by processing references and hashing bottom-up. Hand-rolled setups often do not — the CSS keeps the same hash while the font it points to changed, so readers keep the old font for a year. Let the bundler own every asset that is referenced from CSS or JavaScript, as recommended in Self-Hosting Google Fonts to Eliminate Layout Shift.
Checking Build Determinism
Hashing only saves bandwidth if an unchanged file keeps the same hash from one build to the next. Several things break that silently: a bundler embedding a build timestamp or random chunk IDs, an image encoder whose output varies between library versions, or a CSS pipeline that orders rules differently depending on file-system order. The symptom is that every deploy invalidates every asset, and returning readers re-download everything even when nothing changed.
Check it directly: build the same commit twice in clean directories and compare the asset file lists. They should be identical.
git worktree add /tmp/b1 HEAD && git worktree add /tmp/b2 HEAD
(cd /tmp/b1 && npm ci && npm run build) && (cd /tmp/b2 && npm ci && npm run build)
diff <(cd /tmp/b1/dist && find . -type f | sort) <(cd /tmp/b2/dist && find . -type f | sort)
On the Eleventy site that motivated this check, two builds differed in 38 filenames because a JavaScript bundle embedded Date.now() as a cache-buster and an image plugin wrote EXIF timestamps; removing both made builds deterministic and cut the bytes returning readers downloaded after a typical deploy by 94%. Run the check in CI weekly, or whenever the build toolchain changes.
Keeping Old Assets Available
After a deploy, pages cached in browsers (bfcache, open tabs) and at the edge still reference the previous hashes for a while. Atomic hosts — Cloudflare Pages, Netlify, Vercel — keep previous deploys' assets addressable, so this just works. On S3 or a VM, deletions must lag: upload new assets, then HTML, and delete assets older than N deploys only after a delay, as in Deploying a Static Site to S3 and CloudFront. Deleting immediately produced a burst of 404s for .js chunks on a VitePress site with client-side navigation, because open tabs requested chunks from the old build.
Measured Impact
A 900-page Astro documentation site, before (all assets max-age=3600) and after (hashed assets immutable, one year). Measured with WebPageTest repeat views and RUM over two weeks.
| Measure | 1-hour cache on everything | Hashed + immutable |
|---|---|---|
| Requests on a repeat view, next day | 14 (11 revalidations) | 3 (HTML + 2 new assets) |
| Bytes on repeat view after an unrelated deploy | 186 KB | 9 KB |
| Repeat-view LCP (WebPageTest, 4G) | 1.1 s | 0.6 s |
| CDN requests reaching origin (share) | 18% | 4% |
| Asset 404s in the hour after deploys | 0 | 0 (atomic host) |
Pitfalls & Rollback
- Immutable on unhashed files. A year-long
immutableheader on/logo.svgor/pagefind/pagefind.jsmeans readers keep the old file for a year. Only hashed filenames get the long tier. - Hashing HTML. Page URLs must stay stable; HTML gets the revalidating tier.
- Hashes that change without content changes. Non-deterministic builds (timestamps embedded in bundles) change every hash every deploy and waste the cache. Check that two builds of the same commit produce identical asset names.
- Deleting old assets immediately. Keep previous builds' files for at least a day on non-atomic hosts.
- Service workers caching HTML forever. A service worker that serves cached HTML without checking the network defeats the revalidating tier; readers see old pages pointing at old hashes. Use network-first for navigations.
- Hash length too short. Four-character hashes collide on large sites; eight or more hex characters is the common, safe default.
- Rollback: revert the header rule; hashed filenames remain harmless with any cache policy.
Conclusion
Content-hashed filenames are what make aggressive caching safe: the HTML is revalidated on every visit and names the current assets, and every asset it names can be cached for a year without revalidation. Let the bundler or generator fingerprint everything referenced from HTML, CSS and JavaScript, apply immutable only to hashed paths, and keep old assets available briefly after deploys. On a 900-page docs site that cut repeat-view requests from 14 to 3 and repeat-view LCP from 1.1 to 0.6 seconds.
FAQ
What is a content-hashed filename?
A filename that includes a short hash of the file's contents, such as app.3f9a2c1e.js. When the contents change, the hash and therefore the URL change, so browsers and CDNs can cache the old URL forever and fetch the new one immediately.
Why not use query strings like app.js?v=2?
Some caches ignore or strip query strings, version numbers must be bumped by hand, and a version bump invalidates files that did not change. A content hash changes only when the bytes change.
Which files should not be hashed?
HTML pages, whose URLs are public and must stay stable, plus files with fixed names that other systems request, such as robots.txt, sitemap.xml, favicon.ico, service worker scripts and search index entry files. Give those short cache lifetimes instead.
What happens to old hashed files after a deploy?
Keep them available for a while. Pages cached in browsers or at the edge may still reference them. Atomic hosts keep previous deploys' files; on object storage, delete old assets only after a delay.
Related
- Parent: CDN Caching Rules for SSGs — the full caching policy.
- Stale-While-Revalidate for Static HTML — the other tier.
- Purging the CDN Cache After a Static Deploy — why hashed assets rarely need purging.
- Atomic Deploys vs Incremental Uploads — keeping old assets reachable.
- Alerting on Cache Hit Ratio Drops — noticing when hashing breaks.