Unverified Commit b679a610 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

fix: handle optional catchalls correctly (#75377)

Previously when there was an optional catch-all present where it wasn't
provided it could not get read directly from the query parameters (as it
was done in PPR resumes) and instead it was inferring the default
parameters.

<!-- 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 #

-->
parent 20a90c55
...@@ -1237,16 +1237,13 @@ export default abstract class Server< ...@@ -1237,16 +1237,13 @@ export default abstract class Server<
typeof routeMatchesHeader === 'string' && typeof routeMatchesHeader === 'string' &&
routeMatchesHeader && routeMatchesHeader &&
isDynamicRoute(matchedPath) && isDynamicRoute(matchedPath) &&
!paramsResult.hasValidParams (Object.keys(params).length === 0 || !paramsResult.hasValidParams)
) { ) {
const routeMatches = const routeMatches =
utils.getParamsFromRouteMatches(routeMatchesHeader) utils.getParamsFromRouteMatches(routeMatchesHeader)
if (routeMatches) { if (routeMatches) {
paramsResult = utils.normalizeDynamicRouteParams( paramsResult = utils.normalizeDynamicRouteParams(routeMatches)
routeMatches,
true
)
if (paramsResult.hasValidParams) { if (paramsResult.hasValidParams) {
params = paramsResult.params params = paramsResult.params
...@@ -1259,8 +1256,7 @@ export default abstract class Server< ...@@ -1259,8 +1256,7 @@ export default abstract class Server<
utils.defaultRouteMatches && utils.defaultRouteMatches &&
normalizedUrlPath === srcPathname && normalizedUrlPath === srcPathname &&
!paramsResult.hasValidParams && !paramsResult.hasValidParams &&
!utils.normalizeDynamicRouteParams({ ...params }, true) !utils.normalizeDynamicRouteParams({ ...params }).hasValidParams
.hasValidParams
) { ) {
params = utils.defaultRouteMatches params = utils.defaultRouteMatches
...@@ -1276,7 +1272,7 @@ export default abstract class Server< ...@@ -1276,7 +1272,7 @@ export default abstract class Server<
} }
if (pageIsDynamic || didRewrite) { if (pageIsDynamic || didRewrite) {
utils.normalizeVercelUrl(req, true, [ utils.normalizeVercelUrl(req, [
...rewriteParamKeys, ...rewriteParamKeys,
...Object.keys(utils.defaultRouteRegex?.groups || {}), ...Object.keys(utils.defaultRouteRegex?.groups || {}),
]) ])
......
...@@ -24,36 +24,34 @@ import { normalizeNextQueryParam } from './web/utils' ...@@ -24,36 +24,34 @@ import { normalizeNextQueryParam } from './web/utils'
export function normalizeVercelUrl( export function normalizeVercelUrl(
req: BaseNextRequest, req: BaseNextRequest,
trustQuery: boolean, paramKeys: string[],
paramKeys?: string[], defaultRouteRegex: ReturnType<typeof getNamedRouteRegex> | undefined
pageIsDynamic?: boolean,
defaultRouteRegex?: ReturnType<typeof getNamedRouteRegex> | undefined
) { ) {
if (!defaultRouteRegex) return
// make sure to normalize req.url on Vercel to strip dynamic params // make sure to normalize req.url on Vercel to strip dynamic params
// from the query which are added during routing // from the query which are added during routing
if (pageIsDynamic && trustQuery && defaultRouteRegex) { const _parsedUrl = parseUrl(req.url!, true)
const _parsedUrl = parseUrl(req.url!, true) delete (_parsedUrl as any).search
delete (_parsedUrl as any).search
for (const key of Object.keys(_parsedUrl.query)) {
for (const key of Object.keys(_parsedUrl.query)) { const isNextQueryPrefix =
const isNextQueryPrefix = key !== NEXT_QUERY_PARAM_PREFIX && key.startsWith(NEXT_QUERY_PARAM_PREFIX)
key !== NEXT_QUERY_PARAM_PREFIX &&
key.startsWith(NEXT_QUERY_PARAM_PREFIX) const isNextInterceptionMarkerPrefix =
key !== NEXT_INTERCEPTION_MARKER_PREFIX &&
const isNextInterceptionMarkerPrefix = key.startsWith(NEXT_INTERCEPTION_MARKER_PREFIX)
key !== NEXT_INTERCEPTION_MARKER_PREFIX &&
key.startsWith(NEXT_INTERCEPTION_MARKER_PREFIX) if (
isNextQueryPrefix ||
if ( isNextInterceptionMarkerPrefix ||
isNextQueryPrefix || (paramKeys || Object.keys(defaultRouteRegex.groups)).includes(key)
isNextInterceptionMarkerPrefix || ) {
(paramKeys || Object.keys(defaultRouteRegex.groups)).includes(key) delete _parsedUrl.query[key]
) {
delete _parsedUrl.query[key]
}
} }
req.url = formatUrl(_parsedUrl)
} }
req.url = formatUrl(_parsedUrl)
} }
export function interpolateDynamicPath( export function interpolateDynamicPath(
...@@ -90,13 +88,10 @@ export function interpolateDynamicPath( ...@@ -90,13 +88,10 @@ export function interpolateDynamicPath(
export function normalizeDynamicRouteParams( export function normalizeDynamicRouteParams(
params: ParsedUrlQuery, params: ParsedUrlQuery,
ignoreOptional?: boolean, defaultRouteRegex: ReturnType<typeof getNamedRouteRegex>,
defaultRouteRegex?: ReturnType<typeof getNamedRouteRegex> | undefined, defaultRouteMatches: ParsedUrlQuery
defaultRouteMatches?: ParsedUrlQuery | undefined
) { ) {
let hasValidParams = true let hasValidParams = true
if (!defaultRouteRegex) return { params, hasValidParams: false }
params = Object.keys(defaultRouteRegex.groups).reduce((prev, key) => { params = Object.keys(defaultRouteRegex.groups).reduce((prev, key) => {
let value: string | string[] | undefined = params[key] let value: string | string[] | undefined = params[key]
...@@ -126,10 +121,7 @@ export function normalizeDynamicRouteParams( ...@@ -126,10 +121,7 @@ export function normalizeDynamicRouteParams(
}) })
: value?.includes(defaultValue as string) : value?.includes(defaultValue as string)
if ( if (isDefaultValue || (typeof value === 'undefined' && !isOptional)) {
isDefaultValue ||
(typeof value === 'undefined' && !(isOptional && ignoreOptional))
) {
hasValidParams = false hasValidParams = false
} }
...@@ -375,28 +367,19 @@ export function getUtils({ ...@@ -375,28 +367,19 @@ export function getUtils({
dynamicRouteMatcher, dynamicRouteMatcher,
defaultRouteMatches, defaultRouteMatches,
getParamsFromRouteMatches, getParamsFromRouteMatches,
normalizeDynamicRouteParams: ( normalizeDynamicRouteParams: (params: ParsedUrlQuery) => {
params: ParsedUrlQuery, if (!defaultRouteRegex || !defaultRouteMatches) {
ignoreOptional?: boolean return { params, hasValidParams: false }
) => }
normalizeDynamicRouteParams(
return normalizeDynamicRouteParams(
params, params,
ignoreOptional,
defaultRouteRegex, defaultRouteRegex,
defaultRouteMatches defaultRouteMatches
), )
normalizeVercelUrl: ( },
req: BaseNextRequest, normalizeVercelUrl: (req: BaseNextRequest, paramKeys: string[]) =>
trustQuery: boolean, normalizeVercelUrl(req, paramKeys, defaultRouteRegex),
paramKeys?: string[]
) =>
normalizeVercelUrl(
req,
trustQuery,
paramKeys,
pageIsDynamic,
defaultRouteRegex
),
interpolateDynamicPath: ( interpolateDynamicPath: (
pathname: string, pathname: string,
params: Record<string, undefined | string | string[]> params: Record<string, undefined | string | string[]>
......
...@@ -173,7 +173,6 @@ export default class NextWebServer extends BaseServer< ...@@ -173,7 +173,6 @@ export default class NextWebServer extends BaseServer<
) as NextParsedUrlQuery ) as NextParsedUrlQuery
const paramsResult = normalizeDynamicRouteParams( const paramsResult = normalizeDynamicRouteParams(
query, query,
false,
routeRegex, routeRegex,
defaultRouteMatches defaultRouteMatches
) )
...@@ -186,13 +185,7 @@ export default class NextWebServer extends BaseServer< ...@@ -186,13 +185,7 @@ export default class NextWebServer extends BaseServer<
normalizedParams, normalizedParams,
routeRegex routeRegex
) )
normalizeVercelUrl( normalizeVercelUrl(req, Object.keys(routeRegex.routeKeys), routeRegex)
req,
true,
Object.keys(routeRegex.routeKeys),
true,
routeRegex
)
} }
} }
......
import { useRouter } from 'next/router'
export const getStaticProps = ({ params }) => {
return {
props: {
hello: 'world',
params: params || null,
random: Math.random(),
},
}
}
export const getStaticPaths = () => {
return {
paths: ['/partial-catch-all/hello.com'],
fallback: true,
}
}
export default function Page(props) {
const router = useRouter()
return (
<>
<p id="catch-all">partial optional catch-all page</p>
<p id="router">{JSON.stringify(router)}</p>
<p id="props">{JSON.stringify(props)}</p>
</>
)
}
...@@ -328,7 +328,7 @@ describe('Required Server Files', () => { ...@@ -328,7 +328,7 @@ describe('Required Server Files', () => {
{ {
headers: { headers: {
'x-matched-path': '/catch-all/[[...rest]]', 'x-matched-path': '/catch-all/[[...rest]]',
'x-now-route-matches': 'nxtPrest=hello&catchAll=hello', 'x-now-route-matches': 'nxtPrest=hello',
}, },
} }
) )
...@@ -342,7 +342,7 @@ describe('Required Server Files', () => { ...@@ -342,7 +342,7 @@ describe('Required Server Files', () => {
const html3 = await renderViaHTTP( const html3 = await renderViaHTTP(
appPort, appPort,
'/catch-all/[[..rest]]', '/catch-all/[[...rest]]',
undefined, undefined,
{ {
headers: { headers: {
...@@ -359,6 +359,98 @@ describe('Required Server Files', () => { ...@@ -359,6 +359,98 @@ describe('Required Server Files', () => {
expect(data3.params).toEqual({ rest: ['hello', 'world'] }) expect(data3.params).toEqual({ rest: ['hello', 'world'] })
expect(isNaN(data3.random)).toBe(false) expect(isNaN(data3.random)).toBe(false)
expect(data3.random).not.toBe(data.random) expect(data3.random).not.toBe(data.random)
const html4 = await renderViaHTTP(
appPort,
'/catch-all/[[...rest]]',
{ nxtPrest: 'frank' },
{
headers: {
'x-matched-path': '/catch-all/[[...rest]]',
},
}
)
const $4 = cheerio.load(html4)
const data4 = JSON.parse($4('#props').text())
expect($4('#catch-all').text()).toBe('optional catch-all page')
expect(data4.params).toEqual({ rest: ['frank'] })
expect(isNaN(data4.random)).toBe(false)
expect(data4.random).not.toBe(data.random)
const html5 = await renderViaHTTP(
appPort,
'/catch-all/[[...rest]]',
{},
{
headers: {
'x-matched-path': '/catch-all/[[...rest]]',
},
}
)
const $5 = cheerio.load(html5)
const data5 = JSON.parse($5('#props').text())
expect($5('#catch-all').text()).toBe('optional catch-all page')
expect(data5.params).toEqual({})
expect(isNaN(data5.random)).toBe(false)
expect(data5.random).not.toBe(data.random)
const html6 = await renderViaHTTP(
appPort,
'/catch-all/[[...rest]]',
{ nxtPrest: 'frank' },
{
headers: {
'x-matched-path': '/catch-all/[[...rest]]',
},
}
)
const $6 = cheerio.load(html6)
const data6 = JSON.parse($6('#props').text())
expect($6('#catch-all').text()).toBe('optional catch-all page')
expect(data6.params).toEqual({ rest: ['frank'] })
expect(isNaN(data6.random)).toBe(false)
expect(data6.random).not.toBe(data.random)
})
describe('partial optional catch-all route', () => {
it.each([
{
path: '/partial-catch-all/hello.com',
query: { nxtPdomain: 'hello.com' },
expected: { domain: 'hello.com' },
},
{
path: '/partial-catch-all/hello.com/hello',
query: { nxtPdomain: 'hello.com', nxtPrest: 'hello' },
expected: { domain: 'hello.com', rest: ['hello'] },
},
{
path: '/partial-catch-all/hello.com/hello/world',
query: { nxtPdomain: 'hello.com', nxtPrest: 'hello/world' },
expected: { domain: 'hello.com', rest: ['hello', 'world'] },
},
])('should render $path', async ({ query, expected }) => {
const html = await renderViaHTTP(
appPort,
'/partial-catch-all/[domain]/[[...rest]]',
query,
{
headers: {
'x-matched-path': '/partial-catch-all/[domain]/[[...rest]]',
},
}
)
const $ = cheerio.load(html)
const data = JSON.parse($('#props').text())
expect($('#catch-all').text()).toBe('partial optional catch-all page')
expect(data.params).toEqual(expected)
expect(data.hello).toBe('world')
})
}) })
it('should return data correctly with x-matched-path for optional catch-all route', async () => { it('should return data correctly with x-matched-path for optional catch-all route', async () => {
......
...@@ -14483,6 +14483,9 @@ ...@@ -14483,6 +14483,9 @@
"Required Server Files production mode should render dynamic SSR page correctly", "Required Server Files production mode should render dynamic SSR page correctly",
"Required Server Files production mode should render dynamic SSR page correctly with x-matched-path", "Required Server Files production mode should render dynamic SSR page correctly with x-matched-path",
"Required Server Files production mode should render fallback optional catch-all route correctly with x-matched-path and routes-matches", "Required Server Files production mode should render fallback optional catch-all route correctly with x-matched-path and routes-matches",
"Required Server Files production mode partial optional catch-all route should render /partial-catch-all/hello.com",
"Required Server Files production mode partial optional catch-all route should render /partial-catch-all/hello.com/hello",
"Required Server Files production mode partial optional catch-all route should render /partial-catch-all/hello.com/hello/world",
"Required Server Files production mode should render fallback page correctly", "Required Server Files production mode should render fallback page correctly",
"Required Server Files production mode should render fallback page correctly with x-matched-path and routes-matches", "Required Server Files production mode should render fallback page correctly with x-matched-path and routes-matches",
"Required Server Files production mode should return data correctly with x-matched-path", "Required Server Files production mode should return data correctly with x-matched-path",
...@@ -18641,6 +18641,9 @@ ...@@ -18641,6 +18641,9 @@
"Required Server Files production mode should render dynamic SSR page correctly", "Required Server Files production mode should render dynamic SSR page correctly",
"Required Server Files production mode should render dynamic SSR page correctly with x-matched-path", "Required Server Files production mode should render dynamic SSR page correctly with x-matched-path",
"Required Server Files production mode should render fallback optional catch-all route correctly with x-matched-path and routes-matches", "Required Server Files production mode should render fallback optional catch-all route correctly with x-matched-path and routes-matches",
"Required Server Files production mode partial optional catch-all route should render /partial-catch-all/hello.com",
"Required Server Files production mode partial optional catch-all route should render /partial-catch-all/hello.com/hello",
"Required Server Files production mode partial optional catch-all route should render /partial-catch-all/hello.com/hello/world",
"Required Server Files production mode should render fallback page correctly", "Required Server Files production mode should render fallback page correctly",
"Required Server Files production mode should render fallback page correctly with x-matched-path and routes-matches", "Required Server Files production mode should render fallback page correctly with x-matched-path and routes-matches",
"Required Server Files production mode should return data correctly with x-matched-path", "Required Server Files production mode should return data correctly with x-matched-path",
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