Unverified Commit ee7f8892 authored by dan's avatar dan Committed by GitHub

Fix history push getting treated like replace when followed by refresh (#95392)

Currently this drops a history push:

```tsx
router.push('/target') // this entry was getting lost
router.refresh()
```

So you end up on `/target`, but the previous page's history entry was
replaced instead of a new one being pushed. As a result, pressing Back
yanks you past the previous page.

It seems like a regression from #88046. I verified it's broken in 16.2,
but it was working in 16.1.

This fixes the regression.

## Test Plan

New test fails before, works after. Also tried it in a small repro
project.

---

*Everything below is written by Claude.*

The push happens when React commits a state whose `pushRef.pendingPush`
is true (`HistoryUpdater`). Refresh-type actions (`refresh`,
`hmr-refresh`, `server-patch`) create their state with a fresh `pushRef`
where `pendingPush` is false. React can skip committing the superseded
navigation state entirely, so `pendingPush: true` is never observed and
the push never happens — `HistoryUpdater` replaces the previous page's
history entry with the new URL instead of pushing a new one. Going back
after that does nothing: the entry the browser returns to has no state,
and the popstate handler ignores entries without state.

The old router carried the previous state's `pendingPush` forward unless
a reducer set it explicitly
(https://github.com/vercel/next.js/blob/5ccc9078e0/packages/next/src/client/components/router-reducer/handle-mutable.ts#L41-L43),
and the refresh reducer never set it. That guard was lost in #88046,
which deleted `handleMutable` and moved the final state assembly into
`completeSoftNavigation`, where `pushRef` is created fresh with
`pendingPush: navigateType === 'push'`. This PR restores the old
behavior there. There's no double push: if the navigation's state did
commit, the push already happened and consumed the flag
(`HistoryUpdater` mutates the `pushRef`), and its same-URL check turns a
leftover flag into a replace anyway.

In dev, an `hmr-refresh` dispatched while compiling the destination
route on demand can supersede the navigation the same way. That's what's
behind the recent `browser back to a revalidated page` flakes in
`navigation.test.ts` (traced in #95385).

<!-- NEXT_JS_LLM_PR -->
parent d1268a90
...@@ -78,7 +78,11 @@ export function refreshDynamicData( ...@@ -78,7 +78,11 @@ export function refreshDynamicData(
UnknownDynamicStaleTime UnknownDynamicStaleTime
) )
const navigateType = 'replace' // If the previous navigation hasn't pushed its history entry yet (React
// hasn't committed its state), this refresh may commit in its place, so it
// takes over the push. If the navigation does commit first, HistoryUpdater
// sees that the URL already matches and replaces instead.
const navigateType = state.pushRef.pendingPush ? 'push' : 'replace'
return navigateToKnownRoute( return navigateToKnownRoute(
now, now,
state, state,
......
export default function Page() {
return <h1>Target</h1>
}
'use client'
import { useRouter } from 'next/navigation'
export default function Page() {
const router = useRouter()
return (
<div>
<h1>Home</h1>
<button
id="push-and-refresh"
onClick={() => {
// Refresh in the same tick so the refresh state can supersede the
// navigation's state before React commits it.
router.push('/push-and-refresh/dest')
router.refresh()
}}
>
Push and refresh
</button>
</div>
)
}
export default function Page() {
return <h1>Other</h1>
}
'use client'
import { useRouter } from 'next/navigation'
export default function Page() {
const router = useRouter()
return (
<div>
<h1>Home</h1>
<button
id="push-and-replace"
onClick={() => {
// The destination page suspends forever, so the push settles but
// never commits. The replace then supersedes the pending push.
router.push('/push-and-replace/suspended')
setTimeout(() => {
router.replace('/push-and-replace/other')
}, 500)
}}
>
Push and replace
</button>
</div>
)
}
'use client'
import { use } from 'react'
const forever = new Promise<never>(() => {})
export default function Page() {
if (typeof window !== 'undefined') {
// Suspend the navigation transition forever so it never commits.
use(forever)
}
return null
}
...@@ -948,6 +948,54 @@ describe('app dir - navigation', () => { ...@@ -948,6 +948,54 @@ describe('app dir - navigation', () => {
}) })
}) })
describe('browser back after a push followed by a refresh', () => {
it('should load the previous page', async () => {
const browser = await next.browser('/push-and-refresh')
expect(await browser.elementByCss('h1').text()).toBe('Home')
const historyLength = await browser.eval('window.history.length')
await browser.elementById('push-and-refresh').click()
await retry(async () => {
expect(await browser.elementByCss('h1').text()).toBe('Target')
})
await retry(async () => {
expect(await browser.eval('window.history.length')).toBe(
historyLength + 1
)
})
await browser.back()
await retry(async () => {
expect(await browser.elementByCss('h1').text()).toBe('Home')
})
})
})
describe('replace during a push that has not committed', () => {
it('should supersede the pending push', async () => {
const browser = await next.browser('/push-and-replace')
// Compile the destination pages so the push settles before the replace.
await browser.eval(
`Promise.all([
fetch('/push-and-replace/suspended'),
fetch('/push-and-replace/other'),
]).then(() => 'ok')`
)
expect(await browser.elementByCss('h1').text()).toBe('Home')
const historyLength = await browser.eval('window.history.length')
await browser.elementById('push-and-replace').click()
await retry(async () => {
expect(await browser.elementByCss('h1').text()).toBe('Other')
})
expect(await browser.url()).toContain('/push-and-replace/other')
expect(await browser.eval('window.history.length')).toBe(historyLength)
})
})
describe('middleware redirect', () => { describe('middleware redirect', () => {
it('should change browser location when router.refresh() gets a redirect response', async () => { it('should change browser location when router.refresh() gets a redirect response', async () => {
const browser = await next.browser('/redirect-on-refresh/auth') const browser = await next.browser('/redirect-on-refresh/auth')
......
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