Skip to content

Commit db4e623

Browse files
gaearonerrmakov
andauthored
Fix navigation getting reverted when a Server Action is in flight (#95391)
Alternative to #95188. Fixes #86151 (comment). This fixes a bug where a navigation would spuriously get reverted once a Server Action settles. ## Test Plan New e2e tests that fail before the fix and pass after the fix. I've steered the agent to cover both the broken case now *and* the case that the regressing PR (#82674) was originally trying to fix. The test itself is reduced from #95188. Also, verified before/after in a real tiny app based on the tests. Before the fix, it reverts to the previous route; after the fix, it stays on the last route as it should. The tests themselves are a bit wonky and do some timing assertions. I had no luck reducing them further. ## Summary *Note: Everything below is written by Fable.* Fixes a regression where a navigation could get reverted shortly after it committed if a Server Action was still in flight when the navigation started: the destination page renders, then the router snaps back to the previous URL. Regressed in 15.5.1 via #82674. Reported in #86151, with a repro and initial investigation by @errmakov in #95188. ### Why? When a navigation starts while a Server Action is in flight, the router discards the action and the navigation takes its place at the head of the action queue. The discarded action still runs to completion. Since #82674, its completion also called `runRemainingActions`, which advances the queue — but the discarded action is no longer at the head of the queue, the navigation is. This started the next queued action while the navigation was still running, computed against router state that didn't include the navigation yet. Those actions send their requests with the previous URL, and applying their responses reverts the navigation. The promise rejection path had the same problem even before #82674: a discarded action that rejected would also advance the queue. ### How? Only the settlement of the action at the head of the queue may advance the queue. A discarded action's settlement (resolve or reject) now only records whether the action revalidated, and the deferred refresh is flushed once the queue goes idle. This keeps the behavior #82674 was after: no refresh for discarded actions that didn't revalidate, and a refresh for those that did — including when they settle mid-navigation, a case that could previously lose the refresh entirely. --------- Co-authored-by: errmakov <ide404@gmail.com>
1 parent b420536 commit db4e623

8 files changed

Lines changed: 367 additions & 15 deletions

File tree

‎packages/next/src/client/components/app-router-instance.ts‎

Lines changed: 24 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -67,26 +67,31 @@ export type ActionQueueNode = {
6767

6868
function runRemainingActions(
6969
actionQueue: AppRouterActionQueue,
70+
settledAction: ActionQueueNode,
7071
setState: DispatchStatePromise
7172
) {
72-
if (actionQueue.pending !== null) {
73-
actionQueue.pending = actionQueue.pending.next
73+
// Only advance the queue if the settled action is still at its head. If a
74+
// navigation discarded this action, the navigation took its place and is
75+
// still in flight — starting the next queued action now would run it
76+
// against router state that doesn't include the navigation yet.
77+
if (actionQueue.pending === settledAction) {
78+
actionQueue.pending = settledAction.next
7479
if (actionQueue.pending !== null) {
7580
runAction({
7681
actionQueue,
7782
action: actionQueue.pending,
7883
setState,
7984
})
80-
}
81-
} else {
82-
// Check for refresh when pending is already null
83-
// This handles the case where a discarded server action completes
84-
// after the navigation has already finished and the queue is empty
85-
if (actionQueue.needsRefresh) {
86-
actionQueue.needsRefresh = false
87-
actionQueue.dispatch({ type: ACTION_REFRESH }, setState)
85+
return
8886
}
8987
}
88+
89+
if (actionQueue.pending === null && actionQueue.needsRefresh) {
90+
// The queue is idle; flush the refresh requested by a discarded server
91+
// action that revalidated data.
92+
actionQueue.needsRefresh = false
93+
actionQueue.dispatch({ type: ACTION_REFRESH }, setState)
94+
}
9095
}
9196

9297
async function runAction({
@@ -117,22 +122,22 @@ async function runAction({
117122
// mark that we need to refresh after all actions complete
118123
actionQueue.needsRefresh = true
119124
}
120-
// Still need to run remaining actions even for discarded actions
121-
// to potentially trigger the refresh
122-
runRemainingActions(actionQueue, setState)
125+
// This can't advance the queue (this action is no longer its head), but
126+
// if the queue has already drained, it flushes the refresh now.
127+
runRemainingActions(actionQueue, action, setState)
123128
return
124129
}
125130

126131
actionQueue.state = nextState
127132

128-
runRemainingActions(actionQueue, setState)
133+
runRemainingActions(actionQueue, action, setState)
129134
action.resolve(nextState)
130135
}
131136

132137
// if the action is a promise, set up a callback to resolve it
133138
if (isThenable(actionResult)) {
134139
actionResult.then(handleResult, (err) => {
135-
runRemainingActions(actionQueue, setState)
140+
runRemainingActions(actionQueue, action, setState)
136141
action.reject(err)
137142
})
138143
} else {
@@ -197,6 +202,10 @@ function dispatchAction(
197202
// (Note that it can't contain any earlier navigations, because we always put those into `actionQueue.pending` by calling `runAction`)
198203
newAction.next = actionQueue.pending.next
199204

205+
if (actionQueue.last === actionQueue.pending) {
206+
actionQueue.last = newAction
207+
}
208+
200209
runAction({
201210
actionQueue,
202211
action: newAction,
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
import { nextTestSetup } from 'e2e-utils'
2+
import type * as Playwright from 'playwright'
3+
import { createRouterAct } from 'router-act'
4+
5+
describe('discarded action settling while a navigation is pending (#86151)', () => {
6+
const { next } = nextTestSetup({ files: __dirname })
7+
8+
// Navigating while a server action is in flight discards that action:
9+
// its result is never applied. These tests cover the window where the
10+
// discarded action's response arrives while the navigation is still
11+
// ongoing. The navigation must not be reverted, and later actions must
12+
// not run until it finishes — if one ran earlier, it would see the
13+
// pre-navigation page and undo the navigation.
14+
async function interleave(
15+
dispatchButton: string,
16+
options?: { allowErrorStatusCodes: number[] }
17+
) {
18+
let page: Playwright.Page
19+
const browser = await next.browser('/', {
20+
beforePageLoad(p: Playwright.Page) {
21+
page = p
22+
},
23+
})
24+
const act = createRouterAct(page, options)
25+
26+
// data-render counts how many times the client received new data for
27+
// the root layout. Navigations preserve the root layout, so it only
28+
// changes when the router refreshes.
29+
const initialRender = await browser
30+
.elementById('stamp')
31+
.getAttribute('data-render')
32+
33+
await act(
34+
async () => {
35+
// Start server action A. Its response is withheld, so it stays in
36+
// flight throughout this scope.
37+
await act(async () => {
38+
await browser.elementById(dispatchButton).click()
39+
}, 'block')
40+
41+
// Start server action B. Actions run one at a time, so B waits for
42+
// A and no request is issued yet.
43+
await act(async () => {
44+
await browser.elementById('dispatch-b').click()
45+
}, 'no-requests')
46+
47+
// Navigate before A or B finished. This discards A. The navigation
48+
// response is withheld too, so the navigation is still ongoing when
49+
// A's response arrives below.
50+
await act(
51+
async () => {
52+
await browser.elementById('go-dest').click()
53+
},
54+
{ includes: 'Destination page', block: true }
55+
)
56+
57+
// Exiting this scope delivers the withheld responses in the same
58+
// order: first A's, mid-navigation — the moment under test — then
59+
// the navigation's. Only then may B run.
60+
},
61+
// B ran and completed.
62+
{ includes: 'b-result' }
63+
)
64+
65+
// B completing means all three operations have settled.
66+
await browser.waitForElementByCss('#status-b[data-status="b-result"]')
67+
68+
// If B ran too early, it saw the pre-navigation page — but that is not
69+
// necessarily visible yet. Running one more action makes it visible:
70+
// with the bug, the URL flips back to "/" here instead of staying
71+
// on /dest.
72+
await act(
73+
async () => {
74+
await browser.elementById('dispatch-c').click()
75+
},
76+
{ includes: 'c-result' }
77+
)
78+
await browser.waitForElementByCss('#status-c[data-status="c-result"]')
79+
80+
expect(new URL(await browser.url()).pathname).toBe('/dest')
81+
expect(await browser.elementById('dest').text()).toBe('Destination page')
82+
83+
return { browser, initialRender }
84+
}
85+
86+
it('keeps the navigation when the discarded action resolves', async () => {
87+
const { browser, initialRender } = await interleave('dispatch-resolve')
88+
89+
// The discarded action didn't revalidate anything, so there must be
90+
// no refresh.
91+
expect(await browser.elementById('stamp').getAttribute('data-render')).toBe(
92+
initialRender
93+
)
94+
})
95+
96+
// Same scenario, but the discarded action fails. Failure is handled
97+
// separately from success, so cover both.
98+
it('keeps the navigation when the discarded action rejects', async () => {
99+
const { browser, initialRender } = await interleave('dispatch-reject', {
100+
// A server action that throws responds with a 500.
101+
allowErrorStatusCodes: [500],
102+
})
103+
104+
await browser.waitForElementByCss('#status-a[data-status="rejected"]')
105+
expect(await browser.elementById('stamp').getAttribute('data-render')).toBe(
106+
initialRender
107+
)
108+
})
109+
110+
// An action can also be dispatched *while* the navigation is ongoing.
111+
// It must run once the navigation finishes. (At one point it never ran:
112+
// its caller never settled, and the router stopped applying updates
113+
// entirely — the URL never even changed to the navigation target.)
114+
it('runs an action dispatched during the navigation once it finishes', async () => {
115+
let page: Playwright.Page
116+
const browser = await next.browser('/', {
117+
beforePageLoad(p: Playwright.Page) {
118+
page = p
119+
},
120+
})
121+
const act = createRouterAct(page)
122+
123+
await act(
124+
async () => {
125+
// Start server action A. Its response is withheld, so it stays in
126+
// flight throughout this scope.
127+
await act(async () => {
128+
await browser.elementById('dispatch-resolve').click()
129+
}, 'block')
130+
131+
// Navigate before A finished. This discards A. The navigation
132+
// response is withheld too, so the navigation is still ongoing
133+
// when B is dispatched below.
134+
await act(
135+
async () => {
136+
await browser.elementById('go-dest').click()
137+
},
138+
{ includes: 'Destination page', block: true }
139+
)
140+
141+
// Dispatch server action B while the navigation is ongoing. It
142+
// must wait for the navigation, so no request is issued yet.
143+
await act(async () => {
144+
await browser.elementById('dispatch-b').click()
145+
}, 'no-requests')
146+
},
147+
// B ran once the withheld responses were delivered.
148+
{ includes: 'b-result' }
149+
)
150+
151+
await browser.waitForElementByCss('#status-b[data-status="b-result"]')
152+
expect(new URL(await browser.url()).pathname).toBe('/dest')
153+
expect(await browser.elementById('dest').text()).toBe('Destination page')
154+
})
155+
156+
it('defers the refresh from a discarded revalidating action until the queue drains', async () => {
157+
const { browser, initialRender } = await interleave('dispatch-revalidate')
158+
159+
// The discarded action revalidated, so a refresh must still happen —
160+
// after everything else, and without undoing the navigation.
161+
await browser.waitForElementByCss(
162+
`#stamp:not([data-render="${initialRender}"])`
163+
)
164+
expect(new URL(await browser.url()).pathname).toBe('/dest')
165+
expect(await browser.elementById('dest').text()).toBe('Destination page')
166+
})
167+
})
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
'use server'
2+
3+
import { revalidatePath } from 'next/cache'
4+
5+
export async function echo(value: string) {
6+
return value
7+
}
8+
9+
export async function reject() {
10+
throw new Error('intentional test error')
11+
}
12+
13+
export async function revalidate() {
14+
revalidatePath('/', 'layout')
15+
return 'revalidated'
16+
}
Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,91 @@
1+
'use client'
2+
3+
import { useState } from 'react'
4+
import { useRouter } from 'next/navigation'
5+
import { echo, reject, revalidate } from './actions'
6+
7+
// Rendered in the root layout so the statuses survive navigations.
8+
export function Controls() {
9+
const router = useRouter()
10+
const [a, setA] = useState('idle')
11+
const [b, setB] = useState('idle')
12+
const [c, setC] = useState('idle')
13+
14+
async function dispatchResolve() {
15+
setA('pending')
16+
try {
17+
setA(await echo('a-result'))
18+
} catch {
19+
setA('rejected')
20+
}
21+
}
22+
23+
async function dispatchReject() {
24+
setA('pending')
25+
try {
26+
await reject()
27+
setA('resolved')
28+
} catch {
29+
setA('rejected')
30+
}
31+
}
32+
33+
async function dispatchRevalidate() {
34+
setA('pending')
35+
try {
36+
setA(await revalidate())
37+
} catch {
38+
setA('rejected')
39+
}
40+
}
41+
42+
async function dispatchB() {
43+
setB('pending')
44+
try {
45+
setB(await echo('b-result'))
46+
} catch {
47+
setB('rejected')
48+
}
49+
}
50+
51+
async function dispatchC() {
52+
setC('pending')
53+
try {
54+
setC(await echo('c-result'))
55+
} catch {
56+
setC('rejected')
57+
}
58+
}
59+
60+
return (
61+
<div>
62+
<button id="dispatch-resolve" onClick={dispatchResolve}>
63+
dispatch resolving action
64+
</button>
65+
<button id="dispatch-reject" onClick={dispatchReject}>
66+
dispatch rejecting action
67+
</button>
68+
<button id="dispatch-revalidate" onClick={dispatchRevalidate}>
69+
dispatch revalidating action
70+
</button>
71+
<button id="dispatch-b" onClick={dispatchB}>
72+
dispatch queued action
73+
</button>
74+
<button id="go-dest" onClick={() => router.push('/dest')}>
75+
go to destination
76+
</button>
77+
<button id="dispatch-c" onClick={dispatchC}>
78+
dispatch probe action
79+
</button>
80+
<div id="status-a" data-status={a}>
81+
a:{a}
82+
</div>
83+
<div id="status-b" data-status={b}>
84+
b:{b}
85+
</div>
86+
<div id="status-c" data-status={c}>
87+
c:{c}
88+
</div>
89+
</div>
90+
)
91+
}
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { Suspense } from 'react'
2+
import { connection } from 'next/server'
3+
4+
// connection() makes the page dynamic in all modes, so navigating here
5+
// always produces a router request.
6+
async function Content() {
7+
await connection()
8+
return <div id="dest">Destination page</div>
9+
}
10+
11+
export default function DestPage() {
12+
return (
13+
<Suspense fallback={null}>
14+
<Content />
15+
</Suspense>
16+
)
17+
}

0 commit comments

Comments
 (0)