Unverified Commit 4f693363 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Support accessing root params in `generateStaticParams` (#91189)

A new `GenerateStaticParamsStore` work unit store type is now provided during `generateStaticParams` execution. This enables root param getters (`import { lang } from 'next/root-params'`) to be called inside `generateStaticParams`, allowing shared helpers that internally access root params via the special import to be used in both Server Components and `generateStaticParams` without manually threading params.

Each `generateStaticParams` call now runs within a `workUnitAsyncStorage.run()` context carrying a `GenerateStaticParamsStore` with the correct `rootParams` (extracted from `parentParams` using the already-available `rootParamKeys`). The store extends `CommonWorkUnitStore`, providing `phase` and `implicitTags` which are not strictly necessary but convenient to keep call sites simple.

Request-time APIs (`headers()`, `cookies()`, `connection()`, `draftMode()`) now throw specific errors when called inside `generateStaticParams` instead of the previous generic "called outside a request scope" message. Framework-internal functions like `createSearchParamsFromClient` and `createParamsFromClient` throw `InvariantError` since they should never be reached in this context.

This change also unblocks a follow-up PR that removes `| undefined` from `PublicCacheContext.outerWorkUnitStore` in the use cache wrapper, since `"use cache"` is already supported inside `generateStaticParams` today but previously ran without a `WorkUnitStore`. With this store in place, requiring a `WorkUnitStore` in `"use cache"` won't break that existing usage.
parent 46789444
......@@ -34,6 +34,12 @@ export async function GET() {
}
```
## `generateStaticParams`
Request-time APIs like `headers()`, `cookies()`, `connection()`, and `draftMode()` are not available inside `generateStaticParams` because it runs at build time to determine which pages to statically generate. There is no HTTP request in this context.
Note: Root param getters (`import { lang } from 'next/root-params'`) _are_ supported inside `generateStaticParams` for nested segments, as the parent params are known at that point.
## Useful Links
- [`headers()` function](/docs/app/api-reference/functions/headers)
......
......@@ -1117,5 +1117,20 @@
"1116": "Route \"%s\" accessed header \"%s\" which is not defined in the \\`samples\\` of \\`unstable_instant\\`. Add it to the sample's \\`headers\\` array, or \\`[\"%s\", null]\\` if it should be absent.",
"1117": "Instant validation boundaries should never appear in browser bundles.",
"1118": "An error occurred while attempting to validate instant UI. This error may be preventing the validation from completing.",
"1119": "Expected edge function entrypoint to emit a JavaScript file"
"1119": "Expected edge function entrypoint to emit a JavaScript file",
"1120": "createServerParamsForServerSegment should not be called inside generateStaticParams.",
"1121": "Route %s used \\`%s\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context",
"1122": "createParamsFromClient should not be called inside generateStaticParams.",
"1123": "Route %s used \\`cookies()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context",
"1124": "createPrerenderSearchParamsForClientPage should not be called inside generateStaticParams.",
"1125": "Route %s used \\`connection()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context",
"1126": "createPrerenderParamsForClientSegment should not be called inside generateStaticParams.",
"1127": "Route %s used \"%s\" inside \\`generateStaticParams\\` which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering",
"1128": "createServerSearchParamsForServerPage should not be called inside generateStaticParams.",
"1129": "createServerPathnameForMetadata should not be called inside generateStaticParams.",
"1130": "\\`%s\\` was called in \\`generateStaticParams\\`. Next.js should be preventing %s from being included in server component files statically, but did not in this case.",
"1131": "createServerParamsForRoute should not be called inside generateStaticParams.",
"1132": "Route %s used \\`draftMode()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context",
"1133": "createSearchParamsFromClient should not be called inside generateStaticParams.",
"1134": "Route %s used \\`headers()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context"
}
......@@ -28,6 +28,12 @@ import { throwEmptyGenerateStaticParamsError } from '../../shared/lib/errors/emp
import type { AppRouteModule } from '../../server/route-modules/app-route/module.compiled'
import type { NormalizedAppRoute } from '../../shared/lib/router/routes/app'
import { interceptionPrefixFromParamType } from '../../shared/lib/router/utils/interception-prefix-from-param-type'
import type {
GenerateStaticParamsStore,
WorkUnitAsyncStorage,
} from '../../server/app-render/work-unit-async-storage.external'
import type { ImplicitTags } from '../../server/lib/implicit-tags'
import { getImplicitTags } from '../../server/lib/implicit-tags'
/**
* Filters out duplicate parameters from a list of parameters.
......@@ -594,6 +600,36 @@ export function assignStaticShellMetadata(
}
}
/**
* Calls a single generateStaticParams function within a WorkUnitStore context,
* making root param getters available during static param generation.
*/
async function callGenerateStaticParams(
generateStaticParams: NonNullable<AppSegment['generateStaticParams']>,
workUnitAsyncStorage: WorkUnitAsyncStorage,
parentParams: Params,
rootParamKeys: readonly string[],
implicitTags: ImplicitTags
): Promise<Params[]> {
const rootParams: Params = {}
for (const key of rootParamKeys) {
if (key in parentParams) {
rootParams[key] = parentParams[key]
}
}
const workUnitStore: GenerateStaticParamsStore = {
type: 'generate-static-params',
phase: 'render',
implicitTags,
rootParams,
}
return workUnitAsyncStorage.run(workUnitStore, generateStaticParams, {
params: parentParams,
})
}
/**
* Processes app directory segments to build route parameters from generateStaticParams functions.
* This function walks through the segments array and calls generateStaticParams for each segment that has it,
......@@ -602,18 +638,25 @@ export function assignStaticShellMetadata(
*
* @param segments - Array of app directory segments to process
* @param store - Work store for tracking fetch cache configuration
* @param workUnitAsyncStorage - AsyncLocalStorage for work unit stores
* @param isRoutePPREnabled - Whether PPR is enabled for this route
* @param rootParamKeys - The keys identifying which params are root params
* @returns Promise that resolves to an array of all parameter combinations
*/
export async function generateRouteStaticParams(
segments: ReadonlyArray<
Readonly<Pick<AppSegment, 'config' | 'generateStaticParams'>>
>,
store: Pick<WorkStore, 'fetchCache'>,
isRoutePPREnabled: boolean
store: Pick<WorkStore, 'fetchCache' | 'page'>,
workUnitAsyncStorage: WorkUnitAsyncStorage,
isRoutePPREnabled: boolean,
rootParamKeys: readonly string[]
): Promise<Params[]> {
// Early return if no segments to process
if (segments.length === 0) return []
const implicitTags = await getImplicitTags(store.page, store.page, null)
// Use iterative processing with a work queue to avoid recursion overhead
interface WorkItem {
segmentIndex: number
......@@ -651,9 +694,13 @@ export async function generateRouteStaticParams(
if (params.length > 0) {
// Process each parent parameter combination
for (const parentParams of params) {
const result = await current.generateStaticParams({
params: parentParams,
})
const result = await callGenerateStaticParams(
current.generateStaticParams,
workUnitAsyncStorage,
parentParams,
rootParamKeys,
implicitTags
)
if (result.length > 0) {
// Merge parent params with each result item
......@@ -669,7 +716,13 @@ export async function generateRouteStaticParams(
}
} else {
// No parent params, call generateStaticParams with empty object
const result = await current.generateStaticParams({ params: {} })
const result = await callGenerateStaticParams(
current.generateStaticParams,
workUnitAsyncStorage,
{},
rootParamKeys,
implicitTags
)
if (result.length === 0 && isRoutePPREnabled) {
throwEmptyGenerateStaticParamsError()
}
......@@ -826,7 +879,9 @@ export async function buildAppStaticPaths({
generateRouteStaticParams,
segments,
store,
isRoutePPREnabled
ComponentMod.workUnitAsyncStorage,
isRoutePPREnabled,
rootParamKeys
)
const generatedParamNames = new Set<string>()
for (const params of routeParams) {
......
......@@ -30,6 +30,7 @@ function hasFallbackRouteParams(): boolean {
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......
......@@ -2118,6 +2118,7 @@ async function renderToHTMLOrFlightImpl(
case 'prerender-legacy':
case 'request':
case 'unstable-cache':
case 'generate-static-params':
return false
default:
workUnitStore satisfies never
......
......@@ -335,6 +335,7 @@ async function createComponentTreeInternal(
case 'prerender-client':
case 'validation-client':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -1290,6 +1291,7 @@ function createSeedData(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......
......@@ -147,6 +147,7 @@ export function markCurrentScopeAsDynamic(
case 'prerender-legacy':
case 'prerender-ppr':
case 'request':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -189,6 +190,8 @@ export function markCurrentScopeAsDynamic(
workUnitStore.usedDynamic = true
}
break
case 'generate-static-params':
break
default:
workUnitStore satisfies never
}
......@@ -244,6 +247,7 @@ export function trackDynamicDataInDynamicRender(workUnitStore: WorkUnitStore) {
case 'prerender-ppr':
case 'prerender-client':
case 'validation-client':
case 'generate-static-params':
break
case 'request':
if (process.env.NODE_ENV !== 'production') {
......@@ -564,6 +568,7 @@ export function createHangingInputAbortSignal(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
return undefined
default:
workUnitStore satisfies never
......@@ -633,6 +638,10 @@ export function useDynamicRouteParams(expression: string) {
throw new InvariantError(
`\`${expression}\` was called inside a cache scope. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`
)
case 'generate-static-params':
throw new InvariantError(
`\`${expression}\` was called in \`generateStaticParams\`. Next.js should be preventing ${expression} from being included in server component files statically, but did not in this case.`
)
case 'prerender-legacy':
case 'request':
case 'unstable-cache':
......@@ -689,6 +698,10 @@ export function useDynamicSearchParams(expression: string) {
throw new InvariantError(
`\`${expression}\` was called inside a cache scope. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`
)
case 'generate-static-params':
throw new InvariantError(
`\`${expression}\` was called in \`generateStaticParams\`. Next.js should be preventing ${expression} from being included in server component files statically, but did not in this case.`
)
case 'request':
return
default:
......
......@@ -305,6 +305,7 @@ export async function decryptActionBoundArgs(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
case undefined:
return controller.close()
default:
......
......@@ -31,6 +31,7 @@ function getValidationBoundaryTracking(): ValidationBoundaryTracking | null {
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
store satisfies never
......
......@@ -38,6 +38,7 @@ export function instrumentParamsForClientValidation<TPArams extends Params>(
case 'request':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -77,6 +78,7 @@ export function expectCompleteParamsInClientValidation(
case 'request':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -113,6 +115,7 @@ export function instrumentSearchParamsForClientValidation(
case 'request':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......
......@@ -46,6 +46,7 @@ function getExpectedSampleTracking(): InstantValidationSampleTracking {
case 'prerender-client':
case 'prerender':
case 'prerender-runtime':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......
......@@ -130,6 +130,7 @@ export function getFlightStream<T>(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......
......@@ -134,6 +134,7 @@ export function createVaryParamsAccumulator(): VaryParamsAccumulator | null {
case 'prerender-client':
case 'validation-client':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -162,6 +163,7 @@ export function getMetadataVaryParamsAccumulator(): VaryParamsAccumulator | null
case 'prerender-client':
case 'validation-client':
case 'unstable-cache':
case 'generate-static-params':
return null
default:
workUnitStore satisfies never
......@@ -209,6 +211,7 @@ export function getRootParamsVaryParamsAccumulator(): VaryParamsAccumulator | nu
case 'prerender-client':
case 'validation-client':
case 'unstable-cache':
case 'generate-static-params':
return null
default:
workUnitStore satisfies never
......
......@@ -378,7 +378,16 @@ export interface UnstableCacheStore extends CommonCacheStore {
*/
export type CacheStore = UseCacheStore | UnstableCacheStore
export type WorkUnitStore = RequestStore | CacheStore | PrerenderStore
export interface GenerateStaticParamsStore extends CommonWorkUnitStore {
readonly type: 'generate-static-params'
readonly rootParams: Params
}
export type WorkUnitStore =
| RequestStore
| CacheStore
| PrerenderStore
| GenerateStaticParamsStore
export type WorkUnitAsyncStorage = AsyncLocalStorage<WorkUnitStore>
......@@ -418,6 +427,7 @@ export function getPrerenderResumeDataCache(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
return null
default:
return workUnitStore satisfies never
......@@ -447,6 +457,7 @@ export function getRenderResumeDataCache(
case 'private-cache':
case 'unstable-cache':
case 'prerender-legacy':
case 'generate-static-params':
return null
default:
return workUnitStore satisfies never
......@@ -470,6 +481,7 @@ export function getHmrRefreshHash(
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -493,6 +505,7 @@ export function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -518,6 +531,7 @@ export function getServerComponentsHmrCache(
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -547,6 +561,7 @@ export function getDraftModeProviderForCacheScope(
case 'validation-client':
case 'prerender-ppr':
case 'prerender-legacy':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -571,6 +586,7 @@ export function getStagedRenderingController(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
return null
default:
return workUnitStore satisfies never
......@@ -598,6 +614,7 @@ export function getCacheSignal(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
return null
default:
return workUnitStore satisfies never
......
......@@ -373,6 +373,7 @@ export function createPatchedFetcher(
break
case 'request':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -412,6 +413,7 @@ export function createPatchedFetcher(
case 'request':
case 'cache':
case 'private-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -583,6 +585,7 @@ export function createPatchedFetcher(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -715,6 +718,7 @@ export function createPatchedFetcher(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -759,6 +763,7 @@ export function createPatchedFetcher(
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -913,6 +918,7 @@ export function createPatchedFetcher(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
case undefined:
return createCachedDynamicResponse(
workStore,
......@@ -996,6 +1002,7 @@ export function createPatchedFetcher(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -1125,6 +1132,7 @@ export function createPatchedFetcher(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -1172,6 +1180,7 @@ export function createPatchedFetcher(
case 'unstable-cache':
case 'prerender-legacy':
case 'prerender-ppr':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......
......@@ -262,6 +262,7 @@ function patchConsoleMethod(methodName: InterceptableConsoleMethod): void {
case 'unstable-cache':
case 'private-cache':
case 'request':
case 'generate-static-params':
case undefined:
if (consoleStore?.dim === true) {
return applyWithDimming.call(
......
......@@ -161,6 +161,7 @@ export function io(expression: string, type: ApiType) {
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......
......@@ -620,6 +620,7 @@ function filteringUnhandledRejectionHandler(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......
......@@ -75,6 +75,10 @@ export function connection(): Promise<void> {
throw new Error(
`Route ${workStore.route} used \`connection()\` inside a function cached with \`unstable_cache()\`. The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual Request, but caches must be able to be produced before a Request so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
case 'generate-static-params':
throw new Error(
`Route ${workStore.route} used \`connection()\` inside \`generateStaticParams\`. This is not supported because \`generateStaticParams\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`
)
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
......
......@@ -74,6 +74,10 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
throw new Error(
`Route ${workStore.route} used \`cookies()\` inside a function cached with \`unstable_cache()\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \`cookies()\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
case 'generate-static-params':
throw new Error(
`Route ${workStore.route} used \`cookies()\` inside \`generateStaticParams\`. This is not supported because \`generateStaticParams\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`
)
case 'prerender':
return makeHangingCookies(workStore, workUnitStore)
case 'prerender-client':
......
......@@ -70,6 +70,10 @@ export function draftMode(): Promise<DraftMode> {
`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`
)
}
case 'generate-static-params':
throw new Error(
`Route ${workStore.route} used \`${callingExpression}()\` inside \`generateStaticParams\`. This is not supported because \`generateStaticParams\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`
)
default:
return workUnitStore satisfies never
......@@ -247,6 +251,10 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) {
case 'request':
trackDynamicDataInDynamicRender(workUnitStore)
break
case 'generate-static-params':
throw new Error(
`Route ${workStore.route} used \`${expression}\` inside \`generateStaticParams\`. This is not supported because \`generateStaticParams\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`
)
default:
workUnitStore satisfies never
}
......
......@@ -75,6 +75,10 @@ export function headers(): Promise<ReadonlyHeaders> {
throw new Error(
`Route ${workStore.route} used \`headers()\` inside a function cached with \`unstable_cache()\`. Accessing Dynamic data sources inside a cache scope is not supported. If you need this data inside a cached function use \`headers()\` outside of the cached function and pass the required dynamic data in as an argument. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
case 'generate-static-params':
throw new Error(
`Route ${workStore.route} used \`headers()\` inside \`generateStaticParams\`. This is not supported because \`generateStaticParams\` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`
)
case 'prerender':
case 'prerender-client':
case 'validation-client':
......
......@@ -83,6 +83,10 @@ export function createParamsFromClient(
throw new InvariantError(
'createParamsFromClient should not be called in a runtime prerender.'
)
case 'generate-static-params':
throw new InvariantError(
'createParamsFromClient should not be called inside generateStaticParams.'
)
case 'request':
if (process.env.NODE_ENV === 'development') {
// Semantically we only need the dev tracking when running in `next dev`
......@@ -163,6 +167,10 @@ export function createServerParamsForRoute(
throw new InvariantError(
'createServerParamsForRoute should not be called in cache contexts.'
)
case 'generate-static-params':
throw new InvariantError(
'createServerParamsForRoute should not be called inside generateStaticParams.'
)
case 'prerender-runtime': {
// Route params are not runtime prefetchable
const isRuntimePrefetchable = false
......@@ -233,6 +241,10 @@ export function createServerParamsForServerSegment(
throw new InvariantError(
'createServerParamsForServerSegment should not be called in cache contexts.'
)
case 'generate-static-params':
throw new InvariantError(
'createServerParamsForServerSegment should not be called inside generateStaticParams.'
)
case 'prerender-runtime':
return createRuntimePrerenderParams(
underlyingParams,
......@@ -327,6 +339,10 @@ export function createPrerenderParamsForClientSegment(
throw new InvariantError(
'createPrerenderParamsForClientSegment should not be called in cache contexts.'
)
case 'generate-static-params':
throw new InvariantError(
'createPrerenderParamsForClientSegment should not be called inside generateStaticParams.'
)
case 'prerender-ppr':
case 'prerender-legacy':
case 'prerender-runtime':
......
......@@ -51,7 +51,10 @@ export function createServerPathnameForMetadata(
throw new InvariantError(
'createServerPathnameForMetadata should not be called in cache contexts.'
)
case 'generate-static-params':
throw new InvariantError(
'createServerPathnameForMetadata should not be called inside generateStaticParams.'
)
case 'prerender-runtime':
return delayUntilRuntimeStage(
workUnitStore,
......
......@@ -101,7 +101,8 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
break
}
case 'private-cache':
case 'prerender-runtime': {
case 'prerender-runtime':
case 'generate-static-params': {
break
}
default: {
......
......@@ -77,6 +77,10 @@ export function createSearchParamsFromClient(
throw new InvariantError(
'createSearchParamsFromClient should not be called in cache contexts.'
)
case 'generate-static-params':
throw new InvariantError(
'createSearchParamsFromClient should not be called inside generateStaticParams.'
)
case 'request':
// Client searchParams are not runtime prefetchable
const isRuntimePrefetchable = false
......@@ -133,6 +137,10 @@ export function createServerSearchParamsForServerPage(
throw new InvariantError(
'createServerSearchParamsForServerPage should not be called in cache contexts.'
)
case 'generate-static-params':
throw new InvariantError(
'createServerSearchParamsForServerPage should not be called inside generateStaticParams.'
)
case 'prerender-runtime':
return createRuntimePrerenderSearchParams(
underlyingSearchParams,
......@@ -191,6 +199,10 @@ export function createPrerenderSearchParamsForClientPage(): Promise<SearchParams
throw new InvariantError(
'createPrerenderSearchParamsForClientPage should not be called in cache contexts.'
)
case 'generate-static-params':
throw new InvariantError(
'createPrerenderSearchParamsForClientPage should not be called inside generateStaticParams.'
)
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
......
......@@ -1243,6 +1243,8 @@ function trackDynamic(
workUnitStore.usedDynamic = true
}
break
case 'generate-static-params':
break
default:
workUnitStore satisfies never
}
......
......@@ -92,6 +92,7 @@ export function cacheLife(profile: CacheLifeProfiles | CacheLife): void {
case 'prerender-legacy':
case 'request':
case 'unstable-cache':
case 'generate-static-params':
case undefined:
throw new Error(
'`cacheLife()` can only be called inside a "use cache" function.'
......
......@@ -19,6 +19,7 @@ export function cacheTag(...tags: string[]): void {
case 'prerender-legacy':
case 'request':
case 'unstable-cache':
case 'generate-static-params':
case undefined:
throw new Error(
'`cacheTag()` can only be called inside a "use cache" function.'
......
......@@ -246,6 +246,7 @@ function createUseCacheStore(
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
case 'generate-static-params':
break
default:
outerWorkUnitStore satisfies never
......@@ -405,6 +406,7 @@ function propagateCacheLifeAndTags(
)
break
case 'unstable-cache':
case 'generate-static-params':
case undefined:
break
default:
......@@ -544,6 +546,8 @@ async function collectResult(
propagateCacheLifeAndTags(cacheContext, entry)
break
}
case 'generate-static-params':
break
default: {
outerWorkUnitStore satisfies never
}
......@@ -626,6 +630,7 @@ async function generateCacheEntryImpl(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
outerWorkUnitStore satisfies never
......@@ -766,6 +771,7 @@ async function generateCacheEntryImpl(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
case undefined:
stream = renderToReadableStream(
resultPromise,
......@@ -1003,6 +1009,7 @@ export async function cache(
outerWorkUnitStore: workUnitStore,
}
break
case 'generate-static-params':
case undefined:
throw wrapAsInvalidDynamicUsageError(
new Error(
......@@ -1035,6 +1042,7 @@ export async function cache(
// TODO: We should probably forbid nesting "use cache" inside
// unstable_cache. (fallthrough)
case 'unstable-cache':
case 'generate-static-params':
case undefined:
cacheContext = {
kind: 'public',
......@@ -1286,6 +1294,7 @@ export async function cache(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
case undefined:
encodedCacheKeyParts = await encodeCacheKeyParts()
break
......@@ -1441,6 +1450,7 @@ export async function cache(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -1490,6 +1500,7 @@ export async function cache(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -1567,6 +1578,7 @@ export async function cache(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -1695,6 +1707,7 @@ export async function cache(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -1948,6 +1961,7 @@ function shouldForceRevalidate(
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -1995,6 +2009,7 @@ function shouldDiscardCacheEntry(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......
......@@ -147,6 +147,10 @@ function revalidate(
throw new Error(
`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
case 'generate-static-params':
throw new Error(
`Route ${store.route} used "${expression}" inside \`generateStaticParams\` which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
case 'prerender':
case 'prerender-runtime':
// cacheComponents Prerender
......
......@@ -197,6 +197,7 @@ export function unstable_cache<T extends Callback>(
case 'prerender-client':
case 'validation-client':
case 'request':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......@@ -417,6 +418,7 @@ function getFetchUrlPrefix(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
return workStore.route
default:
return workUnitStore satisfies never
......
......@@ -44,6 +44,7 @@ export function unstable_noStore() {
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'generate-static-params':
break
default:
workUnitStore satisfies never
......
import { lang, locale } from 'next/root-params'
import { Suspense } from 'react'
export async function generateStaticParams() {
const l = await lang()
return [{ slug: `${l}-post` }]
}
export default async function Page({ params }) {
return (
<main>
......
......@@ -36,4 +36,17 @@ describe('app-root-param-getters - generateStaticParams', () => {
const $ = await next.render$(`/${params.lang}/${params.locale}`)
expect($('p').text()).toBe(`hello world ${JSON.stringify(params)}`)
})
it('should allow reading root params inside generateStaticParams', async () => {
// The [slug] segment's generateStaticParams uses `lang()` to produce
// slugs like "en-post". If root params are available during
// generateStaticParams, this page should be statically prerenderable.
const response = await next.fetch('/en/us/other/en-post')
expect(response.status).toBe(200)
const $ = cheerio.load(await response.text())
expect($('#root-params').text()).toBe(
JSON.stringify({ lang: 'en', locale: 'us' })
)
expect($('#dynamic-params').text()).toBe('en-post')
})
})
......@@ -22,35 +22,33 @@ describe('generate-static-params-errors', () => {
it('should error when cookies() is called inside generateStaticParams', async () => {
await buildRoute('app/[lang]/cookies/[slug]/page.tsx')
expect(getCliOutput()).toContain(
'Error: `cookies` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context'
'Error: Route /[lang]/cookies/[slug] used `cookies()` inside `generateStaticParams`. This is not supported because `generateStaticParams` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context'
)
})
it('should error when headers() is called inside generateStaticParams', async () => {
await buildRoute('app/[lang]/headers/[slug]/page.tsx')
expect(getCliOutput()).toContain(
'Error: `headers` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context'
'Error: Route /[lang]/headers/[slug] used `headers()` inside `generateStaticParams`. This is not supported because `generateStaticParams` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context'
)
})
it('should error when connection() is called inside generateStaticParams', async () => {
await buildRoute('app/[lang]/connection/[slug]/page.tsx')
expect(getCliOutput()).toContain(
'Error: `connection` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context'
'Error: Route /[lang]/connection/[slug] used `connection()` inside `generateStaticParams`. This is not supported because `generateStaticParams` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context'
)
})
it('should error when draftMode() is called inside generateStaticParams', async () => {
await buildRoute('app/[lang]/draft-mode/[slug]/page.tsx')
expect(getCliOutput()).toContain(
'Error: `draftMode` was called outside a request scope. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context'
'Error: Route /[lang]/draft-mode/[slug] used `draftMode()` inside `generateStaticParams`. This is not supported because `generateStaticParams` runs at build time without an HTTP request. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context'
)
})
it('should error when root params are accessed inside generateStaticParams', async () => {
it('should allow root params access inside generateStaticParams', async () => {
await buildRoute('app/[lang]/root-params/[slug]/page.tsx')
expect(getCliOutput()).toContain(
"Error: Route /[lang]/root-params/[slug] used `import('next/root-params').lang()` outside of a Server Component. This is not allowed."
)
expect(getCliOutput()).not.toContain('Error')
})
})
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