Skip to content

Commit 936a107

Browse files
committed
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
1 parent da2adec commit 936a107

9 files changed

Lines changed: 314 additions & 5 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
---
2+
'@tanstack/router-core': patch
3+
'@tanstack/react-router': patch
4+
'@tanstack/solid-router': patch
5+
'@tanstack/vue-router': patch
6+
---
7+
8+
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.

‎packages/react-router/src/lazyRouteComponent.tsx‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
11
import * as React from 'react'
2-
import { isModuleNotFoundError } from '@tanstack/router-core'
2+
import {
3+
isModuleNotFoundError,
4+
waitForPageToStay,
5+
watchPageUnload,
6+
} from '@tanstack/router-core'
37
import { isServer } from '@tanstack/router-core/isServer'
48
import { reactUse } from './utils'
59
import type { AsyncRouteComponent } from './route'
@@ -25,12 +29,17 @@ export function lazyRouteComponent<
2529
let loadPromise: Promise<any> | undefined
2630
let comp: T[TKey] | T['default']
2731
let error: any
32+
let cancelledByUnload = false
33+
let staying: Promise<void> | undefined
2834

2935
const load = () => {
3036
if (!loadPromise) {
3137
error = undefined
38+
cancelledByUnload = false
39+
const stopWatchingUnload = watchPageUnload()
3240
loadPromise = importer()
3341
.then((res) => {
42+
stopWatchingUnload()
3443
// Resolved clients have no preload work; SSR can reuse the import.
3544
if (!(isServer ?? typeof window === 'undefined')) {
3645
loadPromise = undefined
@@ -40,6 +49,7 @@ export function lazyRouteComponent<
4049
})
4150
.catch((err) => {
4251
loadPromise = undefined
52+
cancelledByUnload = stopWatchingUnload() && isModuleNotFoundError(err)
4353
// We don't want an error thrown from preload in this case, because
4454
// there's nothing we want to do about module not found during preload.
4555
// Record the error, the rest is handled during the render path.
@@ -51,6 +61,17 @@ export function lazyRouteComponent<
5161
}
5262
const lazyComp = function Lazy(props: any) {
5363
if (error) {
64+
// The browser cancelled the import because the page is unloading, so a
65+
// reload would replace the navigation the user started. If the page
66+
// stays after all, retry the import instead.
67+
if (cancelledByUnload) {
68+
staying ??= waitForPageToStay().then(() => {
69+
staying = undefined
70+
error = undefined
71+
cancelledByUnload = false
72+
})
73+
throw staying
74+
}
5475
// A missing module can mean that a newer deployment replaced the URL.
5576
// Reload only for the error that is still current at render time, so a
5677
// successful retry cannot leave a stale reload request armed.
Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
import * as React from 'react'
2+
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
3+
import { afterEach, expect, test, vi } from 'vitest'
4+
import { createControlledPromise } from '@tanstack/router-core'
5+
import { lazyRouteComponent } from '../src'
6+
7+
// https://github.com/TanStack/router/issues/8827
8+
const message =
9+
'error loading dynamically imported module: http://localhost/assets/page.js'
10+
const reloadKey = `tanstack_router_reload:${message}`
11+
12+
afterEach(() => {
13+
cleanup()
14+
sessionStorage.clear()
15+
vi.restoreAllMocks()
16+
})
17+
18+
// jsdom cannot reload, so React retries the render and reaches the error that
19+
// the reload guard rethrows once its key is set.
20+
class ErrorBoundary extends React.Component<
21+
{ children: React.ReactNode },
22+
{ error: unknown }
23+
> {
24+
state: { error: unknown } = { error: undefined }
25+
static getDerivedStateFromError(error: unknown) {
26+
return { error }
27+
}
28+
render() {
29+
return this.state.error ? <div>Error</div> : this.props.children
30+
}
31+
}
32+
33+
function renderLazy(Page: ReturnType<typeof lazyRouteComponent>) {
34+
return render(
35+
<ErrorBoundary>
36+
<React.Suspense fallback={<div>Loading</div>}>
37+
<Page />
38+
</React.Suspense>
39+
</ErrorBoundary>,
40+
)
41+
}
42+
43+
test('does not reload when the import is cancelled because the page is unloading', async () => {
44+
vi.spyOn(console, 'error').mockImplementation(() => {})
45+
const first = createControlledPromise<never>()
46+
const importer = vi
47+
.fn()
48+
.mockReturnValueOnce(first)
49+
.mockResolvedValueOnce({ default: () => <div>Loaded</div> })
50+
const Page = lazyRouteComponent(importer)
51+
52+
const preload = Page.preload!()
53+
window.dispatchEvent(new Event('beforeunload'))
54+
first.reject(new TypeError(message))
55+
await preload
56+
57+
renderLazy(Page)
58+
expect(screen.getByText('Loading')).toBeInTheDocument()
59+
expect(sessionStorage.getItem(reloadKey)).toBeNull()
60+
61+
// The page stayed after all, so the import is retried.
62+
fireEvent.pointerDown(document.body)
63+
expect(await screen.findByText('Loaded')).toBeInTheDocument()
64+
expect(importer).toHaveBeenCalledTimes(2)
65+
expect(sessionStorage.getItem(reloadKey)).toBeNull()
66+
})
67+
68+
test('reloads once if the retried import is still missing after the page stays', async () => {
69+
vi.spyOn(console, 'error').mockImplementation(() => {})
70+
const first = createControlledPromise<never>()
71+
const importer = vi
72+
.fn()
73+
.mockReturnValueOnce(first)
74+
.mockRejectedValueOnce(new TypeError(message))
75+
const Page = lazyRouteComponent(importer)
76+
77+
const preload = Page.preload!()
78+
window.dispatchEvent(new Event('beforeunload'))
79+
first.reject(new TypeError(message))
80+
await preload
81+
82+
renderLazy(Page)
83+
fireEvent.keyDown(document.body)
84+
await vi.waitFor(() => expect(sessionStorage.getItem(reloadKey)).toBe('1'))
85+
expect(importer).toHaveBeenCalledTimes(2)
86+
})
87+
88+
test('still reloads once for a missing module when the page is not unloading', async () => {
89+
vi.spyOn(console, 'error').mockImplementation(() => {})
90+
const Page = lazyRouteComponent(() => Promise.reject(new TypeError(message)))
91+
92+
await Page.preload!()
93+
renderLazy(Page)
94+
95+
expect(sessionStorage.getItem(reloadKey)).toBe('1')
96+
})
97+
98+
test('stops watching for unload once the import settles', async () => {
99+
vi.spyOn(console, 'error').mockImplementation(() => {})
100+
const Page = lazyRouteComponent(() => Promise.reject(new TypeError(message)))
101+
102+
await Page.preload!()
103+
// A later unload must not be attributed to the import that already failed.
104+
window.dispatchEvent(new Event('beforeunload'))
105+
renderLazy(Page)
106+
107+
expect(sessionStorage.getItem(reloadKey)).toBe('1')
108+
})

‎packages/router-core/src/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -322,6 +322,8 @@ export {
322322
createControlledPromise,
323323
isPromise,
324324
isModuleNotFoundError,
325+
watchPageUnload,
326+
waitForPageToStay,
325327
DEFAULT_PROTOCOL_ALLOWLIST,
326328
escapeHtml,
327329
getUrlScheme,

‎packages/router-core/src/utils.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -516,6 +516,48 @@ export function isModuleNotFoundError(error: any): boolean {
516516
)
517517
}
518518

519+
/**
520+
* Firefox and Safari cancel a pending dynamic import when the page starts to
521+
* unload, and reject it with the same message as a missing module. Call this
522+
* before an import, and the returned function after it settles: it stops
523+
* watching and reports whether the page began unloading in between, in which
524+
* case the failure says nothing about a stale deployment.
525+
*/
526+
export function watchPageUnload(): () => boolean {
527+
if (typeof window === 'undefined') {
528+
return () => false
529+
}
530+
let unloading = false
531+
const onBeforeUnload = () => {
532+
unloading = true
533+
}
534+
window.addEventListener('beforeunload', onBeforeUnload)
535+
return () => {
536+
window.removeEventListener('beforeunload', onBeforeUnload)
537+
return unloading
538+
}
539+
}
540+
541+
/**
542+
* Resolves on the first sign that the page is still in use after
543+
* `beforeunload`. Some browsers fire it for `mailto:` or download links without
544+
* leaving, and a page restored from the back/forward cache comes back too.
545+
*/
546+
export function waitForPageToStay(): Promise<void> {
547+
return new Promise((resolve) => {
548+
const events = ['pageshow', 'pointerdown', 'keydown'] as const
549+
const stay = () => {
550+
for (const event of events) {
551+
window.removeEventListener(event, stay, true)
552+
}
553+
resolve()
554+
}
555+
for (const event of events) {
556+
window.addEventListener(event, stay, true)
557+
}
558+
})
559+
}
560+
519561
export function isPromise<T>(
520562
value: Promise<Awaited<T>> | T,
521563
): value is Promise<Awaited<T>> {

‎packages/solid-router/src/lazyRouteComponent.tsx‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
import { Dynamic } from 'solid-js/web'
22
import { lazy } from 'solid-js'
3-
import { isModuleNotFoundError } from '@tanstack/router-core'
3+
import {
4+
isModuleNotFoundError,
5+
waitForPageToStay,
6+
watchPageUnload,
7+
} from '@tanstack/router-core'
48
import { isServer } from '@tanstack/router-core/isServer'
59
import type { AsyncRouteComponent } from './route'
610

@@ -16,12 +20,16 @@ export function lazyRouteComponent<
1620
let loadPromise: Promise<any> | undefined
1721
let comp: T[TKey] | T['default']
1822
let error: any
23+
let cancelledByUnload = false
1924

2025
const load = () => {
2126
if (!loadPromise) {
2227
error = undefined
28+
cancelledByUnload = false
29+
const stopWatchingUnload = watchPageUnload()
2330
loadPromise = importer()
2431
.then((res) => {
32+
stopWatchingUnload()
2533
// Resolved clients have no preload work; SSR can reuse the import.
2634
if (!(isServer ?? typeof window === 'undefined')) {
2735
loadPromise = undefined
@@ -32,6 +40,7 @@ export function lazyRouteComponent<
3240
})
3341
.catch((err) => {
3442
loadPromise = undefined
43+
cancelledByUnload = stopWatchingUnload() && isModuleNotFoundError(err)
3544
error = err
3645
})
3746
}
@@ -48,6 +57,18 @@ export function lazyRouteComponent<
4857

4958
// Both preload and lazy resolution end here without starting another load.
5059
function render(props: any) {
60+
// The browser cancelled the import because the page is unloading, so a
61+
// reload would replace the navigation the user started. If the page stays
62+
// after all, retry the import instead.
63+
if (error && cancelledByUnload) {
64+
const Retry = lazy(async () => {
65+
await waitForPageToStay()
66+
await load()
67+
return { default: render }
68+
})
69+
return <Retry {...props} />
70+
}
71+
5172
// Now that we're out of preload and into actual render path,
5273
// throw the error if it was a module not found error during preload
5374
if (error) {
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library'
2+
import { afterEach, expect, test, vi } from 'vitest'
3+
import { createControlledPromise } from '@tanstack/router-core'
4+
import { lazyRouteComponent } from '../src'
5+
6+
// https://github.com/TanStack/router/issues/8827
7+
const message =
8+
'error loading dynamically imported module: http://localhost/assets/page.js'
9+
const reloadKey = `tanstack_router_reload:${message}`
10+
11+
afterEach(() => {
12+
cleanup()
13+
sessionStorage.clear()
14+
vi.restoreAllMocks()
15+
})
16+
17+
test('does not reload when the import is cancelled because the page is unloading', async () => {
18+
vi.spyOn(console, 'error').mockImplementation(() => {})
19+
const first = createControlledPromise<never>()
20+
const importer = vi
21+
.fn()
22+
.mockReturnValueOnce(first)
23+
.mockResolvedValueOnce({ default: () => <div>Loaded</div> })
24+
const Page = lazyRouteComponent(importer)
25+
26+
const preload = Page.preload!()
27+
window.dispatchEvent(new Event('beforeunload'))
28+
first.reject(new TypeError(message))
29+
await preload
30+
31+
render(() => <Page />)
32+
expect(sessionStorage.getItem(reloadKey)).toBeNull()
33+
34+
// The page stayed after all, so the import is retried.
35+
fireEvent.pointerDown(document.body)
36+
expect(await screen.findByText('Loaded')).toBeInTheDocument()
37+
expect(importer).toHaveBeenCalledTimes(2)
38+
expect(sessionStorage.getItem(reloadKey)).toBeNull()
39+
})
40+
41+
test('still reloads once for a missing module when the page is not unloading', async () => {
42+
vi.spyOn(console, 'error').mockImplementation(() => {})
43+
const Page = lazyRouteComponent(() => Promise.reject(new TypeError(message)))
44+
45+
await Page.preload!()
46+
render(() => <Page />)
47+
48+
expect(sessionStorage.getItem(reloadKey)).toBe('1')
49+
})

‎packages/vue-router/src/lazyRouteComponent.tsx‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as Vue from 'vue'
2+
import { waitForPageToStay, watchPageUnload } from '@tanstack/router-core'
23
import { Outlet } from './Match'
34
import { ClientOnly } from './ClientOnly'
45
import type { AsyncRouteComponent } from './route'
@@ -34,6 +35,7 @@ export function lazyRouteComponent<
3435
let comp: T[TKey] | T['default'] | null = null
3536
let error: any = null
3637
let attemptedReload = false
38+
let cancelledByUnload = false
3739

3840
const load = () => {
3941
// If we're on the server and SSR is disabled for this component
@@ -45,8 +47,11 @@ export function lazyRouteComponent<
4547
// Use existing promise or create new one
4648
if (!loadPromise) {
4749
error = undefined
50+
cancelledByUnload = false
51+
const stopWatchingUnload = watchPageUnload()
4852
loadPromise = importer()
4953
.then((res) => {
54+
stopWatchingUnload()
5055
if (typeof document !== 'undefined') {
5156
loadPromise = undefined
5257
;(lazyComp as any).preload = undefined
@@ -57,6 +62,7 @@ export function lazyRouteComponent<
5762
.catch((err) => {
5863
error = err
5964
loadPromise = undefined
65+
cancelledByUnload = stopWatchingUnload() && isModuleNotFoundError(err)
6066

6167
// If it's a module not found error, we'll try to handle it in the component
6268
if (isModuleNotFoundError(error)) {
@@ -76,15 +82,18 @@ export function lazyRouteComponent<
7682
// Create refs to track component state
7783
// Use shallowRef for component to avoid making it reactive (Vue warning)
7884
const component = Vue.shallowRef<any>(comp ? Vue.markRaw(comp) : comp)
79-
const errorState = Vue.ref<any>(error)
85+
// The browser cancelled the import because the page is unloading, so a
86+
// reload would replace the navigation the user started. If the page
87+
// stays after all, retry the import instead.
88+
const retryAfterUnload = !!error && cancelledByUnload
89+
const errorState = Vue.ref<any>(retryAfterUnload ? null : error)
8090
const loading = Vue.ref(!component.value && !errorState.value)
8191

8292
// Setup effect to load the component when this component is used
8393
Vue.onMounted(() => {
8494
if (!component.value && !errorState.value) {
8595
loading.value = true
86-
87-
load()
96+
;(retryAfterUnload ? waitForPageToStay().then(load) : load())
8897
.then((result) => {
8998
// Use markRaw to prevent Vue from making the component reactive
9099
component.value = result ? Vue.markRaw(result) : result

0 commit comments

Comments
 (0)