Unverified Commit 78f73b27 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Handle encoded params further (#91627)

Continues https://github.com/vercel/next.js/pull/91603 applying the
encoding normalization further and narrows in a better regression test
separate of root params and specific to vary params flag.
parent afbce6a6
...@@ -71,3 +71,134 @@ describe('getParamsFromRouteMatches', () => { ...@@ -71,3 +71,134 @@ describe('getParamsFromRouteMatches', () => {
expect(params).toEqual({ slug: 'hello-world', rest: ['im-the', 'rest'] }) expect(params).toEqual({ slug: 'hello-world', rest: ['im-the', 'rest'] })
}) })
}) })
describe('normalizeDynamicRouteParams', () => {
it('should reject encoded default placeholders for dynamic params', () => {
const { normalizeDynamicRouteParams } = getServerUtils({
page: '/[teamSlug]/[project]',
basePath: '',
rewrites: {},
i18n: undefined,
pageIsDynamic: true,
caseSensitive: false,
})
const result = normalizeDynamicRouteParams(
{
teamSlug: '%5BteamSlug%5D',
project: '%5Bproject%5D',
},
true
)
expect(result).toEqual({
params: {},
hasValidParams: false,
})
})
it('should reject doubly encoded default placeholders for dynamic params', () => {
const { normalizeDynamicRouteParams } = getServerUtils({
page: '/[teamSlug]/[project]',
basePath: '',
rewrites: {},
i18n: undefined,
pageIsDynamic: true,
caseSensitive: false,
})
const result = normalizeDynamicRouteParams(
{
teamSlug: '%255BteamSlug%255D',
project: '%255Bproject%255D',
},
true
)
expect(result).toEqual({
params: {},
hasValidParams: false,
})
})
it('should continue accepting regular dynamic values', () => {
const { normalizeDynamicRouteParams } = getServerUtils({
page: '/[teamSlug]/[project]',
basePath: '',
rewrites: {},
i18n: undefined,
pageIsDynamic: true,
caseSensitive: false,
})
const result = normalizeDynamicRouteParams(
{
teamSlug: 'vercel',
project: 'nextjs',
},
true
)
expect(result).toEqual({
params: {
teamSlug: 'vercel',
project: 'nextjs',
},
hasValidParams: true,
})
})
it('should not decode matched params beyond the route matcher decode', () => {
const { normalizeDynamicRouteParams } = getServerUtils({
page: '/[teamSlug]/[project]',
basePath: '',
rewrites: {},
i18n: undefined,
pageIsDynamic: true,
caseSensitive: false,
})
const result = normalizeDynamicRouteParams(
{
teamSlug: 'acme',
project: '%23hash',
},
true
)
expect(result).toEqual({
params: {
teamSlug: 'acme',
project: '%23hash',
},
hasValidParams: true,
})
})
it('should not reject non-placeholder values that only contain decoded placeholder text', () => {
const { normalizeDynamicRouteParams } = getServerUtils({
page: '/[teamSlug]/[project]',
basePath: '',
rewrites: {},
i18n: undefined,
pageIsDynamic: true,
caseSensitive: false,
})
const result = normalizeDynamicRouteParams(
{
teamSlug: 'acme',
project: '%5Bproject%5D-suffix',
},
true
)
expect(result).toEqual({
params: {
teamSlug: 'acme',
project: '%5Bproject%5D-suffix',
},
hasValidParams: true,
})
})
})
...@@ -112,6 +112,34 @@ export function normalizeDynamicRouteParams( ...@@ -112,6 +112,34 @@ export function normalizeDynamicRouteParams(
defaultRouteMatches: ParsedUrlQuery, defaultRouteMatches: ParsedUrlQuery,
ignoreMissingOptional: boolean ignoreMissingOptional: boolean
) { ) {
const isDefaultValueMatch = (
candidateValue: string | undefined,
defaultValue: string
) => {
if (!candidateValue) {
return false
}
let normalizedCandidateValue = normalizeRscURL(candidateValue)
for (let i = 0; i < 3; i++) {
if (normalizedCandidateValue === defaultValue) {
return true
}
const decodedCandidateValue = decodeQueryPathParameter(
normalizedCandidateValue
)
if (decodedCandidateValue === normalizedCandidateValue) {
break
}
normalizedCandidateValue = decodedCandidateValue
}
return false
}
let hasValidParams = true let hasValidParams = true
let params: ParsedUrlQuery = {} let params: ParsedUrlQuery = {}
...@@ -133,10 +161,12 @@ export function normalizeDynamicRouteParams( ...@@ -133,10 +161,12 @@ export function normalizeDynamicRouteParams(
const isDefaultValue = Array.isArray(defaultValue) const isDefaultValue = Array.isArray(defaultValue)
? defaultValue.some((defaultVal) => { ? defaultValue.some((defaultVal) => {
return Array.isArray(value) return Array.isArray(value)
? value.some((val) => val.includes(defaultVal)) ? value.some((val) => isDefaultValueMatch(val, defaultVal))
: value?.includes(defaultVal) : isDefaultValueMatch(value, defaultVal)
}) })
: value?.includes(defaultValue as string) : Array.isArray(value)
? value.some((val) => isDefaultValueMatch(val, defaultValue as string))
: isDefaultValueMatch(value, defaultValue as string)
if ( if (
isDefaultValue || isDefaultValue ||
......
export default function TeamProjectLoading() {
return (
<div data-team-project-loading="true">Loading team project page...</div>
)
}
import { cacheLife } from 'next/cache'
import { Suspense } from 'react'
type Params = { teamSlug: string; project: string }
export default function TeamProjectPage({
params,
}: {
params: Promise<Params>
}) {
return (
<div id="team-project-page">
<Suspense
fallback={<div data-loading="true">Loading team/project route...</div>}
>
<TeamProjectContent params={params} />
</Suspense>
</div>
)
}
async function TeamProjectContent({ params }: { params: Promise<Params> }) {
'use cache'
cacheLife({ stale: 0, revalidate: 1, expire: 60 })
const { teamSlug, project } = await params
const marker = Date.now()
return (
<div data-team-project-content="true">
{`Team project content - team: ${teamSlug}, project: ${project}, marker: ${marker}`}
</div>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { LinkAccordion } from '../components/link-accordion'
export default function HomePage() {
return (
<div id="home-page">
<h1>Root Dynamic Route Vary Params</h1>
<p>
Prefetch dynamic team/project routes and validate segment payload
params.
</p>
<ul>
<li>
<LinkAccordion href="/acme/dashboard">
Team project: acme/dashboard
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/globex/portal">
Team project: globex/portal
</LinkAccordion>
</li>
</ul>
</div>
)
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children?: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
const displayChildren = children !== undefined ? children : href
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{displayChildren}
</Link>
) : (
<>{displayChildren} (link is hidden)</>
)}
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
experimental: {
optimisticRouting: true,
varyParams: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import { waitFor } from 'next-test-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
describe('segment cache - vary params base dynamic', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
test('prefetching is disabled in dev mode', () => {})
return
}
it('keeps dynamic segment params valid before and after time-based revalidation', async () => {
const collectSegmentPrefetchResponses = async (href: string) => {
let act: ReturnType<typeof createRouterAct>
const segmentPrefetchResponses: Array<
Promise<{ body: string; segmentPrefetchPath: string }>
> = []
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
p.on('response', (response) => {
const request = response.request()
const segmentPath =
request.headers()['next-router-segment-prefetch']
if (segmentPath) {
const pathname = new URL(request.url()).pathname
const segmentPrefetchPath = pathname.endsWith('.rsc')
? `${pathname.slice(0, -'.rsc'.length)}.segments${segmentPath}.segment.rsc`
: `${pathname}.segments${segmentPath}.segment.rsc`
segmentPrefetchResponses.push(
response
.text()
.then((body) => ({ body, segmentPrefetchPath }))
.catch(() => ({ body: '', segmentPrefetchPath }))
)
}
})
},
})
await act(async () => {
const toggle = await browser.elementByCss(
`input[data-link-accordion="${href}"]`
)
await toggle.click()
})
const settledResponses = await Promise.all(segmentPrefetchResponses)
await browser.close()
return settledResponses
}
const readRouteMarker = async (path: string, expectedText: string) => {
const browser = await next.browser(path)
const content = await browser.elementByCss('[data-team-project-content]')
const text = await content.text()
await browser.close()
expect(text).toContain(expectedText)
const markerMatch = text.match(/marker: (\d+)/)
expect(markerMatch).not.toBeNull()
return Number(markerMatch![1])
}
const assertValidSegmentResponses = (
responses: Array<{ body: string; segmentPrefetchPath: string }>
) => {
const bodies = responses.map((response) => response.body)
const allBodies = bodies.join('\n')
const segmentPrefetchPaths = [
...new Set(responses.map((response) => response.segmentPrefetchPath)),
]
expect(bodies.length).toBeGreaterThan(0)
expect(allBodies.includes('%5BteamSlug%5D')).toBe(false)
expect(allBodies.includes('%5Bproject%5D')).toBe(false)
expect(
segmentPrefetchPaths.some((path) =>
path.startsWith('/acme/dashboard.segments/')
)
).toBe(true)
expect(
segmentPrefetchPaths.some((path) =>
path.startsWith('/globex/portal.segments/')
)
).toBe(true)
expect(
segmentPrefetchPaths.every(
(path) => path.includes('.segments/') && path.endsWith('.segment.rsc')
)
).toBe(true)
}
const initialAcmeMarker = await readRouteMarker(
'/acme/dashboard',
'Team project content - team: acme, project: dashboard'
)
const initialGlobexMarker = await readRouteMarker(
'/globex/portal',
'Team project content - team: globex, project: portal'
)
const initialResponses = [
...(await collectSegmentPrefetchResponses('/acme/dashboard')),
...(await collectSegmentPrefetchResponses('/globex/portal')),
]
assertValidSegmentResponses(initialResponses)
let lastAcmeMarker = initialAcmeMarker
let lastGlobexMarker = initialGlobexMarker
for (let checkIndex = 0; checkIndex < 5; checkIndex++) {
await waitFor(2_000)
const revalidatedResponses = [
...(await collectSegmentPrefetchResponses('/acme/dashboard')),
...(await collectSegmentPrefetchResponses('/globex/portal')),
]
assertValidSegmentResponses(revalidatedResponses)
const revalidatedAcmeMarker = await readRouteMarker(
'/acme/dashboard',
'Team project content - team: acme, project: dashboard'
)
const revalidatedGlobexMarker = await readRouteMarker(
'/globex/portal',
'Team project content - team: globex, project: portal'
)
expect(revalidatedAcmeMarker).not.toBe(lastAcmeMarker)
expect(revalidatedGlobexMarker).not.toBe(lastGlobexMarker)
lastAcmeMarker = revalidatedAcmeMarker
lastGlobexMarker = revalidatedGlobexMarker
}
})
})
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse<{ revalidated: boolean }>
) {
const pathParam = req.query['path']
if (!pathParam) {
return res.status(400).json({ revalidated: false })
}
const paths = Array.isArray(pathParam) ? pathParam : [pathParam]
try {
await Promise.all(paths.map((path) => res.revalidate(path)))
return res.status(200).json({ revalidated: true })
} catch (error) {
console.error('Failed to revalidate paths:', paths, error)
return res.status(500).json({ revalidated: false })
}
}
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