Skip to content
Source
Sign inSign up
TanStack/router

lazyRouteComponent renders the error component after it has already triggered the stale-chunk reload #8377

Send to my agent
Openabouroubi(GitHub profile, opens in a new tab) opened this issue 4 comments

Which project does this relate to?

Router

Describe the bug

When a code-split route chunk 404s after a deploy, lazyRouteComponent sets the tanstack_router_reload:<message> sessionStorage key, calls window.location.reload() and suspends with a never-resolving promise. That part works.

The problem is what happens between the reload() call and the navigation actually committing. reload() is asynchronous, and the error variable in the closure is never cleared. If Lazy re-renders during that gap (in our case the router store settling after the navigation is enough), the guard key is already set, so the if (!sessionStorage.getItem(storageKey)) check fails and the component falls through to throw error. The route's errorComponent then renders the Failed to fetch dynamically imported module TypeError for a moment, until the reload lands and the page comes back healthy.

This is point 2 in the description of #3262 ("I'm not 100% sure a re-render is possible here"). It is: our users report the error screen appearing and then the page refreshing on its own, and the error our errorComponent receives is that TypeError, which can only reach it through that branch.

The Solid and Vue lazyRouteComponent implementations have the same structure.

Steps to Reproduce the Bug or Issue

  1. Build an app with automatic code splitting and a defaultErrorComponent.
  2. Open it in a tab and stay on a route without refreshing.
  3. Deploy a new build so the chunk hashes change and the old chunks are no longer served.
  4. In the same tab, navigate to a route whose chunk has not been loaded yet.

Expected behavior

The pending state stays up until the reload completes.

Actual behavior

The errorComponent flashes with the import error, then the page reloads and works.

Proposed fix

Remember in the closure that a reload has been requested, and keep suspending on later renders instead of re-evaluating the sessionStorage guard:

let reloadRequested = false

const lazyComp = function Lazy(props: any) {
  if (error) {
    if (reloadRequested) {
      throw new Promise(() => {})
    }
    if (
      isModuleNotFoundError(error) &&
      !(isServer ?? typeof window === 'undefined') &&
      typeof sessionStorage !== 'undefined'
    ) {
      const storageKey = `tanstack_router_reload:${error.message}`
      if (!sessionStorage.getItem(storageKey)) {
        sessionStorage.setItem(storageKey, '1')
        reloadRequested = true
        window.location.reload()
        throw new Promise(() => {})
      }
    }
    throw error
  }
  // ...
}

The sessionStorage guard still prevents a reload loop across page loads; the closure flag only covers renders within the page that is already reloading.

