In an SPA tab that had been open for more than a day, navigating to a route not yet visited failed to load its lazy chunk and fell into the error boundary. In the WebKit network cache, the content-hashed module URLs for that route held a text/html response. Fetching the same URLs again returned 200 text/html with Cache-Control: public, max-age=31536000, immutable.
The fetch itself did not fail. The browser successfully fetched HTML from a .js URL and cached that response as immutable for a year. Module scripts enforce a strict MIME type check, so the text/html body is never executed and the load fails.
Version skew does not explain it alone
The first suspect is version skew. A new deploy removes the old chunks, and a tab still running the old HTML calls import() on an old hashed name. This is common with Vite’s hashed builds, and Vite documents load error handling for it: listen for vite:preloadError, call preventDefault(), and reload so the fresh HTML references the new hashes.
This tab had outlived the skew protection window (the period during which a host keeps serving assets from previous deploys), so the old chunks being gone was expected. The problem was that recovery did not work. There were two causes.
The SPA fallback returns index.html for missing assets
SPA hosts rewrite any path that matches no file to index.html so client-side routing works. Files under /assets/ carry a content hash in their names and never change, so they are usually served with max-age=31536000, immutable.
If that cache header is attached by the path pattern /assets/*, it also applies when the file does not exist and the fallback index.html is served instead.
With a one-year max-age, the entry is not revalidated while fresh, and immutable keeps it from being revalidated even on reload. A retry for the same URL never reaches the origin; it gets the cached HTML back. Even after the next deploy ships healthy assets, the entry for the old URL stays.
The host-side fix is small. Existing hashed files keep their immutable headers; missing /assets/* paths return 404 with Cache-Control: no-store before the SPA catch-all. With the routes of Vercel’s Build Output API, the guard goes right after { handle: "filesystem" }. Routes in that phase only apply to requests that did not match a static file.
export function protectMissingAssets(config) {
const filesystem = config.routes?.findIndex((r) => r.handle === "filesystem");
if (filesystem === undefined || filesystem < 0) {
throw new Error("filesystem route missing");
}
const guard = {
src: "^/assets/.*$",
status: 404,
headers: { "Cache-Control": "no-store" },
};
const next = config.routes[filesystem + 1];
if (next?.src === guard.src && next.status === guard.status) {
config.routes[filesystem + 1] = guard;
} else {
config.routes.splice(filesystem + 1, 0, guard);
}
}
If a guard is already there it is replaced, so running this repeatedly leaves exactly one guard. If the filesystem handler disappears from the config, it throws and fails the deploy. A failed deploy is safer than serving HTML as JavaScript.
As the Vite docs note, the HTML itself should be served with Cache-Control: no-cache. If the HTML is cached, a reload keeps referencing the old hashes.
A retry guard keyed by message gets used up
Some routers reload once when a lazy import fails, and record the error message in sessionStorage to prevent a loop.
WebKit can report failures for different module URLs with the same message, Importing a module script failed. A key built from the message treats a failure in a different chunk as “already retried.” The record also has no expiry. In a long-lived WebView or desktop tab, once the first reload has happened, no further reload happens for the rest of the session, and every later failure lands in the error boundary.
So the outage was three things stacked together: the missing chunk, HTML cached as immutable under the chunk’s URL, and a one-shot retry guard that was already used up.
A bootstrap that reloads within a time window
Recovery has to run before React mounts, because Vite’s preload helper never runs if the entry module itself fails to load. The bootstrap below handles vite:preloadError and error events from module scripts under /assets/. error events on elements do not bubble, so the listener is registered on window in the capture phase.
(() => {
const storageKey = "spa_asset_recovery";
const retryWindowMs = 60_000;
let recoveryPending = false;
let reloading = false;
function recover() {
if (reloading || !navigator.onLine) return false;
try {
const previous = Number(sessionStorage.getItem(storageKey));
if (previous && Date.now() - previous < retryWindowMs) return false;
sessionStorage.setItem(storageKey, String(Date.now()));
} catch {
return false; // no guard → do not risk a reload loop
}
reloading = true;
window.location.reload();
return true;
}
window.addEventListener("vite:preloadError", (event) => {
recoveryPending = true;
if (recover()) event.preventDefault();
});
window.addEventListener(
"error",
(event) => {
const script = event.target;
if (
!(script instanceof HTMLScriptElement) ||
script.type !== "module" ||
!script.src.startsWith(`${window.location.origin}/assets/`)
) {
return;
}
recoveryPending = true;
recover();
},
true
);
window.addEventListener("online", () => {
if (recoveryPending) recover();
});
})();
- The loop guard is keyed by the time of the last reload, not by the message. A repeat within 60 seconds does not reload. If the new deploy itself is broken, the tab does not reload-loop, and after 60 seconds the next failure can try again.
- When
navigator.onLineisfalse, it does not reload and waits for theonlineevent. - If
sessionStoragethrows, the timestamp cannot be recorded, so it does not reload and leaves the error visible. - For
vite:preloadError, it callspreventDefault()only when it reloads. Otherwise the error is thrown and the error boundary handles it.
Inline the script in the HTML, before the entry <script type="module">. If you use CSP, allow it with a nonce or hash. A reload keeps the URL and persistent storage, but unsaved state that exists only in renderer memory is lost. The loaded HTML is already the wrong generation, so that is an acceptable trade.
A long-lived tab outlives the skew protection window. When a content-hashed URL falls through to the SPA fallback and that response is marked immutable, the failure gets pinned in the cache. On the host, return 404 no-store for missing assets before the SPA fallback. In the client, put a time-windowed reload in the bootstrap. The first stops new bad cache entries; the second recovers tabs that already hold an old generation.