Commit 523302a7 authored by Jimmy Lai's avatar Jimmy Lai

Add banner UI for chunk load errors

parent e5cff26b
'use client'
import { useCallback, useState, useEffect } from 'react'
// Copy constants (two lines, always)
const HEADLINE = "This page couldn't be fully loaded"
const DETAIL_DEFAULT = "A required file couldn't be loaded."
const DETAIL_OFFLINE = "You're offline."
// Fixed height for stable layout
const BANNER_HEIGHT = 70
const styles = {
container: {
position: 'fixed' as const,
top: 0,
left: 0,
right: 0,
zIndex: 9999,
height: BANNER_HEIGHT,
padding: '0 20px',
backgroundColor: '#f5f5f5',
borderBottom: '1px solid #d4d4d4',
fontFamily:
'system-ui, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji"',
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: '16px',
boxSizing: 'border-box' as const,
},
spacer: {
height: BANNER_HEIGHT,
flexShrink: 0,
},
left: {
display: 'flex',
alignItems: 'center',
gap: '12px',
flex: 1,
minWidth: 0,
},
icon: {
flexShrink: 0,
width: '20px',
height: '20px',
},
content: {
display: 'flex',
flexDirection: 'column' as const,
gap: '2px',
flex: 1,
minWidth: 0,
},
headline: {
fontSize: '14px',
fontWeight: 600,
color: '#171717',
margin: 0,
lineHeight: 1.4,
},
detail: {
fontSize: '13px',
fontWeight: 400,
color: '#525252',
margin: 0,
lineHeight: 1.4,
},
button: {
padding: '8px 16px',
fontSize: '13px',
fontWeight: 600,
borderRadius: '6px',
cursor: 'pointer',
color: '#171717',
backgroundColor: '#fff',
border: '1px solid #a3a3a3',
lineHeight: 1,
flexShrink: 0,
},
} as const
// Neutral warning icon (circle with exclamation)
function WarningIcon() {
return (
<svg
style={styles.icon}
viewBox="0 0 20 20"
fill="none"
xmlns="http://www.w3.org/2000/svg"
aria-hidden="true"
>
<circle cx="10" cy="10" r="9" stroke="#737373" strokeWidth="1.5" />
<path
d="M10 5.5V11"
stroke="#737373"
strokeWidth="1.5"
strokeLinecap="round"
/>
<circle cx="10" cy="14" r="1" fill="#737373" />
</svg>
)
}
export interface ChunkLoadErrorBannerProps {
pathname: string
error: Error
}
export function ChunkLoadErrorBanner(_props: ChunkLoadErrorBannerProps) {
const [isOffline, setIsOffline] = useState(
typeof navigator !== 'undefined' ? !navigator.onLine : false
)
useEffect(() => {
const handleOnline = () => setIsOffline(false)
const handleOffline = () => setIsOffline(true)
window.addEventListener('online', handleOnline)
window.addEventListener('offline', handleOffline)
return () => {
window.removeEventListener('online', handleOnline)
window.removeEventListener('offline', handleOffline)
}
}, [])
const handleReload = useCallback(() => {
window.location.reload()
}, [])
const detail = isOffline ? DETAIL_OFFLINE : DETAIL_DEFAULT
return (
<>
{/* Fixed banner at top of viewport - immune to body margin */}
<div style={styles.container} role="alert" aria-live="assertive">
<div style={styles.left}>
<WarningIcon />
<div style={styles.content}>
<p style={styles.headline}>{HEADLINE}</p>
<p style={styles.detail}>{detail}</p>
</div>
</div>
<button type="button" style={styles.button} onClick={handleReload}>
Reload page
</button>
</div>
{/* Spacer to push content down */}
<div style={styles.spacer} />
</>
)
}
......@@ -16,6 +16,8 @@ declare global {
| undefined
}
export type ChunkErrorAction = 'retry' | 'banner'
/**
* Context for chunk error handling.
* Tracks where the error occurred and what kind of error it was.
......@@ -290,16 +292,17 @@ export function createChunkErrorContext(
}
/**
* Handle a chunk load failure and determine if we should retry.
* Handle a chunk load failure and determine the action to take.
*
* Returns true if a silent retry should be attempted, false otherwise.
* Returns 'retry' if a silent retry should be attempted,
* or 'banner' if the error should be shown to the user.
* This function updates the failure tracking state.
*/
export function handleChunkFailure(ctx: ChunkErrorContext): boolean {
export function handleChunkFailure(ctx: ChunkErrorContext): ChunkErrorAction {
// Don't count offline failures toward retry limit - they're expected
// and will succeed once connectivity is restored
if (typeof navigator !== 'undefined' && !navigator.onLine) {
return false
return 'banner'
}
// Record failure for online attempts
......@@ -308,10 +311,10 @@ export function handleChunkFailure(ctx: ChunkErrorContext): boolean {
// Check if we should try a silent retry
if (shouldSilentRetry(ctx)) {
markRetried(ctx)
return true
return 'retry'
}
return false
return 'banner'
}
/**
......@@ -325,9 +328,9 @@ export async function retryChunkImport<T>(
ctx: ChunkErrorContext,
importFn: () => Promise<T>
): Promise<T> {
const shouldRetry = handleChunkFailure(ctx)
const action = handleChunkFailure(ctx)
if (shouldRetry) {
if (action === 'retry') {
const delay = getRetryDelayMs()
await sleep(delay)
return importFn()
......
......@@ -6,6 +6,9 @@ import { isNextRouterError } from './is-next-router-error'
import { handleHardNavError } from './nav-failure-handler'
import { HandleISRError } from './handle-isr-error'
import { isBot } from '../../shared/lib/router/utils/is-bot'
import { isChunkOrNetworkError } from './chunk-load-error/is-chunk-load-error'
import { ChunkLoadErrorBanner } from './chunk-load-error/chunk-load-error-banner'
import type { ChunkErrorAction } from './chunk-load-error/chunk-load-error-handler'
const isBotUserAgent =
typeof window !== 'undefined' && isBot(window.navigator.userAgent)
......@@ -32,6 +35,8 @@ interface ErrorBoundaryHandlerProps extends ErrorBoundaryProps {
interface ErrorBoundaryHandlerState {
error: Error | null
previousPathname: string | null
chunkErrorAction: ChunkErrorAction | null
frozenHTML: string | null
}
export class ErrorBoundaryHandler extends React.Component<
......@@ -40,7 +45,12 @@ export class ErrorBoundaryHandler extends React.Component<
> {
constructor(props: ErrorBoundaryHandlerProps) {
super(props)
this.state = { error: null, previousPathname: this.props.pathname }
this.state = {
error: null,
previousPathname: this.props.pathname,
chunkErrorAction: null,
frozenHTML: null,
}
}
static getDerivedStateFromError(error: Error) {
......@@ -50,7 +60,33 @@ export class ErrorBoundaryHandler extends React.Component<
throw error
}
return { error }
// Check if this is a chunk load or network error
if (isChunkOrNetworkError(error)) {
// Capture the current body content before React re-renders with error UI.
// getDerivedStateFromError runs during the render phase, so the DOM still
// has the original content at this point.
let frozenHTML: string | null = null
if (typeof document !== 'undefined' && document.body) {
frozenHTML = document.body.innerHTML
}
return {
error,
chunkErrorAction: 'banner' as ChunkErrorAction,
frozenHTML,
}
}
// For non-chunk errors, explicitly reset chunk error state to ensure the
// correct error UI is rendered. This is necessary because React performs
// shallow state merging - if a chunk error occurred previously and set
// chunkErrorAction to 'banner', a subsequent non-chunk error would otherwise
// keep that banner action set due to state merging.
return {
error,
chunkErrorAction: null,
frozenHTML: null,
}
}
static getDerivedStateFromProps(
......@@ -69,6 +105,8 @@ export class ErrorBoundaryHandler extends React.Component<
return {
error: null,
previousPathname: props.pathname,
chunkErrorAction: null,
frozenHTML: null,
}
}
}
......@@ -83,36 +121,70 @@ export class ErrorBoundaryHandler extends React.Component<
return {
error: null,
previousPathname: props.pathname,
chunkErrorAction: null,
frozenHTML: null,
}
}
return {
error: state.error,
previousPathname: props.pathname,
chunkErrorAction: state.chunkErrorAction,
frozenHTML: state.frozenHTML,
}
}
reset = () => {
this.setState({ error: null })
this.setState({
error: null,
chunkErrorAction: null,
frozenHTML: null,
})
}
// 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 {
//When it's bot request, segment level error boundary will keep rendering the children,
const { error, chunkErrorAction } = this.state
// 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.
if (this.state.error && !isBotUserAgent) {
if (error && !isBotUserAgent) {
// Show banner for chunk load errors
if (chunkErrorAction === 'banner') {
// For chunk errors, we preserve the page content captured from document.body
// in getDerivedStateFromError (before React commits error UI).
// Banner renders first (sticky top) and pushes frozen content down.
const { frozenHTML } = this.state
return (
<>
<HandleISRError error={error} />
<ChunkLoadErrorBanner
pathname={this.props.pathname || '/'}
error={error}
/>
{frozenHTML && (
<div
style={{ pointerEvents: 'none' }}
suppressHydrationWarning
aria-hidden="true"
dangerouslySetInnerHTML={{ __html: frozenHTML }}
/>
)}
</>
)
}
// Full-page error for non-chunk errors
return (
<>
<HandleISRError error={this.state.error} />
<HandleISRError error={error} />
{this.props.errorStyles}
{this.props.errorScripts}
<this.props.errorComponent
error={this.state.error}
reset={this.reset}
/>
<this.props.errorComponent error={error} reset={this.reset} />
</>
)
}
// Normal render - render children directly (no wrapper div)
return this.props.children
}
}
......
......@@ -284,10 +284,10 @@ export async function fetchServerResponse(
)
if (ctx) {
// handleChunkFailure updates failure tracking and returns whether to retry
const shouldRetry = handleChunkFailure(ctx)
// handleChunkFailure updates failure tracking and returns action
const action = handleChunkFailure(ctx)
if (shouldRetry) {
if (action === 'retry') {
// Silent retry with jittered delay
const delay = getRetryDelayMs()
await sleep(delay)
......
......@@ -15,7 +15,7 @@ describe('graceful-degrade - non bot', () => {
deleteBrowserDynamicChunks(next)
})
it('should not degrade to graceful error when chunk loading fails in ssr for non-bot user agents', async () => {
it('should show banner and preserve frozen content when chunk loading fails for non-bot user agents', async () => {
const browser = await next.browser('/chunk-loading-failed')
const logs = await browser.log()
......@@ -25,15 +25,14 @@ describe('graceful-degrade - non bot', () => {
.join('\n')
expect(errors).toMatch(/Failed to load resource./)
// Should not show the original content
const html = await browser.elementByCss('html')
const body = await browser.elementByCss('body')
expect(await html.getAttribute('class')).not.toBe('layout-cls')
expect(await body.getAttribute('class')).not.toBe('body-cls')
const body = await browser.elementByCss('body')
const bodyText = await body.text()
// Client errors show "This page crashed"
expect(bodyText).toMatch(/This page crashed/)
// Chunk load errors show a banner instead of full-page error
expect(bodyText).toMatch(/This page couldn't be fully loaded/)
// Banner should NOT show the "This page crashed" full-page error
expect(bodyText).not.toMatch(/This page crashed/)
})
it('should show error boundary when browser errors when error boundary is defined', async () => {
......
'use client'
import dynamic from 'next/dynamic'
import { useState, Suspense, ComponentType } from 'react'
// Lazy component that loads slowly - gives you time to block in DevTools
const SlowLazyComponent = dynamic(
() =>
new Promise<{ default: ComponentType }>((resolve) => {
// 3 second delay before loading the actual component
setTimeout(() => {
import('../../components/lazy-component').then(resolve)
}, 3000)
}),
{ ssr: false }
)
// This will always fail with a ChunkLoadError
const FailingLazyComponent = dynamic(
() =>
new Promise<{ default: ComponentType }>((_resolve, reject) => {
setTimeout(() => {
const error = new Error(
'Failed to load chunk /_next/static/chunks/fake-chunk.js'
)
error.name = 'ChunkLoadError'
reject(error)
}, 500)
}),
{ ssr: false }
)
export default function DebugPage() {
const [showSlow, setShowSlow] = useState(false)
const [showFailing, setShowFailing] = useState(false)
const [throwDirectly, setThrowDirectly] = useState(false)
// Direct throw to test error boundary
if (throwDirectly) {
const error = new Error(
'Failed to load chunk /_next/static/chunks/direct-throw-chunk.js'
)
error.name = 'ChunkLoadError'
throw error
}
return (
<div style={{ padding: '20px', fontFamily: 'system-ui' }}>
<h1>Chunk Error Debug Page</h1>
<p style={{ color: '#666', marginBottom: '20px' }}>
Use these buttons to test chunk loading errors locally.
</p>
<div
style={{
display: 'flex',
flexDirection: 'column',
gap: '16px',
maxWidth: '500px',
}}
>
{/* Method 1: Fake ChunkLoadError via dynamic import */}
<div
style={{
padding: '16px',
border: '1px solid #ddd',
borderRadius: '8px',
}}
>
<h3 style={{ margin: '0 0 8px 0' }}>1. Fake ChunkLoadError</h3>
<p style={{ margin: '0 0 12px 0', fontSize: '14px', color: '#666' }}>
Triggers a dynamic import that fails with ChunkLoadError after
500ms.
</p>
<button
onClick={() => setShowFailing(true)}
style={{
padding: '8px 16px',
cursor: 'pointer',
background: '#dc2626',
color: 'white',
border: 'none',
borderRadius: '4px',
}}
>
Load Failing Component
</button>
{showFailing && (
<Suspense fallback={<div>Loading (will fail)...</div>}>
<FailingLazyComponent />
</Suspense>
)}
</div>
{/* Method 2: Direct throw */}
<div
style={{
padding: '16px',
border: '1px solid #ddd',
borderRadius: '8px',
}}
>
<h3 style={{ margin: '0 0 8px 0' }}>2. Direct Throw</h3>
<p style={{ margin: '0 0 12px 0', fontSize: '14px', color: '#666' }}>
Directly throws a ChunkLoadError from the render function.
</p>
<button
onClick={() => setThrowDirectly(true)}
style={{
padding: '8px 16px',
cursor: 'pointer',
background: '#dc2626',
color: 'white',
border: 'none',
borderRadius: '4px',
}}
>
Throw ChunkLoadError
</button>
</div>
{/* Method 3: Slow component for DevTools blocking */}
<div
style={{
padding: '16px',
border: '1px solid #ddd',
borderRadius: '8px',
}}
>
<h3 style={{ margin: '0 0 8px 0' }}>3. Manual Block (DevTools)</h3>
<p style={{ margin: '0 0 12px 0', fontSize: '14px', color: '#666' }}>
Loads a component with 3s delay. Open DevTools &gt; Network &gt;
Block request pattern &quot;*lazy-component*&quot; before it loads.
</p>
<button
onClick={() => setShowSlow(true)}
disabled={showSlow}
style={{
padding: '8px 16px',
cursor: showSlow ? 'not-allowed' : 'pointer',
background: showSlow ? '#ccc' : '#2563eb',
color: 'white',
border: 'none',
borderRadius: '4px',
}}
>
{showSlow ? 'Loading...' : 'Load Slow Component'}
</button>
{showSlow && (
<Suspense fallback={<div>Loading in 3 seconds...</div>}>
<SlowLazyComponent />
</Suspense>
)}
</div>
{/* Instructions */}
<div
style={{
padding: '16px',
background: '#f5f5f5',
borderRadius: '8px',
fontSize: '14px',
}}
>
<h4 style={{ margin: '0 0 8px 0' }}>How to test:</h4>
<ol style={{ margin: 0, paddingLeft: '20px' }}>
<li>
<strong>Option 1:</strong> Click "Load Failing Component" - This
simulates a ChunkLoadError immediately.
</li>
<li>
<strong>Option 2:</strong> Click "Throw ChunkLoadError" - This
throws directly from render.
</li>
<li>
<strong>Option 3:</strong> Open DevTools, go to Network tab, add
request blocking for "*lazy-component*", then click "Load Slow
Component".
</li>
</ol>
</div>
</div>
<div
style={{ marginTop: '20px', padding: '10px', background: '#e0f0e0' }}
>
<strong>Page content that should be preserved:</strong>
<p>
If the banner works correctly, this content should remain visible
(frozen) behind the banner.
</p>
</div>
</div>
)
}
'use client'
import dynamic from 'next/dynamic'
import { Suspense } from 'react'
const LazyComponent = dynamic(() => import('../../components/lazy-component'), {
ssr: false,
})
export default function DynamicPage() {
return (
<div id="dynamic-page-content">
<h2>Dynamic Page</h2>
<p>This page has a dynamically loaded component below:</p>
<Suspense fallback={<div id="loading">Loading lazy component...</div>}>
<LazyComponent />
</Suspense>
</div>
)
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>
<header style={{ padding: '20px', background: '#f0f0f0' }}>
<h1>Test App</h1>
<nav>
<a href="/" style={{ marginRight: '10px' }}>
Home
</a>
<a href="/dynamic" style={{ marginRight: '10px' }}>
Dynamic
</a>
<a href="/navigation-target" style={{ marginRight: '10px' }}>
Nav Target
</a>
<a href="/other">Other</a>
</nav>
</header>
<main style={{ padding: '20px' }}>{children}</main>
</body>
</html>
)
}
export default function NavigationTarget() {
return (
<div id="nav-target-content">
<h2>Navigation Target</h2>
<p>This is the navigation target page.</p>
</div>
)
}
export default function Other() {
return (
<div id="other-content">
<h2>Other Page</h2>
<p>This is the other page for navigation tests.</p>
</div>
)
}
import Link from 'next/link'
export default function Home() {
return (
<div id="home-content">
<h2>Home Page</h2>
<p>This is the home page with visible content.</p>
<nav>
<Link
href="/debug"
id="link-debug"
style={{ fontWeight: 'bold', color: '#dc2626' }}
>
Debug Chunk Errors
</Link>
<br />
<Link href="/dynamic" id="link-dynamic">
Go to Dynamic Page
</Link>
<br />
<Link href="/navigation-target" id="link-nav-target">
Go to Navigation Target
</Link>
<br />
<Link href="/other" id="link-other">
Go to Other Page
</Link>
</nav>
</div>
)
}
export default function LazyComponent() {
return <div id="lazy-component">this is a lazy loaded async component</div>
}
/** @type {import('next').NextConfig} */
const nextConfig = {}
export default nextConfig
......@@ -41,8 +41,8 @@ describe('chunk-load-failure', () => {
await retry(async () => {
const body = await browser.elementByCss('body')
// Client errors show "This page crashed"
expect(await body.text()).toMatch(/This page crashed/)
// Chunk load errors show a banner instead of full-page error
expect(await body.text()).toMatch(/This page couldn't be fully loaded/)
})
expect(pageError).toBeDefined()
......
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