Unverified Commit a10f0e93 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Add experimental flag for chunk failure handling during app navigation (#67926)

This ensures when we encounter chunk load errors or uncaught
rejections/exceptions during a client transition in app router that we
properly fallback to a hard navigation which allows us to recover
instead of staying in a bad state.

Currently when a chunk fails to load it in most cases hits the error
boundary and that will be rendered (one bad state), another case that
can occur is the chunk fails to load while react-server-dom-webpack is
handling the stream and it crashes and the error boundary isn't even
triggered (second bad state). Both of which aren't recovered until the
user manually navigates.

This is currently behind a flag to allow testing/validating. 

Closes: NDX-75

---------
Co-authored-by: 's avatarZack Tanner <1939140+ztanner@users.noreply.github.com>
parent 05decb11
......@@ -173,6 +173,9 @@ export function getDefineEnv({
? 'nodejs'
: '',
'process.env.NEXT_MINIMAL': '',
'process.env.__NEXT_APP_NAV_FAIL_HANDLING': Boolean(
config.experimental.appNavFailHandling
),
'process.env.__NEXT_APP_ISR_INDICATOR': Boolean(
config.devIndicators.appIsrStatus
),
......
......@@ -55,6 +55,7 @@ import { removeBasePath } from '../remove-base-path'
import { hasBasePath } from '../has-base-path'
import { getSelectedParams } from './router-reducer/compute-changed-path'
import type { FlightRouterState } from '../../server/app-render/types'
import { useNavFailureHandler } from './nav-failure-handler'
import { useServerActionDispatcher } from '../app-call-server'
import type { AppRouterActionQueue } from '../../shared/lib/router/action-queue'
......@@ -74,6 +75,12 @@ function HistoryUpdater({
sync: ReduxDevtoolsSyncFn
}) {
useInsertionEffect(() => {
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
// clear pending URL as navigation is no longer
// in flight
window.next.__pendingUrl = undefined
}
const { tree, pushRef, canonicalUrl } = appRouterState
const historyState = {
...(pushRef.preserveCustomHistoryState ? window.history.state : {}),
......@@ -138,6 +145,10 @@ function useNavigate(dispatch: React.Dispatch<ReducerActions>): RouterNavigate {
(href, navigateType, shouldScroll) => {
const url = new URL(addBasePath(href), location.href)
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
window.next.__pendingUrl = url
}
return dispatch({
type: ACTION_NAVIGATE,
url,
......@@ -592,6 +603,8 @@ export default function AppRouter({
globalErrorComponent: ErrorComponent
assetPrefix: string
}) {
useNavFailureHandler()
return (
<ErrorBoundary errorComponent={globalErrorComponent}>
<Router actionQueue={actionQueue} assetPrefix={assetPrefix} />
......
......@@ -3,6 +3,7 @@
import React, { type JSX } from 'react'
import { usePathname } from './navigation'
import { isNextRouterError } from './is-next-router-error'
import { handleHardNavError } from './nav-failure-handler'
import { staticGenerationAsyncStorage } from './static-generation-async-storage.external'
const styles = {
......@@ -83,6 +84,22 @@ export class ErrorBoundaryHandler extends React.Component<
props: ErrorBoundaryHandlerProps,
state: ErrorBoundaryHandlerState
): ErrorBoundaryHandlerState | null {
const { error } = state
// if we encounter an error while
// a navigation is pending we shouldn't render
// the error boundary and instead should fallback
// to a hard navigation to attempt recovering
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
if (handleHardNavError(error)) {
// clear error so we don't render anything
return {
error: null,
previousPathname: props.pathname,
}
}
}
/**
* Handles reset of the error boundary when a navigation happens.
* Ensures the error boundary does not stay enabled when navigating to a new page.
......@@ -167,7 +184,9 @@ export function ErrorBoundary({
errorStyles,
errorScripts,
children,
}: ErrorBoundaryProps & { children: React.ReactNode }): JSX.Element {
}: ErrorBoundaryProps & {
children: React.ReactNode
}): JSX.Element {
const pathname = usePathname()
if (errorComponent) {
return (
......
import { useEffect } from 'react'
import { createHrefFromUrl } from './router-reducer/create-href-from-url'
export function handleHardNavError(error: unknown): boolean {
if (
typeof window !== 'undefined' &&
window.next.__pendingUrl &&
createHrefFromUrl(new URL(window.location.href)) !==
createHrefFromUrl(window.next.__pendingUrl)
) {
console.error(
`Error occurred during navigation, falling back to hard navigation`,
error
)
window.location.href = window.next.__pendingUrl.toString()
return true
}
return false
}
export function useNavFailureHandler() {
if (process.env.__NEXT_APP_NAV_FAIL_HANDLING) {
// this if is only for DCE of the feature flag not conditional
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
const uncaughtExceptionHandler = (
evt: ErrorEvent | PromiseRejectionEvent
) => {
const error = 'reason' in evt ? evt.reason : evt.error
// if we have an unhandled exception/rejection during
// a navigation we fall back to a hard navigation to
// attempt recovering to a good state
handleHardNavError(error)
}
window.addEventListener('unhandledrejection', uncaughtExceptionHandler)
window.addEventListener('error', uncaughtExceptionHandler)
return () => {
window.removeEventListener('error', uncaughtExceptionHandler)
window.removeEventListener(
'unhandledrejection',
uncaughtExceptionHandler
)
}
}, [])
}
}
......@@ -252,6 +252,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
after: z.boolean().optional(),
appDocumentPreloading: z.boolean().optional(),
appIsrStatus: z.boolean().optional(),
appNavFailHandling: z.boolean().optional(),
preloadEntriesOnStart: z.boolean().optional(),
adjustFontFallbacks: z.boolean().optional(),
adjustFontFallbacksWithSizeAdjust: z.boolean().optional(),
......
......@@ -200,6 +200,7 @@ export interface ReactCompilerOptions {
}
export interface ExperimentalConfig {
appNavFailHandling?: boolean
flyingShuttle?: boolean
prerenderEarlyExit?: boolean
linkNoTouchStart?: boolean
......@@ -938,6 +939,7 @@ export const defaultConfig: NextConfig = {
output: !!process.env.NEXT_PRIVATE_STANDALONE ? 'standalone' : undefined,
modularizeImports: undefined,
experimental: {
appNavFailHandling: Boolean(process.env.NEXT_PRIVATE_FLYING_SHUTTLE),
flyingShuttle: Boolean(process.env.NEXT_PRIVATE_FLYING_SHUTTLE),
prerenderEarlyExit: true,
serverMinification: true,
......
......@@ -19,7 +19,7 @@ export default function IdPage({ children, params }) {
<p id="search-params">
{JSON.stringify(Object.fromEntries(useSearchParams()))}
</p>
<Button>Click me!!</Button>
<Button>button on app/dynamic-client</Button>
</>
)
}
import fs from 'fs'
import path from 'path'
import { nextTestSetup, isNextStart } from 'e2e-utils'
import type { Route } from 'playwright'
import { retry } from 'next-test-utils'
import { nextTestSetup, isNextStart } from 'e2e-utils'
// This feature is only relevant to Webpack.
;(process.env.TURBOPACK ? describe.skip : describe)(
......@@ -72,29 +73,102 @@ import { retry } from 'next-test-utils'
}
})
it('should hard navigate on chunk load failure', async () => {
let blockChunks = false
const browser = await next.browser('/dashboard', {
beforePageLoad(page) {
page.route('**/_next/static/**', async (route: Route) => {
if (blockChunks) {
return route.abort()
}
return route.continue()
})
},
})
await retry(async () => {
expect(await browser.eval('!!next.router.push')).toBe(true)
})
blockChunks = true
await browser.eval('window.beforeNav = 1')
await browser.eval('next.router.push("/dynamic-client/first/second")')
await retry(async () => {
expect(
await browser.eval('document.documentElement.innerHTML')
).toContain('button on app/dynamic-client')
})
// since we hard navigate on failure global scope should be cleared
expect(await browser.eval('window.beforeNav')).toBeFalsy()
})
async function checkAppPagesNavigation() {
for (const path of [
'/',
'/blog/123',
'/dynamic-client/first/second',
'/dashboard',
'/dashboard/deployments/123',
]) {
const testPaths = [
{ path: '/', content: 'hello from pages/index', type: 'pages' },
{
path: '/blog/123',
content: 'hello from pages/blog/[slug]',
type: 'pages',
},
{
path: '/dynamic-client/first/second',
content: 'button on app/dynamic-client',
type: 'app',
},
{
path: '/dashboard',
content: 'hello from app/dashboard',
type: 'app',
},
{
path: '/dashboard/deployments/123',
content: 'hello from app/dashboard/deployments/[id]',
type: 'app',
},
]
for (const testPath of testPaths) {
const { path, content } = testPath
require('console').error('checking', path)
const res = await next.fetch(path)
expect(res.status).toBe(200)
const browser = await next.browser(path)
// TODO: check for hydration success properly
await retry(async () => {
expect(await browser.eval('!!window.next.router')).toBe(true)
expect(
await browser.eval('document.documentElement.innerHTML')
).toContain(content)
})
const browserLogs = await browser.log()
expect(
browserLogs.some(({ message }) => message.includes('error'))
).toBeFalse()
const checkNav = async (testPath: (typeof testPaths)[0]) => {
await browser.eval(`window.next.router.push("${testPath.path}")`)
await retry(async () => {
expect(await browser.eval('!!window.next.router')).toBe(true)
expect(
await browser.eval('document.documentElement.innerHTML')
).toContain(testPath.content)
})
}
// test navigating to a pages path
const pagesTestPath = testPaths.find(
(item) => item.type === 'pages' && item.path !== path
)
await checkNav(pagesTestPath)
// go back to initial page
await checkNav(testPath)
// test navigating to an app route
const appTestPath = testPaths.find(
(item) => item.type === 'app' && item.path !== path
)
await checkNav(appTestPath)
}
// TODO: check we hard navigate boundaries properly
}
it('should only rebuild just a changed app route correctly', async () => {
......
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