From 936a107f5f5c3f5040e72c5ce7172b5dbbb4e42d Mon Sep 17 00:00:00 2001 From: Rizwan Saleem Date: Wed, 28 Oct 2026 12:40:23 +0000 Subject: [PATCH 1/3] fix(router): do not reload for a chunk cancelled while the page unloads Firefox and Safari cancel a pending dynamic import when the page starts to unload, with the same message as a missing module. lazyRouteComponent took that as a stale deploy and reloaded, replacing the navigation the user had just started. Watch for beforeunload while an import is pending, wait instead of reloading when it fired, and retry the import if the page stays. Fixes #8827 --- .changeset/lazy-chunk-unload-no-reload.md | 8 ++ .../react-router/src/lazyRouteComponent.tsx | 23 +++- .../tests/lazy-route-chunk-unload.test.tsx | 108 ++++++++++++++++++ packages/router-core/src/index.ts | 2 + packages/router-core/src/utils.ts | 42 +++++++ .../solid-router/src/lazyRouteComponent.tsx | 23 +++- .../tests/lazy-route-chunk-unload.test.tsx | 49 ++++++++ .../vue-router/src/lazyRouteComponent.tsx | 15 ++- .../tests/lazy-route-chunk-unload.test.tsx | 49 ++++++++ 9 files changed, 314 insertions(+), 5 deletions(-) create mode 100644 .changeset/lazy-chunk-unload-no-reload.md create mode 100644 packages/react-router/tests/lazy-route-chunk-unload.test.tsx create mode 100644 packages/solid-router/tests/lazy-route-chunk-unload.test.tsx create mode 100644 packages/vue-router/tests/lazy-route-chunk-unload.test.tsx diff --git a/.changeset/lazy-chunk-unload-no-reload.md b/.changeset/lazy-chunk-unload-no-reload.md new file mode 100644 index 00000000000..8eadefd9fda --- /dev/null +++ b/.changeset/lazy-chunk-unload-no-reload.md @@ -0,0 +1,8 @@ +--- +'@tanstack/router-core': patch +'@tanstack/react-router': patch +'@tanstack/solid-router': patch +'@tanstack/vue-router': patch +--- + +Do not reload the page when Firefox or Safari cancel a pending route chunk because the user is leaving the page. The cancellation has the same message as a missing chunk, and the stale-deploy reload replaced the user's navigation. If the page stays after all, the chunk import is retried. diff --git a/packages/react-router/src/lazyRouteComponent.tsx b/packages/react-router/src/lazyRouteComponent.tsx index a7b58c44991..12787711800 100644 --- a/packages/react-router/src/lazyRouteComponent.tsx +++ b/packages/react-router/src/lazyRouteComponent.tsx @@ -1,5 +1,9 @@ import * as React from 'react' -import { isModuleNotFoundError } from '@tanstack/router-core' +import { + isModuleNotFoundError, + waitForPageToStay, + watchPageUnload, +} from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import { reactUse } from './utils' import type { AsyncRouteComponent } from './route' @@ -25,12 +29,17 @@ export function lazyRouteComponent< let loadPromise: Promise | undefined let comp: T[TKey] | T['default'] let error: any + let cancelledByUnload = false + let staying: Promise | undefined const load = () => { if (!loadPromise) { error = undefined + cancelledByUnload = false + const stopWatchingUnload = watchPageUnload() loadPromise = importer() .then((res) => { + stopWatchingUnload() // Resolved clients have no preload work; SSR can reuse the import. if (!(isServer ?? typeof window === 'undefined')) { loadPromise = undefined @@ -40,6 +49,7 @@ export function lazyRouteComponent< }) .catch((err) => { loadPromise = undefined + cancelledByUnload = stopWatchingUnload() && isModuleNotFoundError(err) // We don't want an error thrown from preload in this case, because // there's nothing we want to do about module not found during preload. // Record the error, the rest is handled during the render path. @@ -51,6 +61,17 @@ export function lazyRouteComponent< } const lazyComp = function Lazy(props: any) { if (error) { + // The browser cancelled the import because the page is unloading, so a + // reload would replace the navigation the user started. If the page + // stays after all, retry the import instead. + if (cancelledByUnload) { + staying ??= waitForPageToStay().then(() => { + staying = undefined + error = undefined + cancelledByUnload = false + }) + throw staying + } // A missing module can mean that a newer deployment replaced the URL. // Reload only for the error that is still current at render time, so a // successful retry cannot leave a stale reload request armed. diff --git a/packages/react-router/tests/lazy-route-chunk-unload.test.tsx b/packages/react-router/tests/lazy-route-chunk-unload.test.tsx new file mode 100644 index 00000000000..3b8b3ef9f59 --- /dev/null +++ b/packages/react-router/tests/lazy-route-chunk-unload.test.tsx @@ -0,0 +1,108 @@ +import * as React from 'react' +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, expect, test, vi } from 'vitest' +import { createControlledPromise } from '@tanstack/router-core' +import { lazyRouteComponent } from '../src' + +// https://github.com/TanStack/router/issues/8827 +const message = + 'error loading dynamically imported module: http://localhost/assets/page.js' +const reloadKey = `tanstack_router_reload:${message}` + +afterEach(() => { + cleanup() + sessionStorage.clear() + vi.restoreAllMocks() +}) + +// jsdom cannot reload, so React retries the render and reaches the error that +// the reload guard rethrows once its key is set. +class ErrorBoundary extends React.Component< + { children: React.ReactNode }, + { error: unknown } +> { + state: { error: unknown } = { error: undefined } + static getDerivedStateFromError(error: unknown) { + return { error } + } + render() { + return this.state.error ?
Error
: this.props.children + } +} + +function renderLazy(Page: ReturnType) { + return render( + + Loading}> + + + , + ) +} + +test('does not reload when the import is cancelled because the page is unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + renderLazy(Page) + expect(screen.getByText('Loading')).toBeInTheDocument() + expect(sessionStorage.getItem(reloadKey)).toBeNull() + + // The page stayed after all, so the import is retried. + fireEvent.pointerDown(document.body) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) + +test('reloads once if the retried import is still missing after the page stays', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockRejectedValueOnce(new TypeError(message)) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + renderLazy(Page) + fireEvent.keyDown(document.body) + await vi.waitFor(() => expect(sessionStorage.getItem(reloadKey)).toBe('1')) + expect(importer).toHaveBeenCalledTimes(2) +}) + +test('still reloads once for a missing module when the page is not unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const Page = lazyRouteComponent(() => Promise.reject(new TypeError(message))) + + await Page.preload!() + renderLazy(Page) + + expect(sessionStorage.getItem(reloadKey)).toBe('1') +}) + +test('stops watching for unload once the import settles', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const Page = lazyRouteComponent(() => Promise.reject(new TypeError(message))) + + await Page.preload!() + // A later unload must not be attributed to the import that already failed. + window.dispatchEvent(new Event('beforeunload')) + renderLazy(Page) + + expect(sessionStorage.getItem(reloadKey)).toBe('1') +}) diff --git a/packages/router-core/src/index.ts b/packages/router-core/src/index.ts index 9206ef60dd8..2bd981f229c 100644 --- a/packages/router-core/src/index.ts +++ b/packages/router-core/src/index.ts @@ -322,6 +322,8 @@ export { createControlledPromise, isPromise, isModuleNotFoundError, + watchPageUnload, + waitForPageToStay, DEFAULT_PROTOCOL_ALLOWLIST, escapeHtml, getUrlScheme, diff --git a/packages/router-core/src/utils.ts b/packages/router-core/src/utils.ts index 63aa5186953..e86e4af39f1 100644 --- a/packages/router-core/src/utils.ts +++ b/packages/router-core/src/utils.ts @@ -516,6 +516,48 @@ export function isModuleNotFoundError(error: any): boolean { ) } +/** + * Firefox and Safari cancel a pending dynamic import when the page starts to + * unload, and reject it with the same message as a missing module. Call this + * before an import, and the returned function after it settles: it stops + * watching and reports whether the page began unloading in between, in which + * case the failure says nothing about a stale deployment. + */ +export function watchPageUnload(): () => boolean { + if (typeof window === 'undefined') { + return () => false + } + let unloading = false + const onBeforeUnload = () => { + unloading = true + } + window.addEventListener('beforeunload', onBeforeUnload) + return () => { + window.removeEventListener('beforeunload', onBeforeUnload) + return unloading + } +} + +/** + * Resolves on the first sign that the page is still in use after + * `beforeunload`. Some browsers fire it for `mailto:` or download links without + * leaving, and a page restored from the back/forward cache comes back too. + */ +export function waitForPageToStay(): Promise { + return new Promise((resolve) => { + const events = ['pageshow', 'pointerdown', 'keydown'] as const + const stay = () => { + for (const event of events) { + window.removeEventListener(event, stay, true) + } + resolve() + } + for (const event of events) { + window.addEventListener(event, stay, true) + } + }) +} + export function isPromise( value: Promise> | T, ): value is Promise> { diff --git a/packages/solid-router/src/lazyRouteComponent.tsx b/packages/solid-router/src/lazyRouteComponent.tsx index 32d4f071102..0c766b6dced 100644 --- a/packages/solid-router/src/lazyRouteComponent.tsx +++ b/packages/solid-router/src/lazyRouteComponent.tsx @@ -1,6 +1,10 @@ import { Dynamic } from 'solid-js/web' import { lazy } from 'solid-js' -import { isModuleNotFoundError } from '@tanstack/router-core' +import { + isModuleNotFoundError, + waitForPageToStay, + watchPageUnload, +} from '@tanstack/router-core' import { isServer } from '@tanstack/router-core/isServer' import type { AsyncRouteComponent } from './route' @@ -16,12 +20,16 @@ export function lazyRouteComponent< let loadPromise: Promise | undefined let comp: T[TKey] | T['default'] let error: any + let cancelledByUnload = false const load = () => { if (!loadPromise) { error = undefined + cancelledByUnload = false + const stopWatchingUnload = watchPageUnload() loadPromise = importer() .then((res) => { + stopWatchingUnload() // Resolved clients have no preload work; SSR can reuse the import. if (!(isServer ?? typeof window === 'undefined')) { loadPromise = undefined @@ -32,6 +40,7 @@ export function lazyRouteComponent< }) .catch((err) => { loadPromise = undefined + cancelledByUnload = stopWatchingUnload() && isModuleNotFoundError(err) error = err }) } @@ -48,6 +57,18 @@ export function lazyRouteComponent< // Both preload and lazy resolution end here without starting another load. function render(props: any) { + // The browser cancelled the import because the page is unloading, so a + // reload would replace the navigation the user started. If the page stays + // after all, retry the import instead. + if (error && cancelledByUnload) { + const Retry = lazy(async () => { + await waitForPageToStay() + await load() + return { default: render } + }) + return + } + // Now that we're out of preload and into actual render path, // throw the error if it was a module not found error during preload if (error) { diff --git a/packages/solid-router/tests/lazy-route-chunk-unload.test.tsx b/packages/solid-router/tests/lazy-route-chunk-unload.test.tsx new file mode 100644 index 00000000000..2026e5e3aa6 --- /dev/null +++ b/packages/solid-router/tests/lazy-route-chunk-unload.test.tsx @@ -0,0 +1,49 @@ +import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library' +import { afterEach, expect, test, vi } from 'vitest' +import { createControlledPromise } from '@tanstack/router-core' +import { lazyRouteComponent } from '../src' + +// https://github.com/TanStack/router/issues/8827 +const message = + 'error loading dynamically imported module: http://localhost/assets/page.js' +const reloadKey = `tanstack_router_reload:${message}` + +afterEach(() => { + cleanup() + sessionStorage.clear() + vi.restoreAllMocks() +}) + +test('does not reload when the import is cancelled because the page is unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + render(() => ) + expect(sessionStorage.getItem(reloadKey)).toBeNull() + + // The page stayed after all, so the import is retried. + fireEvent.pointerDown(document.body) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) + +test('still reloads once for a missing module when the page is not unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const Page = lazyRouteComponent(() => Promise.reject(new TypeError(message))) + + await Page.preload!() + render(() => ) + + expect(sessionStorage.getItem(reloadKey)).toBe('1') +}) diff --git a/packages/vue-router/src/lazyRouteComponent.tsx b/packages/vue-router/src/lazyRouteComponent.tsx index 3137e15ba4f..ebd82dea39e 100644 --- a/packages/vue-router/src/lazyRouteComponent.tsx +++ b/packages/vue-router/src/lazyRouteComponent.tsx @@ -1,4 +1,5 @@ import * as Vue from 'vue' +import { waitForPageToStay, watchPageUnload } from '@tanstack/router-core' import { Outlet } from './Match' import { ClientOnly } from './ClientOnly' import type { AsyncRouteComponent } from './route' @@ -34,6 +35,7 @@ export function lazyRouteComponent< let comp: T[TKey] | T['default'] | null = null let error: any = null let attemptedReload = false + let cancelledByUnload = false const load = () => { // If we're on the server and SSR is disabled for this component @@ -45,8 +47,11 @@ export function lazyRouteComponent< // Use existing promise or create new one if (!loadPromise) { error = undefined + cancelledByUnload = false + const stopWatchingUnload = watchPageUnload() loadPromise = importer() .then((res) => { + stopWatchingUnload() if (typeof document !== 'undefined') { loadPromise = undefined ;(lazyComp as any).preload = undefined @@ -57,6 +62,7 @@ export function lazyRouteComponent< .catch((err) => { error = err loadPromise = undefined + cancelledByUnload = stopWatchingUnload() && isModuleNotFoundError(err) // If it's a module not found error, we'll try to handle it in the component if (isModuleNotFoundError(error)) { @@ -76,15 +82,18 @@ export function lazyRouteComponent< // Create refs to track component state // Use shallowRef for component to avoid making it reactive (Vue warning) const component = Vue.shallowRef(comp ? Vue.markRaw(comp) : comp) - const errorState = Vue.ref(error) + // The browser cancelled the import because the page is unloading, so a + // reload would replace the navigation the user started. If the page + // stays after all, retry the import instead. + const retryAfterUnload = !!error && cancelledByUnload + const errorState = Vue.ref(retryAfterUnload ? null : error) const loading = Vue.ref(!component.value && !errorState.value) // Setup effect to load the component when this component is used Vue.onMounted(() => { if (!component.value && !errorState.value) { loading.value = true - - load() + ;(retryAfterUnload ? waitForPageToStay().then(load) : load()) .then((result) => { // Use markRaw to prevent Vue from making the component reactive component.value = result ? Vue.markRaw(result) : result diff --git a/packages/vue-router/tests/lazy-route-chunk-unload.test.tsx b/packages/vue-router/tests/lazy-route-chunk-unload.test.tsx new file mode 100644 index 00000000000..4e33f2ea7fc --- /dev/null +++ b/packages/vue-router/tests/lazy-route-chunk-unload.test.tsx @@ -0,0 +1,49 @@ +import { cleanup, fireEvent, render, screen } from '@testing-library/vue' +import { afterEach, expect, test, vi } from 'vitest' +import { createControlledPromise } from '@tanstack/router-core' +import { lazyRouteComponent } from '../src' + +// https://github.com/TanStack/router/issues/8827 +const message = + 'error loading dynamically imported module: http://localhost/assets/page.js' +const reloadKey = `tanstack_router_reload:${message}` + +afterEach(() => { + cleanup() + sessionStorage.clear() + vi.restoreAllMocks() +}) + +test('does not reload when the import is cancelled because the page is unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + render(Page) + expect(sessionStorage.getItem(reloadKey)).toBeNull() + + // The page stayed after all, so the import is retried. + await fireEvent.pointerDown(document.body) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) + +test('still reloads once for a missing module when the page is not unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const Page = lazyRouteComponent(() => Promise.reject(new TypeError(message))) + + await Page.preload!() + render(Page) + + expect(sessionStorage.getItem(reloadKey)).toBe('1') +}) From d2f183e5f11498b1ff80cf3c07c54c0e97e259e1 Mon Sep 17 00:00:00 2001 From: Rizwan Saleem Date: Wed, 18 Nov 2026 20:27:01 +0000 Subject: [PATCH 2/3] fix(router): listen for the page staying as soon as an unload cancels the import Start waitForPageToStay when the failed import is classified instead of at render time, so a pageshow in between is not missed. In vue-router, a retried import that fails again now waits again or reloads once instead of leaving the route empty. --- .../react-router/src/lazyRouteComponent.tsx | 16 +++-- .../tests/lazy-route-chunk-unload.test.tsx | 24 ++++++++ .../solid-router/src/lazyRouteComponent.tsx | 9 ++- .../tests/lazy-route-chunk-unload.test.tsx | 24 ++++++++ .../vue-router/src/lazyRouteComponent.tsx | 58 ++++++++++++++----- .../tests/lazy-route-chunk-unload.test.tsx | 44 ++++++++++++++ 6 files changed, 151 insertions(+), 24 deletions(-) diff --git a/packages/react-router/src/lazyRouteComponent.tsx b/packages/react-router/src/lazyRouteComponent.tsx index 12787711800..bbe1d3d6fcd 100644 --- a/packages/react-router/src/lazyRouteComponent.tsx +++ b/packages/react-router/src/lazyRouteComponent.tsx @@ -50,6 +50,15 @@ export function lazyRouteComponent< .catch((err) => { loadPromise = undefined cancelledByUnload = stopWatchingUnload() && isModuleNotFoundError(err) + // Start listening now: a pageshow before the next render would + // otherwise go unseen and leave the route suspended. + if (cancelledByUnload) { + staying = waitForPageToStay().then(() => { + staying = undefined + error = undefined + cancelledByUnload = false + }) + } // We don't want an error thrown from preload in this case, because // there's nothing we want to do about module not found during preload. // Record the error, the rest is handled during the render path. @@ -64,12 +73,7 @@ export function lazyRouteComponent< // The browser cancelled the import because the page is unloading, so a // reload would replace the navigation the user started. If the page // stays after all, retry the import instead. - if (cancelledByUnload) { - staying ??= waitForPageToStay().then(() => { - staying = undefined - error = undefined - cancelledByUnload = false - }) + if (cancelledByUnload && staying) { throw staying } // A missing module can mean that a newer deployment replaced the URL. diff --git a/packages/react-router/tests/lazy-route-chunk-unload.test.tsx b/packages/react-router/tests/lazy-route-chunk-unload.test.tsx index 3b8b3ef9f59..21fdb124a34 100644 --- a/packages/react-router/tests/lazy-route-chunk-unload.test.tsx +++ b/packages/react-router/tests/lazy-route-chunk-unload.test.tsx @@ -106,3 +106,27 @@ test('stops watching for unload once the import settles', async () => { expect(sessionStorage.getItem(reloadKey)).toBe('1') }) + +test('retries when the page stays before the route renders', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + // Restored from the back/forward cache before the route is rendered. + window.dispatchEvent(new Event('pageshow')) + await Promise.resolve() + + renderLazy(Page) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) diff --git a/packages/solid-router/src/lazyRouteComponent.tsx b/packages/solid-router/src/lazyRouteComponent.tsx index 0c766b6dced..ba5687bfb6e 100644 --- a/packages/solid-router/src/lazyRouteComponent.tsx +++ b/packages/solid-router/src/lazyRouteComponent.tsx @@ -21,6 +21,7 @@ export function lazyRouteComponent< let comp: T[TKey] | T['default'] let error: any let cancelledByUnload = false + let staying: Promise | undefined const load = () => { if (!loadPromise) { @@ -41,6 +42,9 @@ export function lazyRouteComponent< .catch((err) => { loadPromise = undefined cancelledByUnload = stopWatchingUnload() && isModuleNotFoundError(err) + // Start listening now: a pageshow before the retry is rendered + // would otherwise go unseen and leave the route suspended. + staying = cancelledByUnload ? waitForPageToStay() : undefined error = err }) } @@ -60,9 +64,10 @@ export function lazyRouteComponent< // The browser cancelled the import because the page is unloading, so a // reload would replace the navigation the user started. If the page stays // after all, retry the import instead. - if (error && cancelledByUnload) { + if (error && cancelledByUnload && staying) { + const stay = staying const Retry = lazy(async () => { - await waitForPageToStay() + await stay await load() return { default: render } }) diff --git a/packages/solid-router/tests/lazy-route-chunk-unload.test.tsx b/packages/solid-router/tests/lazy-route-chunk-unload.test.tsx index 2026e5e3aa6..09a64e51b6a 100644 --- a/packages/solid-router/tests/lazy-route-chunk-unload.test.tsx +++ b/packages/solid-router/tests/lazy-route-chunk-unload.test.tsx @@ -47,3 +47,27 @@ test('still reloads once for a missing module when the page is not unloading', a expect(sessionStorage.getItem(reloadKey)).toBe('1') }) + +test('retries when the page stays before the route renders', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + // Restored from the back/forward cache before the route is rendered. + window.dispatchEvent(new Event('pageshow')) + await Promise.resolve() + + render(() => ) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) diff --git a/packages/vue-router/src/lazyRouteComponent.tsx b/packages/vue-router/src/lazyRouteComponent.tsx index ebd82dea39e..b9b71f5f6fb 100644 --- a/packages/vue-router/src/lazyRouteComponent.tsx +++ b/packages/vue-router/src/lazyRouteComponent.tsx @@ -36,6 +36,7 @@ export function lazyRouteComponent< let error: any = null let attemptedReload = false let cancelledByUnload = false + let staying: Promise | undefined const load = () => { // If we're on the server and SSR is disabled for this component @@ -63,6 +64,9 @@ export function lazyRouteComponent< error = err loadPromise = undefined cancelledByUnload = stopWatchingUnload() && isModuleNotFoundError(err) + // Start listening now: a pageshow before the component mounts + // would otherwise go unseen and leave the route empty. + staying = cancelledByUnload ? waitForPageToStay() : undefined // If it's a module not found error, we'll try to handle it in the component if (isModuleNotFoundError(error)) { @@ -75,6 +79,39 @@ export function lazyRouteComponent< return loadPromise } + // Reload once for a missing module. Returns true if a reload was started. + const reloadOnce = (err: any) => { + if ( + attemptedReload || + typeof window === 'undefined' || + typeof sessionStorage === 'undefined' + ) { + return false + } + const storageKey = `tanstack_router_reload:${err.message}` + if (sessionStorage.getItem(storageKey)) { + return false + } + sessionStorage.setItem(storageKey, '1') + attemptedReload = true + window.location.reload() + return true + } + + // After a retry, a failed import comes back as null with the error recorded. + // Wait again if this import was also cancelled by an unload, otherwise give + // the missing module the same single reload as the first render would. + const settleRetry = (result: any): any => { + if (result || !error) return result + if (cancelledByUnload && staying) { + return staying.then(load).then(settleRetry) + } + if (isModuleNotFoundError(error) && reloadOnce(error)) { + return null + } + throw error + } + // Create a lazy component wrapper using defineComponent so it works in Vue SFC templates const lazyComp = Vue.defineComponent({ name: 'LazyRouteComponent', @@ -85,7 +122,8 @@ export function lazyRouteComponent< // The browser cancelled the import because the page is unloading, so a // reload would replace the navigation the user started. If the page // stays after all, retry the import instead. - const retryAfterUnload = !!error && cancelledByUnload + const retryAfterUnload = !!error && cancelledByUnload && !!staying + const stay = staying const errorState = Vue.ref(retryAfterUnload ? null : error) const loading = Vue.ref(!component.value && !errorState.value) @@ -93,7 +131,7 @@ export function lazyRouteComponent< Vue.onMounted(() => { if (!component.value && !errorState.value) { loading.value = true - ;(retryAfterUnload ? waitForPageToStay().then(load) : load()) + ;(retryAfterUnload ? stay!.then(load).then(settleRetry) : load()) .then((result) => { // Use markRaw to prevent Vue from making the component reactive component.value = result ? Vue.markRaw(result) : result @@ -110,21 +148,9 @@ export function lazyRouteComponent< if ( errorState.value && isModuleNotFoundError(errorState.value) && - !attemptedReload + reloadOnce(errorState.value) ) { - if ( - typeof window !== 'undefined' && - typeof sessionStorage !== 'undefined' - ) { - // Try to reload once on module not found error - const storageKey = `tanstack_router_reload:${errorState.value.message}` - if (!sessionStorage.getItem(storageKey)) { - sessionStorage.setItem(storageKey, '1') - attemptedReload = true - window.location.reload() - return () => null // Return empty while reloading - } - } + return () => null // Return empty while reloading } // If we have a non-module-not-found error, throw it diff --git a/packages/vue-router/tests/lazy-route-chunk-unload.test.tsx b/packages/vue-router/tests/lazy-route-chunk-unload.test.tsx index 4e33f2ea7fc..3b06323f213 100644 --- a/packages/vue-router/tests/lazy-route-chunk-unload.test.tsx +++ b/packages/vue-router/tests/lazy-route-chunk-unload.test.tsx @@ -47,3 +47,47 @@ test('still reloads once for a missing module when the page is not unloading', a expect(sessionStorage.getItem(reloadKey)).toBe('1') }) + +test('retries when the page stays before the route renders', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + // Restored from the back/forward cache before the route is rendered. + window.dispatchEvent(new Event('pageshow')) + await Promise.resolve() + + render(Page) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) + +test('reloads once if the retried import is still missing after the page stays', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockRejectedValueOnce(new TypeError(message)) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + render(Page) + await fireEvent.keyDown(document.body) + await vi.waitFor(() => expect(sessionStorage.getItem(reloadKey)).toBe('1')) + expect(importer).toHaveBeenCalledTimes(2) +}) From 1b76a4a1d937ee93d32d288548af9b312c2fc51d Mon Sep 17 00:00:00 2001 From: Rizwan Saleem Date: Sun, 29 Nov 2026 17:27:11 +0000 Subject: [PATCH 3/3] fix(router): treat imports started after beforeunload as cancelled by the unload Keep one page-leaving state in router-core from beforeunload until a stay event, so an import that starts after beforeunload is not mistaken for a missing module. The beforeunload listener is still only attached while an import is pending, which keeps the page eligible for Firefox's bfcache. In react-router, a stay event no longer clears an error recorded by a newer preload. In vue-router, an import started at mount that the unload cancels now waits and retries instead of leaving the route empty. --- .../react-router/src/lazyRouteComponent.tsx | 20 +++--- .../tests/lazy-route-chunk-unload.test.tsx | 56 ++++++++++++++++ packages/router-core/src/utils.ts | 54 ++++++++++++--- .../router-core/tests/page-unload.test.ts | 67 +++++++++++++++++++ .../tests/lazy-route-chunk-unload.test.tsx | 31 +++++++++ .../vue-router/src/lazyRouteComponent.tsx | 3 +- .../tests/lazy-route-chunk-unload.test.tsx | 54 +++++++++++++++ 7 files changed, 264 insertions(+), 21 deletions(-) create mode 100644 packages/router-core/tests/page-unload.test.ts diff --git a/packages/react-router/src/lazyRouteComponent.tsx b/packages/react-router/src/lazyRouteComponent.tsx index bbe1d3d6fcd..932edbe3331 100644 --- a/packages/react-router/src/lazyRouteComponent.tsx +++ b/packages/react-router/src/lazyRouteComponent.tsx @@ -50,19 +50,21 @@ export function lazyRouteComponent< .catch((err) => { loadPromise = undefined cancelledByUnload = stopWatchingUnload() && isModuleNotFoundError(err) - // Start listening now: a pageshow before the next render would - // otherwise go unseen and leave the route suspended. - if (cancelledByUnload) { - staying = waitForPageToStay().then(() => { - staying = undefined - error = undefined - cancelledByUnload = false - }) - } // We don't want an error thrown from preload in this case, because // there's nothing we want to do about module not found during preload. // Record the error, the rest is handled during the render path. error = err + // Start listening now: a pageshow before the next render would + // otherwise go unseen and leave the route suspended. Only clear the + // error if a newer attempt has not replaced it in the meantime. + staying = cancelledByUnload + ? waitForPageToStay().then(() => { + if (error !== err) return + staying = undefined + error = undefined + cancelledByUnload = false + }) + : undefined }) } diff --git a/packages/react-router/tests/lazy-route-chunk-unload.test.tsx b/packages/react-router/tests/lazy-route-chunk-unload.test.tsx index 21fdb124a34..54940d120be 100644 --- a/packages/react-router/tests/lazy-route-chunk-unload.test.tsx +++ b/packages/react-router/tests/lazy-route-chunk-unload.test.tsx @@ -11,6 +11,8 @@ const reloadKey = `tanstack_router_reload:${message}` afterEach(() => { cleanup() + // Clears the shared state left by a test that ends while the page is leaving. + window.dispatchEvent(new Event('pageshow')) sessionStorage.clear() vi.restoreAllMocks() }) @@ -130,3 +132,57 @@ test('retries when the page stays before the route renders', async () => { expect(importer).toHaveBeenCalledTimes(2) expect(sessionStorage.getItem(reloadKey)).toBeNull() }) + +test('does not reload for an import that starts after the page began unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const pending = createControlledPromise() + const late = createControlledPromise() + const Other = lazyRouteComponent(() => pending) + const importer = vi + .fn() + .mockReturnValueOnce(late) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + // Another route is still loading when the user leaves. + void Other.preload!() + window.dispatchEvent(new Event('beforeunload')) + + // This import starts after beforeunload and is cancelled by the unload. + const preload = Page.preload!() + late.reject(new TypeError(message)) + await preload + + renderLazy(Page) + expect(sessionStorage.getItem(reloadKey)).toBeNull() + + fireEvent.pointerDown(document.body) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) + +test('a newer failed preload keeps its error when the page stays', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockRejectedValueOnce(new Error('Broken module')) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + const preload = Page.preload!() + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + await preload + + // A second preload fails for another reason before the route renders. + await Page.preload!() + window.dispatchEvent(new Event('pageshow')) + await Promise.resolve() + + renderLazy(Page) + expect(screen.getByText('Error')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) +}) diff --git a/packages/router-core/src/utils.ts b/packages/router-core/src/utils.ts index e86e4af39f1..6131d5fbc75 100644 --- a/packages/router-core/src/utils.ts +++ b/packages/router-core/src/utils.ts @@ -516,25 +516,58 @@ export function isModuleNotFoundError(error: any): boolean { ) } +const stayEvents = ['pageshow', 'pointerdown', 'keydown'] as const + +// Shared between imports, so one that starts after `beforeunload` still knows +// the page is leaving. The `beforeunload` listener is only attached while an +// import is pending, because Firefox keeps a page with one out of the +// back/forward cache. +let pendingImports = 0 +let pageIsLeaving = false +let leaveCount = 0 + +function onBeforeUnload() { + leaveCount++ + if (pageIsLeaving) return + pageIsLeaving = true + for (const event of stayEvents) { + window.addEventListener(event, onStay, true) + } +} + +function onStay() { + pageIsLeaving = false + for (const event of stayEvents) { + window.removeEventListener(event, onStay, true) + } +} + /** * Firefox and Safari cancel a pending dynamic import when the page starts to * unload, and reject it with the same message as a missing module. Call this * before an import, and the returned function after it settles: it stops - * watching and reports whether the page began unloading in between, in which - * case the failure says nothing about a stale deployment. + * watching and reports whether the page was leaving at any point in between, + * including when the import started after `beforeunload`. In that case the + * failure says nothing about a stale deployment. */ export function watchPageUnload(): () => boolean { if (typeof window === 'undefined') { return () => false } - let unloading = false - const onBeforeUnload = () => { - unloading = true + const leavingAtStart = pageIsLeaving + const leaveCountAtStart = leaveCount + if (pendingImports++ === 0) { + window.addEventListener('beforeunload', onBeforeUnload) } - window.addEventListener('beforeunload', onBeforeUnload) + let stopped = false return () => { - window.removeEventListener('beforeunload', onBeforeUnload) - return unloading + if (!stopped) { + stopped = true + if (--pendingImports === 0) { + window.removeEventListener('beforeunload', onBeforeUnload) + } + } + return leavingAtStart || leaveCount !== leaveCountAtStart } } @@ -545,14 +578,13 @@ export function watchPageUnload(): () => boolean { */ export function waitForPageToStay(): Promise { return new Promise((resolve) => { - const events = ['pageshow', 'pointerdown', 'keydown'] as const const stay = () => { - for (const event of events) { + for (const event of stayEvents) { window.removeEventListener(event, stay, true) } resolve() } - for (const event of events) { + for (const event of stayEvents) { window.addEventListener(event, stay, true) } }) diff --git a/packages/router-core/tests/page-unload.test.ts b/packages/router-core/tests/page-unload.test.ts new file mode 100644 index 00000000000..a8f079cff8a --- /dev/null +++ b/packages/router-core/tests/page-unload.test.ts @@ -0,0 +1,67 @@ +import { afterEach, expect, test, vi } from 'vitest' +import { waitForPageToStay, watchPageUnload } from '../src/utils' + +// https://github.com/TanStack/router/issues/8827 +afterEach(() => { + // Any leftover "leaving" state ends when the page is shown again. + window.dispatchEvent(new Event('pageshow')) + vi.restoreAllMocks() +}) + +test('reports an unload that happens while the import is pending', () => { + const stop = watchPageUnload() + window.dispatchEvent(new Event('beforeunload')) + expect(stop()).toBe(true) +}) + +test('reports nothing when the page does not unload', () => { + const stop = watchPageUnload() + expect(stop()).toBe(false) +}) + +test('reports an import that starts after beforeunload', () => { + const first = watchPageUnload() + window.dispatchEvent(new Event('beforeunload')) + + // Started while the page was already leaving. + const second = watchPageUnload() + first() + expect(second()).toBe(true) +}) + +test('an import that starts after the page stayed is not affected', () => { + const first = watchPageUnload() + window.dispatchEvent(new Event('beforeunload')) + first() + + window.dispatchEvent(new Event('pointerdown')) + const second = watchPageUnload() + expect(second()).toBe(false) +}) + +test('only listens for beforeunload while an import is pending', () => { + const add = vi.spyOn(window, 'addEventListener') + const remove = vi.spyOn(window, 'removeEventListener') + const beforeUnloadCalls = (spy: typeof add) => + spy.mock.calls.filter(([event]) => event === 'beforeunload').length + + const first = watchPageUnload() + const second = watchPageUnload() + expect(beforeUnloadCalls(add)).toBe(1) + + first() + expect(beforeUnloadCalls(remove)).toBe(0) + second() + second() + expect(beforeUnloadCalls(remove)).toBe(1) +}) + +test('waitForPageToStay resolves on the first stay event', async () => { + const stayed = vi.fn() + waitForPageToStay().then(stayed) + await Promise.resolve() + expect(stayed).not.toHaveBeenCalled() + + window.dispatchEvent(new Event('keydown')) + await vi.waitFor(() => expect(stayed).toHaveBeenCalled()) +}) diff --git a/packages/solid-router/tests/lazy-route-chunk-unload.test.tsx b/packages/solid-router/tests/lazy-route-chunk-unload.test.tsx index 09a64e51b6a..08ad789ed08 100644 --- a/packages/solid-router/tests/lazy-route-chunk-unload.test.tsx +++ b/packages/solid-router/tests/lazy-route-chunk-unload.test.tsx @@ -10,6 +10,8 @@ const reloadKey = `tanstack_router_reload:${message}` afterEach(() => { cleanup() + // Clears the shared state left by a test that ends while the page is leaving. + window.dispatchEvent(new Event('pageshow')) sessionStorage.clear() vi.restoreAllMocks() }) @@ -71,3 +73,32 @@ test('retries when the page stays before the route renders', async () => { expect(importer).toHaveBeenCalledTimes(2) expect(sessionStorage.getItem(reloadKey)).toBeNull() }) + +test('does not reload for an import that starts after the page began unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const pending = createControlledPromise() + const late = createControlledPromise() + const Other = lazyRouteComponent(() => pending) + const importer = vi + .fn() + .mockReturnValueOnce(late) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + // Another route is still loading when the user leaves. + void Other.preload!() + window.dispatchEvent(new Event('beforeunload')) + + // This import starts after beforeunload and is cancelled by the unload. + const preload = Page.preload!() + late.reject(new TypeError(message)) + await preload + + render(() => ) + expect(sessionStorage.getItem(reloadKey)).toBeNull() + + fireEvent.pointerDown(document.body) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) diff --git a/packages/vue-router/src/lazyRouteComponent.tsx b/packages/vue-router/src/lazyRouteComponent.tsx index b9b71f5f6fb..67c5df7d9a1 100644 --- a/packages/vue-router/src/lazyRouteComponent.tsx +++ b/packages/vue-router/src/lazyRouteComponent.tsx @@ -131,7 +131,8 @@ export function lazyRouteComponent< Vue.onMounted(() => { if (!component.value && !errorState.value) { loading.value = true - ;(retryAfterUnload ? stay!.then(load).then(settleRetry) : load()) + ;(retryAfterUnload ? stay!.then(load) : load()) + .then(settleRetry) .then((result) => { // Use markRaw to prevent Vue from making the component reactive component.value = result ? Vue.markRaw(result) : result diff --git a/packages/vue-router/tests/lazy-route-chunk-unload.test.tsx b/packages/vue-router/tests/lazy-route-chunk-unload.test.tsx index 3b06323f213..2d32109f63d 100644 --- a/packages/vue-router/tests/lazy-route-chunk-unload.test.tsx +++ b/packages/vue-router/tests/lazy-route-chunk-unload.test.tsx @@ -10,6 +10,8 @@ const reloadKey = `tanstack_router_reload:${message}` afterEach(() => { cleanup() + // Clears the shared state left by a test that ends while the page is leaving. + window.dispatchEvent(new Event('pageshow')) sessionStorage.clear() vi.restoreAllMocks() }) @@ -91,3 +93,55 @@ test('reloads once if the retried import is still missing after the page stays', await vi.waitFor(() => expect(sessionStorage.getItem(reloadKey)).toBe('1')) expect(importer).toHaveBeenCalledTimes(2) }) + +test('does not reload for an import that starts after the page began unloading', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const pending = createControlledPromise() + const late = createControlledPromise() + const Other = lazyRouteComponent(() => pending) + const importer = vi + .fn() + .mockReturnValueOnce(late) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + // Another route is still loading when the user leaves. + void Other.preload!() + window.dispatchEvent(new Event('beforeunload')) + + // This import starts after beforeunload and is cancelled by the unload. + const preload = Page.preload!() + late.reject(new TypeError(message)) + await preload + + render(Page) + expect(sessionStorage.getItem(reloadKey)).toBeNull() + + await fireEvent.pointerDown(document.body) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +}) + +test('retries an import that the unload cancels after the route mounted', async () => { + vi.spyOn(console, 'error').mockImplementation(() => {}) + const first = createControlledPromise() + const importer = vi + .fn() + .mockReturnValueOnce(first) + .mockResolvedValueOnce({ default: () =>
Loaded
}) + const Page = lazyRouteComponent(importer) + + // Mounting starts the import. + render(Page) + await vi.waitFor(() => expect(importer).toHaveBeenCalledTimes(1)) + window.dispatchEvent(new Event('beforeunload')) + first.reject(new TypeError(message)) + // Let the failed import settle before the page shows it stayed. + await new Promise((resolve) => setTimeout(resolve)) + + await fireEvent.pointerDown(document.body) + expect(await screen.findByText('Loaded')).toBeInTheDocument() + expect(importer).toHaveBeenCalledTimes(2) + expect(sessionStorage.getItem(reloadKey)).toBeNull() +})