Add the `unstable_variant` API behind an experimental flag

A variant is a value that each request resolves, from cookies, headers,
or a flags service, and that a route can be prerendered against in
addition to its route params. This change adds the flag that gates the
feature, the `next/variants` entry point, and the reader that a variant
returns. Nothing resolves a value yet, so every read fails or defers
until a later change supplies one.

The name carries the `unstable_` prefix because the shape of the API is
not settled, and not only its behavior. A directive may turn out to be
enough on its own, in which case defining a variant needs no function
from Next.js at all.

Most of the reader is stubbed. No store carries a variant value, so
every read either fails or interrupts the prerender.

Only Turbopack supports the feature, and a webpack build rejects the
config where it loads.
parent 4d621240
......@@ -711,6 +711,7 @@ impl ReactServerComponentValidator {
atom!("server-only").into(),
atom!("next/headers").into(),
atom!("next/root-params").into(),
atom!("next/variants").into(),
],
invalid_client_lib_apis_mapping: FxHashMap::from_iter([
......
// This is a comment.
'use strict'
/**
* This is a comment.
*/
import { unstable_variant } from 'next/variants'
export default function () {
return null
}
// This is a comment.
'use strict';
/**
* This is a comment.
*/ import { unstable_variant } from 'next/variants';
export default function() {
return null;
}
x You're importing a module that depends on "next/variants" into a React Client Component module. This API is only available in Server Components but one of its parents is marked with "use
| client", so this module is also a Client Component.
| Learn more: https://nextjs.org/docs/app/building-your-application/rendering
|
|
,-[input.js:9:1]
8 |
9 | import { unstable_variant } from 'next/variants'
: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
`----
// This is a comment.
'use strict'
/**
* This is a comment.
*/
import { unstable_variant } from 'next/variants'
export default function () {
return null
}
// This is a comment.
'use strict';
/**
* This is a comment.
*/ import { unstable_variant } from 'next/variants';
export default function() {
return null;
}
x You're importing a module that depends on "next/variants". This API is only available in Server Components in the App Router, but you are using it in the Pages Router.
| Learn more: https://nextjs.org/docs/app/building-your-application/rendering/server-components
|
|
,-[input.js:9:1]
8 |
9 | import { unstable_variant } from 'next/variants'
: ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
`----
......@@ -34,6 +34,8 @@
"script.d.ts",
"server.js",
"server.d.ts",
"variants.js",
"variants.d.ts",
"head.js",
"head.d.ts",
"image.js",
......
......@@ -395,6 +395,7 @@ export function getDefineEnv({
'process.env.__NEXT_INSTRUMENTATION_CLIENT_ROUTER_TRANSITION_EVENTS':
config.experimental.instrumentationClientRouterTransitionEvents ?? false,
'process.env.__NEXT_VARY_PARAMS': config.experimental.varyParams ?? false,
'process.env.__NEXT_VARIANTS': config.experimental.variants ?? false,
'process.env.__NEXT_EXPOSE_TESTING_API':
isCacheComponentsEnabled &&
(dev || config.experimental.exposeTestingApiInProductionBuild === true),
......
......@@ -232,6 +232,7 @@ export const experimentalSchema = {
concurrentRouterQueue: z.boolean().optional(),
instrumentationClientRouterTransitionEvents: z.boolean().optional(),
varyParams: z.boolean().optional(),
variants: z.boolean().optional(),
prefetchInlining: z
.union([
z.boolean(),
......
......@@ -546,6 +546,17 @@ export interface ExperimentalConfig {
concurrentRouterQueue?: boolean
instrumentationClientRouterTransitionEvents?: boolean
varyParams?: boolean
/**
* Enables variants.
*
* A variant is a value that each request resolves, from cookies, headers, or
* a flags service. A route can be prerendered against a variant, in addition
* to its route params.
*
* Only Turbopack supports this option. A webpack build rejects it.
*/
variants?: boolean
prefetchInlining?:
| boolean
| {
......
......@@ -600,6 +600,13 @@ function assignDefaultsAndValidate(
)
}
if (result.experimental.variants && !process.env.TURBOPACK) {
throw new Error(
`\`experimental.variants\` is only supported with Turbopack. ` +
`Please remove the option from ${configFileName} or run Next.js with Turbopack.`
)
}
if (
result.experimental.turbopackRustReactCompiler &&
!result.reactCompiler
......
import type { NextRequest } from '../web/spec-extension/request'
import { InvariantError } from '../../shared/lib/invariant-error'
import { throwToInterruptStaticGeneration } from '../app-render/dynamic-rendering'
import {
makeDynamicHangingPromise,
makeRuntimeHangingPromise,
} from '../dynamic-rendering-utils'
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import {
throwForMissingRequestStore,
workUnitAsyncStorage,
} from '../app-render/work-unit-async-storage.external'
/**
* Carries the identity of a variant, in the form `<exportName>@<modulePath>`.
* For example: `theme@variants.ts`, `newNav@src~lib~flags.ts`.
*
* The form escapes the module path. It writes a `/` as `~`, and doubles a
* literal `~`. The identity is therefore one flat token.
*
* Nothing reverses the escaping. Every consumer treats the identity as an
* opaque string and uses it unchanged, so no code needs a mapping table.
*/
const VARIANT_KEY = Symbol.for('next.variant.key')
/**
* Carries the `decide` function, which only the framework may invoke.
*/
const VARIANT_DECIDE = Symbol.for('next.variant.decide')
/**
* A variant, as exported from a `'use variants'` module. A call to it reads the
* value resolved for the current request.
*/
export interface Variant<T extends string = string> {
(): Promise<T>
readonly [VARIANT_KEY]: string
readonly [VARIANT_DECIDE]: (request: NextRequest) => T | Promise<T>
}
/**
* Defines a variant.
*
* A variant is a value that each request resolves, from cookies, headers, or a
* flags service. A route can be prerendered against a variant, in addition to
* its route params.
*
* The framework invokes `decide`, and user code never invokes it. The return
* value is the reader. A call to the reader during a render returns the value
* that the current request resolved.
*
* TODO(variants): `decide` receives the request only until it receives the
* params of the route instead, with cookies and headers reached through their
* own APIs. Resolution then needs the route match that produces those params.
*
* @param key The identity of the variant. TODO(variants): the variants
* transform will inject this, so it is a parameter only until that transform
* exists.
*/
export function unstable_variant<T extends string = string>(
decide: (request: NextRequest) => T | Promise<T>,
key?: string
): Variant<T> {
if (!process.env.__NEXT_VARIANTS) {
throw new Error(
'Variants require the `experimental.variants` option to be enabled in your Next.js config.'
)
}
if (typeof decide !== 'function') {
throw new Error(
'`unstable_variant()` expects a `decide` function as its first argument.'
)
}
if (!key) {
throw new InvariantError(
"A variant was defined without an identity. Variants must be declared in a module with the `'use variants'` directive so that the transform can assign one."
)
}
const read = (): Promise<T> => readVariant(key) as Promise<T>
return Object.defineProperties(read, {
[VARIANT_KEY]: { value: key },
[VARIANT_DECIDE]: { value: decide },
}) as Variant<T>
}
/**
* Reads the value that the current request resolved for a variant.
*
* This function is not `async`, by design. A prerender interrupts a read either
* by postponing or by throwing. The renderer recognizes both only during the
* render itself. A promise rejection would arrive later, and would surface as
* an ordinary error.
*/
function readVariant(key: string): Promise<string> {
const variantName = `variant \`${key}\``
const workStore = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore()
if (!workStore || !workUnitStore) {
throwForMissingRequestStore(variantName)
}
switch (workUnitStore.type) {
case 'request': {
// 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
// that reads a variant, so no matcher configuration explains a missing
// value.
//
// TODO(variants): no code puts values on this store yet, so every read
// reaches this error.
throw new Error(
`Route ${workStore.route} read ${variantName}, but no value was resolved for this request.`
)
}
case 'cache':
case 'unstable-cache':
case 'private-cache': {
throw new Error(
`Route ${workStore.route} read ${variantName} inside a cache scope. This is not supported yet. Read the variant outside the cached function and pass the value in as an argument.`
)
}
case 'generate-static-params': {
throw new Error(
`Route ${workStore.route} read ${variantName} inside \`generateStaticParams\`. This is not supported, because \`generateStaticParams\` is where variant values are enumerated.`
)
}
case 'prerender-client':
case 'validation-client': {
throw new InvariantError(
`${variantName} must not be read within a Client Component. Next.js should be preventing variants from being included in Client Components, but did not in this case.`
)
}
// A request resolves a variant, so no prerender holds a value for one. Each
// read below interrupts the prerender instead, and the value then arrives
// at request time. Each kind of prerender interrupts in the way that it
// requires, as the other request APIs do.
//
// TODO(variants): a prerender produced for a declared combination holds the
// values that the combination fixes, and returns one here. The interrupts
// then cover only the combinations that nothing declared.
case 'prerender': {
// A variant is runtime data, and not dynamic data. A request resolves it
// from cookies and headers, so a runtime prefetch can supply a value
// where a static prerender cannot. This helper also records the access,
// which tells the prefetch encoding that a runtime prefetch returns more
// than the static response.
return makeRuntimeHangingPromise(
workUnitStore.renderSignal,
workStore.route,
variantName,
workUnitStore
)
}
case 'prerender-runtime': {
// A runtime prefetch produces this store. Only a real request resolves a
// variant, so the read is dynamic here.
return makeDynamicHangingPromise(
workUnitStore.renderSignal,
workStore.route,
variantName
)
}
case 'prerender-legacy': {
return throwToInterruptStaticGeneration(
variantName,
workStore,
workUnitStore
)
}
default: {
throw new InvariantError(
`Unexpected work unit store type while reading ${variantName}.`
)
}
}
}
export { unstable_variant, type Variant } from './dist/server/request/variants'
module.exports.unstable_variant =
require('./dist/server/request/variants').unstable_variant
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
import { theme } from '../variants'
// A variant is runtime data, and Cache Components requires a Suspense boundary
// above a read of one.
export default function Page() {
return (
<Suspense fallback={<p id="theme-pending">pending</p>}>
<p id="theme">{theme()}</p>
</Suspense>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
variants: true,
},
}
module.exports = nextConfig
'use variants'
import { unstable_variant } from 'next/variants'
// The second argument is the identity of the variant.
//
// TODO(variants): the variants transform injects the identity. This fixture
// passes it explicitly until that transform exists.
export const theme = unstable_variant(
(request) =>
request.cookies.get('theme')?.value === 'dark' ? 'dark' : 'light',
'theme@variants.ts'
)
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { theme } from '../variants'
// This fixture leaves `experimental.variants` unset. Defining the variant that
// this page imports therefore fails, and the read below never runs.
export default async function Page() {
return <p id="theme">{await theme()}</p>
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {}
module.exports = nextConfig
'use variants'
import { unstable_variant } from 'next/variants'
// The second argument is the identity of the variant.
//
// TODO(variants): the variants transform injects the identity. This fixture
// passes it explicitly until that transform exists.
export const theme = unstable_variant(
(request) =>
request.cookies.get('theme')?.value === 'dark' ? 'dark' : 'light',
'theme@variants.ts'
)
import { isNextDev, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
const rejection =
'Variants require the `experimental.variants` option to be enabled in your Next.js config.'
// Variants are supported with Turbopack only, and a webpack run rejects the
// config before it reaches the check this asserts.
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)(
'variants with the flag off',
() => {
const { next, skipped } = nextTestSetup({
files: __dirname + '/fixtures/flag-off',
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
it('should reject a variant defined without the flag', async () => {
if (isNextDev) {
// Dev compiles a route when a client requests it. Defining the variant
// therefore fails that request, and not a build.
await next.start()
const response = await next.fetch('/')
expect(response.status).toBe(500)
await retry(async () => {
expect(next.cliOutput).toContain(rejection)
})
} else {
const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1)
expect(cliOutput).toContain(rejection)
}
})
}
)
import { isNextDev, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
const rejection = '`experimental.variants` is only supported with Turbopack.'
// This suite is the inverse of the other variants suites. It asserts that the
// config is rejected under a bundler the feature does not support, so it runs
// under webpack only.
;(process.env.IS_TURBOPACK_TEST ? describe.skip : describe)(
'variants with webpack',
() => {
const { next, skipped } = nextTestSetup({
files: __dirname + '/fixtures/default',
skipStart: true,
skipDeployment: true,
})
if (skipped) {
return
}
it('should reject the config', async () => {
if (isNextDev) {
// A dev server reports readiness before the config load that rejects
// it, so the start itself succeeds. The rejection reaches the output,
// and the server then serves nothing.
await next.start()
await retry(async () => {
expect(next.cliOutput).toContain(rejection)
})
} else {
const { exitCode, cliOutput } = await next.build()
expect(exitCode).toBe(1)
expect(cliOutput).toContain(rejection)
}
})
}
)
import { isNextStart, nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
// Variants are supported with Turbopack only, and enabling them rejects a
// webpack build, which `variants-webpack.test.ts` covers.
;(process.env.IS_TURBOPACK_TEST ? describe : describe.skip)('variants', () => {
const { next, skipped } = nextTestSetup({
files: __dirname + '/fixtures/default',
// 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,
// so every mode fails the read alike.
skipDeployment: true,
})
if (skipped) {
return
}
it('should fail a read that no value was resolved for', async () => {
const response = await next.fetch('/')
// A boundary contains a failed read only if something already served that
// boundary. What a request receives therefore depends on what the build
// kept.
if (isNextStart && process.env.__NEXT_CACHE_COMPONENTS) {
// 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
// that shell, and the boundary stays pending.
expect(response.status).toBe(200)
expect(await response.text()).toContain('pending')
} else {
// The build kept no shell. The whole route therefore renders per
// request, and the read fails that request.
expect(response.status).toBe(500)
}
await retry(async () => {
expect(next.cliOutput).toContain(
'read variant `theme@variants.ts`, but no value was resolved for this request'
)
})
})
})
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