Commit f0292f68 authored by Jimmy Lai's avatar Jimmy Lai

fix: suppress error boundary flash during page unload

When `router.refresh()` is in-flight and user refreshes the page,
the browser aborts the RSC fetch which causes an error that briefly
renders the error boundary before the page unloads.

This fix checks `isPageUnloading` in the error boundary's render
method and suppresses the error UI when the page is unloading.

Fixes #87681
parent 8fd79ff4
...@@ -6,6 +6,7 @@ import { isNextRouterError } from './is-next-router-error' ...@@ -6,6 +6,7 @@ import { isNextRouterError } from './is-next-router-error'
import { handleHardNavError } from './nav-failure-handler' import { handleHardNavError } from './nav-failure-handler'
import { HandleISRError } from './handle-isr-error' import { HandleISRError } from './handle-isr-error'
import { isBot } from '../../shared/lib/router/utils/is-bot' import { isBot } from '../../shared/lib/router/utils/is-bot'
import { getIsPageUnloading } from './router-reducer/fetch-server-response'
const isBotUserAgent = const isBotUserAgent =
typeof window !== 'undefined' && isBot(window.navigator.userAgent) typeof window !== 'undefined' && isBot(window.navigator.userAgent)
...@@ -97,9 +98,11 @@ export class ErrorBoundaryHandler extends React.Component< ...@@ -97,9 +98,11 @@ export class ErrorBoundaryHandler extends React.Component<
// Explicit type is needed to avoid the generated `.d.ts` having a wide return type that could be specific to the `@types/react` version. // Explicit type is needed to avoid the generated `.d.ts` having a wide return type that could be specific to the `@types/react` version.
render(): React.ReactNode { render(): React.ReactNode {
//When it's bot request, segment level error boundary will keep rendering the children, // When it's bot request, segment level error boundary will keep rendering the children,
// the final error will be caught by the root error boundary and determine wether need to apply graceful degrade. // the final error will be caught by the root error boundary and determine wether need to apply graceful degrade.
if (this.state.error && !isBotUserAgent) { // Also suppress error rendering when the page is unloading (e.g., during manual refresh)
// to prevent a brief flash of the error boundary before the page reloads.
if (this.state.error && !isBotUserAgent && !getIsPageUnloading()) {
return ( return (
<> <>
<HandleISRError error={this.state.error} /> <HandleISRError error={this.state.error} />
......
...@@ -118,6 +118,10 @@ if (typeof window !== 'undefined') { ...@@ -118,6 +118,10 @@ if (typeof window !== 'undefined') {
}) })
} }
export function getIsPageUnloading(): boolean {
return isPageUnloading
}
/** /**
* Fetch the flight data for the provided url. Takes in the current router state * Fetch the flight data for the provided url. Takes in the current router state
* to decide what to render server-side. * to decide what to render server-side.
......
'use client'
import { useRouter } from 'next/navigation'
import { useTransition } from 'react'
export default function Client() {
const router = useRouter()
const [isPending, startTransition] = useTransition()
return (
<div>
<button
id="refresh-button"
disabled={isPending}
onClick={() => {
startTransition(() => {
router.refresh()
})
}}
>
{isPending ? 'Refreshing...' : 'router.refresh()'}
</button>
<button
id="reload-button"
onClick={() => {
window.location.reload()
}}
>
Reload page
</button>
</div>
)
}
'use client'
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
// Use localStorage to persist that error boundary rendered, even across page reload
// This is needed because console logs are cleared on page reload
if (typeof window !== 'undefined') {
window.localStorage.setItem(
'__ERROR_BOUNDARY_RENDERED__',
JSON.stringify({
rendered: true,
message: error.message,
time: Date.now(),
})
)
}
return (
<div id="error-boundary">
<h2>Something went wrong!</h2>
<p id="error-message">{error.message}</p>
<button onClick={() => reset()}>Try again</button>
</div>
)
}
import { connection } from 'next/server'
import Client from './client'
export default async function Page() {
await connection()
return (
<div>
<div id="page-content">Page loaded successfully</div>
<Client />
</div>
)
}
...@@ -100,4 +100,96 @@ describe('app-dir refresh', () => { ...@@ -100,4 +100,96 @@ describe('app-dir refresh', () => {
expect(await browser.hasElementByCssSelector('#foo-page')).toBe(true) expect(await browser.hasElementByCssSelector('#foo-page')).toBe(true)
expect(await browser.url()).toContain('/redirect-and-refresh/foo') expect(await browser.url()).toContain('/redirect-and-refresh/foo')
}) })
it('should not show error boundary when page is reloaded during pending router.refresh()', async () => {
const browser = await next.browser('/refresh-during-unload')
// Wait for the page to fully load
await retry(async () => {
const content = await browser.elementById('page-content').text()
expect(content).toBe('Page loaded successfully')
}, 10000)
// Clear any previous localStorage flag before the test
await browser.eval(
'window.localStorage.removeItem("__ERROR_BOUNDARY_RENDERED__")'
)
// Intercept fetch - let first chunk through, then dispatch pagehide and error
// This simulates what happens when browser aborts mid-stream during page refresh
await browser.eval(`
window.__fetchIntercepted = false;
const originalFetch = window.fetch;
window.fetch = async function(url, options) {
const urlStr = typeof url === 'string' ? url : url.toString();
const hasRscHeader = options?.headers?.['RSC'] === '1' ||
options?.headers?.['Next-Router-State-Tree'];
if (urlStr.includes('_rsc') || hasRscHeader) {
console.log('[TEST] RSC request intercepted');
window.__fetchIntercepted = true;
// Make the real fetch
const response = await originalFetch.call(this, url, options);
console.log('[TEST] Got response');
const reader = response.body.getReader();
let firstChunk = true;
const errorStream = new ReadableStream({
async pull(controller) {
const { done, value } = await reader.read();
if (done) {
controller.close();
return;
}
if (firstChunk) {
console.log('[TEST] Passing first chunk through');
firstChunk = false;
controller.enqueue(value);
} else {
// Simulate page unload: dispatch pagehide BEFORE the error
// This is what happens in real browser when user refreshes the page
console.log('[TEST] Dispatching pagehide event');
window.dispatchEvent(new Event('pagehide'));
// Then error (simulates browser aborting the connection)
console.log('[TEST] Erroring on second chunk');
controller.error(new DOMException('The operation was aborted.', 'AbortError'));
}
}
});
return new Response(errorStream, {
status: response.status,
statusText: response.statusText,
headers: response.headers
});
}
return originalFetch.apply(this, arguments);
};
`)
// Click router.refresh() to start a pending refresh
await browser.elementById('refresh-button').click()
// Wait for the error to propagate through React
await new Promise((resolve) => setTimeout(resolve, 3000))
// Check if error boundary rendered - check both localStorage and DOM
const errorBoundaryFlag = await browser.eval(
'window.localStorage.getItem("__ERROR_BOUNDARY_RENDERED__")'
)
const hasErrorBoundaryElement = await browser.eval(
'document.getElementById("error-boundary") !== null'
)
console.log('[TEST] Error boundary flag:', errorBoundaryFlag)
console.log(
'[TEST] Error boundary element exists:',
hasErrorBoundaryElement
)
// Without the fix, this SHOULD fail (error boundary rendered)
// With the fix, this should pass (error boundary NOT rendered)
expect(errorBoundaryFlag).toBeNull()
expect(hasErrorBoundaryElement).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