Unverified Commit 6784575f authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

fix: handle optional catchall parameters properly when deployed (#74562)

Previously, we had code responsible for parsing and handling the
`x-now-route-matches` header (sent by Vercel) that included the route
matches used for parameter parsing that only read from the named
parameters _if they were all present_. This doesn't apply to routes with
optional parameters (such as `[[...rest]]`), so it wasn't utilizing that
matching mechanism. It previously fell back onto the second stage of
parsing that utilized numeric based group matching, but this was
recently changed on Vercel, so the fallback no longer applies for
Next.js applications that are running on 15+.
parent e4c07940
...@@ -1229,34 +1229,25 @@ export default abstract class Server< ...@@ -1229,34 +1229,25 @@ export default abstract class Server<
params = paramsResult.params params = paramsResult.params
} }
const routeMatchesHeader = req.headers['x-now-route-matches']
if ( if (
req.headers['x-now-route-matches'] && typeof routeMatchesHeader === 'string' &&
routeMatchesHeader &&
isDynamicRoute(matchedPath) && isDynamicRoute(matchedPath) &&
!paramsResult.hasValidParams !paramsResult.hasValidParams
) { ) {
const opts: Record<string, string> = {} const routeMatches =
const routeParams = utils.getParamsFromRouteMatches( utils.getParamsFromRouteMatches(routeMatchesHeader)
req,
opts,
getRequestMeta(req, 'locale')
)
// If this returns a locale, it means that the locale was detected if (routeMatches) {
// from the pathname. paramsResult = utils.normalizeDynamicRouteParams(
if (opts.locale) { routeMatches,
addRequestMeta(req, 'locale', opts.locale) true
)
// As the locale was parsed from the pathname, we should mark if (paramsResult.hasValidParams) {
// that the locale was not inferred as the default. params = paramsResult.params
removeRequestMeta(req, 'localeInferredFromDefault') }
}
paramsResult = utils.normalizeDynamicRouteParams(
routeParams,
true
)
if (paramsResult.hasValidParams) {
params = paramsResult.params
} }
} }
......
...@@ -350,10 +350,10 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface { ...@@ -350,10 +350,10 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
parsedPageBundleUrl: UrlObject parsedPageBundleUrl: UrlObject
): Promise<{ finished?: true }> => { ): Promise<{ finished?: true }> => {
const { pathname } = parsedPageBundleUrl const { pathname } = parsedPageBundleUrl
if (!pathname) return {}
const params = matchNextPageBundleRequest(pathname) const params = matchNextPageBundleRequest(pathname)
if (!params) { if (!params) return {}
return {}
}
let decodedPagePath: string let decodedPagePath: string
......
import { getUtils } from './server-utils'
describe('getParamsFromRouteMatches', () => {
it('should return nothing for a non-dynamic route', () => {
const { getParamsFromRouteMatches } = getUtils({
page: '/',
basePath: '',
rewrites: {},
i18n: undefined,
pageIsDynamic: false,
caseSensitive: false,
})
const params = getParamsFromRouteMatches('nxtPslug=hello-world')
expect(params).toEqual(null)
})
it('should return the params from the route matches', () => {
const { getParamsFromRouteMatches } = getUtils({
page: '/[slug]',
basePath: '',
rewrites: {},
i18n: undefined,
pageIsDynamic: true,
caseSensitive: false,
})
const params = getParamsFromRouteMatches('nxtPslug=hello-world')
expect(params).toEqual({ slug: 'hello-world' })
})
it('should handle optional params', () => {
const { getParamsFromRouteMatches } = getUtils({
page: '/[slug]/[[...optional]]',
basePath: '',
rewrites: {},
i18n: undefined,
pageIsDynamic: true,
caseSensitive: false,
})
// Missing optional param
let params = getParamsFromRouteMatches('nxtPslug=hello-world')
expect(params).toEqual({ slug: 'hello-world' })
// Providing optional param
params = getParamsFromRouteMatches(
'nxtPslug=hello-world&nxtPoptional=im-optional'
)
expect(params).toEqual({ slug: 'hello-world', optional: ['im-optional'] })
})
it('should handle rest params', () => {
const { getParamsFromRouteMatches } = getUtils({
page: '/[slug]/[...rest]',
basePath: '',
rewrites: {},
i18n: undefined,
pageIsDynamic: true,
caseSensitive: false,
})
// Missing rest param
let params = getParamsFromRouteMatches('nxtPslug=hello-world')
expect(params).toEqual(null)
// Providing rest param
params = getParamsFromRouteMatches(
'nxtPslug=hello-world&nxtPrest=im-the/rest'
)
expect(params).toEqual({ slug: 'hello-world', rest: ['im-the', 'rest'] })
})
})
...@@ -20,6 +20,7 @@ import { ...@@ -20,6 +20,7 @@ import {
NEXT_INTERCEPTION_MARKER_PREFIX, NEXT_INTERCEPTION_MARKER_PREFIX,
NEXT_QUERY_PARAM_PREFIX, NEXT_QUERY_PARAM_PREFIX,
} from '../lib/constants' } from '../lib/constants'
import { normalizeNextQueryParam } from './web/utils'
export function normalizeVercelUrl( export function normalizeVercelUrl(
req: BaseNextRequest, req: BaseNextRequest,
...@@ -221,6 +222,9 @@ export function getUtils({ ...@@ -221,6 +222,9 @@ export function getUtils({
sensitive: !!caseSensitive, sensitive: !!caseSensitive,
} }
) )
if (!parsedUrl.pathname) return false
let params = matcher(parsedUrl.pathname) let params = matcher(parsedUrl.pathname)
if ((rewrite.has || rewrite.missing) && params) { if ((rewrite.has || rewrite.missing) && params) {
...@@ -258,20 +262,17 @@ export function getUtils({ ...@@ -258,20 +262,17 @@ export function getUtils({
Object.assign(parsedUrl, parsedDestination) Object.assign(parsedUrl, parsedDestination)
fsPathname = parsedUrl.pathname fsPathname = parsedUrl.pathname
if (!fsPathname) return false
if (basePath) { if (basePath) {
fsPathname = fsPathname = fsPathname.replace(new RegExp(`^${basePath}`), '') || '/'
fsPathname!.replace(new RegExp(`^${basePath}`), '') || '/'
} }
if (i18n) { if (i18n) {
const destLocalePathResult = normalizeLocalePath( const result = normalizeLocalePath(fsPathname, i18n.locales)
fsPathname!, fsPathname = result.pathname
i18n.locales
)
fsPathname = destLocalePathResult.pathname
parsedUrl.query.nextInternalLocale = parsedUrl.query.nextInternalLocale =
destLocalePathResult.detectedLocale || params.nextInternalLocale result.detectedLocale || params.nextInternalLocale
} }
if (fsPathname === page) { if (fsPathname === page) {
...@@ -314,102 +315,56 @@ export function getUtils({ ...@@ -314,102 +315,56 @@ export function getUtils({
return rewriteParams return rewriteParams
} }
function getParamsFromRouteMatches( function getParamsFromRouteMatches(routeMatchesHeader: string) {
req: BaseNextRequest, // If we don't have a default route regex, we can't get params from route
renderOpts?: any, // matches
detectedLocale?: string if (!defaultRouteRegex) return null
) {
return getRouteMatcher( const { groups, routeKeys } = defaultRouteRegex
(function () {
const { groups, routeKeys } = defaultRouteRegex! const matcher = getRouteMatcher({
re: {
return { // Simulate a RegExp match from the \`req.url\` input
re: { exec: (str: string) => {
// Simulate a RegExp match from the \`req.url\` input // Normalize all the prefixed query params.
exec: (str: string) => { const obj: Record<string, string> = Object.fromEntries(
const obj = Object.fromEntries(new URLSearchParams(str)) new URLSearchParams(str)
const matchesHasLocale = )
i18n && detectedLocale && obj['1'] === detectedLocale for (const [key, value] of Object.entries(obj)) {
const normalizedKey = normalizeNextQueryParam(key)
for (const key of Object.keys(obj)) { if (!normalizedKey) continue
const value = obj[key]
obj[normalizedKey] = value
if ( delete obj[key]
key !== NEXT_QUERY_PARAM_PREFIX && }
key.startsWith(NEXT_QUERY_PARAM_PREFIX)
) { // Use all the named route keys.
const normalizedKey = key.substring( const result = {} as RegExpExecArray
NEXT_QUERY_PARAM_PREFIX.length for (const keyName of Object.keys(routeKeys)) {
) const paramName = routeKeys[keyName]
obj[normalizedKey] = value
delete obj[key] // If this param name is not a valid parameter name, then skip it.
} if (!paramName) continue
}
const group = groups[paramName]
// favor named matches if available const value = obj[keyName]
const routeKeyNames = Object.keys(routeKeys || {})
const filterLocaleItem = (val: string | string[] | undefined) => { // When we're missing a required param, we can't match the route.
if (i18n) { if (!group.optional && !value) return null
// locale items can be included in route-matches
// for fallback SSG pages so ensure they are result[group.pos] = value
// filtered }
const isCatchAll = Array.isArray(val)
const _val = isCatchAll ? val[0] : val return result
},
if ( },
typeof _val === 'string' && groups,
i18n.locales.some((item) => { })
if (item.toLowerCase() === _val.toLowerCase()) {
detectedLocale = item const routeMatches = matcher(routeMatchesHeader)
renderOpts.locale = detectedLocale if (!routeMatches) return null
return true
} return routeMatches
return false
})
) {
// remove the locale item from the match
if (isCatchAll) {
;(val as string[]).splice(0, 1)
}
// the value is only a locale item and
// shouldn't be added
return isCatchAll ? val.length === 0 : true
}
}
return false
}
if (routeKeyNames.every((name) => obj[name])) {
return routeKeyNames.reduce((prev, keyName) => {
const paramName = routeKeys?.[keyName]
if (paramName && !filterLocaleItem(obj[keyName])) {
prev[groups[paramName].pos] = obj[keyName]
}
return prev
}, {} as any)
}
return Object.keys(obj).reduce((prev, key) => {
if (!filterLocaleItem(obj[key])) {
let normalizedKey = key
if (matchesHasLocale) {
normalizedKey = parseInt(key, 10) - 1 + ''
}
return Object.assign(prev, {
[normalizedKey]: obj[key],
})
}
return prev
}, {})
},
},
groups,
}
})() as any
)(req.headers['x-now-route-matches'] as string) as ParsedUrlQuery
} }
return { return {
......
...@@ -159,8 +159,7 @@ export function normalizeNextQueryParam(key: string): null | string { ...@@ -159,8 +159,7 @@ export function normalizeNextQueryParam(key: string): null | string {
const prefixes = [NEXT_QUERY_PARAM_PREFIX, NEXT_INTERCEPTION_MARKER_PREFIX] const prefixes = [NEXT_QUERY_PARAM_PREFIX, NEXT_INTERCEPTION_MARKER_PREFIX]
for (const prefix of prefixes) { for (const prefix of prefixes) {
if (key !== prefix && key.startsWith(prefix)) { if (key !== prefix && key.startsWith(prefix)) {
const normalizedKey = key.substring(prefix.length) return key.substring(prefix.length)
return normalizedKey
} }
} }
return null return null
......
...@@ -26,7 +26,7 @@ interface Options { ...@@ -26,7 +26,7 @@ interface Options {
} }
export type PatchMatcher = ( export type PatchMatcher = (
pathname?: string | null, pathname: string,
params?: Record<string, any> params?: Record<string, any>
) => Record<string, any> | false ) => Record<string, any> | false
......
import type { RouteRegex } from './route-regex' import type { Group } from './route-regex'
import { DecodeError } from '../../utils' import { DecodeError } from '../../utils'
import type { Params } from '../../../../server/request/params' import type { Params } from '../../../../server/request/params'
export interface RouteMatchFn { export interface RouteMatchFn {
(pathname: string | null | undefined): false | Params (pathname: string): false | Params
} }
export function getRouteMatcher({ re, groups }: RouteRegex): RouteMatchFn { type RouteMatcherOptions = {
return (pathname: string | null | undefined) => { // We only use the exec method of the RegExp object. This helps us avoid using
const routeMatch = re.exec(pathname!) // type assertions that the passed in properties are of the correct type.
if (!routeMatch) { re: Pick<RegExp, 'exec'>
return false groups: Record<string, Group>
} }
export function getRouteMatcher({
re,
groups,
}: RouteMatcherOptions): RouteMatchFn {
return (pathname: string) => {
const routeMatch = re.exec(pathname)
if (!routeMatch) return false
const decode = (param: string) => { const decode = (param: string) => {
try { try {
return decodeURIComponent(param) return decodeURIComponent(param)
} catch (_) { } catch {
throw new DecodeError('failed to decode param') throw new DecodeError('failed to decode param')
} }
} }
const params: { [paramName: string]: string | string[] } = {}
Object.keys(groups).forEach((slugName: string) => { const params: Params = {}
const g = groups[slugName] for (const [key, group] of Object.entries(groups)) {
const m = routeMatch[g.pos] const match = routeMatch[group.pos]
if (m !== undefined) { if (match !== undefined) {
params[slugName] = ~m.indexOf('/') if (group.repeat) {
? m.split('/').map((entry) => decode(entry)) params[key] = match.split('/').map((entry) => decode(entry))
: g.repeat } else {
? [decode(m)] params[key] = decode(match)
: decode(m) }
} }
}) }
return params return params
} }
} }
import { nextTestSetup } from 'e2e-utils'
describe('app-catch-all-optional', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should handle optional catchall', async () => {
let $ = await next.render$('/en/flags/the/rest')
expect($('body [data-lang]').text()).toBe('en')
expect($('body [data-flags]').text()).toBe('flags')
expect($('body [data-rest]').text()).toBe('the/rest')
})
it('should handle optional catchall with no params', async () => {
let $ = await next.render$('/en/flags')
expect($('body [data-lang]').text()).toBe('en')
expect($('body [data-flags]').text()).toBe('flags')
expect($('body [data-rest]').text()).toBe('')
})
})
export async function generateStaticParams() {
return []
}
export default async function Page(props) {
const params = await props.params
return (
<div>
<div data-lang={params.lang}>{params.lang}</div>
<div data-flags={params.flags}>{params.flags}</div>
<div data-rest={params.rest?.join('/')}>{params.rest?.join('/')}</div>
</div>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>hello world</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
...@@ -236,7 +236,7 @@ describe('Required Server Files', () => { ...@@ -236,7 +236,7 @@ describe('Required Server Files', () => {
{ {
headers: { headers: {
'x-matched-path': '/fallback/first', 'x-matched-path': '/fallback/first',
'x-now-route-matches': '1=first', 'x-now-route-matches': 'nxtPslug=first',
}, },
} }
) )
...@@ -254,7 +254,7 @@ describe('Required Server Files', () => { ...@@ -254,7 +254,7 @@ describe('Required Server Files', () => {
{ {
headers: { headers: {
'x-matched-path': '/fallback/[slug]', 'x-matched-path': '/fallback/[slug]',
'x-now-route-matches': '1=second', 'x-now-route-matches': 'nxtPslug=second',
}, },
} }
) )
...@@ -291,7 +291,7 @@ describe('Required Server Files', () => { ...@@ -291,7 +291,7 @@ describe('Required Server Files', () => {
{ {
headers: { headers: {
'x-matched-path': `/_next/data/${buildId}/fallback/[slug].json`, 'x-matched-path': `/_next/data/${buildId}/fallback/[slug].json`,
'x-now-route-matches': '1=second', 'x-now-route-matches': 'nxtPslug=second',
}, },
} }
) )
...@@ -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': '1=hello&catchAll=hello', 'x-now-route-matches': 'nxtPrest=hello&catchAll=hello',
}, },
} }
) )
...@@ -347,7 +347,8 @@ describe('Required Server Files', () => { ...@@ -347,7 +347,8 @@ describe('Required Server Files', () => {
{ {
headers: { headers: {
'x-matched-path': '/catch-all/[[...rest]]', 'x-matched-path': '/catch-all/[[...rest]]',
'x-now-route-matches': '1=hello/world&catchAll=hello/world', 'x-now-route-matches':
'nxtPrest=hello/world&catchAll=hello/world',
}, },
} }
) )
...@@ -384,7 +385,7 @@ describe('Required Server Files', () => { ...@@ -384,7 +385,7 @@ describe('Required Server Files', () => {
{ {
headers: { headers: {
'x-matched-path': `/_next/data/${buildId}/catch-all/[[...rest]].json`, 'x-matched-path': `/_next/data/${buildId}/catch-all/[[...rest]].json`,
'x-now-route-matches': '1=hello&rest=hello', 'x-now-route-matches': 'nxtPrest=hello&rest=hello',
}, },
} }
) )
...@@ -401,7 +402,7 @@ describe('Required Server Files', () => { ...@@ -401,7 +402,7 @@ describe('Required Server Files', () => {
{ {
headers: { headers: {
'x-matched-path': `/_next/data/${buildId}/catch-all/[[...rest]].json`, 'x-matched-path': `/_next/data/${buildId}/catch-all/[[...rest]].json`,
'x-now-route-matches': '1=hello/world&rest=hello/world', 'x-now-route-matches': 'nxtPrest=hello/world&rest=hello/world',
}, },
} }
) )
......
...@@ -1522,3 +1522,26 @@ export async function toggleCollapseCallStackFrames(browser: BrowserInterface) { ...@@ -1522,3 +1522,26 @@ export async function toggleCollapseCallStackFrames(browser: BrowserInterface) {
expect(currExpanded).not.toBe(lastExpanded) expect(currExpanded).not.toBe(lastExpanded)
}) })
} }
/**
* Encodes the params into a URLSearchParams object using the format that the
* now builder uses for route matches (adding the `nxtP` prefix to the keys).
*
* @param params - The params to encode.
* @param extraQueryParams - The extra query params to encode (without the `nxtP` prefix).
* @returns The encoded URLSearchParams object.
*/
export function createNowRouteMatches(
params: Record<string, string>,
extraQueryParams: Record<string, string> = {}
): URLSearchParams {
const urlSearchParams = new URLSearchParams()
for (const [key, value] of Object.entries(params)) {
urlSearchParams.append(`nxtP${key}`, value)
}
for (const [key, value] of Object.entries(extraQueryParams)) {
urlSearchParams.append(key, value)
}
return urlSearchParams
}
export async function generateStaticParams() {
return []
}
export default async function Page(props) {
const params = await props.params
return (
<div>
<div data-lang={params.lang}>{params.lang}</div>
<div data-flags={params.flags}>{params.flags}</div>
<div data-slug={params.slug}>{params.slug}</div>
</div>
)
}
...@@ -5,6 +5,7 @@ import cheerio from 'cheerio' ...@@ -5,6 +5,7 @@ import cheerio from 'cheerio'
import { createNext, FileRef } from 'e2e-utils' import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils' import { NextInstance } from 'e2e-utils'
import { import {
createNowRouteMatches,
fetchViaHTTP, fetchViaHTTP,
findPort, findPort,
initNextServerScript, initNextServerScript,
...@@ -107,7 +108,9 @@ describe('required server files app router', () => { ...@@ -107,7 +108,9 @@ describe('required server files app router', () => {
const res = await fetchViaHTTP(appPort, '/api/test/123', undefined, { const res = await fetchViaHTTP(appPort, '/api/test/123', undefined, {
headers: { headers: {
'x-matched-path': '/api/test/[slug]', 'x-matched-path': '/api/test/[slug]',
'x-now-route-matches': '1=123&nxtPslug=123', 'x-now-route-matches': createNowRouteMatches({
slug: '123',
}).toString(),
}, },
}) })
expect(res.status).toBe(200) expect(res.status).toBe(200)
...@@ -116,11 +119,59 @@ describe('required server files app router', () => { ...@@ -116,11 +119,59 @@ describe('required server files app router', () => {
) )
}) })
it('should handle optional catchall', async () => {
let res = await fetchViaHTTP(
appPort,
'/optional-catchall/[lang]/[flags]/[[...slug]]',
undefined,
{
headers: {
'x-matched-path': '/optional-catchall/[lang]/[flags]/[[...slug]]',
'x-now-route-matches': createNowRouteMatches({
lang: 'en',
flags: 'flags',
slug: 'slug',
}).toString(),
},
}
)
expect(res.status).toBe(200)
let html = await res.text()
let $ = cheerio.load(html)
expect($('body [data-lang]').text()).toBe('en')
expect($('body [data-slug]').text()).toBe('slug')
res = await fetchViaHTTP(
appPort,
'/optional-catchall/[lang]/[flags]/[[...slug]]',
undefined,
{
headers: {
'x-matched-path': '/optional-catchall/[lang]/[flags]/[[...slug]]',
'x-now-route-matches': createNowRouteMatches({
lang: 'en',
flags: 'flags',
}).toString(),
},
}
)
expect(res.status).toBe(200)
html = await res.text()
$ = cheerio.load(html)
expect($('body [data-lang]').text()).toBe('en')
expect($('body [data-flags]').text()).toBe('flags')
expect($('body [data-slug]').text()).toBe('')
})
it('should send the right cache headers for an app page', async () => { it('should send the right cache headers for an app page', async () => {
const res = await fetchViaHTTP(appPort, '/test/123', undefined, { const res = await fetchViaHTTP(appPort, '/test/123', undefined, {
headers: { headers: {
'x-matched-path': '/test/[slug]', 'x-matched-path': '/test/[slug]',
'x-now-route-matches': '1=123&nxtPslug=123', 'x-now-route-matches': createNowRouteMatches({
slug: '123',
}).toString(),
}, },
}) })
expect(res.status).toBe(200) expect(res.status).toBe(200)
...@@ -164,7 +215,9 @@ describe('required server files app router', () => { ...@@ -164,7 +215,9 @@ describe('required server files app router', () => {
headers: { headers: {
'user-agent': 'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'x-now-route-matches': '1=second&nxtPslug=new', 'x-now-route-matches': createNowRouteMatches({
slug: 'new',
}).toString(),
'x-matched-path': '/isr/[slug]', 'x-matched-path': '/isr/[slug]',
}, },
}) })
...@@ -179,7 +232,9 @@ describe('required server files app router', () => { ...@@ -179,7 +232,9 @@ describe('required server files app router', () => {
headers: { headers: {
'user-agent': 'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'x-now-route-matches': '1=second&nxtPslug=new', 'x-now-route-matches': createNowRouteMatches({
slug: 'new',
}).toString(),
'x-matched-path': '/isr/[slug]', 'x-matched-path': '/isr/[slug]',
}, },
}) })
......
...@@ -6,6 +6,7 @@ import { createNext, FileRef } from 'e2e-utils' ...@@ -6,6 +6,7 @@ import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils' import { NextInstance } from 'e2e-utils'
import { import {
check, check,
createNowRouteMatches,
fetchViaHTTP, fetchViaHTTP,
findPort, findPort,
initNextServerScript, initNextServerScript,
...@@ -373,7 +374,9 @@ describe('required server files i18n', () => { ...@@ -373,7 +374,9 @@ describe('required server files i18n', () => {
const html = await renderViaHTTP(appPort, '/fallback/first', undefined, { const html = await renderViaHTTP(appPort, '/fallback/first', undefined, {
headers: { headers: {
'x-matched-path': '/fallback/first', 'x-matched-path': '/fallback/first',
'x-now-route-matches': '1=first', 'x-now-route-matches': createNowRouteMatches({
slug: 'first',
}).toString(),
}, },
}) })
const $ = cheerio.load(html) const $ = cheerio.load(html)
...@@ -386,7 +389,9 @@ describe('required server files i18n', () => { ...@@ -386,7 +389,9 @@ describe('required server files i18n', () => {
const html2 = await renderViaHTTP(appPort, `/fallback/[slug]`, undefined, { const html2 = await renderViaHTTP(appPort, `/fallback/[slug]`, undefined, {
headers: { headers: {
'x-matched-path': '/fallback/[slug]', 'x-matched-path': '/fallback/[slug]',
'x-now-route-matches': '1=second', 'x-now-route-matches': createNowRouteMatches({
slug: 'second',
}).toString(),
}, },
}) })
const $2 = cheerio.load(html2) const $2 = cheerio.load(html2)
...@@ -401,7 +406,9 @@ describe('required server files i18n', () => { ...@@ -401,7 +406,9 @@ describe('required server files i18n', () => {
it('should return data correctly with x-matched-path', async () => { it('should return data correctly with x-matched-path', async () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
appPort, appPort,
`/_next/data/${next.buildId}/en/dynamic/first.json?nxtPslug=first`, `/_next/data/${next.buildId}/en/dynamic/first.json?${createNowRouteMatches(
{ slug: 'first' }
).toString()}`,
undefined, undefined,
{ {
headers: { headers: {
...@@ -422,7 +429,9 @@ describe('required server files i18n', () => { ...@@ -422,7 +429,9 @@ describe('required server files i18n', () => {
{ {
headers: { headers: {
'x-matched-path': `/_next/data/${next.buildId}/en/fallback/[slug].json`, 'x-matched-path': `/_next/data/${next.buildId}/en/fallback/[slug].json`,
'x-now-route-matches': '1=second', 'x-now-route-matches': createNowRouteMatches({
slug: 'second',
}).toString(),
}, },
} }
) )
...@@ -459,7 +468,9 @@ describe('required server files i18n', () => { ...@@ -459,7 +468,9 @@ describe('required server files i18n', () => {
{ {
headers: { headers: {
'x-matched-path': '/catch-all/[[...rest]]', 'x-matched-path': '/catch-all/[[...rest]]',
'x-now-route-matches': '1=hello&nxtPcatchAll=hello', 'x-now-route-matches': createNowRouteMatches({
rest: 'hello',
}).toString(),
}, },
} }
) )
...@@ -478,7 +489,9 @@ describe('required server files i18n', () => { ...@@ -478,7 +489,9 @@ describe('required server files i18n', () => {
{ {
headers: { headers: {
'x-matched-path': '/catch-all/[[...rest]]', 'x-matched-path': '/catch-all/[[...rest]]',
'x-now-route-matches': '1=hello/world&nxtPcatchAll=hello/world', 'x-now-route-matches': createNowRouteMatches({
rest: 'hello/world',
}).toString(),
}, },
} }
) )
...@@ -515,7 +528,9 @@ describe('required server files i18n', () => { ...@@ -515,7 +528,9 @@ describe('required server files i18n', () => {
{ {
headers: { headers: {
'x-matched-path': `/_next/data/${next.buildId}/en/catch-all/[[...rest]].json`, 'x-matched-path': `/_next/data/${next.buildId}/en/catch-all/[[...rest]].json`,
'x-now-route-matches': '1=hello&nxtPrest=hello', 'x-now-route-matches': createNowRouteMatches({
rest: 'hello',
}).toString(),
}, },
} }
) )
...@@ -532,7 +547,9 @@ describe('required server files i18n', () => { ...@@ -532,7 +547,9 @@ describe('required server files i18n', () => {
{ {
headers: { headers: {
'x-matched-path': `/_next/data/${next.buildId}/en/catch-all/[[...rest]].json`, 'x-matched-path': `/_next/data/${next.buildId}/en/catch-all/[[...rest]].json`,
'x-now-route-matches': '1=hello/world&nxtPrest=hello/world', 'x-now-route-matches': createNowRouteMatches({
rest: 'hello/world',
}).toString(),
}, },
} }
) )
...@@ -585,7 +602,11 @@ describe('required server files i18n', () => { ...@@ -585,7 +602,11 @@ describe('required server files i18n', () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
appPort, appPort,
'/to-dynamic/%c0.%c0.', '/to-dynamic/%c0.%c0.',
'?path=%c0.%c0.', Object.fromEntries(
createNowRouteMatches({
path: '%c0.%c0.',
})
),
{ {
headers: { headers: {
'x-matched-path': '/dynamic/[slug]', 'x-matched-path': '/dynamic/[slug]',
...@@ -654,7 +675,16 @@ describe('required server files i18n', () => { ...@@ -654,7 +675,16 @@ describe('required server files i18n', () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
appPort, appPort,
'/optional-ssp', '/optional-ssp',
{ nxtPrest: '', another: 'value' }, Object.fromEntries(
createNowRouteMatches(
{
rest: '',
},
{
another: 'value',
}
)
),
{ {
headers: { headers: {
'x-matched-path': '/optional-ssp/[[...rest]]', 'x-matched-path': '/optional-ssp/[[...rest]]',
...@@ -677,7 +707,12 @@ describe('required server files i18n', () => { ...@@ -677,7 +707,12 @@ describe('required server files i18n', () => {
{ {
headers: { headers: {
'x-matched-path': '/en/optional-ssg/[[...rest]]', 'x-matched-path': '/en/optional-ssg/[[...rest]]',
'x-now-route-matches': 'nextLocale=en&1=en', 'x-now-route-matches': createNowRouteMatches(
{},
{
nextLocale: 'en',
}
).toString(),
}, },
} }
) )
...@@ -696,8 +731,10 @@ describe('required server files i18n', () => { ...@@ -696,8 +731,10 @@ describe('required server files i18n', () => {
{ {
headers: { headers: {
'x-matched-path': '/en/[slug]/social/[[...rest]]', 'x-matched-path': '/en/[slug]/social/[[...rest]]',
'x-now-route-matches': 'x-now-route-matches': createNowRouteMatches(
'nextLocale=en&1=en&2=user-123&nxtPslug=user-123', { slug: 'user-123' },
{ nextLocale: 'en' }
).toString(),
}, },
} }
) )
...@@ -719,8 +756,7 @@ describe('required server files i18n', () => { ...@@ -719,8 +756,7 @@ describe('required server files i18n', () => {
{ {
headers: { headers: {
'x-matched-path': '/optional-ssg/[[...rest]]', 'x-matched-path': '/optional-ssg/[[...rest]]',
'x-now-route-matches': 'x-now-route-matches': 'nxtPrest=en%2Fes%2Fhello%252Fworld',
'1=en%2Fes%2Fhello%252Fworld&nxtPrest=en%2Fes%2Fhello%252Fworld',
}, },
} }
) )
...@@ -737,7 +773,16 @@ describe('required server files i18n', () => { ...@@ -737,7 +773,16 @@ describe('required server files i18n', () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
appPort, appPort,
'/api/optional', '/api/optional',
{ nxtPrest: '', another: 'value' }, Object.fromEntries(
createNowRouteMatches(
{
rest: '',
},
{
another: 'value',
}
)
),
{ {
headers: { headers: {
'x-matched-path': '/api/optional/[[...rest]]', 'x-matched-path': '/api/optional/[[...rest]]',
...@@ -780,7 +825,14 @@ describe('required server files i18n', () => { ...@@ -780,7 +825,14 @@ describe('required server files i18n', () => {
const res = await fetchViaHTTP(appPort, '/en/fallback/[slug]', undefined, { const res = await fetchViaHTTP(appPort, '/en/fallback/[slug]', undefined, {
headers: { headers: {
'x-matched-path': '/en/fallback/[slug]', 'x-matched-path': '/en/fallback/[slug]',
'x-now-route-matches': '2=another&nxtPslug=another&1=en&nextLocale=en', 'x-now-route-matches': createNowRouteMatches(
{
slug: 'another',
},
{
nextLocale: 'en',
}
).toString(),
}, },
redirect: 'manual', redirect: 'manual',
}) })
...@@ -798,7 +850,14 @@ describe('required server files i18n', () => { ...@@ -798,7 +850,14 @@ describe('required server files i18n', () => {
const res = await fetchViaHTTP(appPort, '/fr/fallback/[slug]', undefined, { const res = await fetchViaHTTP(appPort, '/fr/fallback/[slug]', undefined, {
headers: { headers: {
'x-matched-path': '/fr/fallback/[slug]', 'x-matched-path': '/fr/fallback/[slug]',
'x-now-route-matches': '2=another&nxtPslug=another&1=fr&nextLocale=fr', 'x-now-route-matches': createNowRouteMatches(
{
slug: 'another',
},
{
nextLocale: 'fr',
}
).toString(),
}, },
redirect: 'manual', redirect: 'manual',
}) })
......
...@@ -5,6 +5,7 @@ import cheerio from 'cheerio' ...@@ -5,6 +5,7 @@ import cheerio from 'cheerio'
import { createNext, FileRef } from 'e2e-utils' import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils' import { NextInstance } from 'e2e-utils'
import { import {
createNowRouteMatches,
fetchViaHTTP, fetchViaHTTP,
findPort, findPort,
initNextServerScript, initNextServerScript,
...@@ -182,7 +183,9 @@ describe('required server files app router', () => { ...@@ -182,7 +183,9 @@ describe('required server files app router', () => {
headers: { headers: {
'user-agent': 'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'x-now-route-matches': '1=second&nxtPslug=new', 'x-now-route-matches': createNowRouteMatches({
slug: 'new',
}).toString(),
'x-matched-path': '/isr/[slug]', 'x-matched-path': '/isr/[slug]',
}, },
}) })
...@@ -197,7 +200,9 @@ describe('required server files app router', () => { ...@@ -197,7 +200,9 @@ describe('required server files app router', () => {
headers: { headers: {
'user-agent': 'user-agent':
'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)', 'Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.179 Mobile Safari/537.36 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)',
'x-now-route-matches': '1=second&nxtPslug=new', 'x-now-route-matches': createNowRouteMatches({
slug: 'new',
}).toString(),
'x-matched-path': '/isr/[slug]', 'x-matched-path': '/isr/[slug]',
}, },
}) })
......
...@@ -7,6 +7,7 @@ import { createNext, FileRef } from 'e2e-utils' ...@@ -7,6 +7,7 @@ import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils' import { NextInstance } from 'e2e-utils'
import { import {
check, check,
createNowRouteMatches,
fetchViaHTTP, fetchViaHTTP,
findPort, findPort,
initNextServerScript, initNextServerScript,
...@@ -669,7 +670,9 @@ describe('required server files', () => { ...@@ -669,7 +670,9 @@ describe('required server files', () => {
const html = await renderViaHTTP(appPort, '/fallback/first', undefined, { const html = await renderViaHTTP(appPort, '/fallback/first', undefined, {
headers: { headers: {
'x-matched-path': '/fallback/first', 'x-matched-path': '/fallback/first',
'x-now-route-matches': '1=first', 'x-now-route-matches': createNowRouteMatches({
slug: 'first',
}).toString(),
}, },
}) })
const $ = cheerio.load(html) const $ = cheerio.load(html)
...@@ -682,7 +685,9 @@ describe('required server files', () => { ...@@ -682,7 +685,9 @@ describe('required server files', () => {
const html2 = await renderViaHTTP(appPort, `/fallback/[slug]`, undefined, { const html2 = await renderViaHTTP(appPort, `/fallback/[slug]`, undefined, {
headers: { headers: {
'x-matched-path': '/fallback/[slug]', 'x-matched-path': '/fallback/[slug]',
'x-now-route-matches': '1=second', 'x-now-route-matches': createNowRouteMatches({
slug: 'second',
}).toString(),
}, },
}) })
const $2 = cheerio.load(html2) const $2 = cheerio.load(html2)
...@@ -698,7 +703,9 @@ describe('required server files', () => { ...@@ -698,7 +703,9 @@ describe('required server files', () => {
const html = await renderViaHTTP(appPort, '/fallback/first', undefined, { const html = await renderViaHTTP(appPort, '/fallback/first', undefined, {
headers: { headers: {
'x-matched-path': '/fallback/first', 'x-matched-path': '/fallback/first',
'x-now-route-matches': '1=fallback%2ffirst', 'x-now-route-matches': createNowRouteMatches({
slug: 'fallback/first',
}).toString(),
}, },
}) })
const $ = cheerio.load(html) const $ = cheerio.load(html)
...@@ -711,7 +718,9 @@ describe('required server files', () => { ...@@ -711,7 +718,9 @@ describe('required server files', () => {
const html2 = await renderViaHTTP(appPort, `/fallback/second`, undefined, { const html2 = await renderViaHTTP(appPort, `/fallback/second`, undefined, {
headers: { headers: {
'x-matched-path': '/fallback/[slug]', 'x-matched-path': '/fallback/[slug]',
'x-now-route-matches': '1=fallback%2fsecond', 'x-now-route-matches': createNowRouteMatches({
slug: 'fallback/second',
}).toString(),
}, },
}) })
const $2 = cheerio.load(html2) const $2 = cheerio.load(html2)
...@@ -727,7 +736,7 @@ describe('required server files', () => { ...@@ -727,7 +736,7 @@ describe('required server files', () => {
const html = await renderViaHTTP(appPort, '/optional-ssg', undefined, { const html = await renderViaHTTP(appPort, '/optional-ssg', undefined, {
headers: { headers: {
'x-matched-path': '/optional-ssg', 'x-matched-path': '/optional-ssg',
'x-now-route-matches': '1=optional-ssg', 'x-now-route-matches': '',
}, },
}) })
const $ = cheerio.load(html) const $ = cheerio.load(html)
...@@ -737,7 +746,9 @@ describe('required server files', () => { ...@@ -737,7 +746,9 @@ describe('required server files', () => {
const html2 = await renderViaHTTP(appPort, `/optional-ssg`, undefined, { const html2 = await renderViaHTTP(appPort, `/optional-ssg`, undefined, {
headers: { headers: {
'x-matched-path': '/optional-ssg', 'x-matched-path': '/optional-ssg',
'x-now-route-matches': '1=optional-ssg%2fanother', 'x-now-route-matches': createNowRouteMatches({
slug: 'another',
}).toString(),
}, },
}) })
const $2 = cheerio.load(html2) const $2 = cheerio.load(html2)
...@@ -750,7 +761,9 @@ describe('required server files', () => { ...@@ -750,7 +761,9 @@ describe('required server files', () => {
it('should return data correctly with x-matched-path', async () => { it('should return data correctly with x-matched-path', async () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
appPort, appPort,
`/_next/data/${next.buildId}/dynamic/first.json?nxtPslug=first`, `/_next/data/${next.buildId}/dynamic/first.json?${createNowRouteMatches({
slug: 'first',
}).toString()}`,
undefined, undefined,
{ {
headers: { headers: {
...@@ -771,7 +784,9 @@ describe('required server files', () => { ...@@ -771,7 +784,9 @@ describe('required server files', () => {
{ {
headers: { headers: {
'x-matched-path': `/_next/data/${next.buildId}/fallback/[slug].json`, 'x-matched-path': `/_next/data/${next.buildId}/fallback/[slug].json`,
'x-now-route-matches': '1=second', 'x-now-route-matches': createNowRouteMatches({
slug: 'second',
}).toString(),
}, },
} }
) )
...@@ -808,7 +823,9 @@ describe('required server files', () => { ...@@ -808,7 +823,9 @@ describe('required server files', () => {
{ {
headers: { headers: {
'x-matched-path': '/catch-all/[[...rest]]', 'x-matched-path': '/catch-all/[[...rest]]',
'x-now-route-matches': '1=hello&nxtPcatchAll=hello', 'x-now-route-matches': createNowRouteMatches({
rest: 'hello',
}).toString(),
}, },
} }
) )
...@@ -827,7 +844,9 @@ describe('required server files', () => { ...@@ -827,7 +844,9 @@ describe('required server files', () => {
{ {
headers: { headers: {
'x-matched-path': '/catch-all/[[...rest]]', 'x-matched-path': '/catch-all/[[...rest]]',
'x-now-route-matches': '1=hello/world&nxtPcatchAll=hello/world', 'x-now-route-matches': createNowRouteMatches({
rest: 'hello/world',
}).toString(),
}, },
} }
) )
...@@ -865,7 +884,9 @@ describe('required server files', () => { ...@@ -865,7 +884,9 @@ describe('required server files', () => {
{ {
headers: { headers: {
'x-matched-path': `/_next/data/${next.buildId}/catch-all/[[...rest]].json`, 'x-matched-path': `/_next/data/${next.buildId}/catch-all/[[...rest]].json`,
'x-now-route-matches': '1=hello&nxtPrest=hello', 'x-now-route-matches': createNowRouteMatches({
rest: 'hello',
}).toString(),
}, },
} }
) )
...@@ -882,7 +903,9 @@ describe('required server files', () => { ...@@ -882,7 +903,9 @@ describe('required server files', () => {
{ {
headers: { headers: {
'x-matched-path': `/_next/data/${next.buildId}/catch-all/[[...rest]].json`, 'x-matched-path': `/_next/data/${next.buildId}/catch-all/[[...rest]].json`,
'x-now-route-matches': '1=hello/world&nxtPrest=hello/world', 'x-now-route-matches': createNowRouteMatches({
rest: 'hello/world',
}).toString(),
}, },
} }
) )
...@@ -934,7 +957,9 @@ describe('required server files', () => { ...@@ -934,7 +957,9 @@ describe('required server files', () => {
const res = await fetchViaHTTP( const res = await fetchViaHTTP(
appPort, appPort,
'/to-dynamic/%c0.%c0.', '/to-dynamic/%c0.%c0.',
'?path=%c0.%c0.', {
path: '%c0.%c0.',
},
{ {
headers: { headers: {
'x-matched-path': '/dynamic/[slug]', 'x-matched-path': '/dynamic/[slug]',
...@@ -1092,7 +1117,9 @@ describe('required server files', () => { ...@@ -1092,7 +1117,9 @@ describe('required server files', () => {
path: `/_next/data/${next.buildId}/optional-ssg/[[...rest]].json`, path: `/_next/data/${next.buildId}/optional-ssg/[[...rest]].json`,
headers: { headers: {
'x-matched-path': `/_next/data/${next.buildId}/optional-ssg/[[...rest]].json`, 'x-matched-path': `/_next/data/${next.buildId}/optional-ssg/[[...rest]].json`,
'x-now-route-matches': '1=', 'x-now-route-matches': createNowRouteMatches({
rest: '',
}).toString(),
}, },
}, },
{ {
...@@ -1149,8 +1176,7 @@ describe('required server files', () => { ...@@ -1149,8 +1176,7 @@ describe('required server files', () => {
{ {
headers: { headers: {
'x-matched-path': '/optional-ssg/[[...rest]]', 'x-matched-path': '/optional-ssg/[[...rest]]',
'x-now-route-matches': 'x-now-route-matches': 'nxtPrest=en%2Fes%2Fhello%252Fworld',
'1=en%2Fes%2Fhello%252Fworld&nxtPrest=en%2Fes%2Fhello%252Fworld',
}, },
} }
) )
......
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