Unverified Commit 3dce2eed authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

refactor: fallback updates (#68631)

This changes the internals to use an enum for the fallback mode instead
of passing around `boolean | string` which required knowledge to
understand what it meant. The enum values are now more verbose to aid in
readability.
parent e21f1b5b
...@@ -200,6 +200,7 @@ import { ...@@ -200,6 +200,7 @@ import {
import { storeShuttle } from './flying-shuttle/store-shuttle' import { storeShuttle } from './flying-shuttle/store-shuttle'
import { stitchBuilds } from './flying-shuttle/stitch-builds' import { stitchBuilds } from './flying-shuttle/stitch-builds'
import { inlineStaticEnv } from './flying-shuttle/inline-static-env' import { inlineStaticEnv } from './flying-shuttle/inline-static-env'
import { FallbackMode } from '../lib/fallback'
interface ExperimentalBypassForInfo { interface ExperimentalBypassForInfo {
experimentalBypassFor?: RouteHas[] experimentalBypassFor?: RouteHas[]
...@@ -2077,7 +2078,11 @@ export default async function build( ...@@ -2077,7 +2078,11 @@ export default async function build(
} }
} }
if (workerResult.prerenderFallback) { if (
workerResult.prerenderFallbackMode !== undefined &&
workerResult.prerenderFallbackMode !==
FallbackMode.NOT_FOUND
) {
// whether or not to allow requests for paths not // whether or not to allow requests for paths not
// returned from generateStaticParams // returned from generateStaticParams
appDynamicParamPaths.add(originalAppPath) appDynamicParamPaths.add(originalAppPath)
...@@ -2130,9 +2135,15 @@ export default async function build( ...@@ -2130,9 +2135,15 @@ export default async function build(
) )
} }
if (workerResult.prerenderFallback === 'blocking') { if (
workerResult.prerenderFallbackMode ===
FallbackMode.BLOCKING_STATIC_RENDER
) {
ssgBlockingFallbackPages.add(page) ssgBlockingFallbackPages.add(page)
} else if (workerResult.prerenderFallback === true) { } else if (
workerResult.prerenderFallbackMode ===
FallbackMode.STATIC_PRERENDER
) {
ssgStaticFallbackPages.add(page) ssgStaticFallbackPages.add(page)
} }
} else if (workerResult.hasServerProps) { } else if (workerResult.hasServerProps) {
......
...@@ -90,6 +90,11 @@ import { formatDynamicImportPath } from '../lib/format-dynamic-import-path' ...@@ -90,6 +90,11 @@ import { formatDynamicImportPath } from '../lib/format-dynamic-import-path'
import { isInterceptionRouteAppPath } from '../server/lib/interception-routes' import { isInterceptionRouteAppPath } from '../server/lib/interception-routes'
import { checkIsRoutePPREnabled } from '../server/lib/experimental/ppr' import { checkIsRoutePPREnabled } from '../server/lib/experimental/ppr'
import type { Params } from '../client/components/params' import type { Params } from '../client/components/params'
import { FallbackMode } from '../lib/fallback'
import {
fallbackToStaticPathsResult,
parseFallbackStaticPathsResult,
} from '../lib/fallback'
export type ROUTER_TYPE = 'pages' | 'app' export type ROUTER_TYPE = 'pages' | 'app'
...@@ -945,7 +950,7 @@ export type PrerenderedRoute = { ...@@ -945,7 +950,7 @@ export type PrerenderedRoute = {
} }
export type StaticPathsResult = { export type StaticPathsResult = {
fallback: boolean | 'blocking' fallbackMode: FallbackMode
prerenderedRoutes: PrerenderedRoute[] prerenderedRoutes: PrerenderedRoute[]
} }
...@@ -1172,7 +1177,7 @@ export async function buildStaticPaths({ ...@@ -1172,7 +1177,7 @@ export async function buildStaticPaths({
const seen = new Set<string>() const seen = new Set<string>()
return { return {
fallback: staticPathsResult.fallback, fallbackMode: parseFallbackStaticPathsResult(staticPathsResult.fallback),
prerenderedRoutes: prerenderRoutes.filter((route) => { prerenderedRoutes: prerenderRoutes.filter((route) => {
if (seen.has(route.path)) return false if (seen.has(route.path)) return false
...@@ -1345,6 +1350,7 @@ export async function buildAppStaticPaths({ ...@@ -1345,6 +1350,7 @@ export async function buildAppStaticPaths({
requestHeaders, requestHeaders,
maxMemoryCacheSize, maxMemoryCacheSize,
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
nextConfigOutput,
ComponentMod, ComponentMod,
}: { }: {
dir: string dir: string
...@@ -1357,6 +1363,7 @@ export async function buildAppStaticPaths({ ...@@ -1357,6 +1363,7 @@ export async function buildAppStaticPaths({
cacheHandler?: string cacheHandler?: string
maxMemoryCacheSize?: number maxMemoryCacheSize?: number
requestHeaders: IncrementalCache['requestHeaders'] requestHeaders: IncrementalCache['requestHeaders']
nextConfigOutput: 'standalone' | 'export' | undefined
ComponentMod: AppPageModule ComponentMod: AppPageModule
}): Promise<PartialStaticPathsResult> { }): Promise<PartialStaticPathsResult> {
ComponentMod.patchFetch() ComponentMod.patchFetch()
...@@ -1479,19 +1486,33 @@ export async function buildAppStaticPaths({ ...@@ -1479,19 +1486,33 @@ export async function buildAppStaticPaths({
} }
const builtParams = await buildParams() const builtParams = await buildParams()
const fallback = !generateParams.some(
if (
generateParams.some(
(generate) => generate.config?.dynamicParams === true
) &&
nextConfigOutput === 'export'
) {
throw new Error(
'"dynamicParams: true" cannot be used with "output: export". See more info here: https://nextjs.org/docs/app/building-your-application/deploying/static-exports'
)
}
const fallbackMode = !generateParams.some(
// TODO: dynamic params should be allowed // TODO: dynamic params should be allowed
// to be granular per segment but we need // to be granular per segment but we need
// additional information stored/leveraged in // additional information stored/leveraged in
// the prerender-manifest to allow this behavior // the prerender-manifest to allow this behavior
(generate) => generate.config?.dynamicParams === false (generate) => generate.config?.dynamicParams === false
) )
? FallbackMode.BLOCKING_STATIC_RENDER
: FallbackMode.NOT_FOUND
if (!hadAllParamsGenerated) { if (!hadAllParamsGenerated) {
return { return {
fallback: fallbackMode:
process.env.NODE_ENV === 'production' && isDynamicRoute(page) process.env.NODE_ENV === 'production' && isDynamicRoute(page)
? true ? FallbackMode.BLOCKING_STATIC_RENDER
: undefined, : undefined,
prerenderedRoutes: undefined, prerenderedRoutes: undefined,
} }
...@@ -1499,7 +1520,7 @@ export async function buildAppStaticPaths({ ...@@ -1499,7 +1520,7 @@ export async function buildAppStaticPaths({
return buildStaticPaths({ return buildStaticPaths({
staticPathsResult: { staticPathsResult: {
fallback, fallback: fallbackToStaticPathsResult(fallbackMode),
paths: builtParams.map((params) => ({ params })), paths: builtParams.map((params) => ({ params })),
}, },
page, page,
...@@ -1519,7 +1540,7 @@ type PageIsStaticResult = { ...@@ -1519,7 +1540,7 @@ type PageIsStaticResult = {
hasServerProps?: boolean hasServerProps?: boolean
hasStaticProps?: boolean hasStaticProps?: boolean
prerenderedRoutes: PrerenderedRoute[] | undefined prerenderedRoutes: PrerenderedRoute[] | undefined
prerenderFallback: boolean | 'blocking' | undefined prerenderFallbackMode: FallbackMode | undefined
isNextImageImported?: boolean isNextImageImported?: boolean
traceIncludes?: string[] traceIncludes?: string[]
traceExcludes?: string[] traceExcludes?: string[]
...@@ -1542,6 +1563,7 @@ export async function isPageStatic({ ...@@ -1542,6 +1563,7 @@ export async function isPageStatic({
originalAppPath, originalAppPath,
isrFlushToDisk, isrFlushToDisk,
maxMemoryCacheSize, maxMemoryCacheSize,
nextConfigOutput,
cacheHandler, cacheHandler,
pprConfig, pprConfig,
}: { }: {
...@@ -1561,7 +1583,7 @@ export async function isPageStatic({ ...@@ -1561,7 +1583,7 @@ export async function isPageStatic({
isrFlushToDisk?: boolean isrFlushToDisk?: boolean
maxMemoryCacheSize?: number maxMemoryCacheSize?: number
cacheHandler?: string cacheHandler?: string
nextConfigOutput: 'standalone' | 'export' nextConfigOutput: 'standalone' | 'export' | undefined
pprConfig: ExperimentalPPRConfig | undefined pprConfig: ExperimentalPPRConfig | undefined
}): Promise<PageIsStaticResult> { }): Promise<PageIsStaticResult> {
const isPageStaticSpan = trace('is-page-static-utils', parentId) const isPageStaticSpan = trace('is-page-static-utils', parentId)
...@@ -1576,7 +1598,7 @@ export async function isPageStatic({ ...@@ -1576,7 +1598,7 @@ export async function isPageStatic({
let componentsResult: LoadComponentsReturnType let componentsResult: LoadComponentsReturnType
let prerenderedRoutes: PrerenderedRoute[] | undefined let prerenderedRoutes: PrerenderedRoute[] | undefined
let prerenderFallback: boolean | 'blocking' | undefined let prerenderFallbackMode: FallbackMode | undefined
let appConfig: AppConfig = {} let appConfig: AppConfig = {}
let isClientComponent: boolean = false let isClientComponent: boolean = false
const pathIsEdgeRuntime = isEdgeRuntime(pageRuntime) const pathIsEdgeRuntime = isEdgeRuntime(pageRuntime)
...@@ -1673,7 +1695,7 @@ export async function isPageStatic({ ...@@ -1673,7 +1695,7 @@ export async function isPageStatic({
} }
if (isDynamicRoute(page)) { if (isDynamicRoute(page)) {
;({ fallback: prerenderFallback, prerenderedRoutes } = ;({ fallbackMode: prerenderFallbackMode, prerenderedRoutes } =
await buildAppStaticPaths({ await buildAppStaticPaths({
dir, dir,
page, page,
...@@ -1685,6 +1707,7 @@ export async function isPageStatic({ ...@@ -1685,6 +1707,7 @@ export async function isPageStatic({
maxMemoryCacheSize, maxMemoryCacheSize,
cacheHandler, cacheHandler,
ComponentMod, ComponentMod,
nextConfigOutput,
})) }))
} }
} else { } else {
...@@ -1729,7 +1752,7 @@ export async function isPageStatic({ ...@@ -1729,7 +1752,7 @@ export async function isPageStatic({
} }
if ((hasStaticProps && hasStaticPaths) || staticPathsResult) { if ((hasStaticProps && hasStaticPaths) || staticPathsResult) {
;({ fallback: prerenderFallback, prerenderedRoutes } = ;({ fallbackMode: prerenderFallbackMode, prerenderedRoutes } =
await buildStaticPaths({ await buildStaticPaths({
page, page,
locales, locales,
...@@ -1761,7 +1784,7 @@ export async function isPageStatic({ ...@@ -1761,7 +1784,7 @@ export async function isPageStatic({
isRoutePPREnabled, isRoutePPREnabled,
isHybridAmp: config.amp === 'hybrid', isHybridAmp: config.amp === 'hybrid',
isAmpOnly: config.amp === true, isAmpOnly: config.amp === true,
prerenderFallback, prerenderFallbackMode,
prerenderedRoutes, prerenderedRoutes,
hasStaticProps, hasStaticProps,
hasServerProps, hasServerProps,
...@@ -1778,50 +1801,71 @@ export async function isPageStatic({ ...@@ -1778,50 +1801,71 @@ export async function isPageStatic({
}) })
} }
function reduceAppConfig(generateParams: GenerateParamsResults): AppConfig { type ReducedAppConfig = Pick<
return generateParams.reduce( AppConfig,
(builtConfig: AppConfig, curGenParams): AppConfig => { | 'dynamic'
| 'fetchCache'
| 'preferredRegion'
| 'revalidate'
| 'experimental_ppr'
>
/**
* Collect the app config from the generate param segments. This only gets a
* subset of the config options.
*
* @param segments the generate param segments
* @returns the reduced app config
*/
function reduceAppConfig(segments: GenerateParamsResults): ReducedAppConfig {
const config: ReducedAppConfig = {}
for (const segment of segments) {
if (!segment.config) continue
const { const {
dynamic, dynamic,
fetchCache, fetchCache,
preferredRegion, preferredRegion,
revalidate: curRevalidate, revalidate,
experimental_ppr, experimental_ppr,
} = curGenParams?.config || {} } = segment.config
// TODO: should conflicting configs here throw an error // TODO: should conflicting configs here throw an error
// e.g. if layout defines one region but page defines another // e.g. if layout defines one region but page defines another
if (typeof builtConfig.preferredRegion === 'undefined') {
builtConfig.preferredRegion = preferredRegion // Get the first value of preferredRegion, dynamic, revalidate, and
// fetchCache.
if (typeof config.preferredRegion === 'undefined') {
config.preferredRegion = preferredRegion
} }
if (typeof builtConfig.dynamic === 'undefined') { if (typeof config.dynamic === 'undefined') {
builtConfig.dynamic = dynamic config.dynamic = dynamic
} }
if (typeof builtConfig.fetchCache === 'undefined') { if (typeof config.fetchCache === 'undefined') {
builtConfig.fetchCache = fetchCache config.fetchCache = fetchCache
} }
// If partial prerendering has been set, only override it if the current value is if (typeof config.revalidate === 'undefined') {
// provided as it's resolved from root layout to leaf page. config.revalidate = revalidate
if (typeof experimental_ppr !== 'undefined') {
builtConfig.experimental_ppr = experimental_ppr
} }
// any revalidate number overrides false // Any revalidate number overrides false, and shorter revalidate overrides
// shorter revalidate overrides longer (initially) // longer (initially).
if (typeof builtConfig.revalidate === 'undefined') {
builtConfig.revalidate = curRevalidate
}
if ( if (
typeof curRevalidate === 'number' && typeof revalidate === 'number' &&
(typeof builtConfig.revalidate !== 'number' || (typeof config.revalidate !== 'number' || revalidate < config.revalidate)
curRevalidate < builtConfig.revalidate)
) { ) {
builtConfig.revalidate = curRevalidate config.revalidate = revalidate
} }
return builtConfig
}, // If partial prerendering has been set, only override it if the current
{} // value is provided as it's resolved from root layout to leaf page.
) if (typeof experimental_ppr !== 'undefined') {
config.experimental_ppr = experimental_ppr
}
}
return config
} }
export async function hasCustomGetInitialProps({ export async function hasCustomGetInitialProps({
......
/**
* Describes the different fallback modes that a given page can have.
*/
export const enum FallbackMode {
/**
* A BLOCKING_STATIC_RENDER fallback will block the request until the page is
* generated. No fallback page will be rendered, and users will have to wait
* to render the page.
*/
BLOCKING_STATIC_RENDER = 'BLOCKING_STATIC_RENDER',
/**
* When set to PRERENDER, a fallback page will be sent to users in place of
* forcing them to wait for the page to be generated. This allows the user to
* see a rendered page earlier.
*/
STATIC_PRERENDER = 'STATIC_PRERENDER',
/**
* When set to NOT_FOUND, pages that are not already prerendered will result
* in a not found response.
*/
NOT_FOUND = 'NOT_FOUND',
}
/**
* The fallback value returned from the `getStaticPaths` function.
*/
export type GetStaticPathsFallback = boolean | 'blocking'
/**
* Parses the fallback field from the prerender manifest.
*
* @param fallbackField The fallback field from the prerender manifest.
* @returns The fallback mode.
*/
export function parseFallbackField(
fallbackField: string | false | null | undefined
): FallbackMode | undefined {
if (typeof fallbackField === 'string') {
return FallbackMode.STATIC_PRERENDER
} else if (fallbackField === null) {
return FallbackMode.BLOCKING_STATIC_RENDER
} else if (fallbackField === false) {
return FallbackMode.NOT_FOUND
} else if (fallbackField === undefined) {
return undefined
} else {
throw new Error(
`Invalid fallback option: ${fallbackField}. Fallback option must be a string, null, undefined, or false.`
)
}
}
/**
* Parses the fallback from the static paths result.
*
* @param result The result from the static paths function.
* @returns The fallback mode.
*/
export function parseFallbackStaticPathsResult(
result: GetStaticPathsFallback
): FallbackMode {
if (result === true) {
return FallbackMode.STATIC_PRERENDER
} else if (result === 'blocking') {
return FallbackMode.BLOCKING_STATIC_RENDER
} else {
return FallbackMode.NOT_FOUND
}
}
/**
* Converts the fallback mode to a static paths result.
*
* @param fallback The fallback mode.
* @returns The static paths fallback result.
*/
export function fallbackToStaticPathsResult(
fallback: FallbackMode
): GetStaticPathsFallback {
switch (fallback) {
case FallbackMode.STATIC_PRERENDER:
return true
case FallbackMode.BLOCKING_STATIC_RENDER:
return 'blocking'
case FallbackMode.NOT_FOUND:
default:
return false
}
}
...@@ -164,6 +164,7 @@ import { NextRequestHint } from './web/adapter' ...@@ -164,6 +164,7 @@ import { NextRequestHint } from './web/adapter'
import { getRevalidateReason } from './instrumentation/utils' import { getRevalidateReason } from './instrumentation/utils'
import { RouteKind } from './route-kind' import { RouteKind } from './route-kind'
import type { RouteModule } from './route-modules/route-module' import type { RouteModule } from './route-modules/route-module'
import { FallbackMode, parseFallbackField } from '../lib/fallback'
export type FindComponentsResult = { export type FindComponentsResult = {
components: LoadComponentsReturnType components: LoadComponentsReturnType
...@@ -293,8 +294,6 @@ export type RequestContext< ...@@ -293,8 +294,6 @@ export type RequestContext<
renderOpts: RenderOpts renderOpts: RenderOpts
} }
export type FallbackMode = false | undefined | 'blocking' | 'static'
export class NoFallbackError extends Error {} export class NoFallbackError extends Error {}
// Internal wrapper around build errors at development // Internal wrapper around build errors at development
...@@ -1831,7 +1830,7 @@ export default abstract class Server< ...@@ -1831,7 +1830,7 @@ export default abstract class Server<
isAppPath: boolean isAppPath: boolean
}): Promise<{ }): Promise<{
staticPaths?: string[] staticPaths?: string[]
fallbackMode?: 'static' | 'blocking' | false fallbackMode?: FallbackMode
}> { }> {
// Read whether or not fallback should exist from the manifest. // Read whether or not fallback should exist from the manifest.
const fallbackField = const fallbackField =
...@@ -1841,12 +1840,7 @@ export default abstract class Server< ...@@ -1841,12 +1840,7 @@ export default abstract class Server<
// `staticPaths` is intentionally set to `undefined` as it should've // `staticPaths` is intentionally set to `undefined` as it should've
// been caught when checking disk data. // been caught when checking disk data.
staticPaths: undefined, staticPaths: undefined,
fallbackMode: fallbackMode: parseFallbackField(fallbackField),
typeof fallbackField === 'string'
? 'static'
: fallbackField === null
? 'blocking'
: fallbackField,
} }
} }
...@@ -1920,7 +1914,7 @@ export default abstract class Server< ...@@ -1920,7 +1914,7 @@ export default abstract class Server<
const isAppPath = components.isAppPath === true const isAppPath = components.isAppPath === true
const hasServerProps = !!components.getServerSideProps const hasServerProps = !!components.getServerSideProps
let hasStaticPaths = !!components.getStaticPaths let hasGetStaticPaths = !!components.getStaticPaths
const isServerAction = getIsServerAction(req) const isServerAction = getIsServerAction(req)
const hasGetInitialProps = !!components.Component?.getInitialProps const hasGetInitialProps = !!components.Component?.getInitialProps
let isSSG = !!components.getStaticProps let isSSG = !!components.getStaticProps
...@@ -1936,7 +1930,7 @@ export default abstract class Server< ...@@ -1936,7 +1930,7 @@ export default abstract class Server<
let staticPaths: string[] | undefined let staticPaths: string[] | undefined
let fallbackMode: FallbackMode let fallbackMode: FallbackMode | undefined
let hasFallback = false let hasFallback = false
const isDynamic = isDynamicRoute(components.page) const isDynamic = isDynamicRoute(components.page)
...@@ -1956,14 +1950,14 @@ export default abstract class Server< ...@@ -1956,14 +1950,14 @@ export default abstract class Server<
if (this.nextConfig.output === 'export') { if (this.nextConfig.output === 'export') {
const page = components.page const page = components.page
if (!staticPaths) {
if (fallbackMode !== 'static') {
throw new Error( throw new Error(
`Page "${page}" is missing exported function "generateStaticParams()", which is required with "output: export" config.` `Page "${page}" is missing exported function "generateStaticParams()", which is required with "output: export" config.`
) )
} }
const resolvedWithoutSlash = removeTrailingSlash(resolvedUrlPathname) const resolvedWithoutSlash = removeTrailingSlash(resolvedUrlPathname)
if (!staticPaths?.includes(resolvedWithoutSlash)) { if (!staticPaths.includes(resolvedWithoutSlash)) {
throw new Error( throw new Error(
`Page "${page}" is missing param "${resolvedWithoutSlash}" in "generateStaticParams()", which is required with "output: export" config.` `Page "${page}" is missing param "${resolvedWithoutSlash}" in "generateStaticParams()", which is required with "output: export" config.`
) )
...@@ -1971,7 +1965,7 @@ export default abstract class Server< ...@@ -1971,7 +1965,7 @@ export default abstract class Server<
} }
if (hasFallback) { if (hasFallback) {
hasStaticPaths = true hasGetStaticPaths = true
} }
} }
...@@ -2355,7 +2349,7 @@ export default abstract class Server< ...@@ -2355,7 +2349,7 @@ export default abstract class Server<
(!isNextDataRequest && opts.dev === true) || (!isNextDataRequest && opts.dev === true) ||
// If this is not SSG or does not have static paths, then it supports // If this is not SSG or does not have static paths, then it supports
// dynamic HTML. // dynamic HTML.
(!isSSG && !hasStaticPaths) || (!isSSG && !hasGetStaticPaths) ||
// If this request has provided postponed data, it supports dynamic // If this request has provided postponed data, it supports dynamic
// HTML. // HTML.
typeof postponed === 'string' || typeof postponed === 'string' ||
...@@ -2723,19 +2717,32 @@ export default abstract class Server< ...@@ -2723,19 +2717,32 @@ export default abstract class Server<
const isProduction = !this.renderOpts.dev const isProduction = !this.renderOpts.dev
const didRespond = hasResolved || res.sent const didRespond = hasResolved || res.sent
// If we haven't found the static paths for the route, then do it now.
if (!staticPaths) { if (!staticPaths) {
;({ staticPaths, fallbackMode } = hasStaticPaths if (hasGetStaticPaths) {
? await this.getStaticPaths({ const pathsResult = await this.getStaticPaths({
pathname, pathname,
requestHeaders: req.headers, requestHeaders: req.headers,
isAppPath, isAppPath,
page: components.page, page: components.page,
}) })
: { staticPaths: undefined, fallbackMode: false })
staticPaths = pathsResult.staticPaths
fallbackMode = pathsResult.fallbackMode
} else {
staticPaths = undefined
fallbackMode = FallbackMode.NOT_FOUND
}
} }
if (fallbackMode === 'static' && isBot(req.headers['user-agent'] || '')) { // When serving a bot request, we want to serve a blocking render and not
fallbackMode = 'blocking' // the prerendered page. This ensures that the correct content is served
// to the bot in the head.
if (
fallbackMode === FallbackMode.STATIC_PRERENDER &&
isBot(req.headers['user-agent'] || '')
) {
fallbackMode = FallbackMode.BLOCKING_STATIC_RENDER
} }
// skip on-demand revalidate if cache is not present and // skip on-demand revalidate if cache is not present and
...@@ -2758,9 +2765,9 @@ export default abstract class Server< ...@@ -2758,9 +2765,9 @@ export default abstract class Server<
// or for prerendered fallback: false paths // or for prerendered fallback: false paths
if ( if (
isOnDemandRevalidate && isOnDemandRevalidate &&
(fallbackMode !== false || previousCacheEntry) (fallbackMode !== FallbackMode.NOT_FOUND || previousCacheEntry)
) { ) {
fallbackMode = 'blocking' fallbackMode = FallbackMode.BLOCKING_STATIC_RENDER
} }
// We use `ssgCacheKey` here as it is normalized to match the encoding // We use `ssgCacheKey` here as it is normalized to match the encoding
...@@ -2777,8 +2784,12 @@ export default abstract class Server< ...@@ -2777,8 +2784,12 @@ export default abstract class Server<
const isPageIncludedInStaticPaths = const isPageIncludedInStaticPaths =
staticPathKey && staticPaths?.includes(staticPathKey) staticPathKey && staticPaths?.includes(staticPathKey)
if ((this.nextConfig.experimental as any).isExperimentalCompile) { // When experimental compile is used, no pages have been prerendered,
fallbackMode = 'blocking' // so they should all be blocking.
// @ts-expect-error internal field
if (this.nextConfig.experimental.isExperimentalCompile) {
fallbackMode = FallbackMode.BLOCKING_STATIC_RENDER
} }
// When we did not respond from cache, we need to choose to block on // When we did not respond from cache, we need to choose to block on
...@@ -2795,7 +2806,7 @@ export default abstract class Server< ...@@ -2795,7 +2806,7 @@ export default abstract class Server<
if ( if (
process.env.NEXT_RUNTIME !== 'edge' && process.env.NEXT_RUNTIME !== 'edge' &&
!this.minimalMode && !this.minimalMode &&
fallbackMode !== 'blocking' && fallbackMode !== FallbackMode.BLOCKING_STATIC_RENDER &&
staticPathKey && staticPathKey &&
!didRespond && !didRespond &&
!isPreviewMode && !isPreviewMode &&
...@@ -2807,7 +2818,7 @@ export default abstract class Server< ...@@ -2807,7 +2818,7 @@ export default abstract class Server<
// getStaticPaths. // getStaticPaths.
(isProduction || (staticPaths && staticPaths?.length > 0)) && (isProduction || (staticPaths && staticPaths?.length > 0)) &&
// When fallback isn't present, abort this render so we 404 // When fallback isn't present, abort this render so we 404
fallbackMode !== 'static' fallbackMode === FallbackMode.NOT_FOUND
) { ) {
throw new NoFallbackError() throw new NoFallbackError()
} }
......
...@@ -5,7 +5,7 @@ import type { Params } from '../../client/components/params' ...@@ -5,7 +5,7 @@ import type { Params } from '../../client/components/params'
import type { ParsedUrl } from '../../shared/lib/router/utils/parse-url' import type { ParsedUrl } from '../../shared/lib/router/utils/parse-url'
import type { ParsedUrlQuery } from 'querystring' import type { ParsedUrlQuery } from 'querystring'
import type { UrlWithParsedQuery } from 'url' import type { UrlWithParsedQuery } from 'url'
import type { FallbackMode, MiddlewareRoutingItem } from '../base-server' import type { MiddlewareRoutingItem } from '../base-server'
import type { FunctionComponent } from 'react' import type { FunctionComponent } from 'react'
import type { RouteDefinition } from '../route-definitions/route-definition' import type { RouteDefinition } from '../route-definitions/route-definition'
import type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager' import type { RouteMatcherManager } from '../route-matcher-managers/route-matcher-manager'
...@@ -69,6 +69,7 @@ import { decorateServerError } from '../../shared/lib/error-source' ...@@ -69,6 +69,7 @@ import { decorateServerError } from '../../shared/lib/error-source'
import type { ServerOnInstrumentationRequestError } from '../app-render/types' import type { ServerOnInstrumentationRequestError } from '../app-render/types'
import type { ServerComponentsHmrCache } from '../response-cache' import type { ServerComponentsHmrCache } from '../response-cache'
import { logRequests } from './log-requests' import { logRequests } from './log-requests'
import { FallbackMode } from '../../lib/fallback'
// Load ReactDevOverlay only when needed // Load ReactDevOverlay only when needed
let ReactDevOverlayImpl: FunctionComponent let ReactDevOverlayImpl: FunctionComponent
...@@ -168,7 +169,7 @@ export default class DevServer extends Server { ...@@ -168,7 +169,7 @@ export default class DevServer extends Server {
// 5MB // 5MB
max: 5 * 1024 * 1024, max: 5 * 1024 * 1024,
length(value) { length(value) {
return JSON.stringify(value.staticPaths).length return JSON.stringify(value.staticPaths)?.length ?? 0
}, },
}) })
this.renderOpts.ampSkipValidation = this.renderOpts.ampSkipValidation =
...@@ -732,7 +733,7 @@ export default class DevServer extends Server { ...@@ -732,7 +733,7 @@ export default class DevServer extends Server {
isAppPath: boolean isAppPath: boolean
}): Promise<{ }): Promise<{
staticPaths?: string[] staticPaths?: string[]
fallbackMode?: false | 'static' | 'blocking' fallbackMode?: FallbackMode
}> { }> {
// we lazy load the staticPaths to prevent the user // we lazy load the staticPaths to prevent the user
// from waiting on them for the page to load in dev mode // from waiting on them for the page to load in dev mode
...@@ -767,6 +768,7 @@ export default class DevServer extends Server { ...@@ -767,6 +768,7 @@ export default class DevServer extends Server {
fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix, fetchCacheKeyPrefix: this.nextConfig.experimental.fetchCacheKeyPrefix,
isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk, isrFlushToDisk: this.nextConfig.experimental.isrFlushToDisk,
maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize, maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize,
nextConfigOutput: this.nextConfig.output,
}) })
return pathsResult return pathsResult
} finally { } finally {
...@@ -781,29 +783,26 @@ export default class DevServer extends Server { ...@@ -781,29 +783,26 @@ export default class DevServer extends Server {
[] []
) )
.then((res) => { .then((res) => {
const { prerenderedRoutes: staticPaths = [], fallback } = res.value const { prerenderedRoutes: staticPaths, fallbackMode: fallback } =
res.value
if (!isAppPath && this.nextConfig.output === 'export') { if (!isAppPath && this.nextConfig.output === 'export') {
if (fallback === 'blocking') { if (fallback === FallbackMode.BLOCKING_STATIC_RENDER) {
throw new Error( throw new Error(
'getStaticPaths with "fallback: blocking" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export' 'getStaticPaths with "fallback: blocking" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'
) )
} else if (fallback === true) { } else if (fallback === FallbackMode.STATIC_PRERENDER) {
throw new Error( throw new Error(
'getStaticPaths with "fallback: true" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export' 'getStaticPaths with "fallback: true" cannot be used with "output: export". See more info here: https://nextjs.org/docs/advanced-features/static-html-export'
) )
} }
} }
const value: { const value: {
staticPaths: string[] staticPaths: string[] | undefined
fallbackMode: FallbackMode fallbackMode: FallbackMode | undefined
} = { } = {
staticPaths: staticPaths.map((route) => route.path), staticPaths: staticPaths?.map((route) => route.path),
fallbackMode: fallbackMode: fallback,
fallback === 'blocking'
? 'blocking'
: fallback === true
? 'static'
: fallback,
} }
this.staticPathsCache.set(pathname, value) this.staticPathsCache.set(pathname, value)
return value return value
......
...@@ -41,6 +41,7 @@ export async function loadStaticPaths({ ...@@ -41,6 +41,7 @@ export async function loadStaticPaths({
maxMemoryCacheSize, maxMemoryCacheSize,
requestHeaders, requestHeaders,
cacheHandler, cacheHandler,
nextConfigOutput,
}: { }: {
dir: string dir: string
distDir: string distDir: string
...@@ -56,6 +57,7 @@ export async function loadStaticPaths({ ...@@ -56,6 +57,7 @@ export async function loadStaticPaths({
maxMemoryCacheSize?: number maxMemoryCacheSize?: number
requestHeaders: IncrementalCache['requestHeaders'] requestHeaders: IncrementalCache['requestHeaders']
cacheHandler?: string cacheHandler?: string
nextConfigOutput: 'standalone' | 'export' | undefined
}): Promise<PartialStaticPathsResult> { }): Promise<PartialStaticPathsResult> {
// update work memory runtime-config // update work memory runtime-config
require('../../shared/lib/runtime-config.external').setConfig(config) require('../../shared/lib/runtime-config.external').setConfig(config)
...@@ -107,6 +109,7 @@ export async function loadStaticPaths({ ...@@ -107,6 +109,7 @@ export async function loadStaticPaths({
fetchCacheKeyPrefix, fetchCacheKeyPrefix,
maxMemoryCacheSize, maxMemoryCacheSize,
ComponentMod: components.ComponentMod, ComponentMod: components.ComponentMod,
nextConfigOutput,
}) })
} }
......
...@@ -18,6 +18,7 @@ import type { ...@@ -18,6 +18,7 @@ import type {
NextApiRequest, NextApiRequest,
NextApiHandler, NextApiHandler,
} from './shared/lib/utils' } from './shared/lib/utils'
import type { GetStaticPathsFallback } from './lib/fallback'
import type { NextApiRequestCookies } from './server/api-utils' import type { NextApiRequestCookies } from './server/api-utils'
...@@ -220,7 +221,7 @@ export type GetStaticPathsResult< ...@@ -220,7 +221,7 @@ export type GetStaticPathsResult<
Params extends ParsedUrlQuery = ParsedUrlQuery, Params extends ParsedUrlQuery = ParsedUrlQuery,
> = { > = {
paths: Array<string | { params: Params; locale?: string }> paths: Array<string | { params: Params; locale?: string }>
fallback: boolean | 'blocking' fallback: GetStaticPathsFallback
} }
/** /**
......
...@@ -14,6 +14,16 @@ describe('app dir - with output export - dynamic missing gsp dev', () => { ...@@ -14,6 +14,16 @@ describe('app dir - with output export - dynamic missing gsp dev', () => {
}) })
}) })
it('should error when dynamic route is set to true', async () => {
await runTests({
isDev: true,
dynamicPage: 'undefined',
dynamicParams: 'true',
expectedErrMsg:
'"dynamicParams: true" cannot be used with "output: export". See more info here: https://nextjs.org/docs/app/building-your-application/deploying/static-exports',
})
})
it('should error when client component has generateStaticParams', async () => { it('should error when client component has generateStaticParams', async () => {
const expectedErrMsg = process.env.TURBOPACK_DEV const expectedErrMsg = process.env.TURBOPACK_DEV
? 'Page "test/integration/app-dir-export/app/another/[slug]/page.js" cannot use both "use client" and export function "generateStaticParams()".' ? 'Page "test/integration/app-dir-export/app/another/[slug]/page.js" cannot use both "use client" and export function "generateStaticParams()".'
......
...@@ -106,6 +106,7 @@ export async function runTests({ ...@@ -106,6 +106,7 @@ export async function runTests({
isDev = false, isDev = false,
trailingSlash = true, trailingSlash = true,
dynamicPage, dynamicPage,
dynamicParams,
dynamicApiRoute, dynamicApiRoute,
generateStaticParamsOpt, generateStaticParamsOpt,
expectedErrMsg, expectedErrMsg,
...@@ -113,6 +114,7 @@ export async function runTests({ ...@@ -113,6 +114,7 @@ export async function runTests({
isDev?: boolean isDev?: boolean
trailingSlash?: boolean trailingSlash?: boolean
dynamicPage?: string dynamicPage?: string
dynamicParams?: string
dynamicApiRoute?: string dynamicApiRoute?: string
generateStaticParamsOpt?: 'set noop' | 'set client' generateStaticParamsOpt?: 'set noop' | 'set client'
expectedErrMsg?: string expectedErrMsg?: string
...@@ -129,12 +131,18 @@ export async function runTests({ ...@@ -129,12 +131,18 @@ export async function runTests({
`const dynamic = ${dynamicPage}` `const dynamic = ${dynamicPage}`
) )
} }
if (dynamicApiRoute !== undefined) { if (dynamicApiRoute !== undefined) {
apiJson.replace( apiJson.replace(
`const dynamic = 'force-static'`, `const dynamic = 'force-static'`,
`const dynamic = ${dynamicApiRoute}` `const dynamic = ${dynamicApiRoute}`
) )
} }
if (dynamicParams !== undefined) {
slugPage.prepend(`export const dynamicParams = ${dynamicParams}\n`)
}
if (generateStaticParamsOpt === 'set noop') { if (generateStaticParamsOpt === 'set noop') {
slugPage.replace('export function generateStaticParams', 'function noop') slugPage.replace('export function generateStaticParams', 'function noop')
} else if (generateStaticParamsOpt === 'set client') { } else if (generateStaticParamsOpt === 'set client') {
......
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