Fixing "Failed to Fetch Dynamically Imported Module"
Fix Vite Failed to fetch dynamically imported module errors. Identify version skew, bad paths, HTML fallbacks, and network issues, then apply asset retention and guarded reloads.
“Failed to fetch dynamically imported module” means the browser could not load a JavaScript chunk requested through import(). In production, the usual reason is that a new deploy removed a chunk that an already-open tab still expects.
The pattern is familiar: you ship a release, the error tracker lights up within minutes, and every route works when you click through it yourself. Nothing is broken in the new build. The failing requests come from tabs that loaded the previous build.
This article covers the deploy-time mechanism, three fixes that build on each other (asset retention, a reload handler, and a loop guard), the less common causes that produce the same message, and a network-tab table that tells them apart.
Key Takeaways
- The most common cause of “Failed to fetch dynamically imported module” is version skew: an open tab from the previous deploy requests a lazy chunk by a hashed filename that no longer exists on the server.
- Serving
index.htmlwithCache-Control: no-cacheand keeping the previous deploy’s assets available stops most skew failures before any client-side code runs. - Vite’s
vite:preloadErrorevent lets you reload the page on a failed chunk load, but the handler needs a sessionStorage timestamp guard so it cannot reload forever. - A failing
.jsrequest that returns 200 withContent-Type: text/htmlis a server or CDN fallback problem, not version skew. - Retrying a failed dynamic import cannot fix version skew, because the file the old build references is gone.
Why Does a Deploy Break Open Tabs?
The Vite troubleshooting guide lists three causes for TypeError: Failed to fetch dynamically imported module: version skew, poor network conditions, and browser extensions blocking requests. Version skew is the one that spikes after a release.
Here is the sequence. A user loads index.html from build A, which references chunks such as assets/Settings-a1b2c3.js. You deploy build B, and the content hashes change. The user’s tab is still running build A. When they navigate to a lazy route, the browser requests Settings-a1b2c3.js, gets a 404, and the import rejects:
TypeError: Failed to fetch dynamically imported module: https://example.com/assets/Settings-a1b2c3.js
That is the Chromium wording. Other browsers phrase the same failure differently, so group by cause in your tracker, not by exact string.
You can rarely reproduce this locally, because a fresh page load always gets HTML and chunks from the same build. The failure only happens in a tab that loaded the old build before the deploy and requested a lazy route after it. It is also unrelated to Vite’s “Failed to resolve import” error. That one is a build-time resolution failure. This one happens at runtime.
Fix 1: Keep Old Assets and Revalidate the HTML
The cheapest fix for version skew happens on the server: keep the previous build’s chunks available and serve the HTML with Cache-Control: no-cache. If build A’s chunks still exist after build B ships, old tabs keep working. Vite’s load error handling notes point out that many hosting setups delete the previous deployment’s assets, and they recommend Cache-Control: no-cache on the HTML.
Serving index.html with Cache-Control: no-cache makes the browser revalidate the HTML on every load. A reload then picks up the new build’s chunk names instead of the deleted ones. Hashed assets are the opposite case. Their URLs change whenever their content changes, so they can safely use a long max-age with the immutable directive described on MDN.
location = /index.html {
add_header Cache-Control "no-cache";
}
location /assets/ {
add_header Cache-Control "public, max-age=31536000, immutable";
try_files $uri =404;
}
location / {
try_files $uri $uri/ /index.html;
}
Make your deploys additive: upload the new assets/ alongside the old ones, then prune old files on a schedule. How long to keep them is a judgment call. It should be long enough to outlast the open tabs your users realistically keep.
Fix 2: Reload Once on vite:preloadError
On the client, Vite dispatches a vite:preloadError event on window when a dynamic import fails to load, and reloading the page from that handler recovers from version skew. Server-side retention helps, but eventually old chunks get pruned. The original error is in event.payload, and calling event.preventDefault() stops Vite from throwing it. The build guide suggests reloading the page from this handler.
A reload fetches the current index.html, which references build B’s chunks. That fixes version skew. Retrying the import does not, because the file build A points to no longer exists on the server. Only loading the new HTML helps. (Retrying in place only helps with transient network failures. The HTML spec once cached failed module fetches; whatwg/html#10327 changed that, and support varies, as shown in MDN’s import() compatibility table.)
Fix 3: Guard Against Reload Loops
A vite:preloadError reload handler needs a guard against reload loops. If the HTML itself is stale, for example because an edge cache ignores no-cache, or if the chunk is missing from both builds, the reload fails the same way and the page reloads forever. Some frameworks ship this recovery built in, so check your framework’s docs first. Nuxt, for example, reloads on chunk load errors by default, and its reload helper records each reload in sessionStorage and ignores repeat requests for 10 seconds. For plain Vite with React, Vue or Svelte, add it to your entry file:
// src/main.js
const RELOAD_KEY = 'chunk-reload-at';
const RELOAD_WINDOW_MS = 10_000; // tunable, not a standard value
function lastReload() {
try {
return Number(sessionStorage.getItem(RELOAD_KEY)) || 0;
} catch {
return 0;
}
}
function markReload() {
try {
sessionStorage.setItem(RELOAD_KEY, String(Date.now()));
return true;
} catch {
return false; // storage unavailable: don't risk a loop
}
}
window.addEventListener('vite:preloadError', (event) => {
console.error(event.payload); // send to your error tracker instead
const recentlyReloaded = Date.now() - lastReload() < RELOAD_WINDOW_MS;
if (!recentlyReloaded && markReload()) {
event.preventDefault();
window.location.reload();
}
// Otherwise let the error reach the app's error boundary.
});
The handler reloads right away, so nothing depends on what the import resolves to after preventDefault(). If a reload already happened within the window, the handler does not suppress the error. The error propagates, and an error boundary shows a message instead:
import React from 'react';
class ChunkErrorBoundary extends React.Component {
state = { failed: false };
static getDerivedStateFromError() {
return { failed: true };
}
render() {
if (!this.state.failed) return this.props.children;
return (
<div role="alert">
<p>A new version is available.</p>
<button onClick={() => window.location.reload()}>Refresh</button>
</div>
);
}
}
The Refresh button is user-initiated, so the guard does not need to block it. Vue and Svelte have equivalent error-handling hooks. Handle the rejection at the route or boundary level either way, because the Vite docs don’t specify whether every failed dynamic import passes through this event.
Less Common Causes of the Same Error
“Failed to fetch dynamically imported module” also comes from path, server and client problems that have nothing to do with deploys. These failures usually affect sessions that started after the release as well.
-
Wrong
basepath. If the failing chunk URL is missing a path prefix that the app is deployed under, the cause is thebaseoption in the Vite config, not a stale deploy. Set it to match the deploy path, or pass--baseat build time, as covered in Vite’s public base path docs:// vite.config.js — app served from https://example.com/app/ // without base: /assets/c-x1y2.js (404) // with base: /app/assets/c-x1y2.js import { defineConfig } from 'vite'; export default defineConfig({ base: '/app/' }); -
HTML served for a
.jsURL. An SPA fallback or CDN rewrite answers the unknown chunk path withindex.html. The browser then rejects the response as a module because its MIME type isn’t JavaScript. Exclude/assets/from the fallback so missing files return real 404s, as the nginx block above does. -
Ad blockers. Extensions often block files whose names contain words like “ad” or “track”. Vite suggests renaming chunks with
build.rolldownOptions.output.chunkFileNames. In Vite 7 and earlier the option isbuild.rollupOptions, which Vite 8 still accepts as a deprecated alias.build: { rolldownOptions: { output: { chunkFileNames: 'assets/c-[hash].js' } } } -
Network drops. These are intermittent, hit any filename, and have no HTTP status. The guarded reload covers them too.
How Do You Tell Which Cause You Have?
Open the network tab, find the failing chunk request, and check two things: its status code and its Content-Type. Together they identify the cause.
| What the failing chunk request shows | Likely cause | Fix |
|---|---|---|
| 404, hashed filename from an older build | Version skew | Fixes 1 to 3 |
200, Content-Type: text/html | SPA fallback or CDN rewrite | Return real 404s under /assets/ |
| 404, URL missing the deploy subpath | Wrong base | Set base |
| Blocked, filename contains ad-like words | Extension | Rename via chunkFileNames |
| Failed with no status, intermittent | Network | Guarded reload |
Usually you can’t reproduce the failure yourself, so production data has to tell you which case you’re in. Record the release identifier with each error, as part of solid error logging practices. Error tracking combined with session replay shows whether the failures cluster just after a deploy in sessions that started before it, which is the signature of skew. The replay also shows whether the guard reloaded once and recovered. Like “ResizeObserver loop completed” errors, this is a noisy production error that you should classify, not mute.
Fixing the Root Cause
“Failed to fetch dynamically imported module” is usually a deployment problem that shows up in client code. Start on the server: keep previous assets, serve index.html with no-cache, and make sure /assets/ never falls back to HTML. Then add the guarded vite:preloadError handler and an error boundary as a safety net. Before changing any config, open the network tab on a failing request and confirm the cause from its status code and content type.
FAQs
Is this the same problem as webpack's ChunkLoadError?
Yes, the root cause is the same, but the error comes from a different place. Webpack loads chunks through its own runtime, which rejects with ChunkLoadError and a message like 'Loading chunk 42 failed'. Vite production builds use native import(), so the browser's own error appears. The server-side fixes are the same for both: retain old assets and revalidate HTML. The vite:preloadError event exists only in Vite.
Can a service worker or chunk prefetching prevent version skew errors?
Both are mitigations listed in the Vite troubleshooting guide. A service worker that prefetches and caches all assets keeps the old build's chunks available to tabs that are already open, even after the server deletes them. Prefetching dynamic chunks loads them before a deploy can remove them, but it does not help if the browser has cached the HTML because of its Cache-Control headers.
Why does this error appear on the Vite dev server, where there is no deploy?
On the dev server, the usual cause is a browser extension. The Vite troubleshooting guide notes that extensions such as ad blockers can stop the Vite client from sending requests to the dev server, and this produces the same error message. To confirm it, disable extensions for localhost or test in a clean browser profile. Version skew cannot happen in development, because nothing replaces the build under an open tab.
Gain Debugging Superpowers
Unleash the power of session replay to reproduce bugs, track slowdowns and uncover frustrations in your app. Get complete visibility into your frontend with OpenReplay — the most advanced open-source session replay tool for developers.
Star on GitHub12k