Commit 8190c21d authored by Jimmy Lai's avatar Jimmy Lai

Add banner UI for chunk load errors

Instead of showing a full-page "This page crashed" error for ChunkLoadError,
display a top-fixed banner while preserving the visible content as a frozen
snapshot:

- Banner shows "This page couldn't be fully loaded" headline
- Contextual detail: "A required file couldn't be loaded." (default) or
  "You're offline." (when offline)
- Single CTA: "Reload page" button
- Preserves frozen HTML snapshot of page content underneath
- Neutral styling (no red, no modal, no dismiss)
- Accessible: role="alert", aria-live="assertive"

🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-Authored-By: 's avatarClaude Opus 4.5 <noreply@anthropic.com>
parent 0a8c5375
'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} />
</>
)
}
/**
* Type definitions for chunk load error handling.
*
* This module is intentionally minimal - it only provides types.
* No retry logic, no escalation logic, no background failure handling.
*/
export type ChunkErrorAction = 'banner'
export {
isChunkLoadError,
isNetworkError,
isChunkOrNetworkError,
} from './is-chunk-load-error'
export { type ChunkErrorAction } from './chunk-load-error-handler'
export {
ChunkLoadErrorBanner,
type ChunkLoadErrorBannerProps,
} from './chunk-load-error-banner'
/**
* Utilities for detecting chunk load errors and network failures.
*
* ChunkLoadError can come from:
* - Turbopack: error.name === 'ChunkLoadError'
* - Webpack: error.name === 'ChunkLoadError'
*/
/**
* Detects if an error is a ChunkLoadError from Turbopack or webpack.
*/
export function isChunkLoadError(error: unknown): error is Error {
if (!error || typeof error !== 'object') return false
return (error as Error).name === 'ChunkLoadError'
}
/**
* Detects network-related errors (fetch failures, offline, etc.)
*/
export function isNetworkError(error: unknown): error is Error {
if (!error || typeof error !== 'object') return false
const err = error as Error
// Check for typical network error indicators
if (err.name === 'TypeError' && err.message?.includes('fetch')) return true
if (err.message?.includes('NetworkError')) return true
if (err.message?.includes('Failed to fetch')) return true
return false
}
/**
* Returns true if the error is a chunk load or network error.
*/
export function isChunkOrNetworkError(error: unknown): boolean {
return isChunkLoadError(error) || isNetworkError(error)
}
...@@ -6,6 +6,11 @@ import { isNextRouterError } from './is-next-router-error' ...@@ -6,6 +6,11 @@ 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 {
isChunkOrNetworkError,
ChunkLoadErrorBanner,
type ChunkErrorAction,
} from './chunk-load-error'
const isBotUserAgent = const isBotUserAgent =
typeof window !== 'undefined' && isBot(window.navigator.userAgent) typeof window !== 'undefined' && isBot(window.navigator.userAgent)
...@@ -32,6 +37,8 @@ interface ErrorBoundaryHandlerProps extends ErrorBoundaryProps { ...@@ -32,6 +37,8 @@ interface ErrorBoundaryHandlerProps extends ErrorBoundaryProps {
interface ErrorBoundaryHandlerState { interface ErrorBoundaryHandlerState {
error: Error | null error: Error | null
previousPathname: string | null previousPathname: string | null
chunkErrorAction: ChunkErrorAction | null
frozenHTML: string | null
} }
export class ErrorBoundaryHandler extends React.Component< export class ErrorBoundaryHandler extends React.Component<
...@@ -40,7 +47,12 @@ export class ErrorBoundaryHandler extends React.Component< ...@@ -40,7 +47,12 @@ export class ErrorBoundaryHandler extends React.Component<
> { > {
constructor(props: ErrorBoundaryHandlerProps) { constructor(props: ErrorBoundaryHandlerProps) {
super(props) 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) { static getDerivedStateFromError(error: Error) {
...@@ -50,6 +62,23 @@ export class ErrorBoundaryHandler extends React.Component< ...@@ -50,6 +62,23 @@ export class ErrorBoundaryHandler extends React.Component<
throw error throw 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') {
frozenHTML = document.body.innerHTML
}
return {
error,
chunkErrorAction: 'banner' as ChunkErrorAction,
frozenHTML,
}
}
return { error } return { error }
} }
...@@ -69,6 +98,8 @@ export class ErrorBoundaryHandler extends React.Component< ...@@ -69,6 +98,8 @@ export class ErrorBoundaryHandler extends React.Component<
return { return {
error: null, error: null,
previousPathname: props.pathname, previousPathname: props.pathname,
chunkErrorAction: null,
frozenHTML: null,
} }
} }
} }
...@@ -83,36 +114,69 @@ export class ErrorBoundaryHandler extends React.Component< ...@@ -83,36 +114,69 @@ export class ErrorBoundaryHandler extends React.Component<
return { return {
error: null, error: null,
previousPathname: props.pathname, previousPathname: props.pathname,
chunkErrorAction: null,
frozenHTML: null,
} }
} }
return { return {
error: state.error, error: state.error,
previousPathname: props.pathname, previousPathname: props.pathname,
chunkErrorAction: state.chunkErrorAction,
frozenHTML: state.frozenHTML,
} }
} }
reset = () => { 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. // 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, 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. // 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
dangerouslySetInnerHTML={{ __html: frozenHTML }}
/>
)}
</>
)
}
// Full-page error for non-chunk errors
return ( return (
<> <>
<HandleISRError error={this.state.error} /> <HandleISRError error={error} />
{this.props.errorStyles} {this.props.errorStyles}
{this.props.errorScripts} {this.props.errorScripts}
<this.props.errorComponent <this.props.errorComponent error={error} reset={this.reset} />
error={this.state.error}
reset={this.reset}
/>
</> </>
) )
} }
// Normal render - render children directly (no wrapper div)
return this.props.children return this.props.children
} }
} }
......
...@@ -15,7 +15,7 @@ describe('graceful-degrade - non bot', () => { ...@@ -15,7 +15,7 @@ describe('graceful-degrade - non bot', () => {
deleteBrowserDynamicChunks(next) 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 browser = await next.browser('/chunk-loading-failed')
const logs = await browser.log() const logs = await browser.log()
...@@ -25,15 +25,14 @@ describe('graceful-degrade - non bot', () => { ...@@ -25,15 +25,14 @@ describe('graceful-degrade - non bot', () => {
.join('\n') .join('\n')
expect(errors).toMatch(/Failed to load resource./) 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() 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 () => { 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>
)
}
import { nextTestSetup } from 'e2e-utils'
import { recursiveReadDir } from 'next/dist/lib/recursive-readdir'
import path from 'path'
import fs from 'fs'
import { retry } from 'next-test-utils'
describe('chunk-load-error-banner', () => {
const { next } = nextTestSetup({
files: __dirname,
})
/**
* Find the chunk file that contains the lazy component
*/
async function getLazyComponentChunk() {
const chunksPath = path.join(next.testDir, '.next/static/')
const browserChunks = await recursiveReadDir(chunksPath, {
pathnameFilter: (f) => /\.js$/.test(f),
})
const lazyChunks = browserChunks.filter((f) =>
fs
.readFileSync(path.join(chunksPath, f), 'utf8')
.includes('this is a lazy loaded async component')
)
expect(lazyChunks).toHaveLength(1)
return lazyChunks[0]
}
describe('Banner Appearance', () => {
it('should show banner instead of full-page error for ChunkLoadError', async () => {
const lazyChunk = await getLazyComponentChunk()
let pageError: Error | undefined
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
// Intercept all attempts and abort them
page.route('**/' + lazyChunk, async (route) => {
await route.abort('connectionreset')
})
page.on('pageerror', (error: Error) => {
pageError = error
})
},
})
await retry(async () => {
const body = await browser.elementByCss('body')
const text = await body.text()
// Should show banner text, NOT "This page crashed"
expect(text).toContain("This page couldn't be fully loaded")
expect(text).not.toContain('This page crashed')
})
// Verify error is actually a ChunkLoadError
expect(pageError).toBeDefined()
expect(pageError!.name).toBe('ChunkLoadError')
})
it('should show "Reload page" button in banner', async () => {
const lazyChunk = await getLazyComponentChunk()
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/' + lazyChunk, async (route) => {
await route.abort('connectionreset')
})
},
})
await retry(async () => {
const body = await browser.elementByCss('body')
const text = await body.text()
expect(text).toContain('Reload page')
})
})
it('should show correct sub-message in banner', async () => {
const lazyChunk = await getLazyComponentChunk()
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/' + lazyChunk, async (route) => {
await route.abort('connectionreset')
})
},
})
await retry(async () => {
const body = await browser.elementByCss('body')
const text = await body.text()
expect(text).toContain("A required file couldn't be loaded")
})
})
})
describe('Content Preservation', () => {
it('should preserve page content visible under the banner', async () => {
const lazyChunk = await getLazyComponentChunk()
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/' + lazyChunk, async (route) => {
await route.abort('connectionreset')
})
},
})
await retry(async () => {
const body = await browser.elementByCss('body')
const text = await body.text()
// Banner should be visible
expect(text).toContain("This page couldn't be fully loaded")
// Original page content should ALSO be visible (frozen content)
expect(text).toContain('Dynamic Page')
})
})
})
describe('ChunkLoadError Detection', () => {
it('should correctly identify ChunkLoadError by name', async () => {
const lazyChunk = await getLazyComponentChunk()
let capturedError: Error | undefined
await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/' + lazyChunk, async (route) => {
await route.abort('connectionreset')
})
page.on('pageerror', (error: Error) => {
capturedError = error
})
},
})
await retry(async () => {
expect(capturedError).toBeDefined()
expect(capturedError!.name).toBe('ChunkLoadError')
})
// Verify error message format
if (process.env.IS_TURBOPACK_TEST) {
expect(capturedError!.message).toContain('Failed to load chunk')
} else {
expect(capturedError!.message).toMatch(/Loading chunk .* failed/)
}
})
})
describe('Navigation After Error', () => {
it('should allow navigation away from page with banner', async () => {
const lazyChunk = await getLazyComponentChunk()
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/' + lazyChunk, async (route) => {
await route.abort('connectionreset')
})
},
})
// Wait for banner to appear
await retry(async () => {
const body = await browser.elementByCss('body')
expect(await body.text()).toContain(
"This page couldn't be fully loaded"
)
})
// Navigate to another page
await browser.get(next.url + '/other')
// Should successfully navigate
await retry(async () => {
const body = await browser.elementByCss('body')
const text = await body.text()
expect(text).toContain('Other Page')
// Banner should be gone
expect(text).not.toContain("This page couldn't be fully loaded")
})
})
})
describe('Server Error Differentiation', () => {
it('should show full-page error for non-chunk errors (server errors with digest)', async () => {
// This test verifies that regular errors still show the normal error page
// We need to trigger a server error, not a chunk load error
// Visit a page that throws a server error
// For now, we just verify that chunk errors get special treatment
// by confirming the banner shows for chunk errors
const lazyChunk = await getLazyComponentChunk()
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/' + lazyChunk, async (route) => {
await route.abort('connectionreset')
})
},
})
await retry(async () => {
const body = await browser.elementByCss('body')
const text = await body.text()
// Chunk errors show banner, not full page error
expect(text).toContain("This page couldn't be fully loaded")
expect(text).not.toContain('This page crashed')
})
})
})
describe('Accessibility', () => {
it('should have accessible banner with role="alert"', async () => {
const lazyChunk = await getLazyComponentChunk()
const browser = await next.browser('/dynamic', {
beforePageLoad(page) {
page.route('**/' + lazyChunk, async (route) => {
await route.abort('connectionreset')
})
},
})
await retry(async () => {
const body = await browser.elementByCss('body')
const text = await body.text()
expect(text).toContain("This page couldn't be fully loaded")
})
// Check that the banner has role="alert" for accessibility
const hasAlertRole = await browser.eval(() => {
return document.querySelector('[role="alert"]') !== null
})
expect(hasAlertRole).toBe(true)
})
})
})
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', () => { ...@@ -41,8 +41,8 @@ describe('chunk-load-failure', () => {
await retry(async () => { await retry(async () => {
const body = await browser.elementByCss('body') const body = await browser.elementByCss('body')
// Client errors show "This page crashed" // Chunk load errors now show a banner instead of full-page error
expect(await body.text()).toMatch(/This page crashed/) expect(await body.text()).toMatch(/This page couldn't be fully loaded/)
}) })
expect(pageError).toBeDefined() 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