Unverified Commit abe3b50d authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[PPF] `ensureStatic = "navigation"` (#99171)

Closes NAR-930

Initial implementation of `ensureStatic = "navigation"`

### Behavior

This version of `ensureStatic = "navigation"` makes all prerenders
blocking. All params must be specified via `generateStaticParams`,
similar to `output: "export"`. This is meant to ensure that we don't
serve a fallback + a resume for a param that wasn't prerendered, which
would violate the expectation that `ensureStatic = "navigation"` means
no per-request compute, which is what we're trying to provide.

Note that Client-only IO (like `use(io())` or `useSearchParams()`) is
allowed, because it doesn't require a resume render -- we serve HTML
with fallbacks and render the missing content in the browser. (this is
existing behavior and not changed here)

Earlier versions of this PR attempted to allow fallback shells if they
managed to produce a complete RSC result, e.g. on a route with params
that are only used via `useParams()`, where could use the same browser
bailout trick as other client IO. This proved complex to implement
correctly, so we'll revisit that in the future

### Prerender output changes

We skip producing all fallback shells except the most generic one in
`buildAppStaticPaths`. Initially, i wanted to remove all of them, but it
seems like the deploy output is incorrect if we don't have segment data
from a fallback prerender. We also error for incomplete/missing
`generateStaticParams`, which makes it impossible to create a
purely-fallback param.

### Validation

This PR extends the Static Shell Validation logic to be more restrictive
when `ensureStatic = "navigation"`. We can't allow _any_ usages of
dynamic data, even when wrapped with suspense. The new logic is
expressed in `trackDynamicAccessInStaticRoute` +
`getDisallowedReasonsInStaticRoute` which we use both in dev and prod.
we check whether the server prerender was partial (which is already an
error) and then run static shell validation so we can report where the
hole was. This has some drawbacks:
- if we have both server and client holes we might misreport the client
ones as dynamic data. I have some ideas for how to address this, but for
now this is the best we can do. (see `mixed server and client holes` in
`ensure-static-navigation.test.ts` for examples)
- if the client got a dynamic data promise but didn't `use()` it during
the prerender (maybe because it was just seeding a cache for use in the
browser), we won't have a dynamic hole to point to. in that case we'll
error with a generic error message instead (see
`errorPattern.body.withoutLocation` in
`ensure-static-navigation.test.ts`).

i've added new error messages to match the constraints of `ensureStatic
= "navigation"`. we no longer recommend `instant = false` or `suspense`
for dynamic data, because that's not a valid fix. there's a new
suggestion: "make your \`params\` static via `generateStaticParams\`".

(note that the messages don't have the "pretty" errors with suggestion
cards yet, just the string message. i will update the dev error logic in
a follow-up. docs are needed as well)

i've also done a bit of cleanup: `trackDynamicHoleInStaticShell` and
`trackDynamicHoleInRuntimeShell` are now one function that takes a
`kind` parameter, because they only differed on the error message
variant they reported (runtime vs dynamic).
parent e32cb8e4
...@@ -244,6 +244,8 @@ import { ...@@ -244,6 +244,8 @@ import {
import { generateRoutesManifest } from './generate-routes-manifest' import { generateRoutesManifest } from './generate-routes-manifest'
import { buildCustomRoute } from '../lib/build-custom-route' import { buildCustomRoute } from '../lib/build-custom-route'
import { validateAppPaths } from './validate-app-paths' import { validateAppPaths } from './validate-app-paths'
import { throwMissingGspErrorInStaticRoute } from '../shared/lib/errors/ensure-static-gsp-errors'
import { isEmptyParams } from '../server/lib/params-utils'
type Fallback = null | boolean | string type Fallback = null | boolean | string
...@@ -321,6 +323,12 @@ export interface PrerenderManifestRoute ...@@ -321,6 +323,12 @@ export interface PrerenderManifestRoute
*/ */
renderingMode: RenderingMode | undefined renderingMode: RenderingMode | undefined
// TODO(ensure-static): communicate this in a better way
/**
* Whether this page had `ensureStatic = "navigation"`
* */
_isEnsureStaticPage?: true
/** /**
* The headers that are allowed to be used when revalidating this route. These * The headers that are allowed to be used when revalidating this route. These
* are used internally by Next.js to revalidate routes. * are used internally by Next.js to revalidate routes.
...@@ -400,6 +408,12 @@ export interface DynamicPrerenderManifestRoute ...@@ -400,6 +408,12 @@ export interface DynamicPrerenderManifestRoute
*/ */
renderingMode: RenderingMode | undefined renderingMode: RenderingMode | undefined
// TODO(ensure-static): communicate this in a better way
/**
* Whether this page had `ensureStatic = "navigation"`
* */
_isEnsureStaticPage?: true
/** /**
* The headers that are allowed to be used when revalidating this route. These * The headers that are allowed to be used when revalidating this route. These
* are used internally by Next.js to revalidate routes. * are used internally by Next.js to revalidate routes.
...@@ -2343,6 +2357,7 @@ export default async function build( ...@@ -2343,6 +2357,7 @@ export default async function build(
distDir, distDir,
configFileName, configFileName,
cacheComponents: isAppCacheComponentsEnabled, cacheComponents: isAppCacheComponentsEnabled,
partialPrefetching: config.partialPrefetching,
authInterrupts: isAuthInterruptsEnabled, authInterrupts: isAuthInterruptsEnabled,
useCacheTimeout: config.experimental.useCacheTimeout, useCacheTimeout: config.experimental.useCacheTimeout,
durableUseCacheEntries: Boolean( durableUseCacheEntries: Boolean(
...@@ -2445,6 +2460,7 @@ export default async function build( ...@@ -2445,6 +2460,7 @@ export default async function build(
const actualPage = normalizePagePath(page) const actualPage = normalizePagePath(page)
let isRoutePPREnabled = false let isRoutePPREnabled = false
let isEnsureStaticPage = false
let isSSG = false let isSSG = false
let isStatic = false let isStatic = false
let isServerComponent = false let isServerComponent = false
...@@ -2577,6 +2593,7 @@ export default async function build( ...@@ -2577,6 +2593,7 @@ export default async function build(
edgeInfo, edgeInfo,
pageType, pageType,
cacheComponents: isAppCacheComponentsEnabled, cacheComponents: isAppCacheComponentsEnabled,
partialPrefetching: config.partialPrefetching,
authInterrupts: isAuthInterruptsEnabled, authInterrupts: isAuthInterruptsEnabled,
useCacheTimeout: useCacheTimeout:
config.experimental.useCacheTimeout, config.experimental.useCacheTimeout,
...@@ -2620,6 +2637,15 @@ export default async function build( ...@@ -2620,6 +2637,15 @@ export default async function build(
typeof workerResult.isRoutePPREnabled === 'boolean' typeof workerResult.isRoutePPREnabled === 'boolean'
) { ) {
isRoutePPREnabled = workerResult.isRoutePPREnabled isRoutePPREnabled = workerResult.isRoutePPREnabled
if (
config.cacheComponents &&
isRoutePPREnabled &&
workerResult.appConfig
) {
isEnsureStaticPage =
workerResult.appConfig.unstable_ensureStatic ===
'navigation'
}
} }
// If this route can be partially pre-rendered, then // If this route can be partially pre-rendered, then
...@@ -2654,16 +2680,22 @@ export default async function build( ...@@ -2654,16 +2680,22 @@ export default async function build(
if (appConfig.revalidate !== 0) { if (appConfig.revalidate !== 0) {
const hasGenerateStaticParams = const hasGenerateStaticParams =
workerResult.prerenderedRoutes && workerResult.prerenderedRoutes &&
workerResult.prerenderedRoutes.length > 0 workerResult.prerenderedRoutes.length > 0 &&
// in PPR, we create fallback routes with empty params.
if ( // If at least one non-empty param exists, it must've been
config.output === 'export' && // generated by `generateStaticParams`.
isDynamic && workerResult.prerenderedRoutes.some(
!hasGenerateStaticParams (route) => !isEmptyParams(route.params)
) {
throw new Error(
`Page "${page}" is missing "generateStaticParams()" so it cannot be used with "output: export" config. See more info here: https://nextjs.org/docs/messages/generate-static-params`
) )
if (isDynamic && !hasGenerateStaticParams) {
if (config.output === 'export') {
throw new Error(
`Page "${page}" is missing "generateStaticParams()" so it cannot be used with "output: export" config. See more info here: https://nextjs.org/docs/messages/generate-static-params`
)
}
if (isEnsureStaticPage) {
throwMissingGspErrorInStaticRoute(page)
}
} }
// Mark the app as static if: // Mark the app as static if:
...@@ -2816,6 +2848,7 @@ export default async function build( ...@@ -2816,6 +2848,7 @@ export default async function build(
isStatic, isStatic,
isSSG, isSSG,
isRoutePPREnabled, isRoutePPREnabled,
isEnsureStaticPage,
ssgPageRoutes, ssgPageRoutes,
initialCacheControl: undefined, initialCacheControl: undefined,
runtime: pageRuntime, runtime: pageRuntime,
...@@ -3544,6 +3577,9 @@ export default async function build( ...@@ -3544,6 +3577,9 @@ export default async function build(
} }
} }
const isEnsureStaticPage =
pageInfos.get(page)?.isEnsureStaticPage === true
// Handle all the static routes. // Handle all the static routes.
for (const route of concretePrerenderCandidates) { for (const route of concretePrerenderCandidates) {
if (isDynamicRoute(page) && route.pathname === page) continue if (isDynamicRoute(page) && route.pathname === page) continue
...@@ -3646,6 +3682,7 @@ export default async function build( ...@@ -3646,6 +3682,7 @@ export default async function build(
: RenderingMode.STATIC : RenderingMode.STATIC
: undefined, : undefined,
...classification, ...classification,
_isEnsureStaticPage: isEnsureStaticPage || undefined,
experimentalPPR: isRoutePPREnabled, experimentalPPR: isRoutePPREnabled,
experimentalBypassFor: bypassFor, experimentalBypassFor: bypassFor,
initialRevalidateSeconds: cacheControl.revalidate, initialRevalidateSeconds: cacheControl.revalidate,
...@@ -3950,6 +3987,7 @@ export default async function build( ...@@ -3950,6 +3987,7 @@ export default async function build(
route.remainingPrerenderableParams, route.remainingPrerenderableParams,
throwOnEmptyStaticShell: throwOnEmptyStaticShell:
prerenderCandidate?.throwOnEmptyStaticShell, prerenderCandidate?.throwOnEmptyStaticShell,
_isEnsureStaticPage: isEnsureStaticPage || undefined,
renderingMode: isAppPPREnabled renderingMode: isAppPPREnabled
? isRoutePPREnabled ? isRoutePPREnabled
? RenderingMode.PARTIALLY_STATIC ? RenderingMode.PARTIALLY_STATIC
......
...@@ -18,6 +18,8 @@ import { ...@@ -18,6 +18,8 @@ import {
type LoaderTree, type LoaderTree,
} from '../../../server/lib/app-dir-module' } from '../../../server/lib/app-dir-module'
import type { DynamicParamTypes } from '../../../shared/lib/app-router-types' import type { DynamicParamTypes } from '../../../shared/lib/app-router-types'
import { resolveEnsureStaticConfig } from '../../../server/app-render/segment-config/ensure-static'
import { anySegmentHasPartialPrefetchingEnabled } from '../../../server/app-render/instant-validation/instant-config'
type GenerateStaticParams = (options: { params?: Params }) => Promise<Params[]> type GenerateStaticParams = (options: { params?: Params }) => Promise<Params[]>
...@@ -79,13 +81,31 @@ export type AppSegment = { ...@@ -79,13 +81,31 @@ export type AppSegment = {
* @param routeModule the app page route module * @param routeModule the app page route module
* @returns the segments for the app page route module * @returns the segments for the app page route module
*/ */
async function collectAppPageSegments(routeModule: AppPageRouteModule) { async function collectAppPageSegments(
routeModule: AppPageRouteModule,
config: { cacheComponents: boolean; partialPrefetching: boolean } | undefined
) {
// We keep track of unique segments, since with parallel routes, it's possible // We keep track of unique segments, since with parallel routes, it's possible
// to see the same segment multiple times. // to see the same segment multiple times.
const segments: AppSegment[] = [] const segments: AppSegment[] = []
const rootLoaderTree = routeModule.userland.loaderTree
// `ensureStatic` needs to be validated against the tree structure,
// so we cannot compute it easily in `reduceAppConfig` after the tree
// is turned into an array of segments
const routeHasPartialPrefetching =
(config?.partialPrefetching ?? false) ||
(await anySegmentHasPartialPrefetchingEnabled(rootLoaderTree))
const prefetchConfig = routeHasPartialPrefetching ? 'partial' : 'auto'
const ensureStatic = await resolveEnsureStaticConfig(
rootLoaderTree,
routeHasPartialPrefetching
)
// Queue will store loader trees. // Queue will store loader trees.
const queue: LoaderTree[] = [routeModule.userland.loaderTree] const queue: LoaderTree[] = [rootLoaderTree]
while (queue.length > 0) { while (queue.length > 0) {
const loaderTree = queue.shift()! const loaderTree = queue.shift()!
...@@ -109,6 +129,11 @@ async function collectAppPageSegments(routeModule: AppPageRouteModule) { ...@@ -109,6 +129,11 @@ async function collectAppPageSegments(routeModule: AppPageRouteModule) {
// Only server components can have app segment configurations // Only server components can have app segment configurations
if (!isClientComponent) { if (!isClientComponent) {
attach(segment, userland, routeModule.definition.pathname) attach(segment, userland, routeModule.definition.pathname)
if (segment.config) {
segment.config.prefetch = prefetchConfig
segment.config.unstable_ensureStatic = ensureStatic
}
} }
// If this segment doesn't already exist, then add it to the segments array. // If this segment doesn't already exist, then add it to the segments array.
...@@ -187,14 +212,15 @@ async function collectAppRouteSegments( ...@@ -187,14 +212,15 @@ async function collectAppRouteSegments(
* @returns the segments for the route module * @returns the segments for the route module
*/ */
export function collectSegments( export function collectSegments(
routeModule: AppRouteRouteModule | AppPageRouteModule routeModule: AppRouteRouteModule | AppPageRouteModule,
config: { cacheComponents: boolean; partialPrefetching: boolean } | undefined
): Promise<AppSegment[]> | AppSegment[] { ): Promise<AppSegment[]> | AppSegment[] {
if (isAppRouteRouteModule(routeModule)) { if (isAppRouteRouteModule(routeModule)) {
return collectAppRouteSegments(routeModule) return collectAppRouteSegments(routeModule)
} }
if (isAppPageRouteModule(routeModule)) { if (isAppPageRouteModule(routeModule)) {
return collectAppPageSegments(routeModule) return collectAppPageSegments(routeModule, config)
} }
throw new InvariantError( throw new InvariantError(
......
...@@ -39,6 +39,10 @@ import { ...@@ -39,6 +39,10 @@ import {
} from '../../server/app-render/work-unit-async-storage.external' } from '../../server/app-render/work-unit-async-storage.external'
import type { ImplicitTags } from '../../server/lib/implicit-tags' import type { ImplicitTags } from '../../server/lib/implicit-tags'
import { getImplicitTags } from '../../server/lib/implicit-tags' import { getImplicitTags } from '../../server/lib/implicit-tags'
import {
throwIncompleteStaticParamsErrorInStaticRoute,
throwMissingGspErrorInStaticRoute,
} from '../../shared/lib/errors/ensure-static-gsp-errors'
/** /**
* Filters out duplicate parameters from a list of parameters. * Filters out duplicate parameters from a list of parameters.
...@@ -837,6 +841,7 @@ export async function buildAppStaticPaths({ ...@@ -837,6 +841,7 @@ export async function buildAppStaticPaths({
nextConfigOutput, nextConfigOutput,
ComponentMod, ComponentMod,
isRoutePPREnabled = false, isRoutePPREnabled = false,
isEnsureStaticPage,
buildId, buildId,
deploymentId, deploymentId,
rootParamKeys, rootParamKeys,
...@@ -861,6 +866,7 @@ export async function buildAppStaticPaths({ ...@@ -861,6 +866,7 @@ export async function buildAppStaticPaths({
nextConfigOutput: 'standalone' | 'export' | undefined nextConfigOutput: 'standalone' | 'export' | undefined
ComponentMod: AppPageModule | AppRouteModule ComponentMod: AppPageModule | AppRouteModule
isRoutePPREnabled: boolean isRoutePPREnabled: boolean
isEnsureStaticPage: boolean
buildId: string buildId: string
deploymentId: string deploymentId: string
rootParamKeys: readonly string[] rootParamKeys: readonly string[]
...@@ -982,18 +988,18 @@ export async function buildAppStaticPaths({ ...@@ -982,18 +988,18 @@ export async function buildAppStaticPaths({
} }
const missingParamNames: string[] = [] const missingParamNames: string[] = []
if (routeParams.length > 0) { for (const { paramName } of pathnameRouteParamSegments) {
for (const { paramName } of pathnameRouteParamSegments) { if (
if (routeParams.some((params) => !(paramName in params))) { routeParams.length === 0 ||
missingParamNames.push(paramName) routeParams.some((params) => !(paramName in params))
} ) {
missingParamNames.push(paramName)
} }
} }
// Determine if all the segments have had their parameters provided. // Determine if all the segments have had their parameters provided.
const hadAllParamsGenerated = const hadAllParamsGenerated =
pathnameRouteParamSegments.length === 0 || pathnameRouteParamSegments.length === 0 || missingParamNames.length === 0
(routeParams.length > 0 && missingParamNames.length === 0)
if ( if (
nextConfigOutput === 'export' && nextConfigOutput === 'export' &&
...@@ -1005,6 +1011,18 @@ export async function buildAppStaticPaths({ ...@@ -1005,6 +1011,18 @@ export async function buildAppStaticPaths({
) )
} }
// `ensureStatic = "navigation"` currently requires all params to
// be prerendered via gSP.
if (isEnsureStaticPage && pathnameRouteParamSegments.length > 0) {
if (routeParams.length === 0) {
// In Cache Components we throw in `generateRouteStaticParams` for empty arrays,
// so empty `routeParams` implies that no `generateStaticParams` is present at all
throwMissingGspErrorInStaticRoute(page)
} else if (!hadAllParamsGenerated) {
throwIncompleteStaticParamsErrorInStaticRoute(page, missingParamNames)
}
}
// TODO: dynamic params should be allowed to be granular per segment but // TODO: dynamic params should be allowed to be granular per segment but
// we need additional information stored/leveraged in the prerender // we need additional information stored/leveraged in the prerender
// manifest to allow this behavior. // manifest to allow this behavior.
...@@ -1018,7 +1036,10 @@ export async function buildAppStaticPaths({ ...@@ -1018,7 +1036,10 @@ export async function buildAppStaticPaths({
const fallbackMode = dynamicParams const fallbackMode = dynamicParams
? supportsRoutePreGeneration ? supportsRoutePreGeneration
? isRoutePPREnabled ? isRoutePPREnabled
? FallbackMode.PRERENDER ? isEnsureStaticPage
? // In `ensureStatic = "navigation"` all prerenders have to be blocking.
FallbackMode.BLOCKING_STATIC_RENDER
: FallbackMode.PRERENDER
: FallbackMode.BLOCKING_STATIC_RENDER : FallbackMode.BLOCKING_STATIC_RENDER
: undefined : undefined
: FallbackMode.NOT_FOUND : FallbackMode.NOT_FOUND
...@@ -1032,6 +1053,9 @@ export async function buildAppStaticPaths({ ...@@ -1032,6 +1053,9 @@ export async function buildAppStaticPaths({
let paramsToProcess = routeParams let paramsToProcess = routeParams
if (isRoutePPREnabled) { if (isRoutePPREnabled) {
// NOTE: we do this even if `ensureStatic = "navigation"` is set because
// most of the build plumbing assumes that we'll have done fallback prerenders.
// Discover all unique combinations of the routeParams so we can generate // Discover all unique combinations of the routeParams so we can generate
// routes that won't throw on empty static shell for each of them if // routes that won't throw on empty static shell for each of them if
// they're available. // they're available.
...@@ -1087,7 +1111,13 @@ export async function buildAppStaticPaths({ ...@@ -1087,7 +1111,13 @@ export async function buildAppStaticPaths({
const paramValue = params[paramName] const paramValue = params[paramName]
if (!paramValue) { if (!paramValue) {
if (isRoutePPREnabled) { if (
isRoutePPREnabled &&
// `ensureStatic = "navigation"` does not currently use fallbacks
// with some of the params filled in. We only use create route with all
// the params set to fallback so that ISR is set up correctly.
!isEnsureStaticPage
) {
// Mark remaining params as fallback params. // Mark remaining params as fallback params.
fallbackRouteParams.push({ paramName, paramType }) fallbackRouteParams.push({ paramName, paramType })
for ( for (
......
...@@ -499,6 +499,7 @@ export function createAppPageEntrypoint({ ...@@ -499,6 +499,7 @@ export function createAppPageEntrypoint({
// because we can't cache the HTML (as it's also dynamic). // because we can't cache the HTML (as it's also dynamic).
const staticPrefetchDataRoute = const staticPrefetchDataRoute =
prerenderManifest.routes[resolvedPathname]?.prefetchDataRoute prerenderManifest.routes[resolvedPathname]?.prefetchDataRoute
const isEnsureStaticPage = prerenderInfo?._isEnsureStaticPage === true
let isDynamicRSCRequest = let isDynamicRSCRequest =
isRoutePPREnabled && isRoutePPREnabled &&
...@@ -507,7 +508,11 @@ export function createAppPageEntrypoint({ ...@@ -507,7 +508,11 @@ export function createAppPageEntrypoint({
// If generated at build time, treat the RSC request as static // If generated at build time, treat the RSC request as static
// so we can serve the prebuilt .rsc without a dynamic render. // so we can serve the prebuilt .rsc without a dynamic render.
// Only do this for routes that have a concrete prefetchDataRoute. // Only do this for routes that have a concrete prefetchDataRoute.
!staticPrefetchDataRoute !staticPrefetchDataRoute &&
// Do not serve `ensureStatic = "navigation"` with a dynamic response,
// (we want to do a blocking prerender instead)
// TODO(ensure-static): express this in a cleaner way
!isEnsureStaticPage
// During a PPR revalidation, the RSC request is not dynamic if postponed // During a PPR revalidation, the RSC request is not dynamic if postponed
// metadata is absent. An empty string represents a resume request without // metadata is absent. An empty string represents a resume request without
...@@ -1168,6 +1173,8 @@ export function createAppPageEntrypoint({ ...@@ -1168,6 +1173,8 @@ export function createAppPageEntrypoint({
if ( if (
nextConfig.partialPrefetching && nextConfig.partialPrefetching &&
prerenderInfo?.fallback === null && prerenderInfo?.fallback === null &&
// TODO(ensure-static): express this in a cleaner way
!isEnsureStaticPage &&
!hasOmittedConcreteFallbackParam && !hasOmittedConcreteFallbackParam &&
!hasUnresolvedRootFallbackParams && !hasUnresolvedRootFallbackParams &&
remainingPrerenderableParams.length > 0 remainingPrerenderableParams.length > 0
......
...@@ -214,6 +214,7 @@ export interface PageInfo { ...@@ -214,6 +214,7 @@ export interface PageInfo {
* If true, it means that the route has partial prerendering enabled. * If true, it means that the route has partial prerendering enabled.
*/ */
isRoutePPREnabled: boolean isRoutePPREnabled: boolean
isEnsureStaticPage: boolean
ssgPageRoutes: string[] | null ssgPageRoutes: string[] | null
initialCacheControl: CacheControl | undefined initialCacheControl: CacheControl | undefined
pageDuration: number | undefined pageDuration: number | undefined
...@@ -698,6 +699,7 @@ export async function isPageStatic({ ...@@ -698,6 +699,7 @@ export async function isPageStatic({
edgeInfo, edgeInfo,
pageType, pageType,
cacheComponents, cacheComponents,
partialPrefetching,
authInterrupts, authInterrupts,
useCacheTimeout, useCacheTimeout,
durableUseCacheEntries, durableUseCacheEntries,
...@@ -718,6 +720,7 @@ export async function isPageStatic({ ...@@ -718,6 +720,7 @@ export async function isPageStatic({
page: string page: string
distDir: string distDir: string
cacheComponents: boolean cacheComponents: boolean
partialPrefetching: boolean
authInterrupts: boolean authInterrupts: boolean
useCacheTimeout: number useCacheTimeout: number
durableUseCacheEntries: boolean durableUseCacheEntries: boolean
...@@ -845,7 +848,8 @@ export async function isPageStatic({ ...@@ -845,7 +848,8 @@ export async function isPageStatic({
segments = await collectSegments( segments = await collectSegments(
// We know this is an app page or app route module because we // We know this is an app page or app route module because we
// checked above that the page type is 'app'. // checked above that the page type is 'app'.
routeModule as AppPageRouteModule | AppRouteRouteModule routeModule as AppPageRouteModule | AppRouteRouteModule,
{ cacheComponents, partialPrefetching }
) )
} catch (err) { } catch (err) {
throw new Error(`Failed to collect configuration for ${page}`, { throw new Error(`Failed to collect configuration for ${page}`, {
...@@ -871,6 +875,11 @@ export async function isPageStatic({ ...@@ -871,6 +875,11 @@ export async function isPageStatic({
isRoutePPREnabled = isRoutePPREnabled =
routeModule.definition.kind === RouteKind.APP_PAGE && cacheComponents routeModule.definition.kind === RouteKind.APP_PAGE && cacheComponents
const isEnsureStaticPage =
cacheComponents &&
isRoutePPREnabled &&
appConfig.unstable_ensureStatic === 'navigation'
// If force dynamic was set and we don't have PPR enabled, then set the // If force dynamic was set and we don't have PPR enabled, then set the
// revalidate to 0. // revalidate to 0.
// TODO: (PPR) remove this once PPR is enabled by default // TODO: (PPR) remove this once PPR is enabled by default
...@@ -919,6 +928,7 @@ export async function isPageStatic({ ...@@ -919,6 +928,7 @@ export async function isPageStatic({
ComponentMod, ComponentMod,
nextConfigOutput, nextConfigOutput,
isRoutePPREnabled, isRoutePPREnabled,
isEnsureStaticPage,
buildId, buildId,
deploymentId, deploymentId,
rootParamKeys, rootParamKeys,
...@@ -1020,6 +1030,8 @@ type ReducedAppConfig = Pick< ...@@ -1020,6 +1030,8 @@ type ReducedAppConfig = Pick<
| 'preferredRegion' | 'preferredRegion'
| 'runtime' | 'runtime'
| 'maxDuration' | 'maxDuration'
| 'prefetch'
| 'unstable_ensureStatic'
> >
/** /**
...@@ -1042,6 +1054,8 @@ export function reduceAppConfig( ...@@ -1042,6 +1054,8 @@ export function reduceAppConfig(
revalidate, revalidate,
runtime, runtime,
maxDuration, maxDuration,
prefetch,
unstable_ensureStatic,
} = segment.config || {} } = segment.config || {}
// TODO: should conflicting configs here throw an error // TODO: should conflicting configs here throw an error
...@@ -1079,6 +1093,15 @@ export function reduceAppConfig( ...@@ -1079,6 +1093,15 @@ export function reduceAppConfig(
if (typeof maxDuration !== 'undefined') { if (typeof maxDuration !== 'undefined') {
config.maxDuration = maxDuration config.maxDuration = maxDuration
} }
// These two should be set uniformly across all segments
// in `collectAppPageSegments`, but we need to forward them here.
if (typeof prefetch !== 'undefined') {
config.prefetch = prefetch
}
if (typeof unstable_ensureStatic !== 'undefined') {
config.unstable_ensureStatic = unstable_ensureStatic
}
} }
return config return config
......
...@@ -2473,6 +2473,8 @@ async function retryUpgradeableFallbackPrefetch( ...@@ -2473,6 +2473,8 @@ async function retryUpgradeableFallbackPrefetch(
await new Promise<void>((resolve) => await new Promise<void>((resolve) =>
setTimeout(resolve, FALLBACK_RETRY_DELAY_MS) setTimeout(resolve, FALLBACK_RETRY_DELAY_MS)
) )
console.log('retryUpgradeableFallbackPrefetch', attempt, tree.requestKey)
if (task.isCanceled) { if (task.isCanceled) {
break break
} }
......
...@@ -208,6 +208,122 @@ export function createDynamicOrRuntimeMetadataError(route: string): Error { ...@@ -208,6 +208,122 @@ export function createDynamicOrRuntimeMetadataError(route: string): Error {
) )
} }
//====================================================
// Static routes (with `ensureStatic = "navigation"`)
//====================================================
export function createRuntimeBodyErrorInStaticRoute(route: string): Error {
return new Error(
`Route "${route}": Next.js encountered runtime data on a route that must be fully static.\n\n` +
`\`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` prevent the route from being prerendered.\n\n` +
`Ways to fix this:\n` +
` - [static-params] For \`params\`: specify a static set of params to be prerendered using \`generateStaticParams\`\n` +
` - [client] For \`searchParams\`: read on the client with \`useSearchParams()\`\n`
// TODO(ensure-static): docs for "navigation"-specific messages
// + `Learn more: <TODO>`
)
}
export function createDynamicBodyErrorInStaticRoute(route: string): Error {
return new Error(
`Route "${route}": Next.js encountered uncached data on a route that must be fully static.\n\n` +
`\`fetch(...)\` or \`connection()\` prevents the route from being prerendered.\n\n` +
`Ways to fix this:\n` +
` - [cache] For uncached data (\`fetch\`, database calls): cache the access with \`"use cache"\` (does not apply to \`connection()\`)\n`
// TODO(ensure-static): docs for "navigation"-specific messages
// + `Learn more: <TODO>`
)
}
export function createNonPrerenderableBodyErrorInStaticRoute(
route: string
): Error {
return new Error(
`Route "${route}": Next.js encountered uncached or runtime data on a route that must be fully static.\n\n` +
`\`fetch(...)\`, \`cookies()\`, \`headers()\`, \`params\`, \`searchParams\`, or \`connection()\` prevents the route from being prerendered.\n\n` +
`Ways to fix this:\n` +
` - [cache] For uncached data (\`fetch\`, database calls): cache the access with \`"use cache"\` (does not apply to \`connection()\`)\n`
// TODO(ensure-static): docs for "navigation"-specific messages
// + `Learn more: <TODO>`
)
}
export function createRuntimeMetadataErrorInStaticRoute(route: string): Error {
return new Error(
`Route "${route}": Next.js encountered runtime data in \`generateMetadata()\` on a route that must be fully static.\n\n` +
`\`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` prevents the route from being prerendered.\n\n` +
`Ways to fix this:\n` +
` - [static] Use a static metadata export instead of \`generateMetadata()\`\n` +
` - [static-params] For \`params\`: specify a static set of params to be prerendered using \`generateStaticParams\`\n`
// TODO(ensure-static): docs for "navigation"-specific messages
// + `Learn more: <TODO>`
)
}
export function createDynamicMetadataErrorInStaticRoute(route: string): Error {
return new Error(
`Route "${route}": Next.js encountered uncached data in \`generateMetadata()\` on a route that must be fully static.\n\n` +
`\`fetch(...)\` or \`connection()\` prevents the route from being prerendered.\n\n` +
`Ways to fix this:\n` +
` - [static] Use a static metadata export instead of \`generateMetadata()\`\n` +
` - [cache] Cache the metadata with \`"use cache"\` in \`generateMetadata()\` (only applies to uncached data)\n`
// TODO(ensure-static): docs for "navigation"-specific messages
// + `Learn more: <TODO>`
)
}
export function createNonPrerenderableMetadataErrorInStaticRoute(
route: string
): Error {
return new Error(
`Route "${route}": Next.js encountered uncached or runtime data in \`generateMetadata()\` on a route that must be fully static.\n\n` +
`\`fetch(...)\`, \`cookies()\`, \`headers()\`, \`params\`, \`searchParams\`, or \`connection()\` prevents the route from being prerendered.\n\n` +
`Ways to fix this:\n` +
` - [static] Use a static metadata export instead of \`generateMetadata()\`\n` +
` - [cache] Cache the metadata with \`"use cache"\` in \`generateMetadata()\` (only applies to uncached data)\n`
// TODO(ensure-static): docs for "navigation"-specific messages
// + `Learn more: <TODO>`
)
}
export function createRuntimeViewportErrorInStaticRoute(route: string): Error {
return new Error(
`Route "${route}": Next.js encountered runtime data in \`generateViewport()\` on a route that must be fully static.\n\n` +
`\`cookies()\`, \`headers()\`, \`params\`, or \`searchParams\` prevents the route from being prerendered.\n\n` +
`Ways to fix this:\n` +
` - [static] Use a static viewport export instead of \`generateViewport()\`\n` +
` - [static-params] For \`params\`: specify a static set of params to be prerendered using \`generateStaticParams\`\n`
// TODO(ensure-static): docs for "navigation"-specific messages
// + `Learn more: <TODO>`
)
}
export function createDynamicViewportErrorInStaticRoute(route: string): Error {
return new Error(
`Route "${route}": Next.js encountered uncached data in \`generateViewport()\` on a route that must be fully static.\n\n` +
`\`fetch(...)\` or \`connection()\` prevents the route from being prerendered.\n\n` +
`Ways to fix this:\n` +
` - [static] Use a static viewport export instead of \`generateViewport()\`\n` +
` - [cache] Cache the metadata with \`"use cache"\` in \`generateMetadata()\` (only applies to uncached data)\n`
// TODO(ensure-static): docs for "navigation"-specific messages
// + `Learn more: <TODO>`
)
}
export function createNonPrerenderableViewportErrorInStaticRoute(
route: string
): Error {
return new Error(
`Route "${route}": Next.js encountered uncached or runtime data in \`generateViewport()\` on a route that must be fully static.\n\n` +
`\`fetch(...)\`, \`cookies()\`, \`headers()\`, \`params\`, \`searchParams\`, or \`connection()\` prevents the route from being prerendered.\n\n` +
`Ways to fix this:\n` +
` - [static] Use a static viewport export instead of \`generateViewport()\`\n` +
` - [cache] Cache the metadata with \`"use cache"\` in \`generateMetadata()\` (only applies to uncached data)\n`
// TODO(ensure-static): docs for "navigation"-specific messages
// + `Learn more: <TODO>`
)
}
export function logBuildDebugHint(route: string): void { export function logBuildDebugHint(route: string): void {
if (process.env.NODE_ENV !== 'development') { if (process.env.NODE_ENV !== 'development') {
console.error( console.error(
......
...@@ -3,9 +3,10 @@ import type { OpaqueFallbackRouteParams } from '../request/fallback-params' ...@@ -3,9 +3,10 @@ import type { OpaqueFallbackRouteParams } from '../request/fallback-params'
import type { NextParsedUrlQuery } from '../request-meta' import type { NextParsedUrlQuery } from '../request-meta'
import type { PrefetchingMode } from './app-render' import type { PrefetchingMode } from './app-render'
import type { NextConfigComplete, ValidationLevel } from '../config-shared' import type { NextConfigComplete, ValidationLevel } from '../config-shared'
import type { ImageConfigComplete } from '../../shared/lib/image-config'
import type { StageEndTimes } from './instant-validation/instant-validation' import type { StageEndTimes } from './instant-validation/instant-validation'
import type { AdvanceableRenderStage } from './staged-rendering' import type { AdvanceableRenderStage } from './staged-rendering'
import type { RenderOpts } from './types'
import type { NonPartial } from '../../shared/lib/typescript-utils'
/** /**
* Cross-module handoff for the dev validation worker (client-module warmup, * Cross-module handoff for the dev validation worker (client-module warmup,
...@@ -100,10 +101,9 @@ export interface DevValidationSnapshot { ...@@ -100,10 +101,9 @@ export interface DevValidationSnapshot {
additionalClientReferenceManifestPages: string[] additionalClientReferenceManifestPages: string[]
reactBrowserBailout: boolean reactBrowserBailout: boolean
isDebugChannelEnabled: boolean isDebugChannelEnabled: boolean
renderOpts: { renderOpts: NonPartial<
images: ImageConfigComplete Pick<RenderOpts, 'images' | 'allowEmptyStaticShell' | 'partialPrefetching'>
allowEmptyStaticShell: boolean | undefined >
}
instantInputs: SerializedValidationInputs | null instantInputs: SerializedValidationInputs | null
staticInputs: SerializedValidationInputs staticInputs: SerializedValidationInputs
} }
......
...@@ -93,6 +93,7 @@ export async function buildDevValidationSnapshot( ...@@ -93,6 +93,7 @@ export async function buildDevValidationSnapshot(
renderOpts: { renderOpts: {
images: ctx.renderOpts.images, images: ctx.renderOpts.images,
allowEmptyStaticShell: ctx.renderOpts.allowEmptyStaticShell, allowEmptyStaticShell: ctx.renderOpts.allowEmptyStaticShell,
partialPrefetching: ctx.renderOpts.partialPrefetching,
}, },
instantInputs: instantInputs instantInputs: instantInputs
? await toSerializedInputs(instantInputs) ? await toSerializedInputs(instantInputs)
......
...@@ -59,6 +59,15 @@ export async function resolveEnsureStaticLevel( ...@@ -59,6 +59,15 @@ export async function resolveEnsureStaticLevel(
tree: LoaderTree, tree: LoaderTree,
partialPrefetching: boolean partialPrefetching: boolean
): Promise<EnsureStaticLevel> { ): Promise<EnsureStaticLevel> {
return getEnsureStaticLevel(
await resolveEnsureStaticConfig(tree, partialPrefetching)
)
}
export async function resolveEnsureStaticConfig(
tree: LoaderTree,
partialPrefetching: boolean
): Promise<Exclude<EnsureStatic, false>> {
let { config, filePath } = await resolveEnsureStaticConfigImpl(tree) let { config, filePath } = await resolveEnsureStaticConfigImpl(tree)
if (!partialPrefetching) { if (!partialPrefetching) {
...@@ -95,15 +104,12 @@ export async function resolveEnsureStaticLevel( ...@@ -95,15 +104,12 @@ export async function resolveEnsureStaticLevel(
} }
} }
if (config === 'navigation') { if (config === false) {
throw new Error( // `false` and "auto" are equivalent once resolved.
`\`${formatEnsureStaticExport(config)}\` is not implemented yet.` + return 'auto'
`\n (from: ${filePath})` + } else {
`` return config
)
} }
return getEnsureStaticLevel(config)
} }
type EnsureStaticWithSource = { type EnsureStaticWithSource = {
......
...@@ -754,6 +754,7 @@ export default class DevServer extends Server { ...@@ -754,6 +754,7 @@ export default class DevServer extends Server {
config: { config: {
configFileName, configFileName,
cacheComponents: Boolean(this.nextConfig.cacheComponents), cacheComponents: Boolean(this.nextConfig.cacheComponents),
partialPrefetching: Boolean(this.nextConfig.partialPrefetching),
}, },
httpAgentOptions, httpAgentOptions,
locales, locales,
......
...@@ -27,6 +27,7 @@ import { parseNormalizedAppRoute } from '../../shared/lib/router/routes/app' ...@@ -27,6 +27,7 @@ import { parseNormalizedAppRoute } from '../../shared/lib/router/routes/app'
type RuntimeConfig = { type RuntimeConfig = {
configFileName: string configFileName: string
cacheComponents: boolean cacheComponents: boolean
partialPrefetching: boolean
} }
// we call getStaticPaths in a separate process to ensure // we call getStaticPaths in a separate process to ensure
...@@ -116,7 +117,11 @@ export async function loadStaticPaths({ ...@@ -116,7 +117,11 @@ export async function loadStaticPaths({
const segments = await collectSegments( const segments = await collectSegments(
// We know this is an app page or app route module because we checked // We know this is an app page or app route module because we checked
// above that the page type is 'app'. // above that the page type is 'app'.
routeModule as AppPageRouteModule | AppRouteRouteModule routeModule as AppPageRouteModule | AppRouteRouteModule,
{
cacheComponents: config.cacheComponents,
partialPrefetching: config.partialPrefetching,
}
) )
const route = parseNormalizedAppRoute(pathname) const route = parseNormalizedAppRoute(pathname)
...@@ -129,6 +134,13 @@ export async function loadStaticPaths({ ...@@ -129,6 +134,13 @@ export async function loadStaticPaths({
const isRoutePPREnabled = const isRoutePPREnabled =
isAppPageRouteModule(routeModule) && config.cacheComponents isAppPageRouteModule(routeModule) && config.cacheComponents
const isEnsureStaticPage =
config.cacheComponents &&
isRoutePPREnabled &&
segments.some(
(segment) => segment.config?.unstable_ensureStatic === 'navigation'
)
const rootParamKeys = collectRootParamKeys(routeModule) const rootParamKeys = collectRootParamKeys(routeModule)
return buildAppStaticPaths({ return buildAppStaticPaths({
...@@ -147,6 +159,7 @@ export async function loadStaticPaths({ ...@@ -147,6 +159,7 @@ export async function loadStaticPaths({
ComponentMod: components.ComponentMod, ComponentMod: components.ComponentMod,
nextConfigOutput, nextConfigOutput,
isRoutePPREnabled, isRoutePPREnabled,
isEnsureStaticPage,
buildId, buildId,
deploymentId, deploymentId,
authInterrupts, authInterrupts,
......
...@@ -378,6 +378,7 @@ function createStaticPrerenderParams( ...@@ -378,6 +378,7 @@ function createStaticPrerenderParams(
// to consider the awaiting of this params object "dynamic". Since // to consider the awaiting of this params object "dynamic". Since
// we are in cacheComponents mode we encode this as a promise that never // we are in cacheComponents mode we encode this as a promise that never
// resolves. // resolves.
return makeHangingParams( return makeHangingParams(
underlyingParams, underlyingParams,
workStore, workStore,
......
export function throwMissingGspErrorInStaticRoute(page: string) {
throw new Error(
`Page "${page}" is missing \`generateStaticParams()\` which is currently not supported with \`ensureStatic = "navigation"\`. See more info here: https://nextjs.org/docs/messages/generate-static-params`
)
}
export function throwIncompleteStaticParamsErrorInStaticRoute(
page: string,
missingParamNames: string[]
) {
throw new Error(
`Page "${page}" returned incomplete params from \`generateStaticParams()\`. This is currently unsupported with \`ensureStatic = "navigation"\`. Every params object must include all dynamic route parameters. Missing: ${missingParamNames.map((name) => `"${name}"`).join(', ')}. See more info here: https://nextjs.org/docs/messages/generate-static-params`
)
}
/**
* Turns optional fields into fields that are required but accept undefined, i.e.
* `NonPartial<{ x?: number }>` is `{ x: number | undefined }`.
* Source: https://github.com/microsoft/TypeScript/issues/31025#issuecomment-870011852
* */
export type NonPartial<T> = { [K in keyof Required<T>]: T[K] }
...@@ -12,8 +12,6 @@ import { ...@@ -12,8 +12,6 @@ import {
ErrorSnapshot, ErrorSnapshot,
} from '../../../lib/add-redbox-matchers' } from '../../../lib/add-redbox-matchers'
const NOT_IMPLEMENTED_VALUES: EnsureStatic[] = ['navigation']
// Cannot prerender individual pages in deploy mode // Cannot prerender individual pages in deploy mode
// @force-gate !deploy // @force-gate !deploy
describe('unstable_ensureStatic config validation', () => { describe('unstable_ensureStatic config validation', () => {
...@@ -141,13 +139,6 @@ describe('unstable_ensureStatic config validation', () => { ...@@ -141,13 +139,6 @@ describe('unstable_ensureStatic config validation', () => {
async ({ child, isValid }) => { async ({ child, isValid }) => {
const route = `/nested/parent-${parent}/child-${child}` const route = `/nested/parent-${parent}/child-${child}`
const isNotImplemented =
NOT_IMPLEMENTED_VALUES.includes(parent) ||
NOT_IMPLEMENTED_VALUES.includes(child)
const NOT_IMPLMEMENTED_PATTERN =
/`export const unstable_ensureStatic = .+?` is not implemented yet./
const INVALID_CONFIG_MESSAGE = // `false` has a dedicated error message. const INVALID_CONFIG_MESSAGE = // `false` has a dedicated error message.
parent === false || child === false parent === false || child === false
? `A child segment cannot override a parent segment with an incompatible \`unstable_ensureStatic\`.` ? `A child segment cannot override a parent segment with an incompatible \`unstable_ensureStatic\`.`
...@@ -156,23 +147,7 @@ describe('unstable_ensureStatic config validation', () => { ...@@ -156,23 +147,7 @@ describe('unstable_ensureStatic config validation', () => {
if (isNextDev) { if (isNextDev) {
const browser = await next.browser(route) const browser = await next.browser(route)
if (isValid) { if (isValid) {
// Valid nestings for options that aren't implemented yet still error. await waitForNoRedbox(browser, REDBOX_WAIT_OPTS)
if (isNotImplemented) {
await expectRedboxWith(
browser,
next,
{
label: 'Runtime Error',
description: expect.stringMatching(
NOT_IMPLMEMENTED_PATTERN
),
},
REDBOX_WAIT_OPTS
)
} else {
// Valid nesting should pass.
await waitForNoRedbox(browser, REDBOX_WAIT_OPTS)
}
} else { } else {
// Invalid nestings should error. // Invalid nestings should error.
await expectRedboxWith( await expectRedboxWith(
...@@ -188,14 +163,8 @@ describe('unstable_ensureStatic config validation', () => { ...@@ -188,14 +163,8 @@ describe('unstable_ensureStatic config validation', () => {
} else { } else {
const result = await prerenderPattern(`app/${route}/page.tsx`) const result = await prerenderPattern(`app/${route}/page.tsx`)
if (isValid) { if (isValid) {
// Valid nestings for options that aren't implemented yet still error. // Valid nestings should pass.
if (isNotImplemented) { expect(result.exitCode).toBe(0)
expect(result.exitCode).toBe(1)
expect(result.cliOutput).toMatch(NOT_IMPLMEMENTED_PATTERN)
} else {
// Valid nestings should pass.
expect(result.exitCode).toBe(0)
}
} else { } else {
// Invalid nestings should error. // Invalid nestings should error.
expect(result.exitCode).toBe(1) expect(result.exitCode).toBe(1)
...@@ -227,33 +196,13 @@ describe('unstable_ensureStatic config validation', () => { ...@@ -227,33 +196,13 @@ describe('unstable_ensureStatic config validation', () => {
async ({ left, right, isValid }) => { async ({ left, right, isValid }) => {
const route = `/sibling-slots/left-${left}-right-${right}` const route = `/sibling-slots/left-${left}-right-${right}`
const isNotImplemented =
NOT_IMPLEMENTED_VALUES.includes(left) ||
NOT_IMPLEMENTED_VALUES.includes(right)
const NOT_IMPLMEMENTED_PATTERN =
/`export const unstable_ensureStatic = .+?` is not implemented yet./
const INVALID_CONFIG_MESSAGE = `Parallel slots cannot have incompatible \`unstable_ensureStatic\`.` const INVALID_CONFIG_MESSAGE = `Parallel slots cannot have incompatible \`unstable_ensureStatic\`.`
if (isNextDev) { if (isNextDev) {
const browser = await next.browser(route) const browser = await next.browser(route)
if (isValid) { if (isValid) {
// Valid combinations of options that aren't implemented yet still error. // Valid combinations should pass.
if (isNotImplemented) { await waitForNoRedbox(browser, REDBOX_WAIT_OPTS)
await expectRedboxWith(
browser,
next,
{
label: 'Runtime Error',
description: expect.stringMatching(NOT_IMPLMEMENTED_PATTERN),
},
REDBOX_WAIT_OPTS
)
} else {
// Valid combinations should pass.
await waitForNoRedbox(browser, REDBOX_WAIT_OPTS)
}
} else { } else {
// Invalid combinations should error. // Invalid combinations should error.
await expectRedboxWith( await expectRedboxWith(
...@@ -269,14 +218,8 @@ describe('unstable_ensureStatic config validation', () => { ...@@ -269,14 +218,8 @@ describe('unstable_ensureStatic config validation', () => {
} else { } else {
const result = await prerenderPattern(`app/${route}/*/page.tsx`) const result = await prerenderPattern(`app/${route}/*/page.tsx`)
if (isValid) { if (isValid) {
// Valid combinations of options that aren't implemented yet still error. // Valid combinations should pass.
if (isNotImplemented) { expect(result.exitCode).toBe(0)
expect(result.exitCode).toBe(1)
expect(result.cliOutput).toMatch(NOT_IMPLMEMENTED_PATTERN)
} else {
// Valid combinations should pass.
expect(result.exitCode).toBe(0)
}
} else { } else {
// Invalid combinations should error. // Invalid combinations should error.
expect(result.exitCode).toBe(1) expect(result.exitCode).toBe(1)
......
'use client'
import { use } from 'react'
// @ts-ignore typescript is unhappy with this import for some reason
import { browser } from 'react-dom'
export function BrowserOnly() {
use(browser())
return <p id="browser-content">Browser-only content</p>
}
import { Suspense } from 'react'
import { Timestamp } from '../../../components/timestamp'
import { BrowserOnly } from './client'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<Timestamp />
<p>
This page does not use any params, and should be fully static despite
having content that bails out to browser-only rendering.
</p>
<Suspense
fallback={
<p id="browser-content-fallback">Fallback for browser-only content</p>
}
>
<BrowserOnly />
</Suspense>
</main>
)
}
'use client'
import { use } from 'react'
import { io } from 'next/cache'
export function ClientIO() {
use(io())
return <p id="client-io">Client-only IO</p>
}
import { Suspense } from 'react'
import { Timestamp } from '../../../components/timestamp'
import { ClientIO } from './client'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<Timestamp />
<p>
This page does not use any params, and should be fully static despite
having client-only IO.
</p>
<Suspense
fallback={<p id="client-io-fallback">Fallback for client-only IO</p>}
>
<ClientIO />
</Suspense>
</main>
)
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { Timestamp } from '../../../components/timestamp'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<Timestamp />
<p>This page does not use any params, and should be fully static.</p>
<p id="static-content">Static content</p>
</main>
)
}
import { Suspense } from 'react'
import { Timestamp } from '../../../../components/timestamp'
export async function generateStaticParams() {
return [{ slug: 'prerendered-1' }, { slug: 'prerendered-2' }]
}
export const unstable_ensureStatic = 'navigation'
type Params = { slug: string }
export default function Page({ params }: { params: Promise<Params> }) {
return (
<main>
<p>
This page uses static params, and should be prerendered statically (with
blocking prerenders for new params)
</p>
<Timestamp />
<Suspense fallback={<p>Loading param data...</p>}>
<Inner params={params} />
</Suspense>
</main>
)
}
async function Inner({ params }: { params: Promise<Params> }) {
const { slug } = await params
await cachedDelay(slug)
return <p id="slug">{`Slug: ${slug}`}</p>
}
async function cachedDelay(key: string) {
'use cache'
await new Promise((resolve) => setTimeout(resolve, 500))
return key
}
import type { ReactNode } from 'react'
export async function generateStaticParams() {
return [{ lang: 'en' }, { lang: 'pl' }]
}
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { lang } from 'next/root-params'
export const unstable_ensureStatic = 'navigation'
export default async function Page() {
const currentLang = await lang()
await cachedDelay(currentLang)
return (
<main>
<p id="lang">{`Lang: ${currentLang}`}</p>
</main>
)
}
async function cachedDelay(key: string) {
'use cache'
await new Promise((resolve) => setTimeout(resolve, 500))
return key
}
export function Timestamp() {
const now = Math.floor(performance.timeOrigin + performance.now())
return <div id="timestamp">{`Timestamp: ${now}`}</div>
}
process.env.__NEXT_PARTIAL_PREFETCHING = 'true'
require('./ensure-static-navigation-runtime.test')
import { nextTestSetup, Playwright } from 'e2e-utils'
import cheerio from 'cheerio'
// @force-gate !dev
describe('ensureStatic = "navigation" - runtime behavior', () => {
const { next } = nextTestSetup({
files: __dirname,
})
const HTML = 'html' as const
const RSC = 'rsc' as const
const expectSameStaticResponseForMultipleRequests = async (
href: string,
requestKind: 'html' | 'rsc' = 'html'
): Promise<string> => {
const responses = new Set<string>()
const headers = requestKind === RSC ? { rsc: '1' } : {}
for (let i = 0; i < 4; i++) {
const response = await next
.fetch(href, { headers })
.then((res) => res.text())
expect(response).not.toBeEmpty()
responses.add(response)
}
const responsesArr = [...responses]
expect(responsesArr).toHaveLength(1)
return responsesArr[0]
}
const expectNoBrowserErrorLogs = async (browser: Playwright) => {
const logs = await browser.log()
expect(
logs.filter((log) => log.source === 'warning' || log.source === 'error')
).toBeEmpty()
}
describe('pages without params', () => {
it('basic', async () => {
const href = '/default/no-params'
const response = await expectSameStaticResponseForMultipleRequests(href)
const $ = cheerio.load(response)
expect($('#static-content').text()).toBe('Static content')
const browser = await next.browser(href)
expect(await browser.elementByCss('#static-content').text()).toBe(
'Static content'
)
await expectNoBrowserErrorLogs(browser)
})
it('browser bailout', async () => {
const href = '/default/browser-bailout'
const response = await expectSameStaticResponseForMultipleRequests(href)
const $ = cheerio.load(response)
// sanity check: browser-only content should not be present
// (this is not affected by `ensureStatic`)
expect($('#browser-content-fallback').text()).toBe(
'Fallback for browser-only content'
)
expect($('#browser-content').length).toBe(0)
// Browser-only content should resolve in the browser (duh)
const browser = await next.browser(href)
expect(await browser.elementByCss('#browser-content').text()).toBe(
'Browser-only content'
)
await expectNoBrowserErrorLogs(browser)
})
it('client-only IO', async () => {
const href = '/default/client-io'
const response = await expectSameStaticResponseForMultipleRequests(href)
const $ = cheerio.load(response)
// Client-only IO should not run during SSR if we're serving a static prerender.
expect($('#client-io-fallback').text()).toBe(
'Fallback for client-only IO'
)
expect($('#client-io').length).toBe(0)
// Client-only IO should resolve in the browser.
const browser = await next.browser(href)
expect(await browser.elementByCss('#client-io').text()).toBe(
'Client-only IO'
)
await expectNoBrowserErrorLogs(browser)
})
})
describe('page with static params', () => {
const getHref = (slug: string) => `/default/static-params/${slug}`
const testImpl = async (slug: string, kind: 'html' | 'rsc') => {
const href = getHref(slug)
const response = await expectSameStaticResponseForMultipleRequests(
href,
kind
)
const expected = `Slug: ${slug}`
if (kind === HTML) {
// We should not serve a fallback + resume, so the param should
// be present in the initial HTML.
const $ = cheerio.load(response)
expect($('#slug').text()).toBe(expected)
} else {
expect(response).toContain(expected)
}
const browser = await next.browser(href)
expect(await browser.elementByCss('#slug').text()).toBe(expected)
await expectNoBrowserErrorLogs(browser)
}
describe('serves static results for params that were prerendered at build', () => {
it.each([
{ slug: 'prerendered-1', kind: HTML },
{ slug: 'prerendered-2', kind: RSC },
])('slug: $slug - $kind', async ({ slug, kind }) => {
await testImpl(slug, kind)
})
})
describe('serves blocking static results for params that were not prerendered at build', () => {
it.each([
{ slug: 'not-prerendered-1', kind: HTML },
{ slug: 'not-prerendered-2', kind: RSC },
])('slug: $slug - $kind', async ({ slug, kind }) => {
await testImpl(slug, kind)
})
})
})
describe('page with root params', () => {
const getHref = (lang: string) => `/with-root-param/${lang}`
const testImpl = async (lang: string, kind: 'rsc' | 'html') => {
const href = getHref(lang)
const response = await expectSameStaticResponseForMultipleRequests(
href,
kind
)
const expected = `Lang: ${lang}`
if (kind === HTML) {
const $ = cheerio.load(response)
expect($('#lang').text()).toBe(expected)
} else {
expect(response).toContain(expected)
}
const browser = await next.browser(href)
expect(await browser.elementByCss('#lang').text()).toBe(`Lang: ${lang}`)
await expectNoBrowserErrorLogs(browser)
}
describe('serves static results for params that were prerendered at build', () => {
it.each([
{ lang: 'en', kind: HTML },
{ lang: 'pl', kind: RSC },
])('lang: $lang - $kind', async ({ lang, kind }) => {
await testImpl(lang, kind)
})
})
describe('serves static results for params that were not prerendered at build', () => {
it.each([
{ lang: 'de', kind: HTML },
{ lang: 'jp', kind: RSC },
])('lang: $lang - $kind', async ({ lang, kind }) => {
await testImpl(lang, kind)
})
})
})
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
// Set in tests
// partialPrefetching: true,
}
export default nextConfig
'use client'
import { io } from 'next/cache'
import { use } from 'react'
export function ClientIO() {
use(io())
return <p>{`Client dynamic data`}</p>
}
import type { Instant } from 'next'
import { ClientIO } from './client'
export const unstable_ensureStatic = 'navigation'
export const instant: Instant = {
// We don't care about Instant Validation here,
// Static Shell Validation should still error.
unstable_disableValidation: true,
}
export default function Page() {
return (
<main>
<ClientIO />
</main>
)
}
import { connection } from 'next/server'
import { Suspense } from 'react'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<Inner />
</Suspense>
</main>
)
}
async function Inner() {
await connection()
return <p>Dynamic data</p>
}
'use client'
import { use } from 'react'
export function UserServerDataOnlyInBrowser({
serverData,
}: {
serverData: Promise<string>
}) {
// A client component might save a promise of server data without actually
// calling use() during the prerender, which would not surface as a dynamic
// hole during the prerender.
if (typeof window !== 'undefined') {
const data = use(serverData)
return <p suppressHydrationWarning>{`Server data: ${data}`}</p>
} else {
return (
<p
suppressHydrationWarning
>{`Server data: <skipped during prerender>`}</p>
)
}
}
import { Suspense } from 'react'
import { UserServerDataOnlyInBrowser } from './client'
import { connection } from 'next/server'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<UserServerDataOnlyInBrowser
serverData={connection().then(() => 'Dynamic data')}
/>
</Suspense>
</main>
)
}
'use client'
import { use } from 'react'
export function UseServerData({ serverData }: { serverData: Promise<string> }) {
const data = use(serverData)
return <p>{`Server data: ${data}`}</p>
}
import { Suspense } from 'react'
import { UseServerData } from './client'
import { connection } from 'next/server'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<UseServerData serverData={connection().then(() => 'Dynamic data')} />
</Suspense>
</main>
)
}
import type { Metadata } from 'next'
import { connection } from 'next/server'
export const unstable_ensureStatic = 'navigation'
export async function generateMetadata(): Promise<Metadata> {
await connection()
return {
title: 'Dynamic title',
}
}
export default function Page() {
return (
<main>
<p>This page has a dynamic generateMetadata</p>
</main>
)
}
import type { Viewport } from 'next'
import { connection } from 'next/server'
export const unstable_ensureStatic = 'navigation'
export async function generateViewport(): Promise<Viewport> {
await connection()
return {
themeColor: '#d692b7',
}
}
export default function Page() {
return (
<main>
<p>This page has a dynamic generteViewport</p>
</main>
)
}
import { cacheLife } from 'next/cache'
import { Suspense } from 'react'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<Inner />
</Suspense>
</main>
)
}
async function Inner() {
await nonPrerenderableCache()
return <p>Non-prerenderable data</p>
}
async function nonPrerenderableCache() {
'use cache'
cacheLife({ expire: 300 - 1 }) // smaller than MIN_PRERENDERABLE_EXPIRE
await new Promise((resolve) => setTimeout(resolve))
return Date.now()
}
import { cacheLife } from 'next/cache'
import { Suspense } from 'react'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<Inner />
</Suspense>
</main>
)
}
async function Inner() {
await nonShellCache()
return <p>Non-shell data</p>
}
async function nonShellCache() {
'use cache'
cacheLife({ stale: 300 - 1 }) // smaller than MIN_SHELL_STALE
await new Promise((resolve) => setTimeout(resolve))
return Date.now()
}
'use client'
import { useParams } from 'next/navigation'
import { Suspense } from 'react'
type Params = { slug: string }
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<Inner />
</Suspense>
</main>
)
}
function Inner() {
const { slug } = useParams<Params>()
return <p>Slug: {slug}</p>
}
import { ReactNode } from 'react'
// Can't set this in client modules, so we do it in a parent layout instead
export const unstable_ensureStatic = 'navigation'
export default function Layout({ children }: { children: ReactNode }) {
return children
}
'use client'
import { use } from 'react'
export function SlugClient({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = use(params)
return <p>{`Slug: ${slug}`}</p>
}
import { Suspense } from 'react'
import { SlugClient } from './client'
export const unstable_ensureStatic = 'navigation'
type Params = { slug: string }
export default function Page({ params }: { params: Promise<Params> }) {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<SlugClient params={params} />
</Suspense>
</main>
)
}
import { Suspense } from 'react'
export const unstable_ensureStatic = 'navigation'
type Params = { slug: string }
export default function Page({ params }: { params: Promise<Params> }) {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<Inner params={params} />
</Suspense>
</main>
)
}
async function Inner({ params }: { params: Promise<Params> }) {
const { slug } = await params
return <p>Slug: {slug}</p>
}
import { connection } from 'next/server'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<p>
This page has <code>instant = false</code> in a parent layout, which
would normally allow blocking the root, but calling
<code>connection()</code> should still be disallowed by{' '}
<code>ensureStatic</code>.
</p>
<Inner />
</main>
)
}
async function Inner() {
await connection()
return <p>Dynamic data</p>
}
import type { ReactNode } from 'react'
export const instant = false
export default function Layout({ children }: { children: ReactNode }) {
return children
}
'use client'
import { use } from 'react'
import { browser } from 'react-dom'
export function BrowserOnly() {
use(browser())
return <p>Browser-only content</p>
}
import { BrowserOnly } from './client'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<p>
This page has <code>instant = false</code> in a parent layout, which
allows blocking the root. We're only blocking it with browser-only data,
so this should be allowed regardless of <code>ensureStatic</code>.
</p>
<BrowserOnly />
</main>
)
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
'use client'
import { use } from 'react'
import { browser } from 'react-dom'
export function BrowserOnly() {
use(browser())
return <p>Browser-only content</p>
}
import { connection } from 'next/server'
import { Suspense } from 'react'
import { BrowserOnly } from './client'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<BrowserOnly />
</Suspense>
<Suspense fallback={<p>Loading...</p>}>
<Inner />
</Suspense>
</main>
)
}
async function Inner() {
await connection()
return <p>Dynamic data</p>
}
'use client'
import { io } from 'next/cache'
import { use } from 'react'
export function ClientIO() {
use(io())
return <p>{`Client dynamic data`}</p>
}
import { connection } from 'next/server'
import { Suspense } from 'react'
import { ClientIO } from './client'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<ClientIO />
</Suspense>
<Suspense fallback={<p>Loading...</p>}>
<Inner />
</Suspense>
</main>
)
}
async function Inner() {
await connection()
return <p>Dynamic data</p>
}
'use client'
import { useSearchParams } from 'next/navigation'
export function ClientSearchQuery() {
const searchParams = useSearchParams()
const query = searchParams.get('query') ?? '<none>'
return <p>{`Query: ${query}`}</p>
}
import { connection } from 'next/server'
import { Suspense } from 'react'
import { ClientSearchQuery } from './client'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<ClientSearchQuery />
</Suspense>
<Suspense fallback={<p>Loading...</p>}>
<Inner />
</Suspense>
</main>
)
}
async function Inner() {
await connection()
return <p>Dynamic data</p>
}
export async function generateStaticParams() {
return [{ slug: '123' }]
}
export const unstable_ensureStatic = 'navigation'
// The page awaits `params` without Suspense, which blocks the app shell,
// and would fail Instant Validation in Partial Prefetching.
// It's still statically-prerenderable.
export const instant = false
type Params = { slug: string }
export default function Page({ params }: { params: Promise<Params> }) {
return (
<main>
<Inner params={params} />
</main>
)
}
async function Inner({ params }: { params: Promise<Params> }) {
const { slug } = await params
return <p>Slug: {slug}</p>
}
import { Suspense } from 'react'
export async function generateStaticParams() {
return []
}
export const unstable_ensureStatic = 'navigation'
type Params = { slug: string }
export default function Page({ params }: { params: Promise<Params> }) {
return (
<main>
<Suspense fallback={<p>Loading param data...</p>}>
<Inner params={params} />
</Suspense>
</main>
)
}
async function Inner({ params }: { params: Promise<Params> }) {
const { slug } = await params
return <p>Slug: {slug}</p>
}
export async function generateStaticParams() {
return [{ slug: '123' }]
}
export const unstable_ensureStatic = 'navigation'
type Params = { slug: string; snail: string }
export default function Page(_props: { params: Promise<Params> }) {
return (
<main>
<p>This page has a param that's not in gSP, but does not use it</p>
</main>
)
}
import { type ReactNode, Suspense } from 'react'
type Params = { slug: string }
export default function Layout({
children,
params,
}: {
children: ReactNode
params: Promise<Params>
}) {
return (
<>
<Suspense fallback={<p>Loading param data...</p>}>
<Inner params={params} />
</Suspense>
<hr />
{children}
</>
)
}
async function Inner({ params }: { params: Promise<Params> }) {
const { slug } = await params
return <p>Slug from layout: {slug}</p>
}
import { Suspense } from 'react'
export async function generateStaticParams() {
return [{ slug: '123' }]
}
export const unstable_ensureStatic = 'navigation'
type Params = { slug: string; snail: string }
export default function Page({ params }: { params: Promise<Params> }) {
return (
<main>
<Suspense fallback={<p>Loading param data...</p>}>
<Inner params={params} />
</Suspense>
</main>
)
}
async function Inner({ params }: { params: Promise<Params> }) {
const { slug, snail } = await params
return (
<p>
Slug: {slug}, Snail: {snail}
</p>
)
}
import { Suspense } from 'react'
export async function generateStaticParams() {
return [{ slug: '123' }]
}
export const unstable_ensureStatic = 'navigation'
type Params = { slug: string }
export default function Page({ params }: { params: Promise<Params> }) {
return (
<main>
<Suspense fallback={<p>Loading param data...</p>}>
<Inner params={params} />
</Suspense>
</main>
)
}
async function Inner({ params }: { params: Promise<Params> }) {
const { slug } = await params
return <p>Slug: {slug}</p>
}
import { Suspense } from 'react'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<Inner />
</Suspense>
</main>
)
}
async function Inner() {
// Simulate tasky IO
await new Promise((resolve) => setTimeout(resolve))
return <p>Uncached data</p>
}
'use client'
import { use } from 'react'
import { browser } from 'react-dom'
export function BrowserOnly() {
use(browser())
return <p>Browser-only content</p>
}
import { Suspense } from 'react'
import { BrowserOnly } from './client'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<BrowserOnly />
</Suspense>
</main>
)
}
'use client'
import { io } from 'next/cache'
import { use } from 'react'
export function ClientIO() {
use(io())
return <p>{`Client dynamic data`}</p>
}
import { Suspense } from 'react'
import { ClientIO } from './client'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<Suspense fallback={<p>Loading...</p>}>
<ClientIO />
</Suspense>
</main>
)
}
import { connection } from 'next/server'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<p>
This page has Suspense above the body, which would normally allow
blocking the root, but calling
<code>connection()</code> should still be disallowed by{' '}
<code>ensureStatic</code>.
</p>
<Inner />
</main>
)
}
async function Inner() {
await connection()
return <p>Dynamic data</p>
}
import { Suspense, type ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<Suspense>
<html>
<body>{children}</body>
</html>
</Suspense>
)
}
'use client'
import { use } from 'react'
import { browser } from 'react-dom'
export function BrowserOnly() {
use(browser())
return <p>Browser-only content</p>
}
import { BrowserOnly } from './client'
export const unstable_ensureStatic = 'navigation'
export default function Page() {
return (
<main>
<p>
This page has suspense above body, which allows blocking the root. We're
only blocking it with browser-only data, so this should be allowed
regardless of <code>ensureStatic</code>.
</p>
<BrowserOnly />
</main>
)
}
import type { ReactNode } from 'react'
export async function generateStaticParams() {
return [{ lang: 'en' }]
}
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { lang } from 'next/root-params'
export const unstable_ensureStatic = 'navigation'
export default async function Page() {
const currentLang = await lang()
return (
<main>
<p>{`Lang: ${currentLang}`}</p>
</main>
)
}
process.env.__NEXT_PARTIAL_PREFETCHING = 'true'
require('./ensure-static-navigation.test')
import escapeRegex from 'escape-string-regexp'
export function literalError(message: string) {
return new RegExp(escapeRegex(message))
}
export function samePatternInDevAndBuild(pattern: RegExp): ErrorPattern {
return {
dev: pattern,
build: pattern,
}
}
export type ErrorPattern = {
dev: RegExp
build: RegExp
}
export type ErrorPatternObject = {
[key: string]: ErrorPattern | ErrorPatternObject
}
export function isErrorPattern(
object: Record<string, any>
): object is ErrorPattern {
const keys = ['dev', 'build'] satisfies (keyof ErrorPattern)[]
for (const key of keys) {
if (
!(
key in object &&
object[key] &&
typeof object[key] === 'object' &&
object[key] instanceof RegExp
)
) {
return false
}
}
return true
}
export function flattenErrorPatternObject(
errorPatterns: ErrorPatternObject
): ErrorPattern[] {
return flattenErrorPatternObjectImpl(errorPatterns)
}
function flattenErrorPatternObjectImpl(
item: ErrorPattern | ErrorPatternObject
): ErrorPattern[] {
if (isErrorPattern(item)) {
return [item]
}
return Object.values(item).flatMap((child) => {
if (!(child && typeof child === 'object')) {
throw new Error('Unexpected non-object item in error patterns')
}
return flattenErrorPatternObjectImpl(child)
})
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
// Set in tests
// partialPrefetching: true,
}
export default nextConfig
import type { Instant } from 'next'
import { default as Page } from '../../_base/navigation-without-suspense/page.base'
export const prefetch = 'partial'
export const unstable_ensureStatic = 'navigation'
export const instant: Instant = {
level: 'experimental-error',
unstable_samples: [{}],
}
export default Page
import type { Instant } from 'next'
import { default as Page } from '../../_base/prefetch-without-suspense/page.base'
export const prefetch = 'partial'
export const unstable_ensureStatic = 'navigation'
export const instant: Instant = {
level: 'experimental-error',
unstable_samples: [{}],
}
export default Page
import type { ReactNode } from 'react'
export const instant = false
export default function IgnoreStaticShellValidationLayout({
children,
}: {
children: ReactNode
}) {
return children
}
import type { Instant } from 'next'
import { default as Page } from '../../_base/session-data-without-suspense/page.base'
export const prefetch = 'partial'
export const unstable_ensureStatic = 'navigation'
export const instant: Instant = {
level: 'experimental-error',
unstable_samples: [{ cookies: [] }],
}
export default Page
import type { Instant } from 'next'
import {
default as Page,
generateStaticParams,
} from '../../../_base/static-params-without-suspense/[slug]/page.base'
export const prefetch = 'partial'
export const unstable_ensureStatic = 'navigation'
export const instant: Instant = {
level: 'experimental-error',
unstable_samples: [{ params: { slug: '123' } }],
}
export { generateStaticParams }
export default Page
...@@ -67,33 +67,35 @@ export default async function Page() { ...@@ -67,33 +67,35 @@ export default async function Page() {
<h2>ensureStatic</h2> <h2>ensureStatic</h2>
<ul> <ul>
{[false, 'shell', 'prefetch'].map((ensureStaticConfig) => ( {[false, 'shell', 'prefetch', 'navigation'].map(
<li key={ensureStaticConfig + ''}> (ensureStaticConfig) => (
<code>{`ensureStatic = ${ensureStaticConfig}`}</code> <li key={ensureStaticConfig + ''}>
<ul> <code>{`ensureStatic = ${ensureStaticConfig}`}</code>
<li> <ul>
<DebugLinks <li>
href={`/shells/ensure-static/${ensureStaticConfig}/session-data-without-suspense`} <DebugLinks
/> href={`/shells/ensure-static/${ensureStaticConfig}/session-data-without-suspense`}
</li> />
<li> </li>
<DebugLinks <li>
href={`/shells/ensure-static/${ensureStaticConfig}/static-params-without-suspense/123`} <DebugLinks
/> href={`/shells/ensure-static/${ensureStaticConfig}/static-params-without-suspense/123`}
</li> />
<li> </li>
<DebugLinks <li>
href={`/shells/ensure-static/${ensureStaticConfig}/prefetch-without-suspense`} <DebugLinks
/> href={`/shells/ensure-static/${ensureStaticConfig}/prefetch-without-suspense`}
</li> />
<li> </li>
<DebugLinks <li>
href={`/shells/ensure-static/${ensureStaticConfig}/navigation-without-suspense`} <DebugLinks
/> href={`/shells/ensure-static/${ensureStaticConfig}/navigation-without-suspense`}
</li> />
</ul> </li>
</li> </ul>
))} </li>
)
)}
</ul> </ul>
</main> </main>
) )
......
import { ReactNode } from 'react'
import { NoInline } from '../../../../components/no-inline'
export default function Layout({ children }: { children: ReactNode }) {
return (
<>
<h2>Layout for page with a slug</h2>
<NoInline />
<hr />
{children}
</>
)
}
import { Suspense } from 'react'
export async function generateStaticParams() {
return [{ slug: 'prerendered-1' }]
}
export const unstable_ensureStatic = 'navigation'
type Params = { slug: string }
export default function Page({ params }: { params: Promise<Params> }) {
return (
<main>
<p>
This page uses static params, and should be prerendered statically (with
blocking prerenders for new params)
</p>
<Suspense fallback={<p>Loading param data...</p>}>
<Inner params={params} />
</Suspense>
</main>
)
}
async function Inner({ params }: { params: Promise<Params> }) {
const { slug } = await params
await cachedDelay(slug)
return <p id="slug">{`Slug: ${slug}`}</p>
}
async function cachedDelay(key: string) {
'use cache'
await new Promise((resolve) => setTimeout(resolve, 500))
return key
}
import Link from 'next/link' import Link from 'next/link'
import { LinkAccordion } from '../components/link-accordion' import { LinkAccordion } from '../components/link-accordion'
import { DynamicLinkAccordion } from '../components/dynamic-accordion'
export default function Page() { export default function Page() {
return ( return (
...@@ -288,6 +289,35 @@ export default function Page() { ...@@ -288,6 +289,35 @@ export default function Page() {
</LinkAccordion> </LinkAccordion>
</li> </li>
</ul> </ul>
<h2>ensureStatic = "navigation"</h2>
<li>
<LinkAccordion href="/ensure-static/navigation/prerendered-1">
prerendered param 1
</LinkAccordion>
</li>
<li>
<LinkAccordion
href="/ensure-static/navigation/prerendered-1"
prefetch={true}
>
prerendered param 1 (prefetch=true)
</LinkAccordion>
</li>
<li>
<LinkAccordion
href="/ensure-static/navigation/not-prerendered-1"
prefetch={true}
>
not-prerendered param 1 (prefetch=true)
</LinkAccordion>
</li>
{/* Used for manual testing of on-demand prerenders */}
<DynamicLinkAccordion
hrefPattern="/ensure-static/navigation/not-prerendered-{counter}"
placeholder="{counter}"
initialCount={2}
/>
</main> </main>
) )
} }
'use client'
import { useState } from 'react'
import { LinkAccordion } from './link-accordion'
export function DynamicLinkAccordion({
hrefPattern,
placeholder,
initialCount,
}: {
hrefPattern: string
placeholder: string
initialCount: number
}) {
const [counter, setCounter] = useState(initialCount)
const href = hrefPattern.replace(placeholder, counter + '')
return (
<div style={{ border: '1px solid lightgrey', padding: '1em' }}>
<div>
<span>
Dynamic link generator{' '}
<button type="button" onClick={() => setCounter((c) => c + 1)}>
Increment counter
</button>
</span>
<div>
<code>{hrefPattern}</code>
</div>
</div>
<div>
<LinkAccordion key={href} href={href} prefetch="auto">
{href} (prefetch="auto")
</LinkAccordion>
</div>
<div>
<LinkAccordion key={href} href={href} prefetch={true}>
{href} {`(prefetch={true})`}
</LinkAccordion>
</div>
</div>
)
}
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