Resolve variants in a proxy and read them during a render

A proxy is where a variant is resolved, because the decision has to be
made before anything decides what to serve. This change adds the wrapper
that runs it. For each request the wrapper finds the variants that the
target route reads, invokes their `decide` functions, rejects a value
that is not a string, and passes the values on. A project wires the
wrapper into its own `proxy.ts` for now, and the bundler will inject it
once the variants transform exists.

No route declares yet which combinations to prerender against, so
nothing is prerendered per combination. Every value is therefore
resolved per request, and every read of one happens at request time.

The values reach the origin in `x-next-internal-variants`. That prefix
is reserved for the routing layer of a deployment, and
`filterInternalHeaders` strips such a header when self-hosting, so a
client cannot supply the values itself.

The route module reads the header, and not the router server. The router
server sees the header when self-hosting, but a deployed request reaches
no Next.js code before the route module runs.

Which variants apply follows from the route that renders, and a rewrite
changes that route, so the wrapper resolves against the rewrite target
and not the incoming path. A base path belongs to a request and not to a
route, so it comes off the target before the route table is consulted.

A resolved value reaches a render through the request store, and it
resolves at the runtime stage. No cache key includes a variant, so
nothing a render caches may hold a variant value. A route that the
`config.matcher` of the proxy omits resolves nothing, and a read of a
variant there fails.
parent d8b7334a
...@@ -23,6 +23,8 @@ import { ...@@ -23,6 +23,8 @@ import {
setRequestMeta, setRequestMeta,
} from '../../server/request-meta' with { 'turbopack-transition': 'next-server-utility' } } from '../../server/request-meta' with { 'turbopack-transition': 'next-server-utility' }
import { BaseServerSpan } from '../../server/lib/trace/constants' with { 'turbopack-transition': 'next-server-utility' } import { BaseServerSpan } from '../../server/lib/trace/constants' with { 'turbopack-transition': 'next-server-utility' }
import { NEXT_VARIANTS_HEADER } from '../../lib/constants' with { 'turbopack-transition': 'next-server-utility' }
import { decodeVariants } from '../../server/variants/encoding' with { 'turbopack-transition': 'next-server-utility' }
import { stripFlightHeaders } from '../../server/app-render/strip-flight-headers' with { 'turbopack-transition': 'next-server-utility' } import { stripFlightHeaders } from '../../server/app-render/strip-flight-headers' with { 'turbopack-transition': 'next-server-utility' }
import { import {
NodeNextRequest, NodeNextRequest,
...@@ -813,6 +815,23 @@ export function createAppPageEntrypoint({ ...@@ -813,6 +815,23 @@ export function createAppPageEntrypoint({
incrementalCache?.resetRequestCache() incrementalCache?.resetRequestCache()
;(globalThis as any).__incrementalCache = incrementalCache ;(globalThis as any).__incrementalCache = incrementalCache
// The variants that a proxy resolved for this request.
//
// The route module reads the header, and not the router server. The
// router server sees the header when self-hosting. A deployed request
// reaches no Next.js code before the route module runs.
//
// The flag gates the read, so that a project without variants compiles
// none of it.
const encodedVariants = process.env.__NEXT_VARIANTS
? req.headers[NEXT_VARIANTS_HEADER]
: undefined
const resolvedVariants =
typeof encodedVariants === 'string'
? decodeVariants(encodedVariants)
: null
const doRender = async ({ const doRender = async ({
span, span,
postponed, postponed,
...@@ -851,6 +870,7 @@ export function createAppPageEntrypoint({ ...@@ -851,6 +870,7 @@ export function createAppPageEntrypoint({
), ),
fallbackRouteParams, fallbackRouteParams,
renderOpts: { renderOpts: {
variants: resolvedVariants,
App: () => null, App: () => null,
Document: () => null, Document: () => null,
pageConfig: {}, pageConfig: {},
......
...@@ -29,6 +29,16 @@ export const NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER = ...@@ -29,6 +29,16 @@ export const NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER =
export const NEXT_RESUME_HEADER = 'next-resume' export const NEXT_RESUME_HEADER = 'next-resume'
export const NEXT_RESUME_STATE_LENGTH_HEADER = 'x-next-resume-state-length' export const NEXT_RESUME_STATE_LENGTH_HEADER = 'x-next-resume-state-length'
/**
* Carries the variant values that a request resolved, encoded.
*
* The `x-next-internal-` prefix makes the header safe to trust on arrival. A
* deployment reserves that prefix for its routing layer and removes such a
* header from an incoming client request. `filterInternalHeaders` does the same
* when self-hosting. A client therefore cannot resolve its own variants.
*/
export const NEXT_VARIANTS_HEADER = 'x-next-internal-variants'
// 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
......
...@@ -3018,6 +3018,7 @@ async function renderAppPage( ...@@ -3018,6 +3018,7 @@ async function renderAppPage(
res, res,
url, url,
rootParams, rootParams,
renderOpts.variants ?? null,
implicitTags, implicitTags,
renderOpts.onUpdateCookies, renderOpts.onUpdateCookies,
renderOpts.previewProps, renderOpts.previewProps,
...@@ -6733,6 +6734,7 @@ export async function runValidationInDevFromSnapshot( ...@@ -6733,6 +6734,7 @@ export async function runValidationInDevFromSnapshot(
search: message.request.urlSearch, search: message.request.urlSearch,
}, },
rootParams: message.request.rootParams, rootParams: message.request.rootParams,
variants: message.request.variants,
implicitTags, implicitTags,
resumeDataCache: null, resumeDataCache: null,
previewProps: undefined, previewProps: undefined,
...@@ -8383,6 +8385,8 @@ async function validateInstantConfigInBuildWithSample( ...@@ -8383,6 +8385,8 @@ async function validateInstantConfigInBuildWithSample(
userspaceMutableCookies: unusedMutableCookies, userspaceMutableCookies: unusedMutableCookies,
draftMode, draftMode,
rootParams: sampleRootParams, rootParams: sampleRootParams,
// TODO(variants): Define variants for instant validation.
variants: null,
validationSamples, validationSamples,
validationSampleTracking: createValidationSampleTracking(), validationSampleTracking: createValidationSampleTracking(),
// This will be set when rendering // This will be set when rendering
......
...@@ -50,6 +50,7 @@ export interface DevValidationRequestSnapshot { ...@@ -50,6 +50,7 @@ export interface DevValidationRequestSnapshot {
urlPathname: string urlPathname: string
urlSearch: string urlSearch: string
rootParams: Params rootParams: Params
variants: Record<string, string> | null
isDraftMode: boolean isDraftMode: boolean
isHmrRefresh: boolean isHmrRefresh: boolean
hmrRefreshHash: string | undefined hmrRefreshHash: string | undefined
......
...@@ -72,6 +72,7 @@ export async function buildDevValidationSnapshot( ...@@ -72,6 +72,7 @@ export async function buildDevValidationSnapshot(
urlPathname: requestStore.url.pathname, urlPathname: requestStore.url.pathname,
urlSearch: requestStore.url.search, urlSearch: requestStore.url.search,
rootParams: requestStore.rootParams, rootParams: requestStore.rootParams,
variants: requestStore.variants,
isDraftMode: requestStore.draftMode.isEnabled, isDraftMode: requestStore.draftMode.isEnabled,
isHmrRefresh: requestStore.isHmrRefresh ?? false, isHmrRefresh: requestStore.isHmrRefresh ?? false,
hmrRefreshHash: requestStore.hmrRefreshHash, hmrRefreshHash: requestStore.hmrRefreshHash,
......
...@@ -92,6 +92,12 @@ export type ServerOnInstrumentationRequestError = ( ...@@ -92,6 +92,12 @@ export type ServerOnInstrumentationRequestError = (
) => void | Promise<void> ) => void | Promise<void>
export interface RenderOptsPartial { export interface RenderOptsPartial {
/**
* The variants that the request resolved. The render puts them on the
* request store. Absent for a render that has none.
*/
variants?: Record<string, string> | null
dir?: string dir?: string
previewProps: __ApiPreviewProps | undefined previewProps: __ApiPreviewProps | undefined
err?: Error | null err?: Error | null
......
...@@ -64,6 +64,12 @@ export interface RequestStore extends CommonWorkUnitStore { ...@@ -64,6 +64,12 @@ export interface RequestStore extends CommonWorkUnitStore {
readonly rootParams: Params readonly rootParams: Params
/**
* The variants that this request resolved, keyed by variant identity, for
* example `theme@variants.ts`. It is null when the request resolved none.
*/
readonly variants: Record<string, string> | null
/** /**
* The resume data cache for this request. Either a mutable * The resume data cache for this request. Either a mutable
* `PrerenderResumeDataCache` (e.g. during a dev warmup that fills caches) or * `PrerenderResumeDataCache` (e.g. during a dev warmup that fills caches) or
......
...@@ -135,6 +135,12 @@ export type RequestStoreInputs = { ...@@ -135,6 +135,12 @@ export type RequestStoreInputs = {
onUpdateCookies: ((cookies: string[]) => void) | undefined onUpdateCookies: ((cookies: string[]) => void) | undefined
url: { pathname: string; search?: string } url: { pathname: string; search?: string }
rootParams: Params rootParams: Params
/**
* The variants that this request resolved. This becomes `variants` on the
* store.
*/
variants: Record<string, string> | null
implicitTags: ImplicitTags implicitTags: ImplicitTags
resumeDataCache: ResumeDataCache | null resumeDataCache: ResumeDataCache | null
previewProps: WrapperRenderOpts['previewProps'] previewProps: WrapperRenderOpts['previewProps']
...@@ -187,6 +193,7 @@ export function createRequestStoreForRender( ...@@ -187,6 +193,7 @@ export function createRequestStoreForRender(
res: RequestContext['res'], res: RequestContext['res'],
url: RequestContext['url'], url: RequestContext['url'],
rootParams: Params, rootParams: Params,
variants: Record<string, string> | null,
implicitTags: RequestContext['implicitTags'], implicitTags: RequestContext['implicitTags'],
onUpdateCookies: RenderOpts['onUpdateCookies'], onUpdateCookies: RenderOpts['onUpdateCookies'],
previewProps: WrapperRenderOpts['previewProps'], previewProps: WrapperRenderOpts['previewProps'],
...@@ -209,6 +216,7 @@ export function createRequestStoreForRender( ...@@ -209,6 +216,7 @@ export function createRequestStoreForRender(
: undefined), : undefined),
url, url,
rootParams, rootParams,
variants,
implicitTags, implicitTags,
resumeDataCache, resumeDataCache,
previewProps, previewProps,
...@@ -234,6 +242,16 @@ export function createRequestStoreForAPI( ...@@ -234,6 +242,16 @@ export function createRequestStoreForAPI(
onUpdateCookies, onUpdateCookies,
url, url,
rootParams: {}, rootParams: {},
// Two callers share this store, and no variants means something different
// to each. The edge adapter builds one for the proxy itself, which is the
// code that resolves variants, so none are resolved at that point.
//
// TODO(variants): the other caller is a route handler, which could read a
// variant. It has a route pattern the table keys on, the header reaches it
// like any other origin request, and the reader needs only a request store.
// Support means reading the header where the handler runs and passing the
// values through here, so this becomes a parameter rather than a constant.
variants: null,
implicitTags, implicitTags,
resumeDataCache: null, resumeDataCache: null,
previewProps, previewProps,
...@@ -258,6 +276,7 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore { ...@@ -258,6 +276,7 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore {
onUpdateCookies, onUpdateCookies,
url, url,
rootParams, rootParams,
variants,
implicitTags, implicitTags,
resumeDataCache, resumeDataCache,
previewProps, previewProps,
...@@ -284,6 +303,7 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore { ...@@ -284,6 +303,7 @@ export function createRequestStore(inputs: RequestStoreInputs): RequestStore {
// lets us avoid requiring an empty string for `search` in the type. // lets us avoid requiring an empty string for `search` in the type.
url: { pathname: url.pathname, search: url.search ?? '' }, url: { pathname: url.pathname, search: url.search ?? '' },
rootParams, rootParams,
variants,
get headers() { get headers() {
if (!cache.headers) { if (!cache.headers) {
// Seal the headers object that'll freeze out any methods that could // Seal the headers object that'll freeze out any methods that could
......
...@@ -163,6 +163,9 @@ export async function probeUseCache(msg: ProbeMessage): Promise<boolean> { ...@@ -163,6 +163,9 @@ export async function probeUseCache(msg: ProbeMessage): Promise<boolean> {
onUpdateCookies: undefined, onUpdateCookies: undefined,
url: { pathname: msg.request.urlPathname, search: msg.request.urlSearch }, url: { pathname: msg.request.urlPathname, search: msg.request.urlSearch },
rootParams: msg.request.rootParams, rootParams: msg.request.rootParams,
// A `'use cache'` scope rejects a read of a variant, and this probe
// exercises only such scopes, so it needs no values.
variants: null,
implicitTags: { tags: [], expirationsByCacheKind: new Map() }, implicitTags: { tags: [], expirationsByCacheKind: new Map() },
resumeDataCache: null, resumeDataCache: null,
previewProps: undefined, previewProps: undefined,
......
import { NEXT_VARIANTS_HEADER } from '../../../lib/constants'
export const ipcForbiddenHeaders = [ export const ipcForbiddenHeaders = [
'accept-encoding', 'accept-encoding',
'keepalive', 'keepalive',
...@@ -51,6 +53,7 @@ const INTERNAL_HEADERS = [ ...@@ -51,6 +53,7 @@ const INTERNAL_HEADERS = [
'x-nextjs-data', 'x-nextjs-data',
'x-next-resume-state-length', 'x-next-resume-state-length',
'next-resume', 'next-resume',
NEXT_VARIANTS_HEADER,
] ]
export const filterInternalHeaders = ( export const filterInternalHeaders = (
......
...@@ -5,9 +5,13 @@ import { throwToInterruptStaticGeneration } from '../app-render/dynamic-renderin ...@@ -5,9 +5,13 @@ import { throwToInterruptStaticGeneration } from '../app-render/dynamic-renderin
import { import {
makeDynamicHangingPromise, makeDynamicHangingPromise,
makeRuntimeHangingPromise, makeRuntimeHangingPromise,
RENDER_STAGES_BY_DATA_KIND,
} from '../dynamic-rendering-utils' } from '../dynamic-rendering-utils'
import type { AdvanceableRenderStage } from '../app-render/staged-rendering'
import { workAsyncStorage } from '../app-render/work-async-storage.external' import { workAsyncStorage } from '../app-render/work-async-storage.external'
import type { WorkUnitStore } from '../app-render/work-unit-async-storage.external'
import { import {
getStagedRenderingController,
throwForMissingRequestStore, throwForMissingRequestStore,
workUnitAsyncStorage, workUnitAsyncStorage,
} from '../app-render/work-unit-async-storage.external' } from '../app-render/work-unit-async-storage.external'
...@@ -39,6 +43,33 @@ export interface Variant<T extends string = string> { ...@@ -39,6 +43,33 @@ export interface Variant<T extends string = string> {
readonly [VARIANT_DECIDE]: (request: NextRequest) => T | Promise<T> readonly [VARIANT_DECIDE]: (request: NextRequest) => T | Promise<T>
} }
export function getVariantKey(value: Variant<string>): string {
return value[VARIANT_KEY]
}
export function getVariantDecide(
value: Variant<string>
): (request: NextRequest) => string | Promise<string> {
return value[VARIANT_DECIDE]
}
/**
* Asserts that the value a `decide` function returned is a string.
*
* Any string is allowed, whatever characters it holds, because the transport
* encodes it. A value that is not a string is the one thing to reject: it would
* serialize into something that does not round-trip.
*/
export function assertValidVariantValue(key: string, value: unknown): string {
if (typeof value !== 'string') {
throw new Error(
`The variant \`${key}\` resolved to a ${typeof value} value. Variant values must be strings.`
)
}
return value
}
/** /**
* Defines a variant. * Defines a variant.
* *
...@@ -46,8 +77,8 @@ export interface Variant<T extends string = string> { ...@@ -46,8 +77,8 @@ export interface Variant<T extends string = string> {
* flags service. A route can be prerendered against a variant, in addition to * flags service. A route can be prerendered against a variant, in addition to
* its route params. * its route params.
* *
* The framework invokes `decide`, and user code never invokes it. The return * The framework invokes `decide`. User code calls the return value instead,
* value is the reader. A call to the reader during a render returns the value * which is the reader. A call to the reader during a render returns the value
* that the current request resolved. * that the current request resolved.
* *
* TODO(variants): `decide` receives the request only until it receives the * TODO(variants): `decide` receives the request only until it receives the
...@@ -88,6 +119,31 @@ export function unstable_variant<T extends string = string>( ...@@ -88,6 +119,31 @@ export function unstable_variant<T extends string = string>(
}) as Variant<T> }) as Variant<T>
} }
/**
* Resolves a variant value at the render stage that the value belongs to.
*
* A variant value must not appear in anything a render caches. No cache key
* names a variant, so no shell and no prerender may hold one. The runtime stage
* comes after all of them, so a value delayed to that stage stays out.
*
* A render without staged rendering produces no shell, so the value resolves at
* once.
*/
function resolveInStage(
workUnitStore: WorkUnitStore,
stage: AdvanceableRenderStage,
variantName: string,
value: string
): Promise<string> {
const stagedRendering = getStagedRenderingController(workUnitStore)
if (!stagedRendering) {
return Promise.resolve(value)
}
return stagedRendering.delayUntilStage(stage, variantName, value)
}
/** /**
* Reads the value that the current request resolved for a variant. * Reads the value that the current request resolved for a variant.
* *
...@@ -108,16 +164,28 @@ function readVariant(key: string): Promise<string> { ...@@ -108,16 +164,28 @@ function readVariant(key: string): Promise<string> {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'request': { case 'request': {
// A request resolves its variants before the render, and the values const value = workUnitStore.variants?.[key]
// reach the render through this store. A read finds nothing when the
// request resolved nothing. if (value !== undefined) {
// TODO(variants): a value that a combination declared belongs to an
// earlier stage, because the prerender of that combination can hold it.
// Only a value that no combination declared waits for the runtime
// stage.
return resolveInStage(
workUnitStore,
RENDER_STAGES_BY_DATA_KIND.runtimeLinkData,
variantName,
value
)
}
// A request resolves its variants before the render, and the values reach
// the render through this store. A read finds nothing when the request
// resolved nothing.
// //
// The message names no cause, on purpose. Resolution covers every route // The message names no cause, on purpose. Resolution covers every route
// that reads a variant, so no matcher configuration explains a missing // that reads a variant, so no matcher configuration explains a missing
// value. // value.
//
// TODO(variants): no code puts values on this store yet, so every read
// reaches this error.
throw new Error( throw new Error(
`Route ${workStore.route} read ${variantName}, but no value was resolved for this request.` `Route ${workStore.route} read ${variantName}, but no value was resolved for this request.`
) )
......
/**
* Serializes the variants resolved for a request to a canonical form. The
* entries are sorted by variant identity and written as JSON.
*
* The form is JSON and not `key=value&…`, because a value can contain a
* delimiter. Values travel in a header, so they are not restricted to a charset
* that excludes one, and an array of pairs stays unambiguous for any string.
*
* The entries are sorted by identity, and not left in the order they arrive in.
* A module namespace orders its exports by export name, and that order changes
* when each name is qualified with its module path. For example, `theme2@b.ts`
* sorts before `theme@a.ts`, but `theme` sorts before `theme2`. Anything derived
* from this form therefore has one spelling per set of values.
*/
export function canonicalizeVariants(variants: Record<string, string>): string {
return JSON.stringify(
Object.keys(variants)
.sort()
.map((key) => [key, variants[key]])
)
}
/**
* Encodes the resolved variants for transport in `NEXT_VARIANTS_HEADER`.
*
* This function percent-encodes the whole canonical form. The result holds only
* unreserved ASCII and `%xx` escapes, which is inside `\t\x20-\x7e`. Node's
* header validation and the ByteString conversion of `fetch` both accept that
* class. A variant value can therefore be any string, an emoji or a
* right-to-left script included.
*
* `encodeHeaderSafe` produces the same class with fewer escapes. This function
* does not use it. That function escapes only what it must, and leaves a
* literal `%` unchanged, so its result is not reversible:
*
* - `50%` fails to decode.
* - `100%2F` decodes to `100/`.
*
* Its own callers want that property, because they compare a canonical form.
* This encoding must reverse exactly, so it escapes every character. The result
* is about 1.6 times longer.
*
* This function uses percent-encoding and not base64, because base64 needs
* `Buffer`. The edge runtime that a proxy can run on has no `Buffer`.
*/
export function encodeVariants(variants: Record<string, string>): string {
return encodeURIComponent(canonicalizeVariants(variants))
}
/**
* Reverses `encodeVariants`.
*
* The function returns null for malformed input, and does not throw. Next.js
* strips this header from an incoming client request, so a bad value is a bug on
* our side rather than hostile input. A reader that reports the variant as unresolved
* gives a better error than a parse failure deep in the request pipeline.
*/
export function decodeVariants(encoded: string): Record<string, string> | null {
let parsed: unknown
try {
parsed = JSON.parse(decodeURIComponent(encoded))
} catch {
return null
}
if (!Array.isArray(parsed)) {
return null
}
const variants: Record<string, string> = {}
for (const entry of parsed) {
if (
!Array.isArray(entry) ||
entry.length !== 2 ||
typeof entry[0] !== 'string' ||
typeof entry[1] !== 'string'
) {
return null
}
variants[entry[0]] = entry[1]
}
return variants
}
import type { Variant } from '../request/variants'
import { isDynamicRoute } from '../../shared/lib/router/utils'
import { getRouteRegex } from '../../shared/lib/router/utils/route-regex'
import { sortPages } from '../../shared/lib/router/utils/sortable-routes'
/**
* The variants that each route reads, keyed by page.
*
* A route reads the variants that its own module graph reads, layouts included.
* This table names only those. A `decide` for any other variant produces a
* value that no code reads, and the request then sends that value to the origin
* for nothing.
*
* The keys are page patterns, and not regular expressions, because a project
* currently writes this table by hand.
*
* TODO(variants): the variants transform will build the table from the module
* graph instead.
*/
export type VariantsByRoute = Readonly<Record<string, ReadonlyArray<Variant>>>
interface RouteVariantMatchers {
staticRoutes: Readonly<Record<string, ReadonlyArray<Variant>>>
dynamicRoutes: ReadonlyArray<{
matcher: RegExp
variants: ReadonlyArray<Variant>
}>
}
/**
* Compiles the table into matchers.
*
* The function keeps concrete pages apart from dynamic ones, and consults them
* first, so that `/[slug]` cannot capture `/paramless`. Dynamic pages keep the
* order that `sortPages` gives them, which is the order that route matching
* uses everywhere else.
*/
export function compileRouteVariants(
variantsByRoute: VariantsByRoute
): RouteVariantMatchers {
const staticRoutes: Record<string, ReadonlyArray<Variant>> = {}
const dynamicPages: string[] = []
for (const page of Object.keys(variantsByRoute)) {
if (isDynamicRoute(page)) {
dynamicPages.push(page)
} else {
staticRoutes[page] = variantsByRoute[page]
}
}
return {
staticRoutes,
dynamicRoutes: sortPages(dynamicPages).map((page) => ({
matcher: getRouteRegex(page).re,
variants: variantsByRoute[page],
})),
}
}
/**
* The variants that the route for `pathname` reads.
*
* The result is empty when the table names none for that pathname. That is an
* ordinary answer, and the request then resolves nothing.
*/
export function findVariantsForPathname(
matchers: RouteVariantMatchers,
pathname: string
): ReadonlyArray<Variant> {
const staticVariants = matchers.staticRoutes[pathname]
if (staticVariants) {
return staticVariants
}
for (const { matcher, variants } of matchers.dynamicRoutes) {
if (matcher.test(pathname)) {
return variants
}
}
return []
}
/**
* The route that serves a request after the proxy of the user has run.
*
* The result is the rewrite target when the proxy rewrote the request, and the
* incoming URL otherwise. It is null when the target names another origin.
*/
export function getProxyTarget(
requestURL: URL,
response: Response
): URL | null {
const target = new URL(
response.headers.get('x-middleware-rewrite') ?? requestURL.toString()
)
return target.origin === requestURL.origin ? target : null
}
/**
* The route that a target pathname belongs to, without the base path.
*
* A base path belongs to a request. A route does not hold one, and neither do
* the keys of what the build writes about that route.
*/
export function getTargetRoutePathname(
targetPathname: string,
basePath: string | undefined
): string {
if (
!basePath ||
basePath === '/' ||
(targetPathname !== basePath && !targetPathname.startsWith(`${basePath}/`))
) {
return targetPathname
}
return targetPathname.slice(basePath.length) || '/'
}
import type { NextRequest } from '../web/spec-extension/request'
import type { Variant } from '../request/variants'
import type { VariantsByRoute } from './route-variants'
import { NEXT_VARIANTS_HEADER } from '../../lib/constants'
import { NextResponse } from '../web/spec-extension/response'
import {
assertValidVariantValue,
getVariantDecide,
getVariantKey,
} from '../request/variants'
import { compileRouteVariants, findVariantsForPathname } from './route-variants'
import { getProxyTarget, getTargetRoutePathname } from './target'
import { encodeVariants } from './encoding'
type ProxyResult = Response | undefined | null | void
type UserProxy = (request: NextRequest) => ProxyResult | Promise<ProxyResult>
/**
* Wraps the proxy of the user, and resolves the variants of each request.
*
* The proxy of the user runs first. Its rewrite decides which route serves the
* request, and therefore which variants apply. `userProxy` is absent when the
* project has no `proxy.ts`. That case needs no substitute, because this
* function then resolves variants and nothing else.
*
* This function sets the resolved values on its response, in
* `NEXT_VARIANTS_HEADER`, and the edge adapter sends them to the origin. The
* adapter computes the rewrite headers that a client reads, and it does that
* from the destination the proxy chose.
*
* TODO(variants): resolution belongs in the edge adapter, which already derives
* the target. It is here only while `decide` takes the request. Once `decide`
* takes the params of a route, resolving a variant needs the route match that
* produces them, and to do that here would mean matching the route in this
* wrapper while the adapter does the same work immediately afterwards. At that
* point this function keeps only the proxy of the user and passes the table
* through, and the response header goes away with it.
*/
export function wrapProxy(
variantsByRoute: VariantsByRoute,
userProxy?: UserProxy
) {
const matchers = compileRouteVariants(variantsByRoute)
return async function proxy(request: NextRequest): Promise<Response> {
const response =
(userProxy ? await userProxy(request) : undefined) ?? NextResponse.next()
// A redirect sends the client elsewhere, so no route renders this request
// and no variant applies to it. A rewrite is different. The rewritten route
// is the one that serves the request, so resolution continues below.
if (
response.headers.has('x-middleware-redirect') ||
response.headers.has('location')
) {
return response
}
// A rewrite decides which route renders, and each route reads its own
// variants. Resolution therefore uses the target of the proxy, and not the
// incoming path. A target on another origin renders no route of this
// application, so it has no variants to resolve.
const target = getProxyTarget(new URL(request.url), response)
if (!target) {
return response
}
// The table is keyed by route, and a route carries no base path, while the
// target does.
const values = await resolveVariants(
findVariantsForPathname(
matchers,
getTargetRoutePathname(target.pathname, request.nextUrl.basePath)
),
request
)
if (values === null) {
return response
}
response.headers.set(NEXT_VARIANTS_HEADER, values)
return response
}
}
/**
* Resolves the given variants and encodes them for transport. The result is
* null when the list is empty.
*
* This function validates each value at the point that produces it, so that the
* error names the variant whose `decide` returned it. A validation further down
* could only report the request.
*/
async function resolveVariants(
variants: ReadonlyArray<Variant>,
request: NextRequest
): Promise<string | null> {
if (variants.length === 0) {
return null
}
const values: Record<string, string> = {}
for (const variant of variants) {
const key = getVariantKey(variant)
const value = await getVariantDecide(variant)(request)
values[key] = assertValidVariantValue(key, value)
}
return encodeVariants(values)
}
...@@ -28,6 +28,8 @@ import { workUnitAsyncStorage } from '../app-render/work-unit-async-storage.exte ...@@ -28,6 +28,8 @@ 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 { getProxyTarget } from '../variants/target'
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'
...@@ -109,6 +111,50 @@ let propagator: <T>(request: NextRequestHint, fn: () => T) => T = ( ...@@ -109,6 +111,50 @@ let propagator: <T>(request: NextRequestHint, fn: () => T) => T = (
return tracer.withPropagatedContext(request.headers, fn, headersGetter) return tracer.withPropagatedContext(request.headers, fn, headersGetter)
} }
/**
* Sends one request header to the origin, from code that runs after a proxy.
*
* `x-middleware-override-headers` is not additive. It names the complete set of
* request headers that the origin receives, and the origin drops every header
* that the list omits. Where a proxy overrode nothing, this function therefore
* names every incoming header as well as the new one.
* `NextResponse.next({ request })` builds the same list when user code sets a
* request header.
*/
function setRequestHeaderOverride(
response: Response,
requestHeaders: Headers,
name: string,
value: string
): void {
const existingOverrides = response.headers.get(
'x-middleware-override-headers'
)
if (existingOverrides) {
response.headers.set(
'x-middleware-override-headers',
`${existingOverrides},${name}`
)
} else {
const names: string[] = []
for (const [key, headerValue] of requestHeaders) {
response.headers.set(`x-middleware-request-${key}`, headerValue)
names.push(key)
}
response.headers.set(
'x-middleware-override-headers',
[...names, name].join(',')
)
}
// This is written last, so that the value replaces an incoming header of the
// same name, whichever branch above named it.
response.headers.set(`x-middleware-request-${name}`, value)
}
let testApisIntercepted = false let testApisIntercepted = false
function ensureTestApisIntercepted() { function ensureTestApisIntercepted() {
...@@ -457,6 +503,35 @@ export async function adapter( ...@@ -457,6 +503,35 @@ export async function adapter(
} }
} }
if (response) {
/**
* The variants that a proxy resolved for this request.
*
* The wrapper sets them on its response. This code removes that header and
* sends the values as a request header override instead. The values then
* reach the origin, and neither the CDN nor the browser receives them.
*/
const encodedVariants = response.headers.get(NEXT_VARIANTS_HEADER)
if (encodedVariants) {
response.headers.delete(NEXT_VARIANTS_HEADER)
const target = getProxyTarget(requestURL, response)
// The target is null when the proxy rewrote the request to another
// origin. That origin renders no route of this application, and it does
// not remove an internal header, so this code drops the values.
if (target) {
setRequestHeaderOverride(
response,
requestHeaders,
NEXT_VARIANTS_HEADER,
encodedVariants
)
}
}
}
/** /**
* Always forward the `_rsc` search parameter to the rewritten URL for RSC requests, * Always forward the `_rsc` search parameter to the rewritten URL for RSC requests,
* unless it's already present. This is necessary to ensure that RSC hash validation * unless it's already present. This is necessary to ensure that RSC hash validation
......
/**
* Set by the `-base-path` wrappers, each of which assigns it and then requires
* a suite. Empty for a plain run.
*/
export const basePath = process.env.BASE_PATH ?? ''
/**
* A path as a client asks for it.
*
* A base path belongs to the request, not to the route. The build writes an
* artifact under the route's own path, and the manifests key it that way.
* Therefore only paths that go out over the wire get the prefix, and they go
* through here. Assertions about build output do not.
*/
export function url(pathname: string): string {
if (!basePath) {
return pathname
}
// The root of an app under a base path is the base path itself, with no
// trailing slash, which is also what a browser reports for it.
return pathname === '/' ? basePath : `${basePath}${pathname}`
}
import { createServer } from 'node:http'
/**
* Stands in for an origin outside this Next.js application, so that a test can
* exercise a proxy rewrite to another origin.
*
* The server records each request it receives. A test reads those records to
* assert that nothing variant-related reached an origin that does not remove an
* internal header.
*/
export async function startExternalServer(port) {
const receivedRequests = []
const server = createServer((request, response) => {
receivedRequests.push({ url: request.url, headers: request.headers })
response.writeHead(200, { 'content-type': 'text/html' })
response.end('<html><body><p id="external">external</p></body></html>')
})
await new Promise((resolve, reject) => {
server.once('error', reject)
server.listen(port, resolve)
})
return {
getReceivedRequests: () => receivedRequests,
cleanup: () => new Promise((resolve) => server.close(resolve)),
}
}
import { Suspense } from 'react' import { Suspense } from 'react'
import { theme } from '../variants' import { VariantValues } from './variant-values'
// A variant is runtime data, and Cache Components requires a Suspense boundary
// above a read of one.
export default function Page() { export default function Page() {
return ( return (
<Suspense fallback={<p id="theme-pending">pending</p>}> <Suspense fallback={<p id="pending">pending</p>}>
<p id="theme">{theme()}</p> <VariantValues />
</Suspense> </Suspense>
) )
} }
import { Suspense } from 'react'
import { VariantValues } from '../variant-values'
// The proxy rewrites `/rewrite-source` here. The variants of this route are the
// ones that apply, because a rewrite decides which route renders.
export default function Page() {
return (
<Suspense fallback={<p id="pending">pending</p>}>
<VariantValues />
</Suspense>
)
}
import { Suspense } from 'react'
import { VariantValues } from '../variant-values'
// This route reads variants, and the `config.matcher` of the proxy omits it on
// purpose. A project can write that mistake today, because the matcher and the
// table of variants per route are separate and nothing keeps them in step. The
// proxy resolves nothing for a request here, so the read fails.
//
// TODO(variants): the variants transform derives the matcher as the union of
// the matcher of the user and every route that reads a variant. A route that
// reads a variant is then always matched.
export default function Page() {
return (
<Suspense fallback={<p id="pending">pending</p>}>
<VariantValues />
</Suspense>
)
}
import { connection } from 'next/server'
import { locale, theme } from '../variants'
// `connection()` holds both reads at request time. A prerender cannot yet
// supply a variant value, so a read during one has nothing to return.
//
// A variant is runtime data, and Cache Components requires a Suspense boundary
// above a read of one. Every caller of this component provides that boundary.
export async function VariantValues() {
await connection()
return (
<>
<p id="theme">{await theme()}</p>
<p id="locale">{await locale()}</p>
</>
)
}
...@@ -7,4 +7,11 @@ const nextConfig = { ...@@ -7,4 +7,11 @@ const nextConfig = {
}, },
} }
// Set by `variants-base-path.test.ts`, which runs the whole suite a second time
// under a base path. The value arrives through `nextTestSetup`'s `env`, so that
// it reaches a local build and a deployed build alike.
if (process.env.BASE_PATH) {
nextConfig.basePath = process.env.BASE_PATH
}
module.exports = nextConfig module.exports = nextConfig
import { NextResponse, type NextRequest } from 'next/server'
import { wrapProxy } from 'next/dist/server/variants/wrap-proxy'
import { locale, theme } from './variants'
// This table names the variants of each route by hand.
//
// TODO(variants): the variants transform wraps the proxy, synthesizes one for a
// project that has none, and derives each route's variants from its module
// graph, layouts included.
//
// A route reads only some of the variants that a project declares. Resolution
// of the rest would send the origin values that no code reads. The table lists
// `/rewrite-target` and not `/rewrite-source`, because the rewrite below decides
// which route renders.
const variantsByRoute = {
'/': [locale, theme],
'/rewrite-target': [locale, theme],
// The `config.matcher` below omits this route on purpose. See the route.
'/unmatched-by-proxy': [locale, theme],
}
export const proxy = wrapProxy(variantsByRoute, (request: NextRequest) => {
const { pathname } = request.nextUrl
if (pathname === '/rewrite-source') {
// Cloned rather than built from `request.url`, so that a configured base
// path is kept: `nextUrl` holds the pathname without it and adds it back
// when the URL is stringified.
const target = request.nextUrl.clone()
target.pathname = '/rewrite-target'
return NextResponse.rewrite(target)
}
if (pathname === '/external') {
const port = process.env.EXTERNAL_SERVER_PORT
if (!port) {
throw new Error(
'The `EXTERNAL_SERVER_PORT` environment variable is not set. The test starts the external server and sets it before starting Next.js.'
)
}
return NextResponse.rewrite(`http://localhost:${port}/external`)
}
})
export const config = {
matcher: ['/', '/rewrite-source', '/external'],
}
...@@ -11,3 +11,10 @@ export const theme = unstable_variant( ...@@ -11,3 +11,10 @@ export const theme = unstable_variant(
request.cookies.get('theme')?.value === 'dark' ? 'dark' : 'light', request.cookies.get('theme')?.value === 'dark' ? 'dark' : 'light',
'theme@variants.ts' 'theme@variants.ts'
) )
// A second variant. A resolved set then holds more than one pair, which
// exercises the canonical ordering.
export const locale = unstable_variant(
(request) => (request.cookies.get('locale')?.value === 'de' ? 'de' : 'en'),
'locale@variants.ts'
)
// Runs the whole variants suite again under a base path.
//
// A base path prefixes every path a client asks for, while a route carries
// none, so every site that matches a request against a route has to remove it
// first.
//
// The variable is read by `variants.test.ts`, which hands it to the build and
// prefixes the paths it requests, and by the fixture's `next.config.js`.
process.env.BASE_PATH = '/base'
require('./variants.test')
import { isNextStart, nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { findPort, retry } from 'next-test-utils'
import { basePath, url } from './base-path'
import { startExternalServer } from './external-server.mjs'
// Variants are supported with Turbopack only, and enabling them rejects a // Variants are supported with Turbopack only, and enabling them rejects a
// webpack build, which `variants-webpack.test.ts` covers. // webpack build, which `variants-webpack.test.ts` covers.
...@@ -7,32 +10,119 @@ import { retry } from 'next-test-utils' ...@@ -7,32 +10,119 @@ import { retry } from 'next-test-utils'
const { next, skipped } = nextTestSetup({ const { next, skipped } = nextTestSetup({
files: __dirname + '/fixtures/default', files: __dirname + '/fixtures/default',
// TODO(variants): a platform serves a variant from its build output, which // TODO(variants): a platform serves a variant from its build output, which
// comes later. No test here depends on that. Nothing resolves a value yet, // comes later. No test here depends on that, because every read below
// so every mode fails the read alike. // happens at request time.
skipDeployment: true, skipDeployment: true,
// The harness forwards only what goes through `env`, so the value reaches a
// deployed build as well as a local one.
env: basePath ? { BASE_PATH: basePath } : undefined,
// The proxy rewrites `/external` to a port that only exists once the
// external server is listening, so Next.js is started by hand below.
skipStart: true,
}) })
if (skipped) { if (skipped) {
return return
} }
it('should fail a read that no value was resolved for', async () => { let externalServer: Awaited<ReturnType<typeof startExternalServer>>
const response = await next.fetch('/')
beforeAll(async () => {
// A boundary contains a failed read only if something already served that const port = await findPort()
// boundary. What a request receives therefore depends on what the build
// kept. externalServer = await startExternalServer(port)
if (isNextStart && process.env.__NEXT_CACHE_COMPONENTS) { next.env.EXTERNAL_SERVER_PORT = String(port)
// A variant is runtime data, so the read interrupts the prerender and
// leaves a shell that ends at the boundary above it. The server sends await next.start()
// that shell, and the boundary stays pending. })
expect(response.status).toBe(200)
expect(await response.text()).toContain('pending') afterAll(async () => {
} else { await next.stop()
// The build kept no shell. The whole route therefore renders per await externalServer.cleanup()
// request, and the read fails that request. })
expect(response.status).toBe(500)
} it('should resolve a variant to its default value', async () => {
const $ = await next.render$(url('/'))
expect($('#theme').text()).toBe('light')
expect($('#locale').text()).toBe('en')
})
it('should resolve several variants from one request', async () => {
const $ = await next.render$(url('/'), undefined, {
headers: { cookie: 'theme=dark; locale=de' },
})
expect($('#theme').text()).toBe('dark')
expect($('#locale').text()).toBe('de')
})
it('should not expose the resolved values to the client', async () => {
const response = await next.fetch(url('/'), {
headers: { cookie: 'theme=dark' },
})
// The values reach the origin as a request header, so the response does not
// carry them back to the client.
expect(response.headers.get('x-next-internal-variants')).toBeNull()
})
it('should resolve a variant on the route the proxy rewrote to', async () => {
const $ = await next.render$(url('/rewrite-source'), undefined, {
headers: { cookie: 'theme=dark' },
})
// The rewrite decides which route renders. The variants of
// `/rewrite-target` therefore apply, and not those of the source.
expect($('#theme').text()).toBe('dark')
expect($('#locale').text()).toBe('en')
})
it('should not send resolved values to another origin', async () => {
const $ = await next.render$(url('/external'), undefined, {
headers: { cookie: 'theme=dark' },
})
expect($('#external').text()).toBe('external')
const received = externalServer.getReceivedRequests()
expect(received).toHaveLength(1)
expect(received[0].url).toBe('/external')
// The other origin renders no route of this application, and it does not
// remove an internal header. The proxy therefore drops the values.
expect(received[0].headers['x-next-internal-variants']).toBeUndefined()
})
it('should not let a client resolve the variants itself', async () => {
const forged = encodeURIComponent(
JSON.stringify([['theme@variants.ts', 'dark']])
)
const $ = await next.render$(url('/unmatched-by-proxy'), undefined, {
headers: { 'x-next-internal-variants': forged },
})
// Next.js removes the header on arrival. The read therefore finds nothing,
// and not the values that the client sent.
expect($('#theme').length).toBe(0)
expect($('#pending').text()).toBe('pending')
await retry(async () => {
expect(next.cliOutput).toContain(
'read variant `theme@variants.ts`, but no value was resolved for this request'
)
})
})
it('should fail a read on a route the proxy does not match', async () => {
const $ = await next.render$(url('/unmatched-by-proxy'))
// `connection()` holds the read until request time. The shell reaches the
// client before the read fails, so the boundary below it stays pending.
expect($('#pending').text()).toBe('pending')
expect($('#theme').length).toBe(0)
await retry(async () => { await retry(async () => {
expect(next.cliOutput).toContain( expect(next.cliOutput).toContain(
......
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