Commit 98317f5a authored by Zack Tanner's avatar Zack Tanner Committed by Jiachi Liu

fix: prevent fetch abort errors propagating to user error boundaries (#86277)

When navigating away from a page due to an MPA navigation or browser
refresh, we were aborting any pending RSC requests. However, in the case
where the abort was due to an MPA navigation, the browser would restore
the execution context via the built-in bfcache, and the aborted fetch
would cause React to get in an errored state, leading to
"BodyStreamBuffer was aborted".

Rather than aborting the pending requests, we instead mark that we would
have aborted due to the page unloading. That still solves the original
reason the flag was added (suppressing the fetch errors that get logged)

Fixes NAR-519
parent 7780025a
...@@ -102,21 +102,20 @@ function doMpaNavigation(url: string): FetchServerResponseResult { ...@@ -102,21 +102,20 @@ function doMpaNavigation(url: string): FetchServerResponseResult {
return urlToUrlWithoutFlightMarker(new URL(url, location.origin)).toString() return urlToUrlWithoutFlightMarker(new URL(url, location.origin)).toString()
} }
let abortController = new AbortController() let isPageUnloading = false
if (typeof window !== 'undefined') { if (typeof window !== 'undefined') {
// Abort any in-flight requests when the page is unloaded, e.g. due to // Track when the page is unloading, e.g. due to reloading the page or
// reloading the page or performing hard navigations. This allows us to ignore // performing hard navigations. This allows us to suppress error logging when
// what would otherwise be a thrown TypeError when the browser cancels the // the browser cancels in-flight requests during page unload.
// requests.
window.addEventListener('pagehide', () => { window.addEventListener('pagehide', () => {
abortController.abort() isPageUnloading = true
}) })
// Use a fresh AbortController instance on pageshow, e.g. when navigating back // Reset the flag on pageshow, e.g. when navigating back and the JavaScript
// and the JavaScript execution context is restored by the browser. // execution context is restored by the browser.
window.addEventListener('pageshow', () => { window.addEventListener('pageshow', () => {
abortController = new AbortController() isPageUnloading = false
}) })
} }
...@@ -197,8 +196,7 @@ export async function fetchServerResponse( ...@@ -197,8 +196,7 @@ export async function fetchServerResponse(
url, url,
headers, headers,
fetchPriority, fetchPriority,
shouldImmediatelyDecode, shouldImmediatelyDecode
abortController.signal
) )
const responseUrl = urlToUrlWithoutFlightMarker(new URL(res.url)) const responseUrl = urlToUrlWithoutFlightMarker(new URL(res.url))
...@@ -287,7 +285,7 @@ export async function fetchServerResponse( ...@@ -287,7 +285,7 @@ export async function fetchServerResponse(
debugInfo: flightResponsePromise._debugInfo ?? null, debugInfo: flightResponsePromise._debugInfo ?? null,
} }
} catch (err) { } catch (err) {
if (!abortController.signal.aborted) { if (!isPageUnloading) {
console.error( console.error(
`Failed to fetch RSC payload for ${originalUrl}. Falling back to browser navigation.`, `Failed to fetch RSC payload for ${originalUrl}. Falling back to browser navigation.`,
err err
......
import React from 'react'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
import { useRouter } from 'next/navigation'
export function TriggerMpaNavigation() {
const router = useRouter()
return (
<button
id="trigger-navigation"
onClick={async () => {
router.push('/slow-page')
await new Promise((resolve) => setTimeout(resolve, 500))
router.push('/other-root')
}}
>
Trigger Navigation
</button>
)
}
import { TriggerMpaNavigation } from './mpa'
export default function StartPage() {
return (
<div style={{ padding: '20px' }}>
<h1 id="start-page">Start Page</h1>
<TriggerMpaNavigation />
</div>
)
}
import { connection } from 'next/server'
import { Suspense } from 'react'
async function SlowData() {
// Artificial delay to simulate slow RSC fetch
await connection()
await new Promise((resolve) => setTimeout(resolve, 5_000))
return (
<div
id="slow-data-loaded"
style={{ padding: '10px', background: '#e0e0ff' }}
>
Slow data loaded successfully!
</div>
)
}
export default function SlowPage() {
return (
<div id="slow-page">
<Suspense
fallback={<div id="loading-slow-data">Loading slow data...</div>}
>
<SlowData />
</Suspense>
</div>
)
}
import React from 'react'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function StartPage() {
return <div id="root-2">Root 2</div>
}
'use client' // Error boundaries must be Client Components
export default function GlobalError({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
return (
// global-error must include html and body tags
<html>
<body>
<h2 id="global-error">Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</body>
</html>
)
}
import { nextTestSetup } from 'e2e-utils'
const describeHeaded = process.env.HEADLESS ? describe.skip : describe
describeHeaded('fetch-abort-on-refresh', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should not show abort error in global error boundary when restoring from bfcache', async () => {
// This test ensures that when restoring a page from the browser bfcache that was pending RSC data,
// that the abort does not propagate to a user's error boundary.
const browser = await next.browser('/', { headless: false })
await browser.elementById('trigger-navigation').click()
await browser.waitForElementByCss('#root-2')
// Go back to trigger bfcache restoration
// we overwrite the typical waitUntil: 'load' option here as the event is never being triggered if we hit the bfcache
await browser.back({ waitUntil: 'commit' })
// Check that we're back on the slow page (the page that was first redirected to, before the MPA, not the error boundary)
// We use element checks instead of eval() because eval() triggers waitForLoadState which times out with bfcache
const hasSlowPage = await browser.hasElementByCss('#slow-page')
const hasGlobalError = await browser.hasElementByCss(
'h2:has-text("Something went wrong!")'
)
expect(hasSlowPage).toBe(true)
expect(hasGlobalError).toBe(false)
})
})
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment