Prevent clients from selecting a Variants combination

A client could request `/__variants/<hash>/page` or `/page?nxtV=<hash>`
and receive the artifact of a static variant combination it did not
resolve to. Only the proxy writes the prefix, and routing derives the
query parameter from it after a request arrives, so either one on an
incoming request came from the client. This change rejects such a
request in both modes and answers it as a 404, like any request for a
pathname no route serves.

When self-hosting, `resolveRoutes` checks the request before headers,
redirects, the proxy, and every route. That also covers a route that
declares combinations while the proxy's `config.matcher` leaves it out.
The check reads the decoded and slash-normalized pathname and every
spelling of the parameter that `normalizeNextQueryParam` folds into
`nxtV`. Minimal mode skips it, because the platform writes the parameter
itself there.

On a deployment, the web adapter checks the URL as it arrived, not the
proxy's rewrite target, because a proxy that rewrites to
`request.nextUrl` carries a normalized `nxtV` into its target. A
rejected request is rewritten to `/__variants/not-routed` and the user's
proxy does not run. The adapter marks a prefix it writes with
`x-next-internal-variants-prefix`, and `handleBuildComplete` emits
`beforeFiles` rules that rewrite an unmarked prefixed request, or one
carrying the parameter, to the same pathname. The rejection is a rewrite
rather than a status, because a routing rule with only a status still
serves the output the pathname matches. The prefix rule admits
percent-encoded spellings, because a deployment matches a rule against
the pathname as sent and decodes it before it looks an artifact up.

The rejection pathname lies inside the artifact namespace, so the
exclusion that already keeps ordinary matchers out of `/__variants/`
also keeps them off it. The exclusion now applies to data routes and to
user rewrites as well, so a catch-all rewrite no longer matches a
prefixed request. Its segment contains a hyphen, which the hash alphabet
does not, and the route aliases in the routes manifest now match a hash
as `[0-9a-z]+` like every other matcher, so no matcher can take it for a
hash.

A build fails when a route, a generated static param, or a `public/`
entry lies under `/__variants/`, because content there would answer a
rejected request. The marker header joins `INTERNAL_HEADERS` and the
headers hidden from `headers()`.
parent 06aa4156
...@@ -53,6 +53,7 @@ import { ...@@ -53,6 +53,7 @@ import {
VARIANTS_PATH_PREFIX, VARIANTS_PATH_PREFIX,
} from '../../lib/constants' } from '../../lib/constants'
import { splitVariantsPrefix } from '../../server/variants/prefix' import { splitVariantsPrefix } from '../../server/variants/prefix'
import { buildVariantsRejectionRoutes } from '../variants/rejection-routes'
import { normalizeLocalePath } from '../../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../../shared/lib/i18n/normalize-locale-path'
import { getStaticMetadataPrerenderPathname } from '../../lib/metadata/get-metadata-route' import { getStaticMetadataPrerenderPathname } from '../../lib/metadata/get-metadata-route'
...@@ -2145,6 +2146,12 @@ export async function handleBuildComplete({ ...@@ -2145,6 +2146,12 @@ export async function handleBuildComplete({
const dynamicRoutes: DynamicRouteItem[] = [] const dynamicRoutes: DynamicRouteItem[] = []
const dynamicDataRoutes: DynamicRouteItem[] = [] const dynamicDataRoutes: DynamicRouteItem[] = []
const dynamicSegmentRoutes: DynamicRouteItem[] = [] const dynamicSegmentRoutes: DynamicRouteItem[] = []
// Ordinary matchers exclude the artifact namespace, so a broad dynamic
// route cannot consume a variants prefix instead of capturing its hash. The
// pathname that a rejected request is rewritten to lies in the namespace as
// well, so no route serves such a request either. The lookahead sits before
// the optional slash of a matcher, so that backtracking over that slash
// cannot bypass it.
const variantsPathExclusion = config.experimental.variants const variantsPathExclusion = config.experimental.variants
? `(?![/]?/${VARIANTS_PATH_PREFIX}/)` ? `(?![/]?/${VARIANTS_PATH_PREFIX}/)`
: '' : ''
...@@ -2486,7 +2493,7 @@ export async function handleBuildComplete({ ...@@ -2486,7 +2493,7 @@ export async function handleBuildComplete({
config.basePath, config.basePath,
`_next/data`, `_next/data`,
escapeStringRegexp(buildId) escapeStringRegexp(buildId)
)}[/]?${shouldLocalize ? '(?<nextLocale>[^/]{1,})' : ''}` )}${variantsPathExclusion}[/]?${shouldLocalize ? '(?<nextLocale>[^/]{1,})' : ''}`
), ),
destination, destination,
has: isFallbackFalse ? fallbackFalseHasCondition : undefined, has: isFallbackFalse ? fallbackFalseHasCondition : undefined,
...@@ -2495,13 +2502,26 @@ export async function handleBuildComplete({ ...@@ -2495,13 +2502,26 @@ export async function handleBuildComplete({
} }
} }
// A user rewrite never matches a pathname in the artifact namespace. That
// leaves a prefixed request to the prefixed matchers below, and it leaves a
// rejected request to no route at all.
const rewriteRestrictedPaths = config.experimental.variants
? [
`${escapeStringRegexp(
path.posix.join('/', config.basePath, VARIANTS_PATH_PREFIX)
)}/`,
]
: undefined
const buildRewriteItem = (route: ManifestRewriteRoute): RewriteItem => { const buildRewriteItem = (route: ManifestRewriteRoute): RewriteItem => {
const converted = convertRewrites([route], ['nextInternalLocale'])[0] const converted = convertRewrites([route], ['nextInternalLocale'])[0]
const regex = converted.src || route.regex const regex = converted.src || route.regex
return { return {
source: route.source, source: route.source,
sourceRegex: route.internal ? regex : modifyRouteRegex(regex), sourceRegex: route.internal
? regex
: modifyRouteRegex(regex, rewriteRestrictedPaths),
destination: converted.dest || route.destination, destination: converted.dest || route.destination,
has: route.has, has: route.has,
missing: route.missing, missing: route.missing,
...@@ -2531,7 +2551,15 @@ export async function handleBuildComplete({ ...@@ -2531,7 +2551,15 @@ export async function handleBuildComplete({
] satisfies Route[] ] satisfies Route[]
const rewrites = { const rewrites = {
beforeFiles: routesManifest.rewrites.beforeFiles.map(buildRewriteItem), beforeFiles: [
// The variants rejection rules come before every user rewrite, so a
// rewrite cannot admit a request that names a static variant
// combination itself.
...(config.experimental.variants
? buildVariantsRejectionRoutes(config.basePath)
: []),
...routesManifest.rewrites.beforeFiles.map(buildRewriteItem),
],
afterFiles: routesManifest.rewrites.afterFiles.map(buildRewriteItem), afterFiles: routesManifest.rewrites.afterFiles.map(buildRewriteItem),
fallback: routesManifest.rewrites.fallback.map(buildRewriteItem), fallback: routesManifest.rewrites.fallback.map(buildRewriteItem),
} }
......
...@@ -222,6 +222,10 @@ import { handleBuildComplete } from './adapter/build-complete' ...@@ -222,6 +222,10 @@ import { handleBuildComplete } from './adapter/build-complete'
import type { VariantCombinationGroups } from '../server/variants/combinations' import type { VariantCombinationGroups } from '../server/variants/combinations'
import { buildVariantsManifest, recordVariantOutput } from './variants/manifest' import { buildVariantsManifest, recordVariantOutput } from './variants/manifest'
import { buildVariantRouteAliases } from './variants/route-aliases' import { buildVariantRouteAliases } from './variants/route-aliases'
import {
assertNotVariantsReservedPathname,
assertNoVariantsReservedPublicEntries,
} from './variants/reserved-paths'
import { getVariantOutputPath } from '../server/variants/prefix' import { getVariantOutputPath } from '../server/variants/prefix'
import { import {
sortPageObjects, sortPageObjects,
...@@ -1548,6 +1552,26 @@ export default async function build( ...@@ -1548,6 +1552,26 @@ export default async function build(
const mappedPages = NextBuildContext.mappedPages const mappedPages = NextBuildContext.mappedPages
const mappedAppPages = NextBuildContext.mappedAppPages const mappedAppPages = NextBuildContext.mappedAppPages
// A route at a pathname that Variants reserves can never be served, so
// the build rejects it here, before it compiles anything.
if (config.experimental.variants) {
for (const appKey of discoveredAppPageKeys ?? []) {
assertNotVariantsReservedPathname(
normalizeAppPath(appKey),
(discovery.mappedAppPages?.[appKey] ?? appKey).replace(
/^private-next-app-dir/,
'app'
)
)
}
for (const page of pagesPageKeys) {
assertNotVariantsReservedPathname(
page,
mappedPages[page].replace(/^private-next-pages/, 'pages')
)
}
}
// Validate that the app paths are valid. This is currently duplicating // Validate that the app paths are valid. This is currently duplicating
// the logic from packages/next/src/shared/lib/router/utils/sorted-routes.ts // the logic from packages/next/src/shared/lib/router/utils/sorted-routes.ts
// but is instead specifically focused on code that can be shared // but is instead specifically focused on code that can be shared
...@@ -1645,6 +1669,10 @@ export default async function build( ...@@ -1645,6 +1669,10 @@ export default async function build(
if (hasPublicUnderScoreNextDir) { if (hasPublicUnderScoreNextDir) {
throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT) throw new Error(PUBLIC_DIR_MIDDLEWARE_CONFLICT)
} }
if (config.experimental.variants) {
assertNoVariantsReservedPublicEntries(publicDir)
}
} }
await nextBuildSpan await nextBuildSpan
...@@ -2582,6 +2610,21 @@ export default async function build( ...@@ -2582,6 +2610,21 @@ export default async function build(
} }
) )
// A generated path in the namespace that Variants
// reserves would answer a rejected request with content,
// so the build rejects it.
if (
config.experimental.variants &&
workerResult.prerenderedRoutes
) {
for (const route of workerResult.prerenderedRoutes) {
assertNotVariantsReservedPathname(
route.pathname,
`the static params of "${page}"`
)
}
}
if (pageType === 'app' && originalAppPath) { if (pageType === 'app' && originalAppPath) {
appNormalizedPaths.set(originalAppPath, page) appNormalizedPaths.set(originalAppPath, page)
// TODO-APP: handle prerendering with edge // TODO-APP: handle prerendering with edge
......
import type { RouteHas } from '../../lib/load-custom-routes'
import path from 'node:path'
import {
NEXT_VARIANTS_PREFIX_HEADER,
VARIANTS_NOT_ROUTED_PATH,
VARIANTS_PATH_PREFIX,
} from '../../lib/constants'
import { VARIANTS_SELECTOR_QUERY_KEYS } from '../../server/variants/prefix'
import { escapeStringRegexp } from '../../shared/lib/escape-regexp'
/**
* A routing rule for a deployment, in the shape `handleBuildComplete` hands to
* the adapter.
*/
export interface VariantsRejectionRoute {
source: string
sourceRegex: string
destination: string
has: RouteHas[] | undefined
missing: RouteHas[] | undefined
}
/**
* Matches one character of a pathname as the deployment receives it: either the
* character itself or its percent-encoded form, with either case of the
* hexadecimal digits.
*
* A deployment matches a routing rule against the pathname as sent, and it
* decodes the pathname before it looks an artifact up. A rule that names the
* artifact namespace therefore has to match the encoded spellings too.
*/
function encodedCharacterPattern(character: string): string {
const hex = character.charCodeAt(0).toString(16).toUpperCase()
const digits = hex
.split('')
.map((digit) =>
/[A-F]/.test(digit) ? `[${digit}${digit.toLowerCase()}]` : digit
)
.join('')
return `(?:${escapeStringRegexp(character)}|%${digits})`
}
/**
* Matches a path separator as the deployment receives it. A backslash counts,
* because the lookup converts it into a slash, and so does an encoded slash.
*/
const SEPARATOR_PATTERN = `(?:/|\\\\|%2[fF]|%5[cC])`
/**
* Matches the namespace segment in any spelling that decodes to it.
*/
const VARIANTS_SEGMENT_PATTERN = VARIANTS_PATH_PREFIX.split('')
.map((character) => encodedCharacterPattern(character))
.join('')
/**
* The pattern of a request pathname under the artifact namespace, after any
* base path. It admits every spelling that decodes to `/__variants/`, and it
* consumes the rest of the pathname, because a deployment anchors a rule at
* both ends.
*/
const VARIANTS_PREFIX_SOURCE_PATTERN = `${SEPARATOR_PATTERN}+${VARIANTS_SEGMENT_PATTERN}${SEPARATOR_PATTERN}.*$`
/**
* The rules that reject a request naming a static variant combination itself.
*
* They run before the files and before every user rewrite, and after the proxy.
* A request for an artifact path, or one carrying the query parameter that
* routing derives from the prefix, is admitted only when the proxy marked it.
* Otherwise the rules rewrite it to a pathname that no matcher serves, so the
* deployment answers 404. A deployment cannot answer with a status from a
* routing rule without also looking the pathname up, which is why the rejection
* is a rewrite.
*
* The destination lies under the artifact namespace itself, so the prefix rule
* also matches it. The rewrite it then produces names the same pathname.
*
* The query rules name every spelling of the parameter that a route would
* normalize into `NEXT_VARIANTS_QUERY_PARAM`.
*/
export function buildVariantsRejectionRoutes(
basePath: string
): VariantsRejectionRoute[] {
const basePathPattern =
basePath && basePath !== '/'
? escapeStringRegexp(path.posix.join('/', basePath))
: ''
const destination = path.posix.join('/', basePath, VARIANTS_NOT_ROUTED_PATH)
const missing: RouteHas[] = [
{ type: 'header', key: NEXT_VARIANTS_PREFIX_HEADER },
]
return [
{
source: `/${VARIANTS_PATH_PREFIX}/:path*`,
sourceRegex: `^${basePathPattern}${VARIANTS_PREFIX_SOURCE_PATTERN}`,
destination,
has: undefined,
missing,
},
...VARIANTS_SELECTOR_QUERY_KEYS.map(
(key): VariantsRejectionRoute => ({
source: '/:path*',
sourceRegex: '^/.*$',
destination,
has: [{ type: 'query', key }],
missing,
})
),
]
}
import { existsSync } from 'node:fs'
import path from 'node:path'
import { VARIANTS_PATH_PREFIX } from '../../lib/constants'
/**
* Returns true when a route pathname lies in the artifact namespace
* `/__variants/`, which Variants reserves. Every route matcher excludes the
* namespace, so a page there could never be served, and a prerendered path at
* the pathname that routing rewrites a rejected request to would answer that
* request with content.
*/
export function isVariantsReservedPathname(pathname: string): boolean {
return pathname.startsWith(`/${VARIANTS_PATH_PREFIX}/`)
}
/**
* Throws when a route or a generated path uses a reserved pathname. The build
* calls this for every route it discovers and every path it prerenders.
*/
export function assertNotVariantsReservedPathname(
pathname: string,
origin: string
): void {
if (isVariantsReservedPathname(pathname)) {
throw new Error(
`The path "${pathname}" from ${origin} is reserved by \`experimental.variants\`. ` +
`Paths under "/${VARIANTS_PATH_PREFIX}/" cannot be routes.`
)
}
}
/**
* Throws when the public directory has an entry named after the artifact
* namespace. A public file is served by path before any route, so a file under
* that entry would shadow an artifact or answer a rejected request.
*/
export function assertNoVariantsReservedPublicEntries(publicDir: string): void {
if (existsSync(path.join(publicDir, VARIANTS_PATH_PREFIX))) {
throw new Error(
`The public directory has an entry at "/${VARIANTS_PATH_PREFIX}", which is reserved by \`experimental.variants\`. Remove or rename it.`
)
}
}
...@@ -17,7 +17,8 @@ import { getNamedRouteRegex } from '../../shared/lib/router/utils/route-regex' ...@@ -17,7 +17,8 @@ import { getNamedRouteRegex } from '../../shared/lib/router/utils/route-regex'
* *
* `page` stays unprefixed and names the module. The regexes carry the prefix, * `page` stays unprefixed and names the module. The regexes carry the prefix,
* and the named regex captures the hash as `nxtV`. One alias matches every hash * and the named regex captures the hash as `nxtV`. One alias matches every hash
* for a page. * for a page. The hash is matched as `[0-9a-z]+`, the shape `hashVariants`
* produces, so the pathname of a rejected request cannot match an alias.
*/ */
export function buildVariantRouteAliases( export function buildVariantRouteAliases(
pages: Iterable<string> pages: Iterable<string>
...@@ -33,12 +34,12 @@ export function buildVariantRouteAliases( ...@@ -33,12 +34,12 @@ export function buildVariantRouteAliases(
sourcePage: undefined, sourcePage: undefined,
regex: normalizeRouteRegex(routeRegex.re.source).replace( regex: normalizeRouteRegex(routeRegex.re.source).replace(
page === '/' ? '^/' : '^', page === '/' ? '^/' : '^',
`^/${VARIANTS_PATH_PREFIX}/[^/]+` `^/${VARIANTS_PATH_PREFIX}/[0-9a-z]+`
), ),
routeKeys: routeRegex.routeKeys, routeKeys: routeRegex.routeKeys,
namedRegex: routeRegex.namedRegex.replace( namedRegex: routeRegex.namedRegex.replace(
page === '/' ? '^/' : '^', page === '/' ? '^/' : '^',
`^/${VARIANTS_PATH_PREFIX}/(?<${NEXT_VARIANTS_QUERY_PARAM}>[^/]+)` `^/${VARIANTS_PATH_PREFIX}/(?<${NEXT_VARIANTS_QUERY_PARAM}>[0-9a-z]+)`
), ),
skipInternalRouting: true, skipInternalRouting: true,
variantsPrefixed: true, variantsPrefixed: true,
......
...@@ -67,6 +67,31 @@ export const NEXT_VARIANTS_QUERY_PARAM = 'nxtV' ...@@ -67,6 +67,31 @@ export const NEXT_VARIANTS_QUERY_PARAM = 'nxtV'
*/ */
export const NEXT_VARIANTS_HEADER = 'x-next-internal-variants' export const NEXT_VARIANTS_HEADER = 'x-next-internal-variants'
/**
* Marks a request whose variants prefix the application's own proxy wrote. A
* deployment's routing rules read it to admit such a prefix, and to reject a
* prefix or a `NEXT_VARIANTS_QUERY_PARAM` that a client supplied.
*
* The `x-next-internal-` prefix is what makes the marker trustworthy: a
* deployment removes such a header from an incoming client request before it
* runs the proxy, and `filterInternalHeaders` does the same when self-hosting.
*/
export const NEXT_VARIANTS_PREFIX_HEADER = 'x-next-internal-variants-prefix'
/**
* The pathname that routing rewrites a rejected request to. A client can supply
* a variants prefix or a `NEXT_VARIANTS_QUERY_PARAM`, and a deployment's
* routing rules cannot answer such a request with a status directly. They send
* it here instead. Every route matcher and rewrite excludes the namespace under
* `VARIANTS_PATH_PREFIX`, so no output serves this pathname and the answer is a
* 404.
*
* The segment after the prefix contains a hyphen, which the hash alphabet
* `[0-9a-z]` does not. A matcher that captures a hash therefore cannot match
* this pathname either.
*/
export const VARIANTS_NOT_ROUTED_PATH = `${VARIANTS_PATH_PREFIX}/not-routed`
// if these change make sure we update the related // if these change make sure we update the related
// documentation as well // documentation as well
export const NEXT_CACHE_TAG_MAX_ITEMS = 128 export const NEXT_CACHE_TAG_MAX_ITEMS = 128
......
...@@ -10,7 +10,10 @@ import { ...@@ -10,7 +10,10 @@ import {
NEXT_HTML_REQUEST_ID_HEADER, NEXT_HTML_REQUEST_ID_HEADER,
NEXT_REQUEST_ID_HEADER, NEXT_REQUEST_ID_HEADER,
} from '../../client/components/app-router-headers' } from '../../client/components/app-router-headers'
import { NEXT_VARIANTS_HEADER } from '../../lib/constants' import {
NEXT_VARIANTS_HEADER,
NEXT_VARIANTS_PREFIX_HEADER,
} from '../../lib/constants'
import { import {
HeadersAdapter, HeadersAdapter,
type ReadonlyHeaders, type ReadonlyHeaders,
...@@ -46,6 +49,7 @@ const HIDDEN_REQUEST_HEADERS: ReadonlySet<string> = new Set( ...@@ -46,6 +49,7 @@ const HIDDEN_REQUEST_HEADERS: ReadonlySet<string> = new Set(
[ [
...FLIGHT_HEADERS, ...FLIGHT_HEADERS,
NEXT_VARIANTS_HEADER, NEXT_VARIANTS_HEADER,
NEXT_VARIANTS_PREFIX_HEADER,
// The client sends these dev-only request IDs so the server can route debug // The client sends these dev-only request IDs so the server can route debug
// information back to the originating request. Like the flight headers, // information back to the originating request. Like the flight headers,
// they are internal plumbing. // they are internal plumbing.
......
...@@ -30,7 +30,13 @@ import { detectDomainLocale } from '../../../shared/lib/i18n/detect-domain-local ...@@ -30,7 +30,13 @@ import { detectDomainLocale } from '../../../shared/lib/i18n/detect-domain-local
import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path' import { normalizeLocalePath } from '../../../shared/lib/i18n/normalize-locale-path'
import { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix' import { removePathPrefix } from '../../../shared/lib/router/utils/remove-path-prefix'
import { NextDataPathnameNormalizer } from '../../normalizers/request/next-data' import { NextDataPathnameNormalizer } from '../../normalizers/request/next-data'
import { splitVariantsPrefix } from '../../variants/prefix' import {
getVariantsNotRoutedPathname,
hasVariantsPathPrefix,
hasVariantsSelector,
splitVariantsPrefix,
VARIANTS_SELECTOR_QUERY_KEYS,
} from '../../variants/prefix'
import { NEXT_VARIANTS_QUERY_PARAM } from '../../../lib/constants' import { NEXT_VARIANTS_QUERY_PARAM } from '../../../lib/constants'
import { BasePathPathnameNormalizer } from '../../normalizers/request/base-path' import { BasePathPathnameNormalizer } from '../../normalizers/request/base-path'
...@@ -142,6 +148,37 @@ export function getResolveRoutes( ...@@ -142,6 +148,37 @@ export function getResolveRoutes(
let parsedUrl = parseUrl(req.url || '') as NextUrlWithParsedQuery let parsedUrl = parseUrl(req.url || '') as NextUrlWithParsedQuery
let didRewrite = false let didRewrite = false
// Reject a request that names a static variant combination itself, through
// the artifact prefix or through the query parameter that routing derives
// from the prefix. Only the proxy writes the prefix, and only the rewrite
// branch below writes the parameter, both after this point. Either one on
// an incoming request therefore came from the client, and it would select
// an artifact that this request did not resolve to.
//
// This runs before every route, so it also covers a route that declares
// combinations while the proxy's `config.matcher` leaves it out. The
// request is answered as a 404 like any other request for a pathname that
// no route serves. In minimal mode the platform in front performs this
// check and writes the parameter itself, so this must not act there.
if (
config.experimental.variants &&
!opts.minimalMode &&
(hasVariantsPathPrefix(parsedUrl.pathname || '/', config.basePath) ||
hasVariantsSelector(Object.keys(parsedUrl.query)))
) {
parsedUrl.pathname = getVariantsNotRoutedPathname(config.basePath)
for (const key of VARIANTS_SELECTOR_QUERY_KEYS) {
delete parsedUrl.query[key]
}
return {
parsedUrl,
resHeaders,
finished: true,
}
}
const urlParts = (req.url || '').split('?', 1) const urlParts = (req.url || '').split('?', 1)
const urlNoQuery = urlParts[0] const urlNoQuery = urlParts[0]
...@@ -760,17 +797,9 @@ export function getResolveRoutes( ...@@ -760,17 +797,9 @@ export function getResolveRoutes(
// locale included. // locale included.
// //
// This is the only place the prefix is removed, and only a // This is the only place the prefix is removed, and only a
// destination a proxy rewrote to reaches it. A prefix a client // destination a proxy rewrote to reaches it. A prefix or a
// wrote therefore stays on the pathname and matches no route, so // `NEXT_VARIANTS_QUERY_PARAM` that a client sent is rejected at
// a self-hosted server answers 404. // the start of routing, before the proxy runs.
//
// TODO(variants): reject a prefix and a
// `NEXT_VARIANTS_QUERY_PARAM` that arrive from a client. A
// deployment serves an artifact by path before any function runs,
// so a client reaches one there whatever this code does. The
// query write below overwrites a client's value only where a
// prefix is present, so a request the proxy matched no
// combination for keeps it.
if (config.experimental?.variants) { if (config.experimental?.variants) {
const withoutPrefix = splitVariantsPrefix( const withoutPrefix = splitVariantsPrefix(
parsedUrl.pathname || '', parsedUrl.pathname || '',
......
import { NEXT_VARIANTS_HEADER } from '../../../lib/constants' import {
NEXT_VARIANTS_HEADER,
NEXT_VARIANTS_PREFIX_HEADER,
} from '../../../lib/constants'
export const ipcForbiddenHeaders = [ export const ipcForbiddenHeaders = [
'accept-encoding', 'accept-encoding',
...@@ -54,6 +57,7 @@ const INTERNAL_HEADERS = [ ...@@ -54,6 +57,7 @@ const INTERNAL_HEADERS = [
'x-next-resume-state-length', 'x-next-resume-state-length',
'next-resume', 'next-resume',
NEXT_VARIANTS_HEADER, NEXT_VARIANTS_HEADER,
NEXT_VARIANTS_PREFIX_HEADER,
] ]
export const filterInternalHeaders = ( export const filterInternalHeaders = (
......
import { VARIANTS_PATH_PREFIX } from '../../lib/constants' import {
NEXT_INTERCEPTION_MARKER_PREFIX,
NEXT_QUERY_PARAM_PREFIX,
NEXT_VARIANTS_QUERY_PARAM,
VARIANTS_NOT_ROUTED_PATH,
VARIANTS_PATH_PREFIX,
} from '../../lib/constants'
import { hashVariants } from './encoding' import { hashVariants } from './encoding'
/** /**
...@@ -11,6 +17,21 @@ const VARIANTS_PREFIX_PATTERN = new RegExp( ...@@ -11,6 +17,21 @@ const VARIANTS_PREFIX_PATTERN = new RegExp(
`^/${VARIANTS_PATH_PREFIX}/([0-9a-z]+)` `^/${VARIANTS_PATH_PREFIX}/([0-9a-z]+)`
) )
/**
* The query keys that name a static variant combination once routing has
* processed them. Routing writes `NEXT_VARIANTS_QUERY_PARAM` itself, and it
* writes it after a request arrives, so any of these keys on an incoming
* request came from the client.
*
* The prefixed spellings are listed because `normalizeNextQueryParam` removes
* one `nxtP` or `nxtI` prefix from a query key before a route reads it.
*/
export const VARIANTS_SELECTOR_QUERY_KEYS: readonly string[] = [
NEXT_VARIANTS_QUERY_PARAM,
`${NEXT_QUERY_PARAM_PREFIX}${NEXT_VARIANTS_QUERY_PARAM}`,
`${NEXT_INTERCEPTION_MARKER_PREFIX}${NEXT_VARIANTS_QUERY_PARAM}`,
]
/** /**
* Splits a base path off a pathname, and returns the two parts. * Splits a base path off a pathname, and returns the two parts.
* *
...@@ -59,6 +80,69 @@ export function splitVariantsPrefix( ...@@ -59,6 +80,69 @@ export function splitVariantsPrefix(
} }
} }
/**
* Returns true when a pathname names the artifact namespace after any base
* path. The namespace is `/__variants/` and everything under it.
*
* Unlike `splitVariantsPrefix`, which parses a prefix the framework wrote, this
* checks a pathname a client sent. It therefore also decodes the pathname and
* normalizes its slashes, because a server does the same before it looks an
* artifact up, so an encoded spelling reaches the same artifact as the plain
* one.
*/
export function hasVariantsPathPrefix(
pathname: string,
basePath: string | undefined
): boolean {
for (const candidate of [pathname, decodePathname(pathname)]) {
if (candidate === null) {
continue
}
const normalized = candidate.replace(/\\/g, '/').replace(/\/{2,}/g, '/')
const [, rest] = splitBasePath(normalized, basePath)
if (rest.startsWith(`/${VARIANTS_PATH_PREFIX}/`)) {
return true
}
}
return false
}
function decodePathname(pathname: string): string | null {
try {
return decodeURIComponent(pathname)
} catch {
return null
}
}
/**
* Returns true when the query keys name a static variant combination.
*/
export function hasVariantsSelector(queryKeys: Iterable<string>): boolean {
for (const key of queryKeys) {
if (VARIANTS_SELECTOR_QUERY_KEYS.includes(key)) {
return true
}
}
return false
}
/**
* The pathname that routing rewrites a rejected request to, after any base
* path.
*/
export function getVariantsNotRoutedPathname(
basePath: string | undefined
): string {
const base = basePath && basePath !== '/' ? basePath : ''
return `${base}/${VARIANTS_NOT_ROUTED_PATH}`
}
/** /**
* Inserts the prefix into a pathname, after any base path. * Inserts the prefix into a pathname, after any base path.
*/ */
......
...@@ -28,14 +28,22 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.exte ...@@ -28,14 +28,22 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.exte
import { createWorkStore } from '../async-storage/work-store' import { createWorkStore } from '../async-storage/work-store'
import { workAsyncStorage } from '../app-render/work-async-storage.external' import { workAsyncStorage } from '../app-render/work-async-storage.external'
import { InvariantError } from '../../shared/lib/invariant-error' import { InvariantError } from '../../shared/lib/invariant-error'
import { NEXT_VARIANTS_HEADER } from '../../lib/constants' import {
NEXT_VARIANTS_HEADER,
NEXT_VARIANTS_PREFIX_HEADER,
} from '../../lib/constants'
import type { VariantsManifest } from '../variants/manifest' import type { VariantsManifest } from '../variants/manifest'
import { getProxyTarget, getTargetRoutePathname } from '../variants/target' import { getProxyTarget, getTargetRoutePathname } from '../variants/target'
import { findVariantGroupsForPathname } from '../variants/manifest' import { findVariantGroupsForPathname } from '../variants/manifest'
import { findMatchingVariantCombination } from '../variants/combinations' import { findMatchingVariantCombination } from '../variants/combinations'
import { decodeVariants, encodeVariants } from '../variants/encoding' import { decodeVariants, encodeVariants } from '../variants/encoding'
import { insertVariantsPrefix } from '../variants/prefix' import {
getVariantsNotRoutedPathname,
hasVariantsPathPrefix,
hasVariantsSelector,
insertVariantsPrefix,
} from '../variants/prefix'
import type { ResolvedCacheLifeProfiles } from '../config-shared' import type { ResolvedCacheLifeProfiles } from '../config-shared'
import { NEXT_ROUTER_PREFETCH_HEADER } from '../../client/components/app-router-headers' import { NEXT_ROUTER_PREFETCH_HEADER } from '../../client/components/app-router-headers'
import { getTracer } from '../lib/trace/tracer' import { getTracer } from '../lib/trace/tracer'
...@@ -185,6 +193,38 @@ function encodeUndeclaredVariants( ...@@ -185,6 +193,38 @@ function encodeUndeclaredVariants(
return Object.keys(undeclared).length > 0 ? encodeVariants(undeclared) : null return Object.keys(undeclared).length > 0 ? encodeVariants(undeclared) : null
} }
/**
* Returns the URL to rewrite a request to when the request names a static
* variant combination itself, and null when it does not.
*
* Only the proxy writes the artifact prefix, and only routing writes the query
* parameter it becomes, so either one on an incoming request came from the
* client. The check reads the URL as it arrived, because the proxy's rewrite
* target can drop or normalize the client's query, and a deployment merges the
* incoming query back into the destination.
*
* The rejected request is rewritten rather than answered, because a rewrite is
* the one effect of a proxy response that a deployment's routing rules act on.
* Every route matcher and rewrite excludes the destination, so the deployment
* answers 404. A self-hosted server rejects such a request before the proxy
* runs, so it never reaches this code.
*/
function getRejectedVariantsTarget(
requestUrl: string,
basePath: string | undefined
): URL | null {
const incoming = new URL(requestUrl)
if (
!hasVariantsPathPrefix(incoming.pathname, basePath) &&
!hasVariantsSelector(incoming.searchParams.keys())
) {
return null
}
return new URL(getVariantsNotRoutedPathname(basePath), incoming.origin)
}
let testApisIntercepted = false let testApisIntercepted = false
function ensureTestApisIntercepted() { function ensureTestApisIntercepted() {
...@@ -210,6 +250,22 @@ export async function adapter( ...@@ -210,6 +250,22 @@ export async function adapter(
const isEdgeRendering = const isEdgeRendering =
typeof (globalThis as any).__BUILD_MANIFEST !== 'undefined' typeof (globalThis as any).__BUILD_MANIFEST !== 'undefined'
const isMiddleware =
params.page === '/middleware' ||
params.page === '/src/middleware' ||
params.page === '/proxy' ||
params.page === '/src/proxy'
// Read before the URL below is normalized, so that the check sees the request
// as the client sent it.
const rejectedVariantsTarget =
process.env.__NEXT_VARIANTS && isMiddleware && !isEdgeRendering
? getRejectedVariantsTarget(
params.request.url,
params.request.nextConfig?.basePath
)
: null
params.request.url = normalizeRscURL(params.request.url) params.request.url = normalizeRscURL(params.request.url)
const requestURL = params.bypassNextUrl const requestURL = params.bypassNextUrl
...@@ -345,18 +401,14 @@ export async function adapter( ...@@ -345,18 +401,14 @@ export async function adapter(
let cookiesFromResponse let cookiesFromResponse
response = await propagator(request, () => { response = await propagator(request, () => {
// we only care to make async storage available for middleware // The proxy does not run for a request that names a static variant
const isMiddleware = // combination itself. The rewrite below rejects it.
params.page === '/middleware' || if (rejectedVariantsTarget) {
params.page === '/src/middleware' || return NextResponse.rewrite(rejectedVariantsTarget)
params.page === '/proxy' || }
params.page === '/src/proxy'
// we only care to make async storage available for middleware
if (isMiddleware) { if (isMiddleware) {
// if we're in an edge function, we only get a subset of `nextConfig` (no `experimental`),
// so we have to inject it via DefinePlugin.
// in `next start` this will be passed normally (see `NextNodeServer.runMiddleware`).
const waitUntil = event.waitUntil.bind(event) const waitUntil = event.waitUntil.bind(event)
const closeController = new CloseController() const closeController = new CloseController()
...@@ -556,11 +608,6 @@ export async function adapter( ...@@ -556,11 +608,6 @@ export async function adapter(
if (target && resolvedVariants) { if (target && resolvedVariants) {
const basePath = params.request.nextConfig?.basePath const basePath = params.request.nextConfig?.basePath
// TODO(variants): reject a request whose target already carries
// `NEXT_VARIANTS_QUERY_PARAM`. Only this code writes that parameter, so
// one already present came from the client. A deployment has to reject
// rather than remove it, because a rewrite merges the incoming query
// into the destination.
const groups = params.variantsManifest const groups = params.variantsManifest
? findVariantGroupsForPathname( ? findVariantGroupsForPathname(
params.variantsManifest, params.variantsManifest,
...@@ -586,9 +633,18 @@ export async function adapter( ...@@ -586,9 +633,18 @@ export async function adapter(
response.headers.set('x-middleware-rewrite', target.toString()) response.headers.set('x-middleware-rewrite', target.toString())
// TODO(variants): set a marker header saying this application's own // The marker says that this proxy wrote the prefix. A deployment's
// proxy wrote the prefix. A deployment needs one, because its routing // routing rules admit a prefixed path that carries it, and reject one
// rules read it to tell a prefix of ours from one a client invented. // that does not, because a client can request an artifact path
// directly. A client cannot supply the marker: a deployment removes
// every `x-next-internal-` header from an incoming request before the
// proxy runs.
setRequestHeaderOverride(
response,
requestHeaders,
NEXT_VARIANTS_PREFIX_HEADER,
'1'
)
} }
// The runtime tier is what travels on. The prefix carries the hash of // The runtime tier is what travels on. The prefix carries the hash of
......
...@@ -2,6 +2,7 @@ import { nextTestSetup } from 'e2e-utils' ...@@ -2,6 +2,7 @@ import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright' import type * as Playwright from 'playwright'
import { retry } from 'next-test-utils' import { retry } from 'next-test-utils'
import { createRouterAct } from 'router-act' import { createRouterAct } from 'router-act'
import { hashVariants } from 'next/dist/server/variants/encoding'
import { basePath, url } from '../variants/base-path' import { basePath, url } from '../variants/base-path'
// @force-gate turbopack && (!deploy || adapter) // @force-gate turbopack && (!deploy || adapter)
...@@ -30,6 +31,29 @@ describe('Variants on a root catch-all', () => { ...@@ -30,6 +31,29 @@ describe('Variants on a root catch-all', () => {
} }
}) })
it('should reject a client naming the combination, without the catch-all serving the request', async () => {
// A catch-all matches any pathname, so it would render the pathname that a
// rejected request is rewritten to, and the client would receive a page for
// it. The rejection has to hold with such a route present.
const declared = hashVariants({ 'theme@variants.ts': 'light' })
for (const pathname of [
`/__variants/${declared}/built`,
`/__variants/${declared}/document`,
`/built?nxtV=${declared}`,
`/document?nxtV=${declared}`,
]) {
const response = await next.fetch(url(pathname), {
headers: { cookie: 'theme=dark' },
})
const body = await response.text()
expect(response.status).toBe(404)
expect(body).not.toContain('id="slug"')
expect(body).not.toContain('id="theme"')
}
})
it('should resolve unenumerated catch-all params for each combination', async () => { it('should resolve unenumerated catch-all params for each combination', async () => {
for (const slug of ['document', 'nested/document']) { for (const slug of ['document', 'nested/document']) {
for (const theme of ['dark', 'light']) { for (const theme of ['dark', 'light']) {
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p id="page">page</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
variants: true,
},
}
module.exports = nextConfig
// `%5F` becomes an underscore in the route, so this page is at the pathname
// that routing reserves for a rejected request. A plain double underscore would
// make the folder private instead.
export default function Page() {
return <p id="page">page</p>
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
variants: true,
},
}
module.exports = nextConfig
// The route pattern is fine. One of its generated params names the pathname
// that routing reserves for a rejected request.
export function generateStaticParams() {
return [{ slug: ['ordinary'] }, { slug: ['__variants', 'not-routed'] }]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string[] }>
}) {
const { slug } = await params
return <p id="slug">{slug.join('/')}</p>
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
variants: true,
},
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
// Each case names a fixture that occupies a pathname routing reserves, and the
// part of the build error that names the offending file or route. The pathname
// is where routing sends a request that a client tried to name a combination
// for, so content there would answer such a request.
const cases: ReadonlyArray<readonly [fixture: string, expected: string]> = [
[
'reserved-route',
'The path "/__variants/not-routed" from app/%5F_variants/not-routed/page.tsx is reserved by `experimental.variants`.',
],
[
'reserved-static-param',
'The path "/__variants/not-routed" from the static params of "/[...slug]" is reserved by `experimental.variants`.',
],
[
'reserved-public',
'The public directory has an entry at "/__variants", which is reserved by `experimental.variants`.',
],
]
// Only a build reads every route and the public directory, so these are
// production-only. Variants are supported with Turbopack only.
// @force-gate turbopack && !dev
describe('a build occupying a path reserved by Variants', () => {
for (const [fixture, expected] of cases) {
describe(fixture, () => {
const { next, skipped } = nextTestSetup({
files: __dirname + `/fixtures/${fixture}`,
// The build is expected to fail, so nothing can start or deploy.
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
it('should fail the build and name the conflict', async () => {
const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1)
expect(cliOutput).toContain(expected)
})
})
}
})
...@@ -2,6 +2,7 @@ import { isNextDeploy, isNextDev, isNextStart, nextTestSetup } from 'e2e-utils' ...@@ -2,6 +2,7 @@ import { isNextDeploy, isNextDev, isNextStart, nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright' import type * as Playwright from 'playwright'
import { createRouterAct } from '../../../lib/router-act' import { createRouterAct } from '../../../lib/router-act'
import { findPort, retry } from 'next-test-utils' import { findPort, retry } from 'next-test-utils'
import { hashVariants } from 'next/dist/server/variants/encoding'
import { basePath, url } from './base-path' import { basePath, url } from './base-path'
import { startExternalServer } from './external-server.mjs' import { startExternalServer } from './external-server.mjs'
...@@ -779,10 +780,94 @@ describe('variants', () => { ...@@ -779,10 +780,94 @@ describe('variants', () => {
expect(await browser.elementByCss('#slug').text()).toBe('undeclared') expect(await browser.elementByCss('#slug').text()).toBe('undeclared')
}) })
// TODO(variants): cover that a client cannot name the combination it is describe('a client naming the combination it is served', () => {
// served, whether by supplying the prefix or the `nxtV` parameter. One change // `/enumerated/a` has a prerender for this combination, and it is not the
// covers a self-hosted server and a deployment alike, so the guards and these // one the cookies below resolve to. A request that is served it has picked
// tests belong together. // its own combination.
const declared = hashVariants({
'locale@variants.ts': 'en',
'theme@variants.ts': 'light',
})
// The request is rejected before any route renders, so the response carries
// no variant value and no marker of the routes involved. It is answered as
// a 404 like any request for a pathname no route serves.
async function expectRejected(
pathname: string,
init: Parameters<typeof next.fetch>[1] = {
headers: { cookie: 'theme=dark; locale=en' },
}
) {
const response = await next.fetch(url(pathname), init)
const body = await response.text()
expect(response.status).toBe(404)
expect(body).not.toContain('id="theme"')
expect(body).not.toContain('id="slug"')
}
it('should reject a supplied prefix', async () => {
await expectRejected(`/__variants/${declared}/enumerated/a`)
})
it('should reject a supplied prefix naming no combination', async () => {
// Every value would otherwise create a cache entry of its own.
await expectRejected('/__variants/zzzzz/enumerated/a')
})
it('should reject an encoded prefix', async () => {
// A server decodes a pathname before it looks an artifact up, so these
// spellings name the same artifact as the plain prefix.
await expectRejected(`/%5F%5Fvariants/${declared}/enumerated/a`)
await expectRejected(`/__%76ariants/${declared}/enumerated/a`)
await expectRejected(`//__variants/${declared}/enumerated/a`)
})
it('should reject a prefix on a route without dynamic segments', async () => {
await expectRejected(`/__variants/${declared}/paramless`)
})
it('should reject a supplied query parameter on a matched route', async () => {
// These cookies resolve a combination no group declares, so the proxy
// writes no prefix. The supplied parameter would be the only one present.
await expectRejected(`/enumerated/a?nxtV=${declared}`, {
headers: { cookie: 'theme=dark; locale=de' },
})
// These cookies resolve a declared combination. The proxy writes a prefix
// for it, and the supplied parameter must not travel beside it.
await expectRejected(`/enumerated/a?nxtV=${declared}`, {
headers: { cookie: 'theme=dark; locale=en' },
})
})
it('should reject every spelling of the query parameter', async () => {
// A route removes one `nxtP` or `nxtI` prefix from a query key before it
// reads the key, so these name the same parameter.
await expectRejected(`/enumerated/a?nxtPnxtV=${declared}`)
await expectRejected(`/enumerated/a?nxtInxtV=${declared}`)
await expectRejected('/enumerated/a?nxtV=')
await expectRejected('/enumerated/a?nxtV')
})
it('should reject the query parameter on a route the proxy does not match', async () => {
// The proxy runs only for the paths its `config.matcher` names, and a
// route can declare combinations while being left out. The rejection runs
// for every request, so it covers that route.
await expectRejected(`/unmatched-by-proxy?nxtV=${declared}`, {
headers: { cookie: 'theme=light; locale=en' },
})
})
it('should reject a supplied prefix on a payload request', async () => {
// The prefix names the artifact of a payload as it names the artifact of
// a document.
await expectRejected(`/__variants/${declared}/enumerated/a`, {
headers: { cookie: 'theme=dark; locale=en', rsc: '1' },
})
await expectRejected(`/__variants/${declared}/enumerated/a.rsc`)
})
})
it('should not expose the internal combination query parameter to the page', async () => { it('should not expose the internal combination query parameter to the page', async () => {
// A combination with an output reaches the origin as a query parameter. A // A combination with an output reaches the origin as a query parameter. A
......
...@@ -144,6 +144,112 @@ describe('adapter-variants', () => { ...@@ -144,6 +144,112 @@ describe('adapter-variants', () => {
`) `)
}) })
it('should reject a client naming the combination before any file or rewrite', () => {
const { beforeFiles } = fourCombinations.routing
const rejections = beforeFiles.filter(
(route) => route.destination === '/__variants/not-routed'
)
// One rule for the artifact prefix and one for each spelling of the query
// parameter, and every one of them admits only a request the proxy marked.
expect(rejections).toHaveLength(4)
expect(beforeFiles.slice(0, rejections.length)).toEqual(rejections)
for (const route of rejections) {
expect(route.missing).toEqual([
{ type: 'header', key: 'x-next-internal-variants-prefix' },
])
}
const [prefixRule, ...queryRules] = rejections
const prefixRegex = new RegExp(prefixRule.sourceRegex)
// The rule matches every spelling of the prefix that decodes to the same
// pathname, and nothing else.
for (const pathname of [
'/__variants/1eggkwr/concrete',
'/%5F%5Fvariants/1eggkwr/concrete',
'/__%76ariants/1eggkwr/concrete',
'//__variants/1eggkwr/concrete',
'/%2F__variants/1eggkwr/concrete',
]) {
expect(pathname).toMatch(prefixRegex)
}
for (const pathname of ['/__variants-extra/x', '/plain/__variants/x']) {
expect(pathname).not.toMatch(prefixRegex)
}
expect(queryRules.map((route) => route.has)).toEqual([
[{ type: 'query', key: 'nxtV' }],
[{ type: 'query', key: 'nxtPnxtV' }],
[{ type: 'query', key: 'nxtInxtV' }],
])
})
it('should exclude the rejection pathname from every matcher and rewrite', async () => {
const { routing } = fourCombinations
const matchers = [
...routing.beforeFiles.filter(
(route) => route.destination !== '/__variants/not-routed'
),
...routing.afterFiles,
...routing.fallback,
...routing.dynamicRoutes,
]
// The fixture has a rewrite in each phase and a catch-all fallback rewrite,
// so this covers a rewrite that would otherwise match the pathname.
expect(matchers.length).toBeGreaterThanOrEqual(3)
// The prefixed matchers capture a hash after the namespace, so the pathname
// is also checked with a page path behind it.
const pathnames = [
'/__variants/not-routed',
'/__variants/not-routed/',
'/__variants/not-routed.rsc',
'/__variants/not-routed.segments/_tree.segment.rsc',
'/__variants/not-routed/concrete',
'/__variants/not-routed/dynamic/x',
]
const matching = matchers.flatMap((route) =>
pathnames
.filter((pathname) => new RegExp(route.sourceRegex).test(pathname))
.map((pathname) => `${route.source} matches ${pathname}`)
)
expect(matching).toEqual([])
// The catch-all rewrite still matches an ordinary pathname, so the
// exclusion is what stops it above.
const fallback = routing.fallback[0]
expect(new RegExp(fallback.sourceRegex).test('/anything/else')).toBe(true)
// The deployment function resolves an artifact pathname to its page through
// the aliases in the routes manifest. Those capture a hash too, and the
// rejection pathname must not pass for one there either.
const manifest: {
dynamicRoutes: Array<{
page: string
regex: string
variantsPrefixed?: boolean
}>
} = await next.readJSON('.next/routes-manifest.json')
const aliases = manifest.dynamicRoutes.filter(
(route) => route.variantsPrefixed
)
expect(aliases.map((alias) => alias.page).sort()).toEqual([
'/concrete',
'/dynamic/[slug]',
])
for (const alias of aliases) {
const regex = new RegExp(alias.regex)
const pagePath = alias.page.replace('[slug]', 'x')
expect(regex.test(`/__variants/1eggkwr${pagePath}`)).toBe(true)
expect(regex.test(`/__variants/not-routed${pagePath}`)).toBe(false)
}
})
it('should leave prerenders unchanged by the collapse', () => { it('should leave prerenders unchanged by the collapse', () => {
// This option changes routing only. It must not merge or remove the // This option changes routing only. It must not merge or remove the
// per-combination prerender outputs themselves. // per-combination prerender outputs themselves.
......
...@@ -8,6 +8,15 @@ const nextConfig = { ...@@ -8,6 +8,15 @@ const nextConfig = {
collapseAdapterRoutes: process.env.COLLAPSE_ADAPTER_ROUTES === '1', collapseAdapterRoutes: process.env.COLLAPSE_ADAPTER_ROUTES === '1',
}, },
adapterPath: require.resolve('./my-adapter.mjs'), adapterPath: require.resolve('./my-adapter.mjs'),
// A rewrite in each phase, so the test can check that none of them matches
// the pathname a rejected request is rewritten to.
async rewrites() {
return {
beforeFiles: [{ source: '/before/:path*', destination: '/concrete' }],
afterFiles: [{ source: '/after/:path*', destination: '/concrete' }],
fallback: [{ source: '/:path*', destination: '/concrete' }],
}
},
} }
module.exports = nextConfig module.exports = nextConfig
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