Platform

  • Router / Start Version: 1.170.35 (same code on main)
  • Bundler: Vite
  • Browser: Chrome
  1. Independent confirmation of this in production, with data that I think pins the branch down precisely.

    We hit it on @tanstack/react-router@1.170.36 / @tanstack/router-core@1.171.30, TanStack Start + Vite, deploying every 5-10 minutes. Over the last few days one app accumulated ~400 events across ~93 issue groups (each dead chunk URL fingerprints separately, since the URL is in the message).

    Evidence that it is the throw error fall-through and not the initial failure

    Our minified lazyRouteComponent in the deployed bundle:

    function P(e,t){let n,i,a,o=()=>(n||=(a=void 0,e().then(...).catch(e=>{n=void 0,a=e})),n),
      s=function(e){if(a){if(r(a)&&typeof sessionStorage<`u`){let e=`tanstack_router_reload:${a.message}`;
      if(!sessionStorage.getItem(e))throw sessionStorage.setItem(e,`1`),window.location.reload(),new Promise(()=>{})}
      throw a}...}

    s is the Lazy component, and the reported error's culprit is exactly that frame:

    culprit:  s(<anonymous>)
    frames:   [..., 'zm', 's']

    So the throw can only be coming from the throw error line after the guard check failed — which, on a first-time failure in a fresh tab, means the sessionStorage key was set moments earlier by the very same render cycle. That matches your reading.

    Timeline from one event's breadcrumbs

    06:53:37 → 06:54:08   normal SPA navigation between routes
            ...53 minutes idle, tab left open...
    07:47:05 → 07:47:07   tab reactivated
    07:47:08   ui.click   → navigation /apps/vk-video → /desktop
    07:47:08   console    TypeError: Failed to fetch dynamically imported module

    Ten deploys landed during that idle window, so the tab was holding long-dead chunk names. Note the whole trail is a single page load — the event is emitted before the reload commits, which is exactly the gap you describe.

    Why this is worth fixing beyond the visual flash

    The error reaches the router's defaultOnCatch, so for anyone wiring that to error tracking it is reported as unhandled. The practical problem is not the flash — users do recover — but that a recovered failure is indistinguishable from an unrecovered one in the error tracker. We spent a while assuming users were stuck on an error screen before the culprit frame showed they were being reloaded correctly all along.

    On the fix

    The closure flag reads right to us. Worth noting the sessionStorage guard is keyed on error.message, which embeds the chunk URL, so it is per-chunk rather than per-tab — it cannot suppress the re-render within the page that is already reloading. And since error is never cleared, every subsequent render in that window falls through too, not just the first.

    Happy to test a patch against our production traffic if that is useful — the failure reproduces on its own within an hour or two at our deploy frequency.

  2. @Sheraff @schiller-manuel I'm experiencing the same issue in production with TanStack Start and Vite.

    A tab left open across deployments sometimes briefly shows our defaultErrorComponent (“Something went wrong”) when navigating to a code-split route, then reloads automatically and displays the page correctly. From the user's perspective, it looks like a server error that immediately fixes itself.

    We reproduced the flash in an existing, signed-in Chrome tab while navigating to /buy. We also found these entries in that tab's sessionStorage:

    tanstack_router_reload:Failed to fetch dynamically imported module: https://beta.abari.ph/assets/buy-Mssc2LlD.js
    tanstack_router_reload:Failed to fetch dynamically imported module: https://beta.abari.ph/assets/buy-_6BNcvYs.js

    Both referenced chunks returned HTTP 404, while the current deployment served differently hashed chunks. After the tab refreshed onto the current build, repeated navigation and reload tests no longer reproduced the error screen.

    This matches the sequence described here: the stale chunk triggers recovery, but the error UI becomes visible before the reload completes. We have confirmed the missing chunks and the visible flash; we have not independently traced the intermediate re-render inside lazyRouteComponent.

    Versions:

    • @tanstack/react-router: 1.170.46
    • @tanstack/router-core: 1.171.39 (resolved by the installed React Router package)
    • @tanstack/react-start: 1.169.4
    • Vite 8, via @voidzero-dev/vite-plus-core@1.4.0
    • React / React DOM: 19.3.1
    • Chrome 156.0.8078.48 on macOS

    Our installed lazyRouteComponent still calls window.location.reload() and suspends on the first failure, with no closure flag to keep subsequent renders suspended while the reload is pending. Adding this as another production report of the same symptoms.

  3. I followed up on my earlier production report with an isolated test against the installed @tanstack/react-router@1.170.46 package.

    With a rejected route import and a mocked window.location.reload(), the first render requests a reload and suspends. Calling the same lazy component again throws the original TypeError, because the sessionStorage key is already set.

    Applying the closure flag proposed in #8433 keeps subsequent renders suspended and requests only one reload. I also checked that a new lazy component instance with the existing sessionStorage key still throws, that ordinary errors still propagate, and that successful imports still render normally. The checks passed against both the ESM and CommonJS builds with the browser export condition enabled.

    This confirms the re-entry behavior in the installed package. The test invokes the component directly; it does not reproduce React's scheduling or an actual browser reload. Our earlier production observation remains the brief error screen followed by a successful automatic reload.

  4. Also hit this one in production

Sign in to join this conversation.