Unverified Commit 51549d92 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

fix refreshing inactive segments that contained searchParams (#64086)

When adding refresh markers for refetching segments that are "stale"
(the soft navigation case where they are still in the Router State Tree
but not part of the page that we're rendering), they only contained a
reference to the pathname. Once the actual refresh was triggered we
added the current search params to the request.

However, this causes an issue: segments in the `FlightRouterState` can
contain searchParams (ie, `__PAGE__?{"foo": "bar}` is what the segment
becomes when adding `?foo=bar` to a page). This means that when we
refresh those nodes from the server, it won't know how to find the
`CacheNode` for the stale segment since we won't have them in the
refetch tree. This updates to keep a reference to the searchParams that
were part of the request that made it active.

While fixing this, I also noticed that we were missing a spot to add the
refetch marker in `applyRouterStatePatchToTree` in the case of a root
refresh (caught by these tests failing in PPR)


[x-ref](https://github.com/vercel/next.js/discussions/63900#discussioncomment-9002137)

<!-- Thanks for opening a PR! Your contribution is much appreciated.
To make sure your PR is handled as smoothly as possible we request that
you follow the checklist sections below.
Choose the right checklist for the change(s) that you're making:

## For Contributors

### Improving Documentation

- Run `pnpm prettier-fix` to fix formatting issues before opening the
PR.
- Read the Docs Contribution Guide to ensure your contribution follows
the docs guidelines:
https://nextjs.org/docs/community/contribution-guide

### Adding or Updating Examples

- The "examples guidelines" are followed from our contributing doc
https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md
- Make sure the linting passes by running `pnpm build && pnpm lint`. See
https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md

### Fixing a bug

- Related issues linked using `fixes #number`
- Tests added. See:
https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md

### Adding a feature

- Implements an existing feature request or RFC. Make sure the feature
request has been accepted for implementation before opening a PR. (A
discussion must be opened, see
https://github.com/vercel/next.js/discussions/new?category=ideas)
- Related issues/discussions are linked using `fixes #number`
- e2e tests added
(https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs)
- Documentation added
- Telemetry added. In case of a feature if it's used or not.
- Errors have a helpful link attached, see
https://github.com/vercel/next.js/blob/canary/contributing.md


## For Maintainers

- Minimal description (aim for explaining to someone not on the team to
understand the PR)
- When linking to a Slack thread, you might want to share details of the
conclusion
- Link both the Linear (Fixes NEXT-xxx) and the GitHub issues
- Add review comments if necessary to explain to the reviewer the logic
behind a change

### What?

### Why?

### How?

Closes NEXT-
Fixes #

-->


Closes NEXT-3007
parent 3d3311b1
...@@ -93,6 +93,8 @@ export function applyRouterStatePatchToTree( ...@@ -93,6 +93,8 @@ export function applyRouterStatePatchToTree(
flightSegmentPath flightSegmentPath
) )
addRefreshMarkerToActiveParallelSegments(tree, pathname)
return tree return tree
} }
......
...@@ -74,7 +74,7 @@ function fastRefreshReducerImpl( ...@@ -74,7 +74,7 @@ function fastRefreshReducerImpl(
[''], [''],
currentTree, currentTree,
treePatch, treePatch,
location.pathname state.canonicalUrl
) )
if (newTree === null) { if (newTree === null) {
......
...@@ -176,7 +176,7 @@ function navigateReducer_noPPR( ...@@ -176,7 +176,7 @@ function navigateReducer_noPPR(
flightSegmentPathWithLeadingEmpty, flightSegmentPathWithLeadingEmpty,
currentTree, currentTree,
treePatch, treePatch,
url.pathname href
) )
// If the tree patch can't be applied to the current tree then we use the tree at time of prefetch // If the tree patch can't be applied to the current tree then we use the tree at time of prefetch
...@@ -187,7 +187,7 @@ function navigateReducer_noPPR( ...@@ -187,7 +187,7 @@ function navigateReducer_noPPR(
flightSegmentPathWithLeadingEmpty, flightSegmentPathWithLeadingEmpty,
treeAtTimeOfPrefetch, treeAtTimeOfPrefetch,
treePatch, treePatch,
url.pathname href
) )
} }
...@@ -354,7 +354,7 @@ function navigateReducer_PPR( ...@@ -354,7 +354,7 @@ function navigateReducer_PPR(
flightSegmentPathWithLeadingEmpty, flightSegmentPathWithLeadingEmpty,
currentTree, currentTree,
treePatch, treePatch,
url.pathname href
) )
// If the tree patch can't be applied to the current tree then we use the tree at time of prefetch // If the tree patch can't be applied to the current tree then we use the tree at time of prefetch
...@@ -365,7 +365,7 @@ function navigateReducer_PPR( ...@@ -365,7 +365,7 @@ function navigateReducer_PPR(
flightSegmentPathWithLeadingEmpty, flightSegmentPathWithLeadingEmpty,
treeAtTimeOfPrefetch, treeAtTimeOfPrefetch,
treePatch, treePatch,
url.pathname href
) )
} }
......
...@@ -74,7 +74,7 @@ export function refreshReducer( ...@@ -74,7 +74,7 @@ export function refreshReducer(
[''], [''],
currentTree, currentTree,
treePatch, treePatch,
location.pathname state.canonicalUrl
) )
if (newTree === null) { if (newTree === null) {
......
...@@ -225,7 +225,7 @@ export function serverActionReducer( ...@@ -225,7 +225,7 @@ export function serverActionReducer(
[''], [''],
currentTree, currentTree,
treePatch, treePatch,
location.pathname href
) )
if (newTree === null) { if (newTree === null) {
......
...@@ -48,7 +48,7 @@ export function serverPatchReducer( ...@@ -48,7 +48,7 @@ export function serverPatchReducer(
['', ...flightSegmentPath], ['', ...flightSegmentPath],
currentTree, currentTree,
treePatch, treePatch,
location.pathname state.canonicalUrl
) )
if (newTree === null) { if (newTree === null) {
......
...@@ -61,9 +61,7 @@ async function refreshInactiveParallelSegmentsImpl({ ...@@ -61,9 +61,7 @@ async function refreshInactiveParallelSegmentsImpl({
// Eagerly kick off the fetch for the refetch path & the parallel routes. This should be fine to do as they each operate // Eagerly kick off the fetch for the refetch path & the parallel routes. This should be fine to do as they each operate
// independently on their own cache nodes, and `applyFlightData` will copy anything it doesn't care about from the existing cache. // independently on their own cache nodes, and `applyFlightData` will copy anything it doesn't care about from the existing cache.
const fetchPromise = fetchServerResponse( const fetchPromise = fetchServerResponse(
// we capture the pathname of the refetch without search params, so that it can be refetched with new URL(refetchPathname, location.origin),
// the "latest" search params when it comes time to actually trigger the fetch (below)
new URL(refetchPathname + location.search, location.origin),
// refetch from the root of the updated tree, otherwise it will be scoped to the current segment // refetch from the root of the updated tree, otherwise it will be scoped to the current segment
// and might not contain the data we need to patch in interception route data (such as dynamic params from a previous segment) // and might not contain the data we need to patch in interception route data (such as dynamic params from a previous segment)
[rootTree[0], rootTree[1], rootTree[2], 'refetch'], [rootTree[0], rootTree[1], rootTree[2], 'refetch'],
......
'use client'
import { useRouter } from 'next/navigation'
export function UpdateSearchParamsButton({
searchParams,
id,
}: {
searchParams: any
id?: string
}) {
const router = useRouter()
return (
<div>
<div id={`search-params${id ? `-${id}` : ''}`}>
Params: {JSON.stringify(searchParams.random)}
</div>
<button
id={`update-search-params${id ? `-${id}` : ''}`}
style={{ color: 'blue', padding: '10px' }}
onClick={() => router.replace(`?random=${Math.random()}#hash-test`)}
>
Add Search Params
</button>
</div>
)
}
import { RefreshButton } from '../../../../components/RefreshButton' import { RefreshButton } from '../../../../components/RefreshButton'
import { RevalidateButton } from '../../../../components/RevalidateButton' import { RevalidateButton } from '../../../../components/RevalidateButton'
import { UpdateSearchParamsButton } from '../../../../components/UpdateSearchParamsButton'
const getRandom = async () => Math.random() const getRandom = async () => Math.random()
export default async function Page({ params }) { export default async function Page({ params, searchParams }) {
const someProp = await getRandom() const someProp = await getRandom()
return ( return (
...@@ -16,6 +17,7 @@ export default async function Page({ params }) { ...@@ -16,6 +17,7 @@ export default async function Page({ params }) {
</div> </div>
<RefreshButton /> <RefreshButton />
<RevalidateButton /> <RevalidateButton />
<UpdateSearchParamsButton searchParams={searchParams} id="modal" />
</div> </div>
</dialog> </dialog>
) )
......
import Link from 'next/link' import Link from 'next/link'
import { UpdateSearchParamsButton } from '../../components/UpdateSearchParamsButton'
export default function Home() { export default function Home({ searchParams }) {
return ( return (
<main> <main>
<Link href="/dynamic-refresh/foo/login"> <Link href="/dynamic-refresh/foo/login">
...@@ -9,6 +10,7 @@ export default function Home() { ...@@ -9,6 +10,7 @@ export default function Home() {
<div> <div>
Random # from Root Page: <span id="random-number">{Math.random()}</span> Random # from Root Page: <span id="random-number">{Math.random()}</span>
</div> </div>
<UpdateSearchParamsButton searchParams={searchParams} />
</main> </main>
) )
} }
import { RefreshButton } from '../../../components/RefreshButton' import { RefreshButton } from '../../../components/RefreshButton'
import { RevalidateButton } from '../../../components/RevalidateButton' import { RevalidateButton } from '../../../components/RevalidateButton'
import { UpdateSearchParamsButton } from '../../../components/UpdateSearchParamsButton'
const getRandom = async () => Math.random() const getRandom = async () => Math.random()
export default async function Page() { export default async function Page({ searchParams }) {
const someProp = await getRandom() const someProp = await getRandom()
return ( return (
...@@ -15,6 +16,7 @@ export default async function Page() { ...@@ -15,6 +16,7 @@ export default async function Page() {
</div> </div>
<RefreshButton /> <RefreshButton />
<RevalidateButton /> <RevalidateButton />
<UpdateSearchParamsButton searchParams={searchParams} id="modal" />
</div> </div>
</dialog> </dialog>
) )
......
import Link from 'next/link' import Link from 'next/link'
import { UpdateSearchParamsButton } from '../components/UpdateSearchParamsButton'
export default function Home() { export default function Home({ searchParams }) {
return ( return (
<main> <main>
<Link href="/refreshing/login"> <Link href="/refreshing/login">
...@@ -9,6 +10,7 @@ export default function Home() { ...@@ -9,6 +10,7 @@ export default function Home() {
<div> <div>
Random # from Root Page: <span id="random-number">{Math.random()}</span> Random # from Root Page: <span id="random-number">{Math.random()}</span>
</div> </div>
<UpdateSearchParamsButton searchParams={searchParams} />
</main> </main>
) )
} }
...@@ -159,13 +159,38 @@ createNextDescribe( ...@@ -159,13 +159,38 @@ createNextDescribe(
}) })
describe.each([ describe.each([
{ basePath: '/refreshing', label: 'regular' }, { basePath: '/refreshing', label: 'regular', withSearchParams: false },
{ basePath: '/dynamic-refresh/foo', label: 'dynamic' }, { basePath: '/refreshing', label: 'regular', withSearchParams: true },
])('router.refresh ($label)', ({ basePath }) => { {
basePath: '/dynamic-refresh/foo',
label: 'dynamic',
withSearchParams: false,
},
{
basePath: '/dynamic-refresh/foo',
label: 'dynamic',
withSearchParams: true,
},
])(
'router.refresh ($label) - searchParams: $withSearchParams',
({ basePath, withSearchParams }) => {
it('should correctly refresh data for the intercepted route and previously active page slot', async () => { it('should correctly refresh data for the intercepted route and previously active page slot', async () => {
const browser = await next.browser(basePath) const browser = await next.browser(basePath)
let initialRandomNumber = await browser.elementById('random-number') let initialSearchParams: string | undefined
if (withSearchParams) {
// add some search params prior to proceeding
await browser.elementById('update-search-params').click()
await retry(async () => {
initialSearchParams = await browser
.elementById('search-params')
.text()
expect(initialSearchParams).toMatch(/^Params: "0\.\d+"$/)
})
}
let initialRandomNumber = await browser.elementById('random-number')
await browser.elementByCss(`[href='${basePath}/login']`).click() await browser.elementByCss(`[href='${basePath}/login']`).click()
// interception modal should be visible // interception modal should be visible
...@@ -203,6 +228,19 @@ createNextDescribe( ...@@ -203,6 +228,19 @@ createNextDescribe(
.text() .text()
expect(initialRandomNumber).not.toBe(newRandomNumber) expect(initialRandomNumber).not.toBe(newRandomNumber)
expect(initialModalRandomNumber).not.toBe(newModalRandomNumber) expect(initialModalRandomNumber).not.toBe(newModalRandomNumber)
if (withSearchParams) {
// add additional search params in the new modal
await browser.elementById('update-search-params-modal').click()
expect(
await browser.elementById('search-params-modal').text()
).toMatch(/^Params: "0\.\d+"$/)
// make sure the old params are still there too
expect(await browser.elementById('search-params').text()).toBe(
initialSearchParams
)
}
}) })
// reload the page, triggering which will remove the interception route and show the full page // reload the page, triggering which will remove the interception route and show the full page
...@@ -280,7 +318,8 @@ createNextDescribe( ...@@ -280,7 +318,8 @@ createNextDescribe(
) )
}) })
}) })
}) }
)
describe('server action revalidation', () => { describe('server action revalidation', () => {
it('handles refreshing when multiple parallel slots are active', async () => { it('handles refreshing when multiple parallel slots are active', async () => {
......
...@@ -2272,10 +2272,14 @@ ...@@ -2272,10 +2272,14 @@
"parallel-routes-revalidation should handle a redirect action when called in a slot", "parallel-routes-revalidation should handle a redirect action when called in a slot",
"parallel-routes-revalidation should handle router.refresh() when called in a slot", "parallel-routes-revalidation should handle router.refresh() when called in a slot",
"parallel-routes-revalidation should not trigger full page when calling router.refresh() on an intercepted route", "parallel-routes-revalidation should not trigger full page when calling router.refresh() on an intercepted route",
"parallel-routes-revalidation router.refresh (dynamic) should correctly refresh data for the intercepted route and previously active page slot", "parallel-routes-revalidation router.refresh (dynamic) - searchParams: false should correctly refresh data for the intercepted route and previously active page slot",
"parallel-routes-revalidation router.refresh (dynamic) should correctly refresh data for previously intercepted modal and active page slot", "parallel-routes-revalidation router.refresh (dynamic) - searchParams: false should correctly refresh data for previously intercepted modal and active page slot",
"parallel-routes-revalidation router.refresh (regular) should correctly refresh data for the intercepted route and previously active page slot", "parallel-routes-revalidation router.refresh (dynamic) - searchParams: true should correctly refresh data for the intercepted route and previously active page slot",
"parallel-routes-revalidation router.refresh (regular) should correctly refresh data for previously intercepted modal and active page slot", "parallel-routes-revalidation router.refresh (dynamic) - searchParams: true should correctly refresh data for previously intercepted modal and active page slot",
"parallel-routes-revalidation router.refresh (regular) - searchParams: false should correctly refresh data for the intercepted route and previously active page slot",
"parallel-routes-revalidation router.refresh (regular) - searchParams: false should correctly refresh data for previously intercepted modal and active page slot",
"parallel-routes-revalidation router.refresh (regular) - searchParams: true should correctly refresh data for the intercepted route and previously active page slot",
"parallel-routes-revalidation router.refresh (regular) - searchParams: true should correctly refresh data for previously intercepted modal and active page slot",
"parallel-routes-revalidation server action revalidation handles refreshing when multiple parallel slots are active" "parallel-routes-revalidation server action revalidation handles refreshing when multiple parallel slots are active"
], ],
"pending": [], "pending": [],
......
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