Unverified Commit 8514cd64 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

Revert "fix: handle optional catchalls correctly" (#75442)

We noticed a routing regression, so reverting while we investigate. 

Reverts vercel/next.js#75377
parent c0d23aee
...@@ -1237,13 +1237,16 @@ export default abstract class Server< ...@@ -1237,13 +1237,16 @@ export default abstract class Server<
typeof routeMatchesHeader === 'string' && typeof routeMatchesHeader === 'string' &&
routeMatchesHeader && routeMatchesHeader &&
isDynamicRoute(matchedPath) && isDynamicRoute(matchedPath) &&
(Object.keys(params).length === 0 || !paramsResult.hasValidParams) !paramsResult.hasValidParams
) { ) {
const routeMatches = const routeMatches =
utils.getParamsFromRouteMatches(routeMatchesHeader) utils.getParamsFromRouteMatches(routeMatchesHeader)
if (routeMatches) { if (routeMatches) {
paramsResult = utils.normalizeDynamicRouteParams(routeMatches) paramsResult = utils.normalizeDynamicRouteParams(
routeMatches,
true
)
if (paramsResult.hasValidParams) { if (paramsResult.hasValidParams) {
params = paramsResult.params params = paramsResult.params
...@@ -1256,7 +1259,8 @@ export default abstract class Server< ...@@ -1256,7 +1259,8 @@ export default abstract class Server<
utils.defaultRouteMatches && utils.defaultRouteMatches &&
normalizedUrlPath === srcPathname && normalizedUrlPath === srcPathname &&
!paramsResult.hasValidParams && !paramsResult.hasValidParams &&
!utils.normalizeDynamicRouteParams({ ...params }).hasValidParams !utils.normalizeDynamicRouteParams({ ...params }, true)
.hasValidParams
) { ) {
params = utils.defaultRouteMatches params = utils.defaultRouteMatches
...@@ -1272,7 +1276,7 @@ export default abstract class Server< ...@@ -1272,7 +1276,7 @@ export default abstract class Server<
} }
if (pageIsDynamic || didRewrite) { if (pageIsDynamic || didRewrite) {
utils.normalizeVercelUrl(req, [ utils.normalizeVercelUrl(req, true, [
...rewriteParamKeys, ...rewriteParamKeys,
...Object.keys(utils.defaultRouteRegex?.groups || {}), ...Object.keys(utils.defaultRouteRegex?.groups || {}),
]) ])
......
...@@ -24,34 +24,36 @@ import { normalizeNextQueryParam } from './web/utils' ...@@ -24,34 +24,36 @@ import { normalizeNextQueryParam } from './web/utils'
export function normalizeVercelUrl( export function normalizeVercelUrl(
req: BaseNextRequest, req: BaseNextRequest,
paramKeys: string[], trustQuery: boolean,
defaultRouteRegex: ReturnType<typeof getNamedRouteRegex> | undefined paramKeys?: string[],
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
const _parsedUrl = parseUrl(req.url!, true) if (pageIsDynamic && trustQuery && defaultRouteRegex) {
delete (_parsedUrl as any).search const _parsedUrl = parseUrl(req.url!, true)
delete (_parsedUrl as any).search
for (const key of Object.keys(_parsedUrl.query)) {
const isNextQueryPrefix = for (const key of Object.keys(_parsedUrl.query)) {
key !== NEXT_QUERY_PARAM_PREFIX && key.startsWith(NEXT_QUERY_PARAM_PREFIX) const isNextQueryPrefix =
key !== NEXT_QUERY_PARAM_PREFIX &&
const isNextInterceptionMarkerPrefix = key.startsWith(NEXT_QUERY_PARAM_PREFIX)
key !== NEXT_INTERCEPTION_MARKER_PREFIX &&
key.startsWith(NEXT_INTERCEPTION_MARKER_PREFIX) const isNextInterceptionMarkerPrefix =
key !== NEXT_INTERCEPTION_MARKER_PREFIX &&
if ( key.startsWith(NEXT_INTERCEPTION_MARKER_PREFIX)
isNextQueryPrefix ||
isNextInterceptionMarkerPrefix || if (
(paramKeys || Object.keys(defaultRouteRegex.groups)).includes(key) isNextQueryPrefix ||
) { isNextInterceptionMarkerPrefix ||
delete _parsedUrl.query[key] (paramKeys || Object.keys(defaultRouteRegex.groups)).includes(key)
) {
delete _parsedUrl.query[key]
}
} }
req.url = formatUrl(_parsedUrl)
} }
req.url = formatUrl(_parsedUrl)
} }
export function interpolateDynamicPath( export function interpolateDynamicPath(
...@@ -88,10 +90,13 @@ export function interpolateDynamicPath( ...@@ -88,10 +90,13 @@ export function interpolateDynamicPath(
export function normalizeDynamicRouteParams( export function normalizeDynamicRouteParams(
params: ParsedUrlQuery, params: ParsedUrlQuery,
defaultRouteRegex: ReturnType<typeof getNamedRouteRegex>, ignoreOptional?: boolean,
defaultRouteMatches: ParsedUrlQuery defaultRouteRegex?: ReturnType<typeof getNamedRouteRegex> | undefined,
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]
...@@ -121,7 +126,10 @@ export function normalizeDynamicRouteParams( ...@@ -121,7 +126,10 @@ export function normalizeDynamicRouteParams(
}) })
: value?.includes(defaultValue as string) : value?.includes(defaultValue as string)
if (isDefaultValue || (typeof value === 'undefined' && !isOptional)) { if (
isDefaultValue ||
(typeof value === 'undefined' && !(isOptional && ignoreOptional))
) {
hasValidParams = false hasValidParams = false
} }
...@@ -367,19 +375,28 @@ export function getUtils({ ...@@ -367,19 +375,28 @@ export function getUtils({
dynamicRouteMatcher, dynamicRouteMatcher,
defaultRouteMatches, defaultRouteMatches,
getParamsFromRouteMatches, getParamsFromRouteMatches,
normalizeDynamicRouteParams: (params: ParsedUrlQuery) => { normalizeDynamicRouteParams: (
if (!defaultRouteRegex || !defaultRouteMatches) { params: ParsedUrlQuery,
return { params, hasValidParams: false } ignoreOptional?: boolean
} ) =>
normalizeDynamicRouteParams(
return normalizeDynamicRouteParams(
params, params,
ignoreOptional,
defaultRouteRegex, defaultRouteRegex,
defaultRouteMatches defaultRouteMatches
) ),
}, normalizeVercelUrl: (
normalizeVercelUrl: (req: BaseNextRequest, paramKeys: string[]) => req: BaseNextRequest,
normalizeVercelUrl(req, paramKeys, defaultRouteRegex), trustQuery: boolean,
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,6 +173,7 @@ export default class NextWebServer extends BaseServer< ...@@ -173,6 +173,7 @@ export default class NextWebServer extends BaseServer<
) as NextParsedUrlQuery ) as NextParsedUrlQuery
const paramsResult = normalizeDynamicRouteParams( const paramsResult = normalizeDynamicRouteParams(
query, query,
false,
routeRegex, routeRegex,
defaultRouteMatches defaultRouteMatches
) )
...@@ -185,7 +186,13 @@ export default class NextWebServer extends BaseServer< ...@@ -185,7 +186,13 @@ export default class NextWebServer extends BaseServer<
normalizedParams, normalizedParams,
routeRegex routeRegex
) )
normalizeVercelUrl(req, Object.keys(routeRegex.routeKeys), routeRegex) normalizeVercelUrl(
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', 'x-now-route-matches': 'nxtPrest=hello&catchAll=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,98 +359,6 @@ describe('Required Server Files', () => { ...@@ -359,98 +359,6 @@ 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,9 +14483,6 @@ ...@@ -14483,9 +14483,6 @@
"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,9 +18641,6 @@ ...@@ -18641,9 +18641,6 @@
"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