Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gracefully handle client router segment mismatches #60141

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import type { FlightRouterState } from '../../../server/app-render/types'
import { handleExternalUrl } from './reducers/navigate-reducer'
import type {
ReadonlyReducerState,
ReducerActions,
} from './router-reducer-types'

/**
* Handles the case where the client router attempted to patch the tree but, due to a mismatch, the patch failed.
* This will perform an MPA navigation to return the router to a valid state.
*/
export function handleSegmentMismatch(
state: ReadonlyReducerState,
action: ReducerActions,
treePatch: FlightRouterState
) {
if (process.env.NODE_ENV === 'development') {
console.warn(
'Performing hard navigation because your application experienced an unrecoverable error. If this keeps occurring, please file a Next.js issue.\n\n' +
'Reason: Segment mismatch\n' +
`Last Action: ${action.type}\n\n` +
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice

`Current Tree: ${JSON.stringify(state.tree)}\n\n` +
`Tree Patch Payload: ${JSON.stringify(treePatch)}`
)
}

return handleExternalUrl(state, {}, state.canonicalUrl, true)
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { handleMutable } from '../handle-mutable'
import { applyFlightData } from '../apply-flight-data'
import type { CacheNode } from '../../../../shared/lib/app-router-context.shared-runtime'
import { createEmptyCacheNode } from '../../app-router'
import { handleSegmentMismatch } from '../handle-segment-mismatch'

// A version of refresh reducer that keeps the cache around instead of wiping all of it.
function fastRefreshReducerImpl(
Expand Down Expand Up @@ -71,7 +72,7 @@ function fastRefreshReducerImpl(
)

if (newTree === null) {
throw new Error('SEGMENT MISMATCH')
return handleSegmentMismatch(state, action, treePatch)
}

if (isNavigatingToNewRootLayout(currentTree, newTree)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import { handleMutable } from '../handle-mutable'
import type { CacheNode } from '../../../../shared/lib/app-router-context.shared-runtime'
import { fillLazyItemsTillLeafWithHead } from '../fill-lazy-items-till-leaf-with-head'
import { createEmptyCacheNode } from '../../app-router'
import { handleSegmentMismatch } from '../handle-segment-mismatch'

export function refreshReducer(
state: ReadonlyReducerState,
Expand Down Expand Up @@ -69,7 +70,7 @@ export function refreshReducer(
)

if (newTree === null) {
throw new Error('SEGMENT MISMATCH')
return handleSegmentMismatch(state, action, treePatch)
}

if (isNavigatingToNewRootLayout(currentTree, newTree)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import { handleMutable } from '../handle-mutable'
import { fillLazyItemsTillLeafWithHead } from '../fill-lazy-items-till-leaf-with-head'
import { createEmptyCacheNode } from '../../app-router'
import { extractPathFromFlightRouterState } from '../compute-changed-path'
import { handleSegmentMismatch } from '../handle-segment-mismatch'

type FetchServerActionResult = {
redirectLocation: URL | undefined
Expand Down Expand Up @@ -224,7 +225,7 @@ export function serverActionReducer(
)

if (newTree === null) {
throw new Error('SEGMENT MISMATCH')
return handleSegmentMismatch(state, action, treePatch)
}

if (isNavigatingToNewRootLayout(currentTree, newTree)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -501,4 +501,62 @@ describe('serverPatchReducer', () => {
}
`)
})

it("should gracefully recover if the server patch doesn't match the current tree", async () => {
const initialTree = getInitialRouterStateTree()
const initialCanonicalUrl = '/linking'
const children = (
<html>
<head></head>
<body>Root layout</body>
</html>
)

const state = createInitialRouterState({
buildId,
initialTree,
initialHead: null,
initialCanonicalUrl,
initialSeedData: ['', {}, children],
initialParallelRoutes: new Map(),
isServer: false,
location: new URL('/linking/about', 'https://localhost') as any,
})

const action: ServerPatchAction = {
type: ACTION_SERVER_PATCH,
// this flight data is intentionally completely unrelated to the existing tree
flightData: [
[
'children',
'tree-patch-failure',
'children',
'new-page',
['new-page', { children: ['__PAGE__', {}] }],
null,
null,
],
],
previousTree: [
'',
{
children: [
'linking',
{
children: ['about', { children: ['', {}] }],
},
],
},
undefined,
undefined,
true,
],
overrideCanonicalUrl: undefined,
}

const newState = await serverPatchReducer(state, action)
expect(newState.pushRef.pendingPush).toBe(true)
expect(newState.pushRef.mpaNavigation).toBe(true)
expect(newState.canonicalUrl).toBe('/linking/about')
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { applyFlightData } from '../apply-flight-data'
import { handleMutable } from '../handle-mutable'
import type { CacheNode } from '../../../../shared/lib/app-router-context.shared-runtime'
import { createEmptyCacheNode } from '../../app-router'
import { handleSegmentMismatch } from '../handle-segment-mismatch'

export function serverPatchReducer(
state: ReadonlyReducerState,
Expand Down Expand Up @@ -49,7 +50,7 @@ export function serverPatchReducer(
)

if (newTree === null) {
throw new Error('SEGMENT MISMATCH')
return handleSegmentMismatch(state, action, treePatch)
}

if (isNavigatingToNewRootLayout(currentTree, newTree)) {
Expand Down
Loading