Support Variants on adapter deployments

This change extends `experimental.variants` to adapter-based
deployments. The adapter emits per-combination prerender outputs and
routes document, RSC, and segment-prefetch requests to them. The Node
Proxy output includes the Variants manifest so request-time resolution
can select the available static variant combinations.

Deployment requests preserve the selected combination through on-demand
prerendering, partially resolved shells, and revalidation. The origin
receives runtime variant values, and non-PPR prerenders bypass their
cache when those values require a request render. Public route
parameters remain separate from internal artifact paths.

The routing handles root paths, required and optional catch-all routes,
base paths, and route collapsing. Additional combinations produce
separate prerender outputs without multiplying routing entries.
Collapsed routes preserve the selected shell and requested payload form
without changing prerender output paths.

The existing Variants suites now run against adapter deployments.
Additional regression coverage checks routing precedence, prefetches,
partially resolved shells, and root revalidation. Adapter tests verify
route uniqueness, stable ordering, and routing size independent of the
combination count.

Deployment support requires the adapter API. The legacy deployment
builder is not supported, while self-hosted dev and start continue to
work without an adapter. Variants remains experimental, with the
existing Turbopack and Node Proxy requirements.

Anti-forgery checks for client-supplied variant prefixes and `nxtV`
follow in the next change in this stack.
parent 9f4718a5
...@@ -37,6 +37,8 @@ import { ...@@ -37,6 +37,8 @@ import {
NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER, NEXT_CACHE_REVALIDATE_TAG_TOKEN_HEADER,
NEXT_CACHE_REVALIDATED_TAGS_HEADER, NEXT_CACHE_REVALIDATED_TAGS_HEADER,
MATCHED_PATH_HEADER, MATCHED_PATH_HEADER,
NEXT_VARIANTS_HEADER,
VARIANTS_PATH_PREFIX,
type RSC_SEGMENTS_DIR_SUFFIX, type RSC_SEGMENTS_DIR_SUFFIX,
type RSC_SEGMENT_SUFFIX, type RSC_SEGMENT_SUFFIX,
} from '../lib/constants' } from '../lib/constants'
...@@ -219,6 +221,7 @@ import { generatePreviewKeys } from './preview-key-utils' ...@@ -219,6 +221,7 @@ import { generatePreviewKeys } from './preview-key-utils'
import { handleBuildComplete } from './adapter/build-complete' 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 { getVariantOutputPath } from '../server/variants/prefix' import { getVariantOutputPath } from '../server/variants/prefix'
import { import {
sortPageObjects, sortPageObjects,
...@@ -553,6 +556,12 @@ export type ManifestRoute = ManifestBuiltRoute & { ...@@ -553,6 +556,12 @@ export type ManifestRoute = ManifestBuiltRoute & {
* routers. * routers.
*/ */
skipInternalRouting?: boolean skipInternalRouting?: boolean
/**
* Marks an alias whose regexes carry a Variants prefix while its `page` does
* not. A consumer cannot derive this entry's matchers from `page`.
*/
variantsPrefixed?: boolean
} }
type ManifestDataRoute = { type ManifestDataRoute = {
...@@ -2192,6 +2201,7 @@ export default async function build( ...@@ -2192,6 +2201,7 @@ export default async function build(
VariantCombinationGroups VariantCombinationGroups
>() >()
const variantOutputHashesByPage = new Map<string, Set<string>>() const variantOutputHashesByPage = new Map<string, Set<string>>()
const variantDynamicOutputPathnames = new Set<string>()
const prerenderRouteMatchers = new Map<string, PrerenderRouteMatcher[]>() const prerenderRouteMatchers = new Map<string, PrerenderRouteMatcher[]>()
const appNormalizedPaths = new Map<string, string>() const appNormalizedPaths = new Map<string, string>()
const fallbackModes = new Map<string, FallbackMode>() const fallbackModes = new Map<string, FallbackMode>()
...@@ -3061,6 +3071,18 @@ export default async function build( ...@@ -3061,6 +3071,18 @@ export default async function build(
variantCombinationGroups: {}, variantCombinationGroups: {},
} }
// `allowHeader` forwards a header without adding it to the cache key.
// Every prerender in a project with Variants enabled accepts this header
// because the build cannot identify which routes can reach a variant
// reader. Static variant combinations cannot answer that: a route can
// read a variant without declaring a combination.
//
// TODO(variants): Narrow this list with emit and collect data that
// identifies routes which can reach a variant reader.
const allowHeader: string[] = config.experimental.variants
? [...ALLOWED_HEADERS, NEXT_VARIANTS_HEADER]
: ALLOWED_HEADERS
// Accumulate per-route segment inlining decisions for // Accumulate per-route segment inlining decisions for
// prefetch-hints.json. First-writer-wins: if multiple param // prefetch-hints.json. First-writer-wins: if multiple param
// combinations exist for the same route pattern, use the first one. // combinations exist for the same route pattern, use the first one.
...@@ -3460,6 +3482,20 @@ export default async function build( ...@@ -3460,6 +3482,20 @@ export default async function build(
}, },
] ]
: []), : []),
// A non-PPR prerender cannot leave runtime-tier variant values as
// holes. Bypass the platform prerender when the proxy forwards
// any such value, so the request uses a request render instead. A
// blocking prerender cannot preserve the runtime tier.
//
// The proxy omits values assigned by a declared variant
// combination from this header. The header is absent when that
// combination assigns every resolved variant, so the request can
// use its prerender.
...(config.experimental.variants &&
!isRoutePPREnabled &&
variantCombinationGroupsByPage.get(page)?.length
? [{ type: 'header' as const, key: NEXT_VARIANTS_HEADER }]
: []),
] ]
// Candidates without unknown params can become concrete static // Candidates without unknown params can become concrete static
...@@ -3655,7 +3691,7 @@ export default async function build( ...@@ -3655,7 +3691,7 @@ export default async function build(
srcRoute: page, srcRoute: page,
dataRoute, dataRoute,
prefetchDataRoute, prefetchDataRoute,
allowHeader: ALLOWED_HEADERS, allowHeader,
} }
recordVariantOutput( recordVariantOutput(
...@@ -3835,7 +3871,30 @@ export default async function build( ...@@ -3835,7 +3871,30 @@ export default async function build(
} }
} }
if (metadata?.segmentPaths) { // Build a combined prefetch segment data route from the page
// segment metadata, and attach it to the logical dynamic
// route. Its source accepts both the full
// `.../__PAGE__.segment.rsc` form and the shorter
// `.segment.rsc` form, so one entry serves both requests.
//
// A builder that consumes `routes-manifest.json` directly
// needs this route. An adapter also emits it when
// `collapseAdapterRoutes` is off. When the collapse is on,
// the merged RSC suffix matcher handles segment requests
// instead.
//
// A page without variant combinations has at most one
// candidate per pathname. Static variant combinations create
// several candidates with the same pathname and segment
// metadata. The first candidate of such a page attaches the
// shared route, and later candidates skip this block. Pages
// without combinations keep the existing per-candidate
// behavior.
if (
metadata?.segmentPaths &&
(!variantCombinationGroupsByPage.has(page) ||
!dynamicRoute.prefetchSegmentDataRoutes)
) {
const pageSegmentPath = metadata.segmentPaths.find((item) => const pageSegmentPath = metadata.segmentPaths.find((item) =>
item.endsWith('__PAGE__') item.endsWith('__PAGE__')
) )
...@@ -3843,9 +3902,6 @@ export default async function build( ...@@ -3843,9 +3902,6 @@ export default async function build(
throw new Error(`Invariant: missing __PAGE__ segmentPath`) throw new Error(`Invariant: missing __PAGE__ segmentPath`)
} }
// We build a combined segment data route from the
// page segment as we need to limit the number of
// routes we output and they can be shared
const builtSegmentDataRoute = buildPrefetchSegmentDataRoute( const builtSegmentDataRoute = buildPrefetchSegmentDataRoute(
route.pathname, route.pathname,
pageSegmentPath pageSegmentPath
...@@ -4004,14 +4060,18 @@ export default async function build( ...@@ -4004,14 +4060,18 @@ export default async function build(
excludeOptionalTrailingSlash: true, excludeOptionalTrailingSlash: true,
}).re.source }).re.source
), ),
allowHeader: ALLOWED_HEADERS, allowHeader,
} }
recordVariantOutput( const variantValues = prerenderCandidate?.variantValues
variantOutputHashesByPage, if (variantValues) {
page, recordVariantOutput(
prerenderCandidate?.variantValues variantOutputHashesByPage,
) page,
variantValues
)
variantDynamicOutputPathnames.add(route.pathname)
}
} }
} }
}) })
...@@ -4255,7 +4315,7 @@ export default async function build( ...@@ -4255,7 +4315,7 @@ export default async function build(
`${localePage}.json` `${localePage}.json`
), ),
prefetchDataRoute: undefined, prefetchDataRoute: undefined,
allowHeader: ALLOWED_HEADERS, allowHeader,
} }
} }
} else { } else {
...@@ -4285,7 +4345,7 @@ export default async function build( ...@@ -4285,7 +4345,7 @@ export default async function build(
), ),
// Pages does not have a prefetch data route. // Pages does not have a prefetch data route.
prefetchDataRoute: undefined, prefetchDataRoute: undefined,
allowHeader: ALLOWED_HEADERS, allowHeader,
} }
} }
if (pageInfo) { if (pageInfo) {
...@@ -4324,7 +4384,7 @@ export default async function build( ...@@ -4324,7 +4384,7 @@ export default async function build(
), ),
// Pages does not have a prefetch data route. // Pages does not have a prefetch data route.
prefetchDataRoute: undefined, prefetchDataRoute: undefined,
allowHeader: ALLOWED_HEADERS, allowHeader,
} }
if (pageInfo) { if (pageInfo) {
...@@ -4338,6 +4398,28 @@ export default async function build( ...@@ -4338,6 +4398,28 @@ export default async function build(
await writeManifest(pagesManifestPath, pagesManifest) await writeManifest(pagesManifestPath, pagesManifest)
}) })
if (config.experimental.variants) {
// Exclude artifact paths from ordinary origin matchers before adding
// aliases. A broad dynamic route can otherwise consume the prefix
// instead of capturing the hash.
for (const route of dynamicRoutes) {
route.regex = route.regex.replace(
'^',
`^(?![/]?/${VARIANTS_PATH_PREFIX}/)`
)
if (route.namedRegex !== undefined) {
route.namedRegex = route.namedRegex.replace(
'^',
`^(?![/]?/${VARIANTS_PATH_PREFIX}/)`
)
}
}
dynamicRoutes.push(
...buildVariantRouteAliases(variantOutputHashesByPage.keys())
)
}
// As we may have modified the dynamicRoutes, we need to sort the // As we may have modified the dynamicRoutes, we need to sort the
// dynamic routes by page. // dynamic routes by page.
routesManifest.dynamicRoutes = sortSortableRouteObjects( routesManifest.dynamicRoutes = sortSortableRouteObjects(
...@@ -4468,7 +4550,7 @@ export default async function build( ...@@ -4468,7 +4550,7 @@ export default async function build(
// Pages does not have a prefetch data route. // Pages does not have a prefetch data route.
prefetchDataRoute: undefined, prefetchDataRoute: undefined,
prefetchDataRouteRegex: undefined, prefetchDataRouteRegex: undefined,
allowHeader: ALLOWED_HEADERS, allowHeader,
} }
}) })
...@@ -4664,6 +4746,7 @@ export default async function build( ...@@ -4664,6 +4746,7 @@ export default async function build(
appPageKeys: emittedAppPageKeys, appPageKeys: emittedAppPageKeys,
routesManifest, routesManifest,
prerenderManifest, prerenderManifest,
variantDynamicOutputPathnames,
middlewareManifest, middlewareManifest,
functionsConfigManifest, functionsConfigManifest,
hasStatic404: useStaticPages404, hasStatic404: useStaticPages404,
......
import type { DynamicManifestRoute } from '../utils'
import {
NEXT_VARIANTS_QUERY_PARAM,
VARIANTS_PATH_PREFIX,
} from '../../lib/constants'
import { normalizeRouteRegex } from '../../lib/load-custom-routes'
import { getNamedRouteRegex } from '../../shared/lib/router/utils/route-regex'
/**
* Resolves a variant-prefixed artifact pathname to its unprefixed page.
*
* A deployment may invoke the route's function to fill or revalidate a
* prerender. It can construct that request from the artifact pathname without
* repeating external routing. The prefix remains when the deployment handler
* resolves which page module to load.
*
* `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
* for a page.
*/
export function buildVariantRouteAliases(
pages: Iterable<string>
): DynamicManifestRoute[] {
const aliases: DynamicManifestRoute[] = []
for (const page of pages) {
const routeRegex = getNamedRouteRegex(page, { prefixRouteKeys: true })
// Root aliases omit the page slash because root artifacts end at the hash.
aliases.push({
page,
sourcePage: undefined,
regex: normalizeRouteRegex(routeRegex.re.source).replace(
page === '/' ? '^/' : '^',
`^/${VARIANTS_PATH_PREFIX}/[^/]+`
),
routeKeys: routeRegex.routeKeys,
namedRegex: routeRegex.namedRegex.replace(
page === '/' ? '^/' : '^',
`^/${VARIANTS_PATH_PREFIX}/(?<${NEXT_VARIANTS_QUERY_PARAM}>[^/]+)`
),
skipInternalRouting: true,
variantsPrefixed: true,
})
}
return aliases
}
import type { AppPageRouteDefinition } from '../../route-definitions/app-page-route-definition' import type { AppPageRouteDefinition } from '../../route-definitions/app-page-route-definition'
import type RenderResult from '../../render-result' import type RenderResult from '../../render-result'
import type { RenderOpts } from '../../app-render/types' import type { RenderOpts } from '../../app-render/types'
import { addRequestMeta, type NextParsedUrlQuery } from '../../request-meta' import {
addRequestMeta,
getRequestMeta,
type NextParsedUrlQuery,
} from '../../request-meta'
import type { LoaderTree } from '../../lib/app-dir-module' import type { LoaderTree } from '../../lib/app-dir-module'
import type { PrerenderManifest } from '../../../build' import type { PrerenderManifest } from '../../../build'
import type { NextConfigRuntime } from '../../config-shared'
import { splitVariantsPrefix } from '../../variants/prefix'
import { import {
prerenderToHTMLOrFlight, prerenderToHTMLOrFlight,
...@@ -118,7 +124,9 @@ export class AppPageRouteModule extends RouteModule< ...@@ -118,7 +124,9 @@ export class AppPageRouteModule extends RouteModule<
public normalizeUrl( public normalizeUrl(
req: IncomingMessage | BaseNextRequest, req: IncomingMessage | BaseNextRequest,
parsedUrl: UrlWithParsedQuery parsedUrl: UrlWithParsedQuery,
nextConfig?: DeepReadonly<NextConfigRuntime>,
isWrappedByNextServer?: boolean
) { ) {
if (this.normalizers.segmentPrefetchRSC.match(parsedUrl.pathname || '/')) { if (this.normalizers.segmentPrefetchRSC.match(parsedUrl.pathname || '/')) {
const result = this.normalizers.segmentPrefetchRSC.extract( const result = this.normalizers.segmentPrefetchRSC.extract(
...@@ -146,7 +154,24 @@ export class AppPageRouteModule extends RouteModule< ...@@ -146,7 +154,24 @@ export class AppPageRouteModule extends RouteModule<
// Mark the request as a RSC request. // Mark the request as a RSC request.
req.headers[RSC_HEADER] = '1' req.headers[RSC_HEADER] = '1'
} else { } else {
super.normalizeUrl(req, parsedUrl) super.normalizeUrl(req, parsedUrl, nextConfig, isWrappedByNextServer)
}
// Remove the artifact prefix before matching route params. Self-hosted
// routing does this when it processes the proxy rewrite; direct minimal
// invocations do not.
if (
nextConfig?.experimental.variants &&
getRequestMeta(req, 'minimalMode') === true &&
!isWrappedByNextServer
) {
const variantPath = splitVariantsPrefix(
parsedUrl.pathname || '/',
undefined
)
if (variantPath) {
parsedUrl.pathname = variantPath.pathname
}
} }
// Minimal adapters can bypass base-server request normalization and invoke // Minimal adapters can bypass base-server request normalization and invoke
......
...@@ -172,7 +172,9 @@ export abstract class RouteModule< ...@@ -172,7 +172,9 @@ export abstract class RouteModule<
public normalizeUrl( public normalizeUrl(
_req: IncomingMessage | BaseNextRequest, _req: IncomingMessage | BaseNextRequest,
_parsedUrl: UrlWithParsedQuery _parsedUrl: UrlWithParsedQuery,
_nextConfig?: DeepReadonly<NextConfigRuntime>,
_isWrappedByNextServer?: boolean
) {} ) {}
public async instrumentationOnRequestError( public async instrumentationOnRequestError(
...@@ -754,7 +756,12 @@ export abstract class RouteModule< ...@@ -754,7 +756,12 @@ export abstract class RouteModule<
isNextDataRequest = true isNextDataRequest = true
parsedUrl.pathname = normalizeDataPath(parsedUrl.pathname || '/') parsedUrl.pathname = normalizeDataPath(parsedUrl.pathname || '/')
} }
this.normalizeUrl(req, parsedUrl) this.normalizeUrl(
req,
parsedUrl,
nextConfig,
routerServerContext?.isWrappedByNextServer
)
let originalPathname = parsedUrl.pathname || '/' let originalPathname = parsedUrl.pathname || '/'
const originalQuery = { ...parsedUrl.query } const originalQuery = { ...parsedUrl.query }
const pageIsDynamic = isDynamicRoute(srcPage) const pageIsDynamic = isDynamicRoute(srcPage)
......
...@@ -6,6 +6,7 @@ const nextConfig = { ...@@ -6,6 +6,7 @@ const nextConfig = {
partialPrefetching: true, partialPrefetching: true,
experimental: { experimental: {
variants: true, variants: true,
collapseAdapterRoutes: process.env.COLLAPSE_ADAPTER_ROUTES === '1',
}, },
} }
......
process.env.BASE_PATH = '/base' process.env.BASE_PATH = '/base'
process.env.COLLAPSE_ADAPTER_ROUTES = '1'
require('./variants-partial-shells.test') require('./variants-partial-shells.test')
process.env.COLLAPSE_ADAPTER_ROUTES = '1'
require('./variants-partial-shells.test')
...@@ -6,13 +6,14 @@ import { createRouterAct } from 'router-act' ...@@ -6,13 +6,14 @@ import { createRouterAct } from 'router-act'
import { basePath, url } from '../variants/base-path' import { basePath, url } from '../variants/base-path'
// The assertions distinguish build-time preludes from request-time rendering. // The assertions distinguish build-time preludes from request-time rendering.
// TODO(variants): Add deployment coverage for partially resolved shells. // @force-gate turbopack && !dev && (!deploy || adapter)
// @force-gate start && turbopack
describe('Variants on partially resolved shells', () => { describe('Variants on partially resolved shells', () => {
const { next, skipped } = nextTestSetup({ const { next, skipped } = nextTestSetup({
files: __dirname, files: __dirname,
env: { env: {
BASE_PATH: basePath, BASE_PATH: basePath,
COLLAPSE_ADAPTER_ROUTES:
process.env.COLLAPSE_ADAPTER_ROUTES === '1' ? '1' : '0',
}, },
}) })
......
import { Suspense, type JSX } from 'react'
import { theme } from '../../variants'
export function generateStaticParams(): Array<{ slug: string[] }> {
return [{ slug: ['built'] }]
}
export function unstable_generateStaticVariants(): [typeof theme, string][][] {
return [[[theme, 'dark']], [[theme, 'light']]]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string[] }>
}): Promise<JSX.Element> {
const { slug } = await params
return (
<>
<p id="slug">{slug.join('/')}</p>
<Suspense fallback={<p id="theme-pending">pending</p>}>
<p id="theme">{theme()}</p>
</Suspense>
</>
)
}
import type { JSX } from 'react'
export default function Page(): JSX.Element {
return <p id="plain">plain route</p>
}
import type { JSX, ReactNode } from 'react'
export default function Root({
children,
}: {
children: ReactNode
}): JSX.Element {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
import Link from 'next/link'
import { useState, type JSX } from 'react'
export function LinkAccordion({ href }: { href: string }): JSX.Element {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? <Link href={href}>Catch-all page</Link> : null}
</>
)
}
import { Suspense, type JSX } from 'react'
import { LinkAccordion } from './link-accordion'
export default function Page({
searchParams,
}: {
searchParams: Promise<{ slug?: string }>
}): JSX.Element {
return (
<Suspense>
<PrefetchLink searchParams={searchParams} />
</Suspense>
)
}
async function PrefetchLink({
searchParams,
}: {
searchParams: Promise<{ slug?: string }>
}): Promise<JSX.Element | null> {
const { slug } = await searchParams
if (!slug) {
return null
}
return <LinkAccordion href={`/${slug}`} />
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
variants: true,
collapseAdapterRoutes: process.env.COLLAPSE_ADAPTER_ROUTES === '1',
},
}
if (process.env.BASE_PATH) {
nextConfig.basePath = process.env.BASE_PATH
}
module.exports = nextConfig
import { wrapProxy } from 'next/dist/server/variants/wrap-proxy'
import { theme } from './variants'
export const proxy = wrapProxy({
'/[section]/[category]/[item]': [],
'/[...slug]': [theme],
})
export const config = {
matcher: ['/((?!_next/|favicon\\.ico$).*)'],
}
process.env.BASE_PATH = '/base'
require('./variants-root-catchall.test')
process.env.COLLAPSE_ADAPTER_ROUTES = '1'
require('./variants-root-catchall.test')
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { retry } from 'next-test-utils'
import { createRouterAct } from 'router-act'
import { basePath, url } from '../variants/base-path'
// @force-gate turbopack && (!deploy || adapter)
describe('Variants on a root catch-all', () => {
const { next, isNextDeploy, skipped } = nextTestSetup({
files: __dirname,
env: {
BASE_PATH: basePath,
COLLAPSE_ADAPTER_ROUTES:
process.env.COLLAPSE_ADAPTER_ROUTES === '1' ? '1' : '0',
},
})
if (skipped) {
return
}
it('should preserve the more-specific route without Variants', async () => {
for (const pathname of [
'/plain/path/value',
'/__variants-extra/path/value',
'/plain/__variants/value',
]) {
const $ = await next.render$(url(pathname))
expect($('#plain').text()).toBe('plain route')
}
})
it('should resolve unenumerated catch-all params for each combination', async () => {
for (const slug of ['document', 'nested/document']) {
for (const theme of ['dark', 'light']) {
const $ = await next.render$(url(`/${slug}`), undefined, {
headers: { cookie: `theme=${theme}` },
})
expect($('#slug').text()).toBe(slug)
expect($('#theme').text()).toBe(theme)
}
}
})
// @force-gate prefetching
it('should prefetch catch-all params without the internal prefix or payload suffix', async () => {
const slug = `prefetch-${Date.now()}/child`
const pathname = `/${slug}`
async function prefetch() {
let page: Playwright.Page | undefined
try {
const browser = await next.browser(url(`/?slug=${slug}`), {
async beforePageLoad(capturedPage: Playwright.Page) {
page = capturedPage
await capturedPage
.context()
.addCookies([{ name: 'theme', value: 'dark', url: next.url }])
},
})
if (!page) {
throw new Error('The page was not captured before it loaded.')
}
const act = createRouterAct(page, { includeAppShellRequests: true })
await act(async () => {
await browser
.elementByCss(`input[data-link-accordion="${pathname}"]`)
.click()
}, [
{ includes: `"id":"slug","children":"${slug}"`, kind: 'static' },
{ includes: `"id":"slug","children":"${slug}.rsc"`, block: 'reject' },
{ includes: '"id":"slug","children":"__variants/', block: 'reject' },
])
return { browser, act }
} catch (error) {
if (page) {
await page.context().clearCookies()
await page.close()
}
throw error
}
}
if (isNextDeploy) {
// Warm the server through real prefetches. Each attempt uses a fresh page
// so the client router cannot reuse its cached fallback.
//
// TODO: Investigate whether deploy should serve the same cold-prefetch
// content as `next start`. The difference also occurs without Variants.
await retry(async () => {
const { browser } = await prefetch()
await using _ = defer(async () => {
await browser.deleteCookies()
await browser.close()
})
}, 15000)
}
const { browser, act } = await prefetch()
await using _ = defer(async () => {
await browser.deleteCookies()
await browser.close()
})
await act(async () => {
await browser.elementByCss(`a[href="${url(pathname)}"]`).click()
}, 'no-requests')
expect(await browser.elementByCss('#slug').text()).toBe(slug)
expect(await browser.elementByCss('#theme').text()).toBe('dark')
expect(await browser.eval('location.pathname')).toBe(url(pathname))
})
})
function defer(callback: () => Promise<void>) {
return { [Symbol.asyncDispose]: callback }
}
'use variants'
import { unstable_variant } from 'next/variants'
export const theme = unstable_variant(
(request) =>
request.cookies.get('theme')?.value === 'dark' ? 'dark' : 'light',
'theme@variants.ts'
)
import { Suspense, type JSX } from 'react'
import { theme } from '../../variants'
export function generateStaticParams(): Array<{ slug: string[] }> {
return [{ slug: ['built'] }]
}
export function unstable_generateStaticVariants(): [typeof theme, string][][] {
return [[[theme, 'dark']], [[theme, 'light']]]
}
export default async function Page({
params,
}: {
params: Promise<{ slug?: string[] }>
}): Promise<JSX.Element> {
const { slug } = await params
const pathname = slug === undefined ? '/' : `/${slug.join('/')}`
return (
<Suspense fallback={<p>pending</p>}>
<Content pathname={pathname} />
</Suspense>
)
}
async function Content({
pathname,
}: {
pathname: string
}): Promise<JSX.Element> {
return <p id="result">{`${pathname}:${await theme()}`}</p>
}
import type { JSX } from 'react'
import { LinkAccordion } from '../link-accordion'
export default function Page(): JSX.Element {
return <LinkAccordion href="/" />
}
import type { JSX, ReactNode } from 'react'
export default function Root({
children,
}: {
children: ReactNode
}): JSX.Element {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
import Link from 'next/link'
import { useState, type JSX } from 'react'
export function LinkAccordion({ href }: { href: string }): JSX.Element {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? <Link href={href}>Root page</Link> : null}
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
variants: true,
collapseAdapterRoutes: process.env.COLLAPSE_ADAPTER_ROUTES === '1',
},
}
if (process.env.BASE_PATH) {
nextConfig.basePath = process.env.BASE_PATH
}
module.exports = nextConfig
import { wrapProxy } from 'next/dist/server/variants/wrap-proxy'
import { theme } from './variants'
export const proxy = wrapProxy({ '/hub': [], '/[[...slug]]': [theme] })
export const config = {
matcher: ['/', '/((?!_next/|favicon\\.ico$).*)'],
}
process.env.BASE_PATH = '/base'
process.env.COLLAPSE_ADAPTER_ROUTES = '1'
require('./variants-root-optional-catchall.test')
process.env.COLLAPSE_ADAPTER_ROUTES = '1'
require('./variants-root-optional-catchall.test')
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { retry } from 'next-test-utils'
import { createRouterAct } from 'router-act'
import { basePath, url } from '../variants/base-path'
// @force-gate turbopack && (!deploy || adapter)
describe('Variants on an optional root catch-all', () => {
const { next, isNextDeploy, skipped } = nextTestSetup({
files: __dirname,
env: {
BASE_PATH: basePath,
COLLAPSE_ADAPTER_ROUTES:
process.env.COLLAPSE_ADAPTER_ROUTES === '1' ? '1' : '0',
},
})
if (skipped) {
return
}
it('should serve the built param for each combination', async () => {
for (const theme of ['dark', 'light']) {
const $ = await next.render$(url('/built'), undefined, {
headers: { cookie: `theme=${theme}` },
})
expect($('#result').text()).toBe(`/built:${theme}`)
}
})
// @force-gate prefetching
it('should prefetch the unenumerated root without changing the combination hash', async () => {
for (const theme of ['dark', 'light']) {
async function prefetch() {
let page: Playwright.Page | undefined
try {
const browser = await next.browser(url('/hub'), {
async beforePageLoad(capturedPage: Playwright.Page) {
page = capturedPage
await capturedPage
.context()
.addCookies([{ name: 'theme', value: theme, url: next.url }])
},
})
if (!page) {
throw new Error('The page was not captured before it loaded.')
}
const act = createRouterAct(page, { includeAppShellRequests: true })
await act(
async () => {
await browser
.elementByCss('input[data-link-accordion="/"]')
.click()
},
{
includes: `"id":"result","children":"/:${theme}"`,
kind: 'static',
}
)
return { browser, act }
} catch (error) {
if (page) {
await page.context().clearCookies()
await page.close()
}
throw error
}
}
if (isNextDeploy) {
// Warm only through prefetches so no document request can prepare the
// missing root artifact.
//
// TODO: Investigate whether deploy should serve the same cold-prefetch
// content as `next start`. The difference also occurs without Variants.
await retry(async () => {
const { browser } = await prefetch()
await using _ = defer(async () => {
await browser.deleteCookies()
await browser.close()
})
}, 15000)
}
const { browser, act } = await prefetch()
await using _ = defer(async () => {
await browser.deleteCookies()
await browser.close()
})
await act(async () => {
await browser.elementByCss(`a[href="${url('/')}"]`).click()
}, 'no-requests')
expect(await browser.elementByCss('#result').text()).toBe(`/:${theme}`)
expect(await browser.eval('location.pathname')).toBe(url('/'))
}
})
})
function defer(callback: () => Promise<void>) {
return { [Symbol.asyncDispose]: callback }
}
'use variants'
import { unstable_variant } from 'next/variants'
export const theme = unstable_variant(
(request) =>
request.cookies.get('theme')?.value === 'dark' ? 'dark' : 'light',
'theme@variants.ts'
)
import { Suspense, type JSX } from 'react'
import { cacheLife, cacheTag } from 'next/cache'
import { theme } from '../variants'
export function unstable_generateStaticVariants(): [typeof theme, string][][] {
return [[[theme, 'dark']], [[theme, 'light']]]
}
async function cachedByTheme(
currentTheme: string
): Promise<{ currentTheme: string; renderedAt: string }> {
'use cache'
cacheTag('lifetime-root')
cacheLife('hours')
return { currentTheme, renderedAt: new Date().toISOString() }
}
async function Cached(): Promise<JSX.Element> {
const cached = await cachedByTheme(await theme())
return (
<>
<p id="theme">{cached.currentTheme}</p>
<p id="rendered-at">{cached.renderedAt}</p>
</>
)
}
export default function Page(): JSX.Element {
return (
<Suspense fallback={<p id="cached">pending</p>}>
<Cached />
</Suspense>
)
}
...@@ -4,8 +4,8 @@ import { theme } from './variants' ...@@ -4,8 +4,8 @@ import { theme } from './variants'
// The variants transform will wrap the proxy automatically, synthesize one when // The variants transform will wrap the proxy automatically, synthesize one when
// the project has none, and derive each route's variants from its module graph, // the project has none, and derive each route's variants from its module graph,
// layouts included. Wired by hand until then. // layouts included. Wired by hand until then.
export const proxy = wrapProxy({ '/lifetime/[slug]': [theme] }) export const proxy = wrapProxy({ '/': [theme], '/lifetime/[slug]': [theme] })
export const config = { export const config = {
matcher: ['/lifetime/:slug'], matcher: ['/', '/lifetime/:slug'],
} }
...@@ -5,15 +5,13 @@ import { retry } from 'next-test-utils' ...@@ -5,15 +5,13 @@ import { retry } from 'next-test-utils'
import { basePath, url } from './base-path' import { basePath, url } from './base-path'
// 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. Deployments require
// @force-gate turbopack // the adapter's Variants routing and prerender outputs. Self-hosted dev and
// start do not require an adapter.
// @force-gate turbopack && (!deploy || adapter)
describe('variants with a cache lifetime per combination', () => { describe('variants with a cache lifetime per combination', () => {
const { next, skipped } = nextTestSetup({ const { next, skipped } = nextTestSetup({
files: __dirname + '/fixtures/cache-lifetime', files: __dirname + '/fixtures/cache-lifetime',
// TODO(variants): enable this for a deployment. A platform serves a
// combination from the routing rules the adapter emits, and those do not
// exist yet, so every assertion here is about a self-hosted server.
skipDeployment: true,
// Handed to the build rather than read from `process.env` there, so that // Handed to the build rather than read from `process.env` there, so that
// a deployed build receives it too: only what goes through here is // a deployed build receives it too: only what goes through here is
// forwarded to the remote build. // forwarded to the remote build.
...@@ -24,35 +22,39 @@ describe('variants with a cache lifetime per combination', () => { ...@@ -24,35 +22,39 @@ describe('variants with a cache lifetime per combination', () => {
return return
} }
it('should resolve a variant while revalidating a stale prerender', async () => { for (const [pathname, tag] of [
// A tag rather than the route's own lifetime, so the entry goes stale at ['/lifetime/r', 'lifetime-r'],
// once instead of after an hour. ['/', 'lifetime-root'],
const before = await next.render$(url('/lifetime/r'), undefined, { ]) {
headers: { cookie: 'theme=dark' }, it(`should resolve a variant while revalidating a stale prerender at ${pathname}`, async () => {
}) // Expire this route's tagged entries without waiting for their cache
// lifetime.
const before = await next.render$(url(pathname), undefined, {
headers: { cookie: 'theme=dark' },
})
expect(before('#theme').text()).toBe('dark') expect(before('#theme').text()).toBe('dark')
const renderedAt = before('#rendered-at').text() const renderedAt = before('#rendered-at').text()
expect(renderedAt).not.toBe('') expect(renderedAt).not.toBe('')
const revalidateRes = await next.fetch(url('/revalidate?tag=lifetime-r')) const revalidateRes = await next.fetch(url(`/revalidate?tag=${tag}`))
expect(revalidateRes.status).toBe(200) expect(revalidateRes.status).toBe(200)
// The stamp is what shows the entry was replaced. The variant reads // Require a new timestamp to distinguish regenerated content from the
// `dark` before and after, so a response carrying the old stamp is the // stale prerender. The variant value stays the same across revalidation.
// stale entry served while the revalidation runs behind it, and asserting await retry(async () => {
// on the variant alone would pass without that render happening. const after = await next.render$(url(pathname), undefined, {
await retry(async () => { headers: { cookie: 'theme=dark' },
const after = await next.render$(url('/lifetime/r'), undefined, { })
headers: { cookie: 'theme=dark' },
})
expect(after('#rendered-at').text()).not.toBe(renderedAt) expect(after('#rendered-at').text()).not.toBe('')
expect(after('#rendered-at').text()).not.toBe(renderedAt)
expect(after('#theme').text()).toBe('dark') expect(after('#theme').text()).toBe('dark')
})
}) })
}) }
it('should resolve the variant the cache lifetime is selected from', async () => { it('should resolve the variant the cache lifetime is selected from', async () => {
const $ = await next.render$(url('/lifetime/a'), undefined, { const $ = await next.render$(url('/lifetime/a'), undefined, {
......
...@@ -2,15 +2,13 @@ import { isNextDev, nextTestSetup } from 'e2e-utils' ...@@ -2,15 +2,13 @@ import { isNextDev, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils' import { retry } from 'next-test-utils'
// 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. Deployments require
// @force-gate turbopack // the adapter's Variants routing and prerender outputs. Self-hosted dev and
// start do not require an adapter.
// @force-gate turbopack && (!deploy || adapter)
describe('variants on an upgraded fallback shell', () => { describe('variants on an upgraded fallback shell', () => {
const { next, skipped } = nextTestSetup({ const { next, skipped } = nextTestSetup({
files: __dirname + '/fixtures/fallback-upgrade', files: __dirname + '/fixtures/fallback-upgrade',
// TODO(variants): enable this for a deployment. A platform serves a
// combination from the routing rules the adapter emits, and those do not
// exist yet, so every assertion here is about a self-hosted server.
skipDeployment: true,
}) })
if (skipped) { if (skipped) {
......
...@@ -4,15 +4,13 @@ const CONTROL = '/control' ...@@ -4,15 +4,13 @@ const CONTROL = '/control'
const DECLARED = '/declared' const DECLARED = '/declared'
// 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. Deployments require
// @force-gate turbopack // the adapter's Variants routing and prerender outputs. Self-hosted dev and
// start do not require an adapter.
// @force-gate turbopack && (!deploy || adapter)
describe('variants with a param the build did not name', () => { describe('variants with a param the build did not name', () => {
const { next, skipped } = nextTestSetup({ const { next, skipped } = nextTestSetup({
files: __dirname + '/fixtures/on-demand-param', files: __dirname + '/fixtures/on-demand-param',
// TODO(variants): enable this for a deployment. A platform serves a
// combination from the routing rules the adapter emits, and those do not
// exist yet, so every assertion here is about a self-hosted server.
skipDeployment: true,
}) })
if (skipped) { if (skipped) {
......
...@@ -7,15 +7,13 @@ import { basePath, url } from './base-path' ...@@ -7,15 +7,13 @@ import { basePath, url } from './base-path'
import { startExternalServer } from './external-server.mjs' 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. Deployments require
// @force-gate turbopack // the adapter's Variants routing and prerender outputs. Self-hosted dev and
// start do not require an adapter.
// @force-gate turbopack && (!deploy || adapter)
describe('variants', () => { describe('variants', () => {
const { next, skipped } = nextTestSetup({ const { next, skipped } = nextTestSetup({
files: __dirname + '/fixtures/default', files: __dirname + '/fixtures/default',
// TODO(variants): enable this for a deployment. A platform serves a
// combination from the routing rules the adapter emits, and those do not
// exist yet, so every assertion here is about a self-hosted server.
skipDeployment: true,
// Handed to the build rather than read from `process.env` there, so that a // Handed to the build rather than read from `process.env` there, so that a
// deployed build receives it too: only what goes through here is forwarded // deployed build receives it too: only what goes through here is forwarded
// to the remote build. // to the remote build.
...@@ -109,11 +107,15 @@ describe('variants', () => { ...@@ -109,11 +107,15 @@ describe('variants', () => {
expect($('#theme').length).toBe(0) expect($('#theme').length).toBe(0)
expect($('#pending').text()).toBe('pending') expect($('#pending').text()).toBe('pending')
await retry(async () => { // A deployment exposes build logs here, not logs from the function that
expect(next.cliOutput).toContain( // served the request. The response assertions above cover both modes.
'read variant `theme@variants.ts`, but no value was resolved for this request' if (!isNextDeploy) {
) 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 () => { it('should fail a read on a route the proxy does not match', async () => {
...@@ -124,11 +126,13 @@ describe('variants', () => { ...@@ -124,11 +126,13 @@ describe('variants', () => {
expect($('#pending').text()).toBe('pending') expect($('#pending').text()).toBe('pending')
expect($('#theme').length).toBe(0) expect($('#theme').length).toBe(0)
await retry(async () => { if (!isNextDeploy) {
expect(next.cliOutput).toContain( await retry(async () => {
'read variant `theme@variants.ts`, but no value was resolved for this request' expect(next.cliOutput).toContain(
) 'read variant `theme@variants.ts`, but no value was resolved for this request'
}) )
})
}
}) })
it('should resolve a variant on the route the proxy rewrote to', async () => { it('should resolve a variant on the route the proxy rewrote to', async () => {
...@@ -553,6 +557,29 @@ describe('variants', () => { ...@@ -553,6 +557,29 @@ describe('variants', () => {
} }
} }
if (isNextDeploy) {
// Warm the server entry before the final prefetch assertion. A segment
// fallback can omit the concrete param until background generation
// completes.
//
// TODO: Investigate whether deploy should serve the same cold-prefetch
// content as `next start`. The difference also occurs without Variants.
const $ = await next.render$(url(pathname), undefined, {
headers: { cookie: 'theme=light; locale=en' },
})
expect($('#slug').text()).toBe(slug)
await retry(async () => {
// Each attempt uses a fresh page so the client router cannot reuse
// its cached fallback.
const { browser } = await prefetch()
await using _ = defer(async () => {
await browser.deleteCookies()
await browser.close()
})
}, 15000)
}
const { browser, act } = await prefetch() const { browser, act } = await prefetch()
await using _ = defer(async () => { await using _ = defer(async () => {
await browser.deleteCookies() await browser.deleteCookies()
......
import { nextTestSetup } from 'e2e-utils'
import type { NextAdapter } from 'next'
import {
serializeDynamicRoutes,
type AdapterRouting,
} from '../adapter-dynamic-routes/dynamic-routes-snapshot'
type BuildCompleteContext = Parameters<NextAdapter['onBuildComplete']>[0]
type SnapshottableContext = BuildCompleteContext & {
routing: AdapterRouting
}
// These assertions inspect local production build outputs.
// @force-gate start && turbopack
describe('adapter-variants', () => {
const { next } = nextTestSetup({
files: __dirname,
skipStart: true,
})
// The hook performs three production builds. A timeout must not orphan a
// build process that a retry then mistakes for a running Next.js instance.
jest.setTimeout(360_000)
let twoCombinations: BuildCompleteContext
let fourCombinations: BuildCompleteContext
let collapsed: SnapshottableContext
beforeAll(async () => {
await next.build({ env: { VARIANT_LOCALES: '1' } })
twoCombinations = await next.readJSON('build-complete.json')
await next.build({ env: { VARIANT_LOCALES: '2' } })
fourCombinations = await next.readJSON('build-complete.json')
await next.build({
env: { VARIANT_LOCALES: '2', COLLAPSE_ADAPTER_ROUTES: '1' },
})
collapsed = await next.readJSON('build-complete.json')
})
const countByEntry = (context: BuildCompleteContext) => {
const counts = new Map<string, number>()
for (const route of context.routing.dynamicRoutes) {
const key = JSON.stringify(route)
counts.set(key, (counts.get(key) ?? 0) + 1)
}
return counts
}
it('should emit every routing entry once', () => {
// Routing takes the first match. Every identical entry after it is
// unreachable but still increases every deployment's routing table.
for (const context of [twoCombinations, fourCombinations, collapsed]) {
const repeated = Array.from(countByEntry(context))
.filter(([, count]) => count > 1)
.map(([route, count]) => ({ count, route: JSON.parse(route) }))
expect(repeated).toEqual([])
}
})
it('should keep routing and its order independent of the combination count', () => {
// Routing captures any combination hash. Increasing the number of hashes
// must multiply prerenders, not routing entries.
expect(fourCombinations.routing.dynamicRoutes).toEqual(
twoCombinations.routing.dynamicRoutes
)
})
it('should route prefixed payloads before prefixed documents', () => {
const routes = fourCombinations.routing.dynamicRoutes.filter((route) =>
route.sourceRegex.includes('(?<nxtV>')
)
expect(routes).toHaveLength(2)
// The payload matcher also accepts segment prefetches and comes first so
// the document's dynamic param cannot consume either suffix.
expect(routes[0].sourceRegex).toContain('rscSuffix')
expect(routes[0].sourceRegex).toContain('\\.segments/')
expect(routes[1].sourceRegex).not.toContain('rscSuffix')
})
const prerendersByCombination = (
context: BuildCompleteContext,
route: string
) => {
const groups = new Map<string, string[]>()
for (const prerender of context.outputs.prerenders) {
if (prerender.route !== route) {
continue
}
const match = /^\/__variants\/([0-9a-z]+)(?:\/|$)/.exec(
prerender.pathname
)
const combination = match ? match[1] : 'none'
const pathnames = groups.get(combination)
if (pathnames) {
pathnames.push(prerender.pathname)
} else {
groups.set(combination, [prerender.pathname])
}
}
return groups
}
it('should write one set of prerenders per combination', () => {
const two = prerendersByCombination(twoCombinations, '/concrete')
const four = prerendersByCombination(fourCombinations, '/concrete')
expect(two.size).toBe(1 + 2)
expect(four.size).toBe(1 + 4)
// Every combination produces the same artifact forms. An uneven group
// means one form was dropped while routing remained unchanged.
const sizes = new Set(
[...two.values(), ...four.values()].map((pathnames) => pathnames.length)
)
expect(Array.from(sizes)).toHaveLength(1)
})
it('should collapse every form of a prefixed request into one entry', () => {
// The prefixed page and payload follow the same collapse as the ordinary
// route. The prefix does not participate in the suffix group.
expect(serializeDynamicRoutes(collapsed.routing.dynamicRoutes))
.toMatchInlineSnapshot(`
"2 entries
/dynamic/[slug]
^(?![/]?/__variants/)[/]?/dynamic/(?<nxtPslug>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /dynamic/[slug]$rscSuffix?nxtPslug=$nxtPslug
/dynamic/[slug]
^[/]?/__variants/(?<nxtV>[0-9a-z]+)/dynamic/(?<nxtPslug>[^/]+?)(?<rscSuffix>\\.rsc|\\.segments/.+\\.segment\\.rsc|)(?:/)?$
-> /__variants/$nxtV/dynamic/[slug]$rscSuffix?nxtPslug=$nxtPslug&nxtV=$nxtV"
`)
})
it('should leave prerenders unchanged by the collapse', () => {
// This option changes routing only. It must not merge or remove the
// per-combination prerender outputs themselves.
const pathnamesOf = (context: BuildCompleteContext) =>
context.outputs.prerenders.map((prerender) => prerender.pathname).sort()
expect(pathnamesOf(collapsed)).toEqual(pathnamesOf(fourCombinations))
})
})
import { Suspense } from 'react'
import { combinations } from '../../combinations'
import { locale, theme } from '../../variants'
// This route has no dynamic segments. Its combinations produce exact outputs,
// so they multiply prerenders without adding dynamic routing entries.
export function unstable_generateStaticVariants() {
return combinations()
}
export default function Page() {
return (
<>
<Suspense fallback={<p id="theme-pending">pending</p>}>
<p id="theme">{theme()}</p>
</Suspense>
<Suspense fallback={<p id="locale-pending">pending</p>}>
<p id="locale">{locale()}</p>
</Suspense>
</>
)
}
import { Suspense } from 'react'
import { combinations } from '../../../combinations'
import { locale, theme } from '../../../variants'
export function generateStaticParams() {
return [{ slug: 'a' }]
}
// This route contributes the dynamic routing entries under test. Their matcher
// captures any combination hash, so the entries must not multiply with the
// number of combinations.
export function unstable_generateStaticVariants() {
return combinations()
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return (
<>
<Suspense fallback={<p id="theme-pending">pending</p>}>
<p id="theme">{theme()}</p>
</Suspense>
<Suspense fallback={<p id="locale-pending">pending</p>}>
<p id="locale">{locale()}</p>
</Suspense>
<p id="slug">{slug}</p>
</>
)
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { locale, theme } from './variants'
/**
* Returns two or four combinations without changing their variant keys.
* `VARIANT_LOCALES` selects the count, so the test can vary only that axis.
*/
export function combinations() {
const themes = ['light', 'dark']
const locales = process.env.VARIANT_LOCALES === '2' ? ['en', 'de'] : ['en']
return locales.flatMap((localeValue) =>
themes.map((themeValue) => [
[theme, themeValue],
[locale, localeValue],
])
)
}
import fs from 'fs/promises'
/** @type {import('next').NextAdapter} */
export default {
name: 'variants-build-output',
async onBuildComplete(context) {
await fs.writeFile('build-complete.json', JSON.stringify(context, null, 2))
},
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
experimental: {
variants: true,
collapseAdapterRoutes: process.env.COLLAPSE_ADAPTER_ROUTES === '1',
},
adapterPath: require.resolve('./my-adapter.mjs'),
}
module.exports = nextConfig
import { wrapProxy } from 'next/dist/server/variants/wrap-proxy'
import { locale, theme } from './variants'
// The variants transform will wrap the proxy and derive this table from each
// route's module graph. The fixture supplies it until that transform exists.
const variantsByRoute = {
'/concrete': [locale, theme],
'/dynamic/[slug]': [locale, theme],
}
export const proxy = wrapProxy(variantsByRoute, () => undefined)
export const config = {
matcher: ['/concrete', '/dynamic/:slug'],
}
'use variants'
import { unstable_variant } from 'next/variants'
// The variants transform will inject each identity. The fixture supplies them
// until that transform exists.
export const theme = unstable_variant(
(request) =>
request.cookies.get('theme')?.value === 'dark' ? 'dark' : 'light',
'theme@variants.ts'
)
export const locale = unstable_variant(
(request) => (request.cookies.get('locale')?.value === 'de' ? 'de' : 'en'),
'locale@variants.ts'
)
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