Dev.to WebDev 🛠 Dev 👁 2 📖 6 min read

immutable, hashed filenames, and the one-year cache that never goes stale

Cache-Control: public, max-age=31536000, immutable tells browsers and CDNs to keep a file for a year and not even ask whether it changed. That is only safe for one kind of file: one whose URL changes whenever its content

Cache-Control: public, max-age=31536000, immutable tells browsers and CDNs to keep a file for a year and not even ask whether it changed. That is only safe for one kind of file: one whose URL changes whenever its content does. Build tools do this for your bundles by putting a content hash in the filename. The bugs show up in the files that don't get a hash, and in the gap between an old HTML page and a new deploy.

I checked a hashed and an unhashed file on github.com today. First, what immutable is for.

Why immutable exists

A long max-age already means a browser can reuse the file without a request. The problem was the reload button. RFC 8246 explains that when users reload, the browser sends a conditional request for each subresource, and "a user agent that understands HTML and fetches its dependent sub-resources might issue hundreds of conditional requests". For versioned URLs, every one of them comes back 304 Not Modified. Wasted round trips.

immutable says "the origin server will not update the representation of that resource during the freshness lifetime of the response", and the RFC says clients "SHOULD NOT issue a conditional request during the response's freshness lifetime (e.g., upon a reload) unless explicitly overridden by the user (e.g., a force reload)." Three details matter:

  • It only applies while the response is fresh. Once max-age runs out, the file is revalidated as usual, so immutable without a long max-age does nothing useful.
  • A force reload ignores it.
  • Clients should ignore it on plain HTTP.

MDN's compatibility data lists support in Firefox 49 and Safari 11, but not Chrome. Chrome took a different route in 2017: per the Chromium blog, a normal reload now aims "to only validate the main resource" and loads the rest with regular cache rules. Send the directive anyway. It costs nothing.

Hash in the filename vs ?v= query strings

Both change the URL, and RFC 9111 builds the cache key from "at a minimum, the request method and target URI". So app.css?v=3 and app.css?v=4 are different entries. The query string approach isn't broken, but it has two weak spots:

Some caches drop the query string. CloudFront's managed CachingOptimized policy, a common default, is documented as: "CloudFront doesn't include any query strings or cookies in the cache key." Behind it, ?v=3 and ?v=4 are the same object until the TTL runs out or you invalidate. Cloudflare's "Ignore Query String" caching level does the same for static files.

There is only one file on the server. With ?v=, the server has a single app.css. Right after a deploy, an old page asking for app.css?v=3 gets the new file, and a CDN can store that new content under the old key. With app.3f9c2a1b.css, the old and new versions are separate files that can sit side by side.

A content hash also beats a hand-bumped version number that someone eventually forgets. If you generate ?v=<hash> and your CDN keys on the full URL, you're fine. If you can choose, put the hash in the path.

Live check: github.com

The GitHub homepage loads https://github.githubassets.com/assets/core-e0c42d8f864dfe14.js. The header check on it, trimmed:

cache-control: public, max-age=31536000, immutable
etag: "0x8DF44A3150A4F4B"
last-modified: Tue, 17 Nov 2026 12:05:33 GMT
x-cache: HIT, HIT
age: 2007

Two curl -sI requests a few seconds later:

cache-control: public, max-age=31536000, immutable
age: 1559
x-cache: HIT
cache-control: public, max-age=31536000, immutable
age: 1562
x-cache: HIT

Textbook. Built about an hour before I checked, hash in the name, served from Fastly's cache. The validators only matter after a year.

Then https://github.com/favicon.ico, the URL browsers request by convention. Three requests in about four minutes (API check, then two curl -sI) returned:

cache-control: max-age=315360000
expires: Fri, 14 Nov 2036 13:03:27 GMT
etag: W/"6afc4df6-1976"
last-modified: Tue, 17 Nov 2026 12:52:06 GMT
cache-control: max-age=315360000
etag: W/"6afc4e1d-1976"
last-modified: Tue, 17 Nov 2026 12:52:45 GMT
cache-control: max-age=315360000
etag: W/"6afc4eb8-1976"
last-modified: Tue, 17 Nov 2026 12:55:20 GMT

