Unverified Commit 5f6aa1cb authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Fix: server-patch retry preserves push/replace intent of suspended transitions (#90533)

When a navigation triggers a server-patch retry (due to a route tree
mismatch), the retry was unconditionally using navigateType='replace'.
This assumed the original navigation had already committed to the
browser history. But if the original transition was still suspended,
pushState never ran, so replaceState overwrote the initial history entry
instead of creating a new one, breaking the back button.

The fix tracks the last committed router tree. When a server-patch retry
fires, it checks whether the original navigation has committed. If not,
it inherits the original transition's push/replace intent instead of
forcing 'replace'. This works because React entangles the retry with the
original pending transition — they commit together.

Fixes #90513
parent c36d3427
...@@ -25,6 +25,7 @@ import { ...@@ -25,6 +25,7 @@ import {
type NavigationPromises, type NavigationPromises,
} from '../../shared/lib/hooks-client-context.shared-runtime' } from '../../shared/lib/hooks-client-context.shared-runtime'
import { dispatchAppRouterAction, useActionQueue } from './use-action-queue' import { dispatchAppRouterAction, useActionQueue } from './use-action-queue'
import { setLastCommittedTree } from './router-reducer/reducers/committed-state'
import { AppRouterAnnouncer } from './app-router-announcer' import { AppRouterAnnouncer } from './app-router-announcer'
import { RedirectBoundary } from './redirect-boundary' import { RedirectBoundary } from './redirect-boundary'
import { findHeadInCache } from './router-reducer/reducers/find-head-in-cache' import { findHeadInCache } from './router-reducer/reducers/find-head-in-cache'
...@@ -95,6 +96,8 @@ function HistoryUpdater({ ...@@ -95,6 +96,8 @@ function HistoryUpdater({
} else { } else {
window.history.replaceState(historyState, '', canonicalUrl) window.history.replaceState(historyState, '', canonicalUrl)
} }
setLastCommittedTree(tree)
}, [appRouterState]) }, [appRouterState])
useEffect(() => { useEffect(() => {
......
...@@ -21,6 +21,7 @@ import { ...@@ -21,6 +21,7 @@ import {
type ServerPatchAction, type ServerPatchAction,
} from './router-reducer-types' } from './router-reducer-types'
import { isNavigatingToNewRootLayout } from './is-navigating-to-new-root-layout' import { isNavigatingToNewRootLayout } from './is-navigating-to-new-root-layout'
import { getLastCommittedTree } from './reducers/committed-state'
import { import {
convertServerPatchToFullTree, convertServerPatchToFullTree,
type NavigationSeed, type NavigationSeed,
...@@ -1225,7 +1226,11 @@ export function spawnDynamicRequests( ...@@ -1225,7 +1226,11 @@ export function spawnDynamicRequests(
// prediction. Passed through so it can be marked as having a dynamic rewrite // prediction. Passed through so it can be marked as having a dynamic rewrite
// if the server returns a different pathname than expected (indicating // if the server returns a different pathname than expected (indicating
// dynamic rewrite behavior that varies by param value). // dynamic rewrite behavior that varies by param value).
routeCacheEntry: FulfilledRouteCacheEntry | null routeCacheEntry: FulfilledRouteCacheEntry | null,
// The original navigation's push/replace intent. Threaded through to the
// server-patch retry logic so it can inherit the intent if the original
// transition hasn't committed yet.
navigateType: 'push' | 'replace'
): void { ): void {
const dynamicRequestTree = task.dynamicRequestTree const dynamicRequestTree = task.dynamicRequestTree
if (dynamicRequestTree === null) { if (dynamicRequestTree === null) {
...@@ -1313,7 +1318,8 @@ export function spawnDynamicRequests( ...@@ -1313,7 +1318,8 @@ export function spawnDynamicRequests(
nextUrl, nextUrl,
primaryRequestPromise, primaryRequestPromise,
refreshRequestPromises, refreshRequestPromises,
routeCacheEntry routeCacheEntry,
navigateType
) )
// `finishNavigationTask` is responsible for error handling, so we can attach // `finishNavigationTask` is responsible for error handling, so we can attach
// noop callbacks to this promise. // noop callbacks to this promise.
...@@ -1327,7 +1333,8 @@ async function finishNavigationTask( ...@@ -1327,7 +1333,8 @@ async function finishNavigationTask(
refreshRequestPromises: Array< refreshRequestPromises: Array<
ReturnType<typeof fetchMissingDynamicData> ReturnType<typeof fetchMissingDynamicData>
> | null, > | null,
routeCacheEntry: FulfilledRouteCacheEntry | null routeCacheEntry: FulfilledRouteCacheEntry | null,
navigateType: 'push' | 'replace'
): Promise<void> { ): Promise<void> {
// Wait for all the requests to finish, or for the first one to fail. // Wait for all the requests to finish, or for the first one to fail.
let exitStatus = await waitForRequestsToFinish( let exitStatus = await waitForRequestsToFinish(
...@@ -1364,7 +1371,8 @@ async function finishNavigationTask( ...@@ -1364,7 +1371,8 @@ async function finishNavigationTask(
nextUrl, nextUrl,
primaryRequestResult.seed, primaryRequestResult.seed,
task.route, task.route,
routeCacheEntry routeCacheEntry,
navigateType
) )
return return
} }
...@@ -1385,7 +1393,8 @@ async function finishNavigationTask( ...@@ -1385,7 +1393,8 @@ async function finishNavigationTask(
nextUrl, nextUrl,
primaryRequestResult.seed, primaryRequestResult.seed,
task.route, task.route,
routeCacheEntry routeCacheEntry,
navigateType
) )
return return
} }
...@@ -1453,7 +1462,9 @@ function dispatchRetryDueToTreeMismatch( ...@@ -1453,7 +1462,9 @@ function dispatchRetryDueToTreeMismatch(
// The route cache entry used for this navigation, if it came from route // The route cache entry used for this navigation, if it came from route
// prediction. If the navigation results in a mismatch, we mark it as having // prediction. If the navigation results in a mismatch, we mark it as having
// a dynamic rewrite so future predictions bail out. // a dynamic rewrite so future predictions bail out.
routeCacheEntry: FulfilledRouteCacheEntry | null routeCacheEntry: FulfilledRouteCacheEntry | null,
// The original navigation's push/replace intent.
originalNavigateType: 'push' | 'replace'
) { ) {
// If the navigation used a route prediction, mark it as having a dynamic // If the navigation used a route prediction, mark it as having a dynamic
// rewrite since it resulted in a mismatch. // rewrite since it resulted in a mismatch.
...@@ -1491,6 +1502,27 @@ function dispatchRetryDueToTreeMismatch( ...@@ -1491,6 +1502,27 @@ function dispatchRetryDueToTreeMismatch(
// mismatch, fall back to a hard (MPA) refresh. // mismatch, fall back to a hard (MPA) refresh.
isHardRetry = isHardRetry || previousNavigationDidMismatch isHardRetry = isHardRetry || previousNavigationDidMismatch
previousNavigationDidMismatch = true previousNavigationDidMismatch = true
// If the original navigation hasn't committed to the browser history yet
// (the transition suspended before React committed), inherit its push/replace
// intent. Otherwise, the pushState already ran, so use 'replace' to avoid
// creating a duplicate history entry.
//
// This works because React entangles the retry's state update with the
// original pending transition — they commit together as a single batch,
// so the navigate type from the retry is what HistoryUpdater ultimately sees.
//
// TODO: Ideally this check would happen right before we schedule the React
// update (i.e., closer to where the action is dispatched into the queue),
// not here where the action is constructed. But the current action queue
// doesn't provide a natural place for that. Revisit when we refactor the
// action queue into a more reactive navigation model.
const lastCommitted = getLastCommittedTree()
const retryNavigateType: 'push' | 'replace' =
lastCommitted !== null && baseTree !== lastCommitted
? originalNavigateType
: 'replace'
const retryAction: ServerPatchAction = { const retryAction: ServerPatchAction = {
type: ACTION_SERVER_PATCH, type: ACTION_SERVER_PATCH,
previousTree: baseTree, previousTree: baseTree,
...@@ -1498,6 +1530,7 @@ function dispatchRetryDueToTreeMismatch( ...@@ -1498,6 +1530,7 @@ function dispatchRetryDueToTreeMismatch(
nextUrl: retryNextUrl, nextUrl: retryNextUrl,
seed, seed,
mpa: isHardRetry, mpa: isHardRetry,
navigateType: retryNavigateType,
} }
dispatchAppRouterAction(retryAction) dispatchAppRouterAction(retryAction)
} }
......
import type { FlightRouterState } from '../../../../shared/lib/app-router-types'
// The tree from the last state that was committed to the browser history
// (i.e., the last state for which HistoryUpdater's useInsertionEffect ran).
// This lets the server-patch reducer distinguish between retrying a
// navigation that already pushed a history entry vs one whose transition
// suspended and never committed.
//
// Currently only used by the server-patch retry logic, but this module is a
// stepping stone toward a broader refactor of the navigation queue. The
// existing AppRouter action queue will eventually be replaced by a more
// reactive model that explicitly tracks pending vs committed navigation
// state. This file will likely evolve into (or be subsumed by) that new
// implementation.
let lastCommittedTree: FlightRouterState | null = null
export function getLastCommittedTree(): FlightRouterState | null {
return lastCommittedTree
}
export function setLastCommittedTree(tree: FlightRouterState): void {
lastCommittedTree = tree
}
...@@ -81,7 +81,9 @@ export function restoreReducer( ...@@ -81,7 +81,9 @@ export function restoreReducer(
// cache entry to mark as having a dynamic rewrite on mismatch. If a // cache entry to mark as having a dynamic rewrite on mismatch. If a
// mismatch occurs, the retry handler will traverse the known route tree // mismatch occurs, the retry handler will traverse the known route tree
// to find and mark the entry. // to find and mark the entry.
null null,
// History traversal always uses 'replace'.
'replace'
) )
return completeTraverseNavigation( return completeTraverseNavigation(
state, state,
......
...@@ -23,8 +23,7 @@ export function serverPatchReducer( ...@@ -23,8 +23,7 @@ export function serverPatchReducer(
const retryMpa = action.mpa const retryMpa = action.mpa
const retryUrl = new URL(action.url, location.origin) const retryUrl = new URL(action.url, location.origin)
const retrySeed = action.seed const retrySeed = action.seed
// A retry should not create a new history entry. const navigateType = action.navigateType
const navigateType = 'replace'
if (retryMpa || retrySeed === null) { if (retryMpa || retrySeed === null) {
// If the server did not send back data during the mismatch, fall back to // If the server did not send back data during the mismatch, fall back to
// an MPA navigation. // an MPA navigation.
......
...@@ -127,6 +127,7 @@ export interface ServerPatchAction { ...@@ -127,6 +127,7 @@ export interface ServerPatchAction {
nextUrl: string | null nextUrl: string | null
seed: NavigationSeed | null seed: NavigationSeed | null
mpa: boolean mpa: boolean
navigateType: 'push' | 'replace'
} }
/** /**
......
...@@ -211,7 +211,8 @@ export function navigateToKnownRoute( ...@@ -211,7 +211,8 @@ export function navigateToKnownRoute(
nextUrl, nextUrl,
freshnessPolicy, freshnessPolicy,
accumulation, accumulation,
routeCacheEntry routeCacheEntry,
navigateType
) )
} }
return completeSoftNavigation( return completeSoftNavigation(
......
import { Suspense } from 'react'
import { PushButton } from './push-button'
export default function HomePage() {
return (
<div id="home-page">
<h1>Home</h1>
<Suspense>
<PushButton />
</Suspense>
</div>
)
}
'use client'
import { useRouter } from 'next/navigation'
export function PushButton() {
const router = useRouter()
return (
<button
id="push-button"
onClick={() => router.push('/push-search-params?test=pass')}
>
Push with search params
</button>
)
}
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('server patch - history entry', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
test('skipped in dev mode', () => {})
return
}
// When a navigation suspends and then triggers a server patch (tree
// mismatch retry), the retry should preserve the original transition's
// push/replace intent. Because the suspended transition hasn't committed
// to the browser history yet, the retry inherits its navigate type so
// that pushState still runs when the entangled transitions eventually
// commit together.
it('server patch preserves the push intent of a suspended transition', async () => {
const browser = await next.browser('/push-search-params')
await retry(async () => {
const homePage = await browser.elementById('home-page')
expect(await homePage.text()).toContain('Home')
})
// Navigate to the same page with different search params. The transition
// suspends while fetching data, and the server response triggers a tree
// mismatch, causing a server patch retry.
const pushButton = await browser.elementById('push-button')
await pushButton.click()
await retry(async () => {
expect(await browser.url()).toContain('test=pass')
})
// The navigation should have created a new history entry despite the
// server patch retry, so the back button returns to the original URL.
await browser.back()
await retry(async () => {
const url = await browser.url()
expect(url).not.toContain('test=pass')
expect(new URL(url).pathname).toBe('/push-search-params')
})
})
})
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