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<
params = paramsResult.params
}
const routeMatchesHeader = req.headers['x-now-route-matches']
if (
req.headers['x-now-route-matches'] &&
typeof routeMatchesHeader === 'string' &&
routeMatchesHeader &&
isDynamicRoute(matchedPath) &&
!paramsResult.hasValidParams
) {
const opts: Record<string, string> = {}
const routeParams = utils.getParamsFromRouteMatches(
req,
opts,
getRequestMeta(req, 'locale')
)
const routeMatches =
utils.getParamsFromRouteMatches(routeMatchesHeader)
// If this returns a locale, it means that the locale was detected
// from the pathname.
if (opts.locale) {
addRequestMeta(req, 'locale', opts.locale)
if (routeMatches) {
paramsResult = utils.normalizeDynamicRouteParams(
routeMatches,
true
)
// As the locale was parsed from the pathname, we should mark
// that the locale was not inferred as the default.
removeRequestMeta(req, 'localeInferredFromDefault')
}
paramsResult = utils.normalizeDynamicRouteParams(
routeParams,
true
)
if (paramsResult.hasValidParams) {
params = paramsResult.params
if (paramsResult.hasValidParams) {
params = paramsResult.params
}
}
}
......
......@@ -350,10 +350,10 @@ export default class HotReloaderWebpack implements NextJsHotReloaderInterface {
parsedPageBundleUrl: UrlObject
): Promise<{ finished?: true }> => {
const { pathname } = parsedPageBundleUrl
if (!pathname) return {}
const params = matchNextPageBundleRequest(pathname)
if (!params) {
return {}
}
if (!params) return {}
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 {
NEXT_INTERCEPTION_MARKER_PREFIX,
NEXT_QUERY_PARAM_PREFIX,
} from '../lib/constants'
import { normalizeNextQueryParam } from './web/utils'
export function normalizeVercelUrl(
req: BaseNextRequest,
......@@ -221,6 +222,9 @@ export function getUtils({
sensitive: !!caseSensitive,
}
)
if (!parsedUrl.pathname) return false
let params = matcher(parsedUrl.pathname)
if ((rewrite.has || rewrite.missing) && params) {
......@@ -258,20 +262,17 @@ export function getUtils({
Object.assign(parsedUrl, parsedDestination)
fsPathname = parsedUrl.pathname
if (!fsPathname) return false
if (basePath) {
fsPathname =
fsPathname!.replace(new RegExp(`^${basePath}`), '') || '/'
fsPathname = fsPathname.replace(new RegExp(`^${basePath}`), '') || '/'
}
if (i18n) {
const destLocalePathResult = normalizeLocalePath(
fsPathname!,
i18n.locales
)
fsPathname = destLocalePathResult.pathname
const result = normalizeLocalePath(fsPathname, i18n.locales)
fsPathname = result.pathname
parsedUrl.query.nextInternalLocale =
destLocalePathResult.detectedLocale || params.nextInternalLocale
result.detectedLocale || params.nextInternalLocale
}
if (fsPathname === page) {
......@@ -314,102 +315,56 @@ export function getUtils({
return rewriteParams
}
function getParamsFromRouteMatches(
req: BaseNextRequest,
renderOpts?: any,
detectedLocale?: string
) {
return getRouteMatcher(
(function () {
const { groups, routeKeys } = defaultRouteRegex!
return {
re: {
// Simulate a RegExp match from the \`req.url\` input
exec: (str: string) => {
const obj = Object.fromEntries(new URLSearchParams(str))
const matchesHasLocale =
i18n && detectedLocale && obj['1'] === detectedLocale
for (const key of Object.keys(obj)) {
const value = obj[key]
if (
key !== NEXT_QUERY_PARAM_PREFIX &&
key.startsWith(NEXT_QUERY_PARAM_PREFIX)
) {
const normalizedKey = key.substring(
NEXT_QUERY_PARAM_PREFIX.length
)
obj[normalizedKey] = value
delete obj[key]
}
}
// favor named matches if available
const routeKeyNames = Object.keys(routeKeys || {})
const filterLocaleItem = (val: string | string[] | undefined) => {
if (i18n) {
// locale items can be included in route-matches
// for fallback SSG pages so ensure they are
// filtered
const isCatchAll = Array.isArray(val)
const _val = isCatchAll ? val[0] : val
if (
typeof _val === 'string' &&
i18n.locales.some((item) => {
if (item.toLowerCase() === _val.toLowerCase()) {
detectedLocale = item
renderOpts.locale = detectedLocale
return true
}
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
function getParamsFromRouteMatches(routeMatchesHeader: string) {
// If we don't have a default route regex, we can't get params from route
// matches
if (!defaultRouteRegex) return null
const { groups, routeKeys } = defaultRouteRegex
const matcher = getRouteMatcher({
re: {
// Simulate a RegExp match from the \`req.url\` input
exec: (str: string) => {
// Normalize all the prefixed query params.
const obj: Record<string, string> = Object.fromEntries(
new URLSearchParams(str)
)
for (const [key, value] of Object.entries(obj)) {
const normalizedKey = normalizeNextQueryParam(key)
if (!normalizedKey) continue
obj[normalizedKey] = value
delete obj[key]
}
// Use all the named route keys.
const result = {} as RegExpExecArray
for (const keyName of Object.keys(routeKeys)) {
const paramName = routeKeys[keyName]
// If this param name is not a valid parameter name, then skip it.
if (!paramName) continue
const group = groups[paramName]
const value = obj[keyName]
// When we're missing a required param, we can't match the route.
if (!group.optional && !value) return null
result[group.pos] = value
}
return result
},
},
groups,
})
const routeMatches = matcher(routeMatchesHeader)
if (!routeMatches) return null
return routeMatches
}
return {
......
......@@ -159,8 +159,7 @@ export function normalizeNextQueryParam(key: string): null | string {
const prefixes = [NEXT_QUERY_PARAM_PREFIX, NEXT_INTERCEPTION_MARKER_PREFIX]
for (const prefix of prefixes) {
if (key !== prefix && key.startsWith(prefix)) {
const normalizedKey = key.substring(prefix.length)
return normalizedKey
return key.substring(prefix.length)
}
}
return null
......
......@@ -26,7 +26,7 @@ interface Options {
}
export type PatchMatcher = (
pathname?: string | null,
pathname: string,
params?: Record<string, any>
) => Record<string, any> | false
......
import type { RouteRegex } from './route-regex'
import type { Group } from './route-regex'
import { DecodeError } from '../../utils'
import type { Params } from '../../../../server/request/params'
export interface RouteMatchFn {
(pathname: string | null | undefined): false | Params
(pathname: string): false | Params
}
export function getRouteMatcher({ re, groups }: RouteRegex): RouteMatchFn {
return (pathname: string | null | undefined) => {
const routeMatch = re.exec(pathname!)
if (!routeMatch) {
return false
}
type RouteMatcherOptions = {
// We only use the exec method of the RegExp object. This helps us avoid using
// type assertions that the passed in properties are of the correct type.
re: Pick<RegExp, 'exec'>
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) => {
try {
return decodeURIComponent(param)
} catch (_) {
} catch {
throw new DecodeError('failed to decode param')
}
}
const params: { [paramName: string]: string | string[] } = {}
Object.keys(groups).forEach((slugName: string) => {
const g = groups[slugName]
const m = routeMatch[g.pos]
if (m !== undefined) {
params[slugName] = ~m.indexOf('/')
? m.split('/').map((entry) => decode(entry))
: g.repeat
? [decode(m)]
: decode(m)
const params: Params = {}
for (const [key, group] of Object.entries(groups)) {
const match = routeMatch[group.pos]
if (match !== undefined) {
if (group.repeat) {
params[key] = match.split('/').map((entry) => decode(entry))
} else {
params[key] = decode(match)
}
}
})
}
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', () => {
{
headers: {
'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', () => {
{
headers: {
'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', () => {
{
headers: {
'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', () => {
{
headers: {
'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', () => {
{
headers: {
'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', () => {
{
headers: {
'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', () => {
{
headers: {
'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) {
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'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import {
createNowRouteMatches,
fetchViaHTTP,
findPort,
initNextServerScript,
......@@ -107,7 +108,9 @@ describe('required server files app router', () => {
const res = await fetchViaHTTP(appPort, '/api/test/123', undefined, {
headers: {
'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)
......@@ -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 () => {
const res = await fetchViaHTTP(appPort, '/test/123', undefined, {
headers: {
'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)
......@@ -164,7 +215,9 @@ describe('required server files app router', () => {
headers: {
'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)',
'x-now-route-matches': '1=second&nxtPslug=new',
'x-now-route-matches': createNowRouteMatches({
slug: 'new',
}).toString(),
'x-matched-path': '/isr/[slug]',
},
})
......@@ -179,7 +232,9 @@ describe('required server files app router', () => {
headers: {
'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)',
'x-now-route-matches': '1=second&nxtPslug=new',
'x-now-route-matches': createNowRouteMatches({
slug: 'new',
}).toString(),
'x-matched-path': '/isr/[slug]',
},
})
......
......@@ -6,6 +6,7 @@ import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import {
check,
createNowRouteMatches,
fetchViaHTTP,
findPort,
initNextServerScript,
......@@ -373,7 +374,9 @@ describe('required server files i18n', () => {
const html = await renderViaHTTP(appPort, '/fallback/first', undefined, {
headers: {
'x-matched-path': '/fallback/first',
'x-now-route-matches': '1=first',
'x-now-route-matches': createNowRouteMatches({
slug: 'first',
}).toString(),
},
})
const $ = cheerio.load(html)
......@@ -386,7 +389,9 @@ describe('required server files i18n', () => {
const html2 = await renderViaHTTP(appPort, `/fallback/[slug]`, undefined, {
headers: {
'x-matched-path': '/fallback/[slug]',
'x-now-route-matches': '1=second',
'x-now-route-matches': createNowRouteMatches({
slug: 'second',
}).toString(),
},
})
const $2 = cheerio.load(html2)
......@@ -401,7 +406,9 @@ describe('required server files i18n', () => {
it('should return data correctly with x-matched-path', async () => {
const res = await fetchViaHTTP(
appPort,
`/_next/data/${next.buildId}/en/dynamic/first.json?nxtPslug=first`,
`/_next/data/${next.buildId}/en/dynamic/first.json?${createNowRouteMatches(
{ slug: 'first' }
).toString()}`,
undefined,
{
headers: {
......@@ -422,7 +429,9 @@ describe('required server files i18n', () => {
{
headers: {
'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', () => {
{
headers: {
'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', () => {
{
headers: {
'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', () => {
{
headers: {
'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', () => {
{
headers: {
'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', () => {
const res = await fetchViaHTTP(
appPort,
'/to-dynamic/%c0.%c0.',
'?path=%c0.%c0.',
Object.fromEntries(
createNowRouteMatches({
path: '%c0.%c0.',
})
),
{
headers: {
'x-matched-path': '/dynamic/[slug]',
......@@ -654,7 +675,16 @@ describe('required server files i18n', () => {
const res = await fetchViaHTTP(
appPort,
'/optional-ssp',
{ nxtPrest: '', another: 'value' },
Object.fromEntries(
createNowRouteMatches(
{
rest: '',
},
{
another: 'value',
}
)
),
{
headers: {
'x-matched-path': '/optional-ssp/[[...rest]]',
......@@ -677,7 +707,12 @@ describe('required server files i18n', () => {
{
headers: {
'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', () => {
{
headers: {
'x-matched-path': '/en/[slug]/social/[[...rest]]',
'x-now-route-matches':
'nextLocale=en&1=en&2=user-123&nxtPslug=user-123',
'x-now-route-matches': createNowRouteMatches(
{ slug: 'user-123' },
{ nextLocale: 'en' }
).toString(),
},
}
)
......@@ -719,8 +756,7 @@ describe('required server files i18n', () => {
{
headers: {
'x-matched-path': '/optional-ssg/[[...rest]]',
'x-now-route-matches':
'1=en%2Fes%2Fhello%252Fworld&nxtPrest=en%2Fes%2Fhello%252Fworld',
'x-now-route-matches': 'nxtPrest=en%2Fes%2Fhello%252Fworld',
},
}
)
......@@ -737,7 +773,16 @@ describe('required server files i18n', () => {
const res = await fetchViaHTTP(
appPort,
'/api/optional',
{ nxtPrest: '', another: 'value' },
Object.fromEntries(
createNowRouteMatches(
{
rest: '',
},
{
another: 'value',
}
)
),
{
headers: {
'x-matched-path': '/api/optional/[[...rest]]',
......@@ -780,7 +825,14 @@ describe('required server files i18n', () => {
const res = await fetchViaHTTP(appPort, '/en/fallback/[slug]', undefined, {
headers: {
'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',
})
......@@ -798,7 +850,14 @@ describe('required server files i18n', () => {
const res = await fetchViaHTTP(appPort, '/fr/fallback/[slug]', undefined, {
headers: {
'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',
})
......
......@@ -5,6 +5,7 @@ import cheerio from 'cheerio'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import {
createNowRouteMatches,
fetchViaHTTP,
findPort,
initNextServerScript,
......@@ -182,7 +183,9 @@ describe('required server files app router', () => {
headers: {
'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)',
'x-now-route-matches': '1=second&nxtPslug=new',
'x-now-route-matches': createNowRouteMatches({
slug: 'new',
}).toString(),
'x-matched-path': '/isr/[slug]',
},
})
......@@ -197,7 +200,9 @@ describe('required server files app router', () => {
headers: {
'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)',
'x-now-route-matches': '1=second&nxtPslug=new',
'x-now-route-matches': createNowRouteMatches({
slug: 'new',
}).toString(),
'x-matched-path': '/isr/[slug]',
},
})
......
......@@ -7,6 +7,7 @@ import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import {
check,
createNowRouteMatches,
fetchViaHTTP,
findPort,
initNextServerScript,
......@@ -669,7 +670,9 @@ describe('required server files', () => {
const html = await renderViaHTTP(appPort, '/fallback/first', undefined, {
headers: {
'x-matched-path': '/fallback/first',
'x-now-route-matches': '1=first',
'x-now-route-matches': createNowRouteMatches({
slug: 'first',
}).toString(),
},
})
const $ = cheerio.load(html)
......@@ -682,7 +685,9 @@ describe('required server files', () => {
const html2 = await renderViaHTTP(appPort, `/fallback/[slug]`, undefined, {
headers: {
'x-matched-path': '/fallback/[slug]',
'x-now-route-matches': '1=second',
'x-now-route-matches': createNowRouteMatches({
slug: 'second',
}).toString(),
},
})
const $2 = cheerio.load(html2)
......@@ -698,7 +703,9 @@ describe('required server files', () => {
const html = await renderViaHTTP(appPort, '/fallback/first', undefined, {
headers: {
'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)
......@@ -711,7 +718,9 @@ describe('required server files', () => {
const html2 = await renderViaHTTP(appPort, `/fallback/second`, undefined, {
headers: {
'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)
......@@ -727,7 +736,7 @@ describe('required server files', () => {
const html = await renderViaHTTP(appPort, '/optional-ssg', undefined, {
headers: {
'x-matched-path': '/optional-ssg',
'x-now-route-matches': '1=optional-ssg',
'x-now-route-matches': '',
},
})
const $ = cheerio.load(html)
......@@ -737,7 +746,9 @@ describe('required server files', () => {
const html2 = await renderViaHTTP(appPort, `/optional-ssg`, undefined, {
headers: {
'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)
......@@ -750,7 +761,9 @@ describe('required server files', () => {
it('should return data correctly with x-matched-path', async () => {
const res = await fetchViaHTTP(
appPort,
`/_next/data/${next.buildId}/dynamic/first.json?nxtPslug=first`,
`/_next/data/${next.buildId}/dynamic/first.json?${createNowRouteMatches({
slug: 'first',
}).toString()}`,
undefined,
{
headers: {
......@@ -771,7 +784,9 @@ describe('required server files', () => {
{
headers: {
'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', () => {
{
headers: {
'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', () => {
{
headers: {
'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', () => {
{
headers: {
'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', () => {
{
headers: {
'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', () => {
const res = await fetchViaHTTP(
appPort,
'/to-dynamic/%c0.%c0.',
'?path=%c0.%c0.',
{
path: '%c0.%c0.',
},
{
headers: {
'x-matched-path': '/dynamic/[slug]',
......@@ -1092,7 +1117,9 @@ describe('required server files', () => {
path: `/_next/data/${next.buildId}/optional-ssg/[[...rest]].json`,
headers: {
'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', () => {
{
headers: {
'x-matched-path': '/optional-ssg/[[...rest]]',
'x-now-route-matches':
'1=en%2Fes%2Fhello%252Fworld&nxtPrest=en%2Fes%2Fhello%252Fworld',
'x-now-route-matches': '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