Ten years on a URL that can never change name. GitHub leaves out immutable, which is honest, but a browser holding this icon still has no reason to ask again for a decade. The validators don't help much either. The second half of each ETag is the size (0x1976 is 6518 bytes, matching content-length); the first half is the last-modified time as a Unix timestamp, and it differed on every response, so a conditional request can get a full 200 instead of a 304. Each response also set three cookies on a static icon. Without private, a shared cache could store them along with it.

GitHub's HTML points its real icon elsewhere, at https://github.githubassets.com/favicons/favicon.svg. No hash, and no Cache-Control at all:

content-type: image/svg+xml
last-modified: Wed, 14 Aug 2024 19:18:58 GMT
etag: "0x8DCBC95F2647EDF"
x-cache: HIT

With no explicit lifetime, caches fall back to heuristics. RFC 9111 suggests "no more than some fraction of the interval since" Last-Modified, and "a typical setting of this fraction might be 10%". For a file last modified in August 2024, that's roughly 80 days. Nobody chose that number.

The unhashed leftovers

Every project has files that live outside the bundler's hashing:

  • Favicons. /favicon.ico has a fixed name. Give it a moderate max-age, and if you want a long cache, point <link rel="icon"> at a hashed copy.
  • Fonts in /public. Vite's docs say files in public are "copied to the root of the dist directory as-is", with no hash. A font that's imported from CSS through the bundler gets a hashed name. The same font dropped into public doesn't.
  • Open Graph images. Social platforms cache them by URL. Replace og.png in place and the old preview can stick around. Change the filename instead.
  • sw.js. A service worker script must keep its URL. By default (updateViaCache: 'imports'), MDN says the HTTP cache is not consulted when the browser checks the script itself for updates, though scripts pulled in with importScripts() do go through it. Keep sw.js on a short cache anyway, so other caches along the way can't serve a stale copy.

None of these should get immutable. A day with stale-while-revalidate is a reasonable default.

Chunk 404s after a deploy

Code splitting creates a failure mode that only appears in production. A user opens your app, the HTML references route-a1b2c3.js, you deploy, the old chunks are deleted, and when the user clicks to a lazy route, the import 404s.

Vite's build guide describes exactly this: "the hosting service may delete the assets from previous deployments", and the user's outdated code "tries to import the corresponding old chunk, which is deleted." Vite fires a vite:preloadError event you can listen for, usually to reload the page. Guard that reload (for example with a flag in sessionStorage) so a genuinely missing file can't cause a reload loop. Vite's docs also say to "set Cache-Control: no-cache on the HTML file, otherwise the old assets will be still referenced."

Keep the previous build's assets around

The fix that prevents the error is to not delete old hashed files on every deploy. Hashed names can't collide, so keeping them is safe:

  • Upload new assets before you switch the HTML, so no page ever references a file that isn't there yet.
  • Don't sync with --delete on every release. Remove old assets on a schedule, for example after a couple of weeks, which outlasts most open tabs and cached HTML.
  • If your host replaces the whole deployment atomically, check whether it can serve assets from previous deployments.

Setting it in Express

In plain Express, express.static accepts maxAge and immutable, so a hashed-only directory can be served with express.static('dist/assets', { maxAge: '1y', immutable: true }). Mixed directories need a rule per file.

The header checks above came from nocache.dev, which I built. Its Express package, nocache-dev-express, has a staticOptions() helper for mixed directories: app.use(express.static("public", staticOptions())) sends public, max-age=31536000, immutable to files whose names look hashed and public, max-age=86400, stale-while-revalidate=604800 to everything else. The default pattern treats any 8+ character segment after a . or - as a hash, so a name like inter-variable.woff2 matches too. Pass your own hashed regex if your filenames need it. There's also a CLI: npx nocache-dev check <url> --json.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.