The Analogy: The Parts Counter and the Model-Year Diagram
At an auto parts counter, every part on the shelves carries a part number stamped from the part's exact specification: its dimensions, its material, its revision. Two parts built to the same spec are given the same number, and changing the smallest thing about a part assigns it a new number instead. The number is not a label anyone chooses; it falls out of the part itself, which means you can read a part's identity straight off the shelf without opening a separate catalog to decode it.
Because a part number can never stand for two different parts, a mechanic who already has that number on the shelf never has to phone the depot to ask whether it is still the correct part. It is, and it always will be, since a revised part would have arrived under a different number. That single guarantee is what lets a shop keep a wall of parts for years and trust every one of them on sight, with no reordering and no re-checking, because the identity and the contents are locked together for good.
The one document that does change is the model-year diagram: the exploded drawing that lists which part numbers this year's assembly is actually built from. When a mechanic starts a job they always reach for the current diagram, never a filed photocopy, because the diagram is the thing that gets superseded, not the parts. The parts are permanent and self-describing; the list of which parts are current is neither, so it is the one sheet you must always pull fresh at the start of every job.
The failure begins when a shop works from a photocopied last-year diagram it kept by the bench. It orders the numbers printed there, but several have been superseded and pulled from stock, so the counter answers "no such part." Reading the same photocopy again only re-orders the same dead numbers; the sole cure is to fetch the current diagram. A browser allowed to keep an old index.html does exactly this: it requests hashed chunk names that the newest deploy has already removed, every request returns a 404, and a plain reload, which re-serves the same stale HTML, cannot rescue it.
Syntax or Core Structure
A production build writes every asset with a content hash embedded in its filename. The hash is a short slice of a cryptographic digest taken over the file's bytes, so the name is a fact about the contents rather than a sequence number someone hands out:
const crypto = require('node:crypto')
const hash8 = (buf) => crypto.createHash('sha256').update(buf).digest('hex').slice(0, 8)
Feed that helper the exact bytes of an emitted chunk and the same input always produces the same name, while a single changed byte produces a different one. The names below are the real digests node computes for those three inputs:
Output:
appV1 -> index-ffe01325.js
appV1copy -> index-ffe01325.js
appV2 -> index-88d2dc3a.js
identical bytes share a name: true
one changed byte rotates it: true
The build lays those files out with the hashed chunks under assets/ and a small, unhashed index.html at the root that references them by their current names:
dist/
index.html
assets/
index-ffe01325.js
vendor-89a9f9e9.js
index-K2mp0Xd8.css
That layout is the whole mechanism in miniature: the entry HTML is the one mutable pointer, and everything it points at is content-addressed. A URL under assets/ is now a promise about its own bytes, which is exactly the property a cache needs to keep something forever without ever asking again.
Technical Depth: How Names, Caching, and the base Path Fit Together
The two-tier cache policy
The policy falls straight out of hashing. Anything whose name is derived from its contents can be cached for as long as you like, because a change would arrive under a different name; the file that names those hashes must never be cached hard, because it is the only thing that changes on every deploy.
| File | Cache-Control | Why it is safe |
|---|---|---|
| Hashed assets under assets/ | public, max-age=31536000, immutable | Content-addressed: any change produces a new URL, so this URL is safe to keep for a year |
| index.html | no-cache | Must be revalidated every request; it is the sheet that lists the current hashes |
The two directives are easy to misread. immutable is the strong one: it tells the browser not even to revalidate on a manual reload, which is only ever correct for a name that cannot mean different bytes. no-cache does not mean "do not store" as its name suggests; it means "store it, but check with the server before reusing it." That revalidation on every use is precisely what you want for the HTML, so the browser always learns the current hashes.
Why splitting vendor from app code multiplies the payoff
Content hashing rewards you for keeping code that changes apart from code that does not. Put third-party libraries in their own vendor chunk and an edit to your application code rotates only the app chunk's name; the vendor chunk keeps the name a returning visitor already has cached:
Output:
build 1 vendor: vendor-89a9f9e9.js
build 2 vendor: vendor-89a9f9e9.js
vendor URL reused by returning visitors: true
build 1 index: index-21539cbc.js
build 2 index: index-e9cf1b53.js
index URL rotated, forcing a fresh fetch: true
The vendor URL is byte-identical across the two builds, so the browser serves the large dependency bundle straight from cache and downloads only the small, changed app chunk. Bundle everything into one file and the opposite happens: every deploy rotates the single name, and every returning visitor re-downloads the whole payload to pick up a one-line change.
base and sub-path deploys
base is the prefix Vite puts in front of every generated asset URL. The default is /, which is correct for a site served from a domain root. Deploy the same build under https://example.com/app/ without changing it and the HTML asks for /assets/index-....js while the file actually lives at /app/assets/index-....js, so everything 404s. Only the prefix moves; the hashed name is untouched:
Output:
emitted file: index-24c273a8.js
base '/' -> /assets/index-24c273a8.js
base '/app/' -> /app/assets/index-24c273a8.js
base './' -> ./assets/index-24c273a8.js
You set it once in the config, keeping both slashes:
export default defineConfig({
base: '/app/',
})
Two follow-ups keep the prefix consistent. In code, read import.meta.env.BASE_URL rather than hardcoding the string, so the value lives in one place. And tell your router too: Vite's base only fixes asset URLs, so a client-side router still needs its own matching basename or navigation will build wrong paths. When the deploy location is genuinely unknown, base: './' emits relative URLs that work for simple pages but conflict with client-side routing under nested paths, so prefer an explicit base whenever you know it.
SPA fallback on the server
Client-side routing means a path like /dashboard/settings has no file behind it. The server must serve index.html for unmatched navigations and let the router take over, while still returning real 404s for genuinely missing assets. Without that rewrite, a deep link or a refresh on a nested route returns a server 404 even though the app itself is fine. The rewrite has to be narrow: fall back to the HTML for navigations, but never for a request under assets/, or a missing chunk quietly returns the HTML with a 200 and the browser tries to execute markup as JavaScript.
Real World Example: A Cache-Header Step That Trusts the Folder, Not the Hash
A deploy step walks the built dist/ directory and assigns a Cache-Control header to every file before uploading to the CDN. The intent is exactly the two-tier policy: hashed assets get a year of immutable, and index.html stays revalidated. The shipped version decides which is which by looking at the folder a file sits in; a corrected version decides by whether the name actually carries a content hash:
const emitted = [
'index.html',
'assets/index-1f4c8a9e.js',
'assets/vendor-9a1b2c3d.js',
'assets/index-7e2d4f60.css',
'assets/logo.svg', // emitted WITHOUT a hash: a custom assetFileNames dropped the token
]
// SHIPPED: decide the policy from the FOLDER a file sits in.
function policyByFolder(path) {
if (path === 'index.html') return 'no-cache'
if (path.startsWith('assets/')) return 'public, max-age=31536000, immutable'
return 'no-cache'
}
// CORRECT: immutable only when the NAME actually carries a content hash.
const HASHED = /-[0-9a-f]{8}\.[a-z0-9]+$/
function policyByHash(path) {
if (path === 'index.html') return 'no-cache'
if (path.startsWith('assets/') && HASHED.test(path)) return 'public, max-age=31536000, immutable'
return 'public, max-age=0, must-revalidate'
}
Output:
SHIPPED (folder-based):
index.html -> no-cache
assets/index-1f4c8a9e.js -> public, max-age=31536000, immutable
assets/vendor-9a1b2c3d.js -> public, max-age=31536000, immutable
assets/index-7e2d4f60.css -> public, max-age=31536000, immutable
assets/logo.svg -> public, max-age=31536000, immutable
marked immutable but NOT content-hashed: 1
assets/logo.svg
CORRECT (hash-token-based):
index.html -> no-cache
assets/index-1f4c8a9e.js -> public, max-age=31536000, immutable
assets/vendor-9a1b2c3d.js -> public, max-age=31536000, immutable
assets/index-7e2d4f60.css -> public, max-age=31536000, immutable
assets/logo.svg -> public, max-age=0, must-revalidate
The two classifiers agree on every properly named file: the three chunks with an eight-character hash in their names are marked immutable by both, and index.html stays no-cache in both. The single disagreement is assets/logo.svg, which was emitted without a hash because a custom assetFileNames pattern dropped the [hash] token. The folder-based rule sees only that it lives under assets/ and stamps it immutable; the hash-based rule sees no hash in the name and correctly keeps it revalidated.
That one wrong header is worse than a missing one. Once logo.svg goes out with immutable, every returning visitor is instructed never to revalidate it, so the next time you change the logo they keep the old bytes indefinitely. A reload does not help, because immutable tells the browser not to even ask. The only ways back are to rename the file or bolt a query string onto it, and neither reaches the users already holding the poisoned header. A file that is genuinely stable but not content-addressed is the one case where immutable is a trap.
The design flaw is that the step uses directory location as a proxy for "content-addressed," when immutability is really a property of the name carrying a hash. Vite does hash everything under assets/ by default, so the folder-based rule matches the hash-based one in the common case and reports success on every ordinary build. It diverges only when the assumption is broken, exactly the situation the check exists to police: a customized assetFileNames, a plugin that copies a file into assets/ unhashed, or an asset referenced by a stable name. It is correct right up until the one build where it matters, which is the same false-confidence shape as a leak scanner that trusts a prefix or a preflight that lowercases before comparing. The durable fix is to gate immutable on the name actually matching a content-hash pattern and to never drop [hash] from assetFileNames in the first place.
Common Mistakes
- Serving index.html with a long cache lifetime. This is the classic post-deploy bug. The HTML is the sheet that lists the current hashes; cache it hard and returning visitors keep requesting chunk names the new deploy has already deleted, and a reload only re-serves the same stale HTML.
- Reading no-cache as "do not store." It means "store, but revalidate before reuse," which is what you want for the HTML. The directive that actually skips revalidation is
immutable, and it belongs only on hashed names.
- Deleting the previous build's assets the instant you deploy. A visitor who loaded the old HTML seconds earlier still needs the old chunks. Keep a deploy cycle or two of old assets so in-flight sessions do not break mid-navigation.
- Not handling failed dynamic imports. After a deploy, a lazily loaded route can 404 because its chunk was removed. Catching that rejection and prompting a reload turns a blank screen into a recoverable one.
- Forgetting base on a sub-path deploy. Under
/app/, a defaultbaseof/makes every asset URL point one segment too high and 404. This is the number-one "worked locally, blank in production" cause.
- Hardcoding the prefix instead of reading import.meta.env.BASE_URL. Sprinkling
/app/through the code means every path is a place the value can drift. Read it from one source so a change of base is a config edit, not a search-and-replace.
- Setting Vite base but forgetting the router basename.
basefixes asset URLs only. A client-side router with no matching basename still builds navigation paths from the wrong root, so links break even though assets load.
- Using base: './' under nested client-side routes. Relative URLs resolve against the current path, so the same asset reference means different things on
/aand/a/b/c. Fine for a flat page, wrong for a routed app; use an explicit base.
- Marking a non-hashed asset immutable. An unhashed file that happens to sit under
assets/(a dropped[hash]token, a copied file) will ship stale forever once cached immutable, with no reload recovery. Gateimmutableon the hash in the name, not the folder.
Best Practices
- Serve hashed assets immutable and index.html no-cache. This is the whole policy in one line, and it follows directly from the fact that hashed names cannot change meaning while the HTML always can.
- Split stable dependencies into their own chunk. Keeping vendor code apart from app code means an ordinary edit rotates only the small app chunk and returning visitors reuse the large dependency bundle from cache.
- Keep a deploy or two of old assets around. Removing the previous build's chunks immediately breaks anyone who loaded the old HTML moments before; an overlap window costs a little storage and prevents a class of 404s.
- Catch failed dynamic imports and offer a reload. Treat a post-deploy chunk miss as a known, recoverable condition rather than letting it surface as a blank route.
- Set base explicitly when you know the deploy path. An explicit
/app/is unambiguous and works with client-side routing, where./does not; reserve relative base for genuinely flat, path-unknown pages.
- Read the prefix from import.meta.env.BASE_URL. One source of truth for the base keeps asset paths, the router, and any hand-built URLs from drifting apart.
- Give the router a matching basename. Derive it from the same base value so navigation and asset loading agree about where the app is mounted.
- Verify headers in staging with a returning-visitor reload. Deploy twice and reload as a warm cache; that is the only test that actually exercises the stale-HTML path before real users hit it.
Practice Exercises
- Diagnose the returning-visitor blank page. After a deploy, users who had visited before see a blank page while brand-new visitors are fine. Identify the misconfigured cache header, say what it should be instead, and explain precisely why a normal reload does not help the affected users.
- Fix a sub-path deploy. The app is deployed under
https://example.com/app/and every asset request 404s. Give the one config change that fixes the asset URLs, then name the two other places the same prefix has to reach for navigation to work.
- Stop the whole-bundle re-download. Every deploy forces returning visitors to re-download the entire bundle even though only a few lines of app code changed. Explain what about the current chunking causes this and the change that lets the dependency code stay cached across deploys.
- Write the cache-header rule correctly. Given a
dist/listing that includesassets/logo.svgemitted without a hash, write the rule that decides which files getimmutable, and state exactly what your rule does with the unhashed file and why that is the safe choice.