Unverified Commit 1964b17e authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

[Segment Cache] Fix: Key by rewritten search (#81986)

When a request URL is rewritten, the resulting data must be keyed by its
rewritten search params — the ones that were used by the server to
render the page — not the original search params. This works in most
places by encoding the rewritten search params into page's segment key
in the server response. However, the Segment Cache implementation did
not handle this correctly.

The fix is to read the rewritten search params from the
x-nextjs-rewritten-query header in the server response.

In upcoming PRs, we will use a similar approach for regular route
params, too, so that we can lift the params out of the body of the
server response.

---------
Co-authored-by: 's avatarJanka Uryga <lolzatu2@gmail.com>
parent 329bcdc7
import { NEXT_REWRITTEN_QUERY_HEADER } from '../app-router-headers'
import type { RSCResponse } from '../router-reducer/fetch-server-response'
// TypeScript trick to simulate opaque types, like in Flow. // TypeScript trick to simulate opaque types, like in Flow.
type Opaque<K, T> = T & { __brand: K } type Opaque<K, T> = T & { __brand: K }
...@@ -29,3 +32,18 @@ export function createCacheKey( ...@@ -29,3 +32,18 @@ export function createCacheKey(
} as RouteCacheKey } as RouteCacheKey
return cacheKey return cacheKey
} }
export function getRenderedSearch(response: RSCResponse): NormalizedSearch {
// If the server performed a rewrite, the search params used to render the
// page will be different from the params in the request URL. In this case,
// the response will include a header that gives the rewritten search query.
const rewrittenQuery = response.headers.get(NEXT_REWRITTEN_QUERY_HEADER)
if (rewrittenQuery !== null) {
return (
rewrittenQuery === '' ? '' : '?' + rewrittenQuery
) as NormalizedSearch
}
// If the header is not present, there was no rewrite, so we use the search
// query of the response URL.
return new URL(response.url).search as NormalizedSearch
}
...@@ -42,6 +42,7 @@ import type { ...@@ -42,6 +42,7 @@ import type {
NormalizedSearch, NormalizedSearch,
RouteCacheKey, RouteCacheKey,
} from './cache-key' } from './cache-key'
import { getRenderedSearch } from './cache-key'
import { createTupleMap, type TupleMap, type Prefix } from './tuple-map' import { createTupleMap, type TupleMap, type Prefix } from './tuple-map'
import { createLRU } from './lru' import { createLRU } from './lru'
import { import {
...@@ -130,6 +131,7 @@ type PendingRouteCacheEntry = RouteCacheEntryShared & { ...@@ -130,6 +131,7 @@ type PendingRouteCacheEntry = RouteCacheEntryShared & {
status: EntryStatus.Empty | EntryStatus.Pending status: EntryStatus.Empty | EntryStatus.Pending
blockedTasks: Set<PrefetchTask> | null blockedTasks: Set<PrefetchTask> | null
canonicalUrl: null canonicalUrl: null
renderedSearch: null
tree: null tree: null
head: HeadData | null head: HeadData | null
isHeadPartial: true isHeadPartial: true
...@@ -140,6 +142,7 @@ type RejectedRouteCacheEntry = RouteCacheEntryShared & { ...@@ -140,6 +142,7 @@ type RejectedRouteCacheEntry = RouteCacheEntryShared & {
status: EntryStatus.Rejected status: EntryStatus.Rejected
blockedTasks: Set<PrefetchTask> | null blockedTasks: Set<PrefetchTask> | null
canonicalUrl: null canonicalUrl: null
renderedSearch: null
tree: null tree: null
head: null head: null
isHeadPartial: true isHeadPartial: true
...@@ -150,6 +153,7 @@ export type FulfilledRouteCacheEntry = RouteCacheEntryShared & { ...@@ -150,6 +153,7 @@ export type FulfilledRouteCacheEntry = RouteCacheEntryShared & {
status: EntryStatus.Fulfilled status: EntryStatus.Fulfilled
blockedTasks: null blockedTasks: null
canonicalUrl: string canonicalUrl: string
renderedSearch: NormalizedSearch
tree: RouteTree tree: RouteTree
head: HeadData head: HeadData
isHeadPartial: boolean isHeadPartial: boolean
...@@ -413,13 +417,13 @@ export function getSegmentKeypathForTask( ...@@ -413,13 +417,13 @@ export function getSegmentKeypathForTask(
// cache entry is valid for all possible search param values. // cache entry is valid for all possible search param values.
const isDynamicTask = task.includeDynamicData || !route.isPPREnabled const isDynamicTask = task.includeDynamicData || !route.isPPREnabled
return isDynamicTask && path.endsWith('/' + PAGE_SEGMENT_KEY) return isDynamicTask && path.endsWith('/' + PAGE_SEGMENT_KEY)
? [path, task.key.search] ? [path, route.renderedSearch]
: [path] : [path]
} }
export function readSegmentCacheEntry( export function readSegmentCacheEntry(
now: number, now: number,
routeCacheKey: RouteCacheKey, route: FulfilledRouteCacheEntry,
path: string path: string
): SegmentCacheEntry | null { ): SegmentCacheEntry | null {
if (!path.endsWith('/' + PAGE_SEGMENT_KEY)) { if (!path.endsWith('/' + PAGE_SEGMENT_KEY)) {
...@@ -427,15 +431,18 @@ export function readSegmentCacheEntry( ...@@ -427,15 +431,18 @@ export function readSegmentCacheEntry(
return readExactSegmentCacheEntry(now, [path]) return readExactSegmentCacheEntry(now, [path])
} }
// Page segments may or may not contain search params. If they were prefetched const renderedSearch = route.renderedSearch
// using a dynamic request, then we will have an entry with search params. if (renderedSearch !== null) {
// Check for that case first. // Page segments may or may not contain search params. If they were prefetched
const entryWithSearchParams = readExactSegmentCacheEntry(now, [ // using a dynamic request, then we will have an entry with search params.
path, // Check for that case first.
routeCacheKey.search, const entryWithSearchParams = readExactSegmentCacheEntry(now, [
]) path,
if (entryWithSearchParams !== null) { renderedSearch,
return entryWithSearchParams ])
if (entryWithSearchParams !== null) {
return entryWithSearchParams
}
} }
// If we did not find an entry with the given search params, check for a // If we did not find an entry with the given search params, check for a
...@@ -550,6 +557,7 @@ export function readOrCreateRouteCacheEntry( ...@@ -550,6 +557,7 @@ export function readOrCreateRouteCacheEntry(
couldBeIntercepted: true, couldBeIntercepted: true,
// Similarly, we don't yet know if the route supports PPR. // Similarly, we don't yet know if the route supports PPR.
isPPREnabled: false, isPPREnabled: false,
renderedSearch: null,
// LRU-related fields // LRU-related fields
keypath: null, keypath: null,
...@@ -783,6 +791,7 @@ function fulfillRouteCacheEntry( ...@@ -783,6 +791,7 @@ function fulfillRouteCacheEntry(
staleAt: number, staleAt: number,
couldBeIntercepted: boolean, couldBeIntercepted: boolean,
canonicalUrl: string, canonicalUrl: string,
renderedSearch: NormalizedSearch,
isPPREnabled: boolean isPPREnabled: boolean
): FulfilledRouteCacheEntry { ): FulfilledRouteCacheEntry {
const fulfilledEntry: FulfilledRouteCacheEntry = entry as any const fulfilledEntry: FulfilledRouteCacheEntry = entry as any
...@@ -793,6 +802,7 @@ function fulfillRouteCacheEntry( ...@@ -793,6 +802,7 @@ function fulfillRouteCacheEntry(
fulfilledEntry.staleAt = staleAt fulfilledEntry.staleAt = staleAt
fulfilledEntry.couldBeIntercepted = couldBeIntercepted fulfilledEntry.couldBeIntercepted = couldBeIntercepted
fulfilledEntry.canonicalUrl = canonicalUrl fulfilledEntry.canonicalUrl = canonicalUrl
fulfilledEntry.renderedSearch = renderedSearch
fulfilledEntry.isPPREnabled = isPPREnabled fulfilledEntry.isPPREnabled = isPPREnabled
pingBlockedTasks(entry) pingBlockedTasks(entry)
return fulfilledEntry return fulfilledEntry
...@@ -1133,6 +1143,11 @@ export async function fetchRouteOnCacheMiss( ...@@ -1133,6 +1143,11 @@ export async function fetchRouteOnCacheMiss(
return null return null
} }
// Get the search params that were used to render the target page. This may
// be different from the search params in the request URL, if the page
// was rewritten.
const renderedSearch = getRenderedSearch(response)
const staleTimeMs = serverData.staleTime * 1000 const staleTimeMs = serverData.staleTime * 1000
fulfillRouteCacheEntry( fulfillRouteCacheEntry(
entry, entry,
...@@ -1142,6 +1157,7 @@ export async function fetchRouteOnCacheMiss( ...@@ -1142,6 +1157,7 @@ export async function fetchRouteOnCacheMiss(
Date.now() + staleTimeMs, Date.now() + staleTimeMs,
couldBeIntercepted, couldBeIntercepted,
canonicalUrl, canonicalUrl,
renderedSearch,
routeIsPPREnabled routeIsPPREnabled
) )
} else { } else {
...@@ -1366,6 +1382,19 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest( ...@@ -1366,6 +1382,19 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
return null return null
} }
const renderedSearch = getRenderedSearch(response)
if (renderedSearch !== route.renderedSearch) {
// The search params that were used to render the target page are
// different from the search params in the request URL. This only happens
// when there's a dynamic rewrite in between the tree prefetch and the
// data prefetch.
// TODO: For now, since this is an edge case, we reject the prefetch, but
// the proper way to handle this is to evict the stale route tree entry
// then fill the cache with the new response.
rejectSegmentEntriesIfStillPending(spawnedEntries, Date.now() + 10 * 1000)
return null
}
// Track when the network connection closes. // Track when the network connection closes.
const closed = createPromiseWithResolvers<void>() const closed = createPromiseWithResolvers<void>()
...@@ -1462,6 +1491,11 @@ function writeDynamicTreeResponseIntoCache( ...@@ -1462,6 +1491,11 @@ function writeDynamicTreeResponseIntoCache(
const isResponsePartial = const isResponsePartial =
response.headers.get(NEXT_DID_POSTPONE_HEADER) === '1' response.headers.get(NEXT_DID_POSTPONE_HEADER) === '1'
// Get the search params that were used to render the target page. This may
// be different from the search params in the request URL, if the page
// was rewritten.
const renderedSearch = getRenderedSearch(response)
const fulfilledEntry = fulfillRouteCacheEntry( const fulfilledEntry = fulfillRouteCacheEntry(
entry, entry,
convertRootFlightRouterStateToRouteTree(flightRouterState), convertRootFlightRouterStateToRouteTree(flightRouterState),
...@@ -1470,6 +1504,7 @@ function writeDynamicTreeResponseIntoCache( ...@@ -1470,6 +1504,7 @@ function writeDynamicTreeResponseIntoCache(
now + staleTimeMs, now + staleTimeMs,
couldBeIntercepted, couldBeIntercepted,
canonicalUrl, canonicalUrl,
renderedSearch,
routeIsPPREnabled routeIsPPREnabled
) )
......
...@@ -22,12 +22,10 @@ import { ...@@ -22,12 +22,10 @@ import {
readSegmentCacheEntry, readSegmentCacheEntry,
waitForSegmentCacheEntry, waitForSegmentCacheEntry,
type RouteTree, type RouteTree,
type FulfilledRouteCacheEntry,
} from './cache' } from './cache'
import { createCacheKey, type RouteCacheKey } from './cache-key' import { createCacheKey } from './cache-key'
import { import { addSearchParamsIfPageSegment } from '../../../shared/lib/segment'
addSearchParamsIfPageSegment,
PAGE_SEGMENT_KEY,
} from '../../../shared/lib/segment'
import { NavigationResultTag } from '../segment-cache' import { NavigationResultTag } from '../segment-cache'
type MPANavigationResult = { type MPANavigationResult = {
...@@ -116,7 +114,7 @@ export function navigate( ...@@ -116,7 +114,7 @@ export function navigate(
const route = readRouteCacheEntry(now, cacheKey) const route = readRouteCacheEntry(now, cacheKey)
if (route !== null && route.status === EntryStatus.Fulfilled) { if (route !== null && route.status === EntryStatus.Fulfilled) {
// We have a matching prefetch. // We have a matching prefetch.
const snapshot = readRenderSnapshotFromCache(now, cacheKey, route.tree) const snapshot = readRenderSnapshotFromCache(now, route, route.tree)
const prefetchFlightRouterState = snapshot.flightRouterState const prefetchFlightRouterState = snapshot.flightRouterState
const prefetchSeedData = snapshot.seedData const prefetchSeedData = snapshot.seedData
const prefetchHead = route.head const prefetchHead = route.head
...@@ -255,7 +253,7 @@ function navigationTaskToResult( ...@@ -255,7 +253,7 @@ function navigationTaskToResult(
function readRenderSnapshotFromCache( function readRenderSnapshotFromCache(
now: number, now: number,
routeCacheKey: RouteCacheKey, route: FulfilledRouteCacheEntry,
tree: RouteTree tree: RouteTree
): { flightRouterState: FlightRouterState; seedData: CacheNodeSeedData } { ): { flightRouterState: FlightRouterState; seedData: CacheNodeSeedData } {
let childRouterStates: { [parallelRouteKey: string]: FlightRouterState } = {} let childRouterStates: { [parallelRouteKey: string]: FlightRouterState } = {}
...@@ -266,11 +264,7 @@ function readRenderSnapshotFromCache( ...@@ -266,11 +264,7 @@ function readRenderSnapshotFromCache(
if (slots !== null) { if (slots !== null) {
for (const parallelRouteKey in slots) { for (const parallelRouteKey in slots) {
const childTree = slots[parallelRouteKey] const childTree = slots[parallelRouteKey]
const childResult = readRenderSnapshotFromCache( const childResult = readRenderSnapshotFromCache(now, route, childTree)
now,
routeCacheKey,
childTree
)
childRouterStates[parallelRouteKey] = childResult.flightRouterState childRouterStates[parallelRouteKey] = childResult.flightRouterState
childSeedDatas[parallelRouteKey] = childResult.seedData childSeedDatas[parallelRouteKey] = childResult.seedData
} }
...@@ -280,7 +274,7 @@ function readRenderSnapshotFromCache( ...@@ -280,7 +274,7 @@ function readRenderSnapshotFromCache(
let loading: LoadingModuleData | Promise<LoadingModuleData> = null let loading: LoadingModuleData | Promise<LoadingModuleData> = null
let isPartial: boolean = true let isPartial: boolean = true
const segmentEntry = readSegmentCacheEntry(now, routeCacheKey, tree.key) const segmentEntry = readSegmentCacheEntry(now, route, tree.key)
if (segmentEntry !== null) { if (segmentEntry !== null) {
switch (segmentEntry.status) { switch (segmentEntry.status) {
case EntryStatus.Fulfilled: { case EntryStatus.Fulfilled: {
...@@ -315,23 +309,20 @@ function readRenderSnapshotFromCache( ...@@ -315,23 +309,20 @@ function readRenderSnapshotFromCache(
} }
} }
const segment = // The navigation implementation expects the search params to be
tree.segment === PAGE_SEGMENT_KEY && routeCacheKey.search // included in the segment. However, the Segment Cache tracks search
? // The navigation implementation expects the search params to be // params separately from the rest of the segment key. So we need to
// included in the segment. However, the Segment Cache tracks search // add them back here.
// params separately from the rest of the segment key. So we need to //
// add them back here. // See corresponding comment in convertFlightRouterStateToTree.
// //
// See corresponding comment in convertFlightRouterStateToTree. // TODO: What we should do instead is update the navigation diffing
// // logic to compare search params explicitly. This is a temporary
// TODO: What we should do instead is update the navigation diffing // solution until more of the Segment Cache implementation has settled.
// logic to compare search params explicitly. This is a temporary const segment = addSearchParamsIfPageSegment(
// solution until more of the Segment Cache implementation has settled. tree.segment,
addSearchParamsIfPageSegment( Object.fromEntries(new URLSearchParams(route.renderedSearch))
tree.segment, )
Object.fromEntries(new URLSearchParams(routeCacheKey.search))
)
: tree.segment
return { return {
flightRouterState: [ flightRouterState: [
......
import type { import type {
FlightRouterState, FlightRouterState,
Segment as FlightRouterStateSegment, Segment as FlightRouterStateSegment,
Segment,
} from '../../../server/app-render/types' } from '../../../server/app-render/types'
import { HasLoadingBoundary } from '../../../server/app-render/types' import { HasLoadingBoundary } from '../../../server/app-render/types'
import { matchSegment } from '../match-segments' import { matchSegment } from '../match-segments'
...@@ -28,6 +29,10 @@ import { ...@@ -28,6 +29,10 @@ import {
} from './cache' } from './cache'
import type { RouteCacheKey } from './cache-key' import type { RouteCacheKey } from './cache-key'
import { getCurrentCacheVersion, PrefetchPriority } from '../segment-cache' import { getCurrentCacheVersion, PrefetchPriority } from '../segment-cache'
import {
addSearchParamsIfPageSegment,
PAGE_SEGMENT_KEY,
} from '../../../shared/lib/segment'
const scheduleMicrotask = const scheduleMicrotask =
typeof queueMicrotask === 'function' typeof queueMicrotask === 'function'
...@@ -657,7 +662,11 @@ function diffRouteTreeAgainstCurrent( ...@@ -657,7 +662,11 @@ function diffRouteTreeAgainstCurrent(
oldTreeChild?.[0] oldTreeChild?.[0]
if ( if (
oldTreeChildSegment !== undefined && oldTreeChildSegment !== undefined &&
matchSegment(newTreeChildSegment, oldTreeChildSegment) doesCurrentSegmentMatchCachedSegment(
route,
newTreeChildSegment,
oldTreeChildSegment
)
) { ) {
// This segment is already part of the current route. Keep traversing. // This segment is already part of the current route. Keep traversing.
const requestTreeChild = diffRouteTreeAgainstCurrent( const requestTreeChild = diffRouteTreeAgainstCurrent(
...@@ -1177,6 +1186,34 @@ function upsertSegmentOnCompletion( ...@@ -1177,6 +1186,34 @@ function upsertSegmentOnCompletion(
}, noop) }, noop)
} }
function doesCurrentSegmentMatchCachedSegment(
route: FulfilledRouteCacheEntry,
currentSegment: Segment,
cachedSegment: Segment
): boolean {
if (cachedSegment === PAGE_SEGMENT_KEY) {
// In the FlightRouterState stored by the router, the page segment has the
// rendered search params appended to the name of the segment. In the
// prefetch cache, however, this is stored separately. So, when comparing
// the router's current FlightRouterState to the cached FlightRouterState,
// we need to make sure we compare both parts of the segment.
// TODO: This is not modeled clearly. We use the same type,
// FlightRouterState, for both the CacheNode tree _and_ the prefetch cache
// _and_ the server response format, when conceptually those are three
// different things and treated in different ways. We should encode more of
// this information into the type design so mistakes are less likely.
return (
currentSegment ===
addSearchParamsIfPageSegment(
PAGE_SEGMENT_KEY,
Object.fromEntries(new URLSearchParams(route.renderedSearch))
)
)
}
// Non-page segments are compared using the same function as the server
return matchSegment(cachedSegment, currentSegment)
}
// ----------------------------------------------------------------------------- // -----------------------------------------------------------------------------
// The remainder of the module is a MinHeap implementation. Try not to put any // The remainder of the module is a MinHeap implementation. Try not to put any
// logic below here unless it's related to the heap algorithm. We can extract // logic below here unless it's related to the heap algorithm. We can extract
......
import { Suspense } from 'react'
import { LinkAccordion } from '../../components/link-accordion' import { LinkAccordion } from '../../components/link-accordion'
export default function SearchParamsPage() { export default function SearchParamsPage({
searchParams,
}: {
searchParams: Promise<{ greeting?: string }>
}) {
return ( return (
<> <>
<p> <p>
...@@ -34,6 +39,69 @@ export default function SearchParamsPage() { ...@@ -34,6 +39,69 @@ export default function SearchParamsPage() {
</LinkAccordion> </LinkAccordion>
</li> </li>
</ul> </ul>
<p>
Demonstrates that pages that render based on search params are cached
correctly even during a rewrite. Because each of the links below rewrite
to the same URL, they only need to fetch the page once (note: there will
still be separate requests for the route trees, but not for the page
data itself).
</p>
<ul>
<li>
<LinkAccordion
prefetch={true}
href="/search-params/target-page?searchParam=rewritesToANewSearchParam"
>
searchParam=rewritesToANewSearchParam, prefetch=true
</LinkAccordion>
</li>
<li>
<LinkAccordion
prefetch={true}
href="/search-params/target-page?searchParam=alsoRewritesToThatSameSearchParam"
>
searchParam=alsoRewritesToThatSameSearchParam, prefetch=true
</LinkAccordion>
</li>
</ul>
<p>
The first link rewrites to the current page, but with an additional
search param. The router must be able to detect that something on the
new page has changed. So, clicking the first link should cause the
current page to re-render, but with a greeting rendered below.
</p>
<p>
The second link rewrites to the current page, but without any search
params. Clicking this link after clicking the first one should cause the
greeting to disappear.
</p>
<ul>
<li>
<LinkAccordion prefetch={true} href="/search-params-with-greeting">
Rewrite to current page with additional ?greeting=hello search
param, prefetch=true
</LinkAccordion>
</li>
<li>
<LinkAccordion prefetch={true} href="/search-params-with-no-greeting">
Rewrite to current page without any search params, prefetch=true
</LinkAccordion>
</li>
</ul>
<Suspense fallback={null}>
<Greeting searchParams={searchParams} />
</Suspense>
</> </>
) )
} }
async function Greeting({
searchParams,
}: {
searchParams: Promise<{ greeting?: string }>
}) {
const { greeting } = await searchParams
return (
<p id="greeting">{`Greeting (from search params): ${greeting ?? '(none)'}`}</p>
)
}
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
export function middleware(request: NextRequest) {
if (request.nextUrl.pathname.startsWith('/search-params/target-page')) {
const searchParam = request.nextUrl.searchParams.get('searchParam')
if (
searchParam === 'rewritesToANewSearchParam' ||
searchParam === 'alsoRewritesToThatSameSearchParam'
) {
return NextResponse.rewrite(
new URL(
'/search-params/target-page?searchParam=rewrittenSearchParam',
request.url
)
)
}
}
if (request.nextUrl.pathname.startsWith('/search-params-with-greeting')) {
return NextResponse.rewrite(
new URL('/search-params?greeting=hello', request.url)
)
}
if (request.nextUrl.pathname.startsWith('/search-params-with-no-greeting')) {
return NextResponse.rewrite(new URL('/search-params', request.url))
}
}
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { createRouterAct } from '../router-act' import { createRouterAct } from '../router-act'
import { retry } from '../../../../lib/next-test-utils'
describe('segment cache (search params)', () => { describe('segment cache (search params)', () => {
const { next, isNextDev } = nextTestSetup({ const { next, isNextDev, isNextDeploy } = nextTestSetup({
files: __dirname, files: __dirname,
}) })
if (isNextDev) { if (isNextDev) {
...@@ -139,4 +140,148 @@ describe('segment cache (search params)', () => { ...@@ -139,4 +140,148 @@ describe('segment cache (search params)', () => {
'no-requests' 'no-requests'
) )
}) })
it('stores prefetched data by its rewritten search params, not the original ones', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/search-params', {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
const revealLinkThatRewritesToANewSearchParam = await browser.elementByCss(
'input[data-link-accordion="/search-params/target-page?searchParam=rewritesToANewSearchParam"]'
)
const revealLinkThatAlsoRewritesToThatSameSearchParam =
await browser.elementByCss(
'input[data-link-accordion="/search-params/target-page?searchParam=alsoRewritesToThatSameSearchParam"]'
)
await act(
async () => {
await revealLinkThatRewritesToANewSearchParam.click()
},
{
includes: 'Search param: rewrittenSearchParam',
}
)
// This should not fetch the page data again, because it was rewritten to
// the same page.
await act(
async () => {
await revealLinkThatAlsoRewritesToThatSameSearchParam.click()
},
{
includes: 'Search param: rewrittenSearchParam',
block: 'reject',
}
)
// However, fetching any other search param value does a new fetch
const revealB = await browser.elementByCss(
'input[data-link-accordion="/search-params/target-page?searchParam=b_full"]'
)
await act(
async () => {
await revealB.click()
},
{
includes: 'Search param: b_full',
}
)
})
it('handles rewrites to the same page but with different search params', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/search-params', {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
// Make sure HTML streaming finishes, so that we don't get
// multiple `<div id="greeting">` elements in the document when we navigate
// TODO: this seems like it should be handled by waitForHydration?
await retry(async () => {
const greeting = browser.locator('#greeting')
expect(await greeting.isVisible()).toBe(true)
expect(await greeting.innerText()).toEqual(
'Greeting (from search params): (none)'
)
})
// This link rewrites to the current page, but with a search param that
// causes a greeting to be rendered.
const revealLink = await browser.elementByCss(
'input[data-link-accordion="/search-params-with-greeting"]'
)
await act(
async () => {
await revealLink.click()
},
{
includes: 'Greeting (from search params): hello',
}
)
// Clicking the link should update the greeting
const link = await browser.elementByCss(
'a[href="/search-params-with-greeting"]'
)
await act(async () => {
await link.click()
}, 'no-requests')
expect(await browser.elementById('greeting').text()).toBe(
'Greeting (from search params): hello'
)
})
// FIXME: search params seem to be dropped from the resume render when deployed
if (!isNextDeploy) {
it('handles rewrites to the same page but with no search params', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/search-params-with-greeting', {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
// Make sure HTML streaming finishes, so that we don't get
// multiple `<div id="greeting">` elements in the document when we navigate
// TODO: this seems like it should be handled by waitForHydration?
await retry(async () => {
const greeting = browser.locator('#greeting')
expect(await greeting.isVisible()).toBe(true)
expect(await greeting.innerText()).toEqual(
'Greeting (from search params): hello'
)
})
// This link rewrites to same target pathname as the current page, but with
// an internal search param removed
const revealLink = await browser.elementByCss(
'input[data-link-accordion="/search-params-with-no-greeting"]'
)
await act(
async () => {
await revealLink.click()
},
{
includes: 'Greeting (from search params): (none)',
}
)
// Clicking the link should remove the greeting
const link = await browser.elementByCss(
'a[href="/search-params-with-no-greeting"]'
)
await act(async () => {
await link.click()
}, 'no-requests')
expect(await browser.elementById('greeting').text()).toBe(
'Greeting (from search params): (none)'
)
})
}
}) })
...@@ -543,6 +543,10 @@ export class Playwright<TCurrent = undefined> { ...@@ -543,6 +543,10 @@ export class Playwright<TCurrent = undefined> {
return page.locator('nextjs-portal [data-nextjs-dev-tools-button]') return page.locator('nextjs-portal [data-nextjs-dev-tools-button]')
} }
locator(selector: string, options?: Parameters<(typeof page)['locator']>[1]) {
return page.locator(selector, options)
}
/** A call that expects to be chained after a previous call, because it needs its value. */ /** A call that expects to be chained after a previous call, because it needs its value. */
private continueChain<TNext>(nextCall: (value: TCurrent) => Promise<TNext>) { private continueChain<TNext>(nextCall: (value: TCurrent) => Promise<TNext>) {
return this._chain(true, nextCall) return this._chain(true, nextCall)
......
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