Writing · Web · Deployment · Service workers
When a deploy deletes the chunk an open tab still needs
"Failed to fetch dynamically imported module" after a deploy: why code-split apps hit it, how to recover safely, and how to tell a stale tab from a bad release.
If you ship a code-split single-page app, you will eventually see this in your error reports:
TypeError: Failed to fetch dynamically imported module: https://example.com/assets/Gallery-4b1f0c2e.js
It usually means nothing is broken. A tab loaded version A of your app, you deployed version B, the host removed A's files, and then the tab tried to lazy-load a piece of A that no longer exists. In DWEEB this paged me repeatedly in its first months: first during boot, then after boot when a tab that had been open for hours opened the template gallery.
The fix is not one trick. It is a handful of layers, each covering a case the others can't, and a way of reporting that can tell "this visitor's tab is old" from "the release I just shipped is broken". This article walks through all of them.
Why it happens
Bundlers like Vite emit content-hashed chunk names, so every release has a different set of file names. Two facts about the host then do the damage. GitHub Pages, where DWEEB's front end lives, replaces the whole site on each deploy, so the previous release's chunks are gone the moment the new one is live. And the HTML page that points at those chunks is cached briefly (around ten minutes on Pages). So there are two ways to end up asking for a file that doesn't exist:
- A long-lived tab keeps running the old code and lazy-loads an old chunk after the deploy.
- A fresh load during the cache window gets the old HTML from an edge cache, which names chunks that were just deleted.
The layers
1. Let a service worker keep the old release
A precaching service worker stores every chunk of the release it installed, so a tab it controls can lazy-load old chunks long after the host deleted them. One gap is easy to miss: by default, the page that installs the worker isn't controlled by it, so a first visit stays unprotected until it is closed. Setting clientsClaim: true fixes that. It's safe even when you prompt users before updating, because an updated worker still waits, so it never takes over a tab running an older release.
2. Recover a failed boot automatically, but carefully
If the failure happens while the app is booting, there is nothing on screen to lose yet, so an automatic recovery is fine. Mine is a short ladder run from the boot promise's catch:
- Reload the page.
- If that boots the same broken shell (under a service worker a reload is answered from its cache, so it can), unregister the service workers and navigate to the same URL with a one-off query parameter that bypasses every cache, then strip the parameter again on the next boot.
- If that fails too, show a plain notice with a button, instead of a page stuck on "Loading…".
Each rung has guards, and every one of them came from a bug. Progress is recorded in sessionStorage and read back before a navigation happens, so the ladder can never loop (no storage means no automatic step at all). The record is keyed on the build id, not the version number: DWEEB's package.json had said 1.0.0 for every release since launch, so "once per version" quietly meant "once per tab, ever". There's also an absolute cap of four automatic navigations per tab in ten minutes, independent of the build, for the case where two builds alternate behind a CDN. And no automatic navigation happens after the app reports itself ready, because that would throw away someone's unsaved work.
3. After boot, ask, never reload
Once the editor is up, a person may be halfway through a message. Every lazily loaded surface is wrapped in a small error boundary that recognises exactly this failure and shows a "refresh to update" dialog while the rest of the app keeps running. Drafts autosave and the URL is preserved, so the refresh loses nothing, but the person chooses when. Two details matter. The dialog's dismiss action must fully unmount the failed surface, or the cached rejected import is re-thrown on every render. And anything that isn't a stale-chunk failure is re-thrown to the top-level boundary rather than being dressed up as an update.
4. Background imports handle their own failures
The service-worker registration itself was lazy-loaded a few seconds after first paint. In a background tab, browser timer throttling can delay that by hours, until after a deploy has removed the chunk. Nothing on screen was waiting for it, but the unhandled rejection paged me anyway. Fire-and-forget imports now get their own catch that reports a handled, non-paging event.
The message is a symptom, not a diagnosis
Here is the part that took longest to get right. Every browser produces the same error text for any failed module fetch. A visitor whose connection dropped during boot looks byte-for-byte identical to deploy skew, and both look identical to a broken release. I was paged for "fatal" chunk failures that named files the server was serving perfectly well: the requests had simply failed in transit, and the one recovery reload failed the same way.
So before the client reports the serious case, it asks two questions, concurrently, with a four-second limit:
async function diagnoseChunkFailure(chunkUrl) {
const [chunk, shell] = await Promise.all([
// Is the file really gone? Same-origin HEAD, no caches.
probe(chunkUrl, { method: "HEAD", cache: "no-store" }),
// What does the host serve as the app shell right now?
// An unknown query misses the service worker's cache.
probe("/?probe=" + crypto.randomUUID(), { cache: "no-store" }),
]);
if (!chunk || chunk.status < 400 || chunk.status >= 500) return "chunk-unreachable";
if (!shell) return "shell-unverified";
return liveEntry(shell) === currentEntry() ? "broken-release" : "stale-tab";
}
Only a 4xx on the chunk and a live shell that is this very build means the release I'm serving references a file it doesn't have. That is the only case that pages. Everything else is logged at info level and counted. Two implementation notes: probe the full URL from the original error, not a truncated copy (a clipped URL 404s and manufactures a false alarm), and make sure the probe itself can never reject, or its failure lands back in your own error handler.
Old clients never drain
A month after all of that shipped, the same tab paged me again. It was running a bundle 24 days old, from before the live-shell probe existed, so its reporter still sent the old "fatal" shape. With a service worker and a polite update prompt, some tabs simply never update. Waiting for them to drain is not a plan.
The fix had to live where an old client can't overrule it: the server. Each build now stamps its id into the HTML:
<meta name="app-build" content="e699a38eec" />
Crash beacons already carry the build id of the bundle that sent them. When a "fatal" chunk report arrives, the server reads the build id off its own front end (cached for five minutes) and, if the report came from a build that isn't live, logs it as a stale client instead of paging. A few rules keep that safe:
- Nothing is learned from the beacon. The server fetches its own configured origin. A forged beacon can at most claim to be the live build, which pages, which is the old behaviour.
- Every failure fails open. If the shell can't be fetched or has no marker, the answer is "don't know", and the report pages as before.
- The reader follows no redirects and refuses a marker that isn't shaped like a build id, since the value ends up in a log line.
- A fresher answer wins. A current client that checked the live shell itself at the moment of the crash knows more than a five-minute-old server cache, so its verdict is never overruled.
The strangest one: a chunk that arrives empty
Much later, Firefox reported a crash that read like an ordinary bug: can't access property "parse", t is undefined
. The module namespace the boot code read from was empty. Serving an empty body for that one chunk reproduced the report byte for byte, and so did writing an empty entry into the service worker's cache. That second reproduction explained why it kept happening: the precache library skips any URL it already has during install, so unregistering and re-registering the worker puts the damaged copy straight back, and unchanged chunks keep their hash across releases.
A static import of an empty chunk fails at link time with a clear engine message. A dynamic import() just hands back an empty namespace. So every boot-time namespace is now checked for the exports it should have, and the recovery ladder, before each step, deletes that URL from every Cache Storage cache and refetches it with cache: "reload". Tested in Firefox and Chromium, a damaged tab now heals in one reload without anyone noticing.
Summary
- Expect old chunks to disappear. Let a service worker keep them, and claim the first visit too.
- Recover boot failures automatically with a bounded, per-build ladder. Never navigate away from work in progress.
- Key everything on a unique build id, never on a semver string someone forgets to bump.
- Treat "failed to fetch module" as a symptom. Probe the chunk and the live shell before calling it a broken release.
- Let the server, which knows what is live, decide whether old clients' reports matter.
