Unverified Commit f0d81f14 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

[ppr] Route Cardinality Updates (#78476)

This enables a new set of cardinality changes for pages with PPR and
Dynamic IO enabled on it. When a set of more specific routes are
generated, we no longer error when the static shell is empty and instead
infer that as a sign that the user doesn't want to provide a route
fallback. If the user does in fact place suspense boundaries above
params access, the fallback shell will not be empty and will be used.

Given the following application structure:
```
/[lang]/layout.tsx
/[lang]/[teamSlug]/page.tsx
```

Where we have the following returned for `generateStaticProps`: `[{
lang: "en", teamSlug: "nextjs"}]`, we'd have the following rendered:

```
/[lang]/[teamSlug] <- empty shell won't cause error
/en/[teamSlug] <- empty shell won't cause error
/en/nextjs <- empty shell will cause error
```

If `/[lang]/[teamSlug]` generated an empty shell, then a request to
`/fr/nextjs` wouldn't use the `/[lang]/[teamSlug]` fallback shell and
would instead generate a new blocking route shell. Otherwise if it
didn't generate an empty shell, it would use the fallback shell that's
outputted.

If `/en/[teamSlug]` generated an empty shell, then a request to
`/en/react` wouldn't use the `/en/[teamSlug]` fallback shell and would
instead generate a new blocking route shell. Otherwise if it didn't
generate an empty shell, it would use the fallback shell that's
outputted.
parent bf2ad52d
......@@ -444,7 +444,7 @@ export type RoutesManifest = {
}
}
function pageToRoute(page: string) {
function pageToRoute(page: string): ManifestRoute {
const routeRegex = getNamedRouteRegex(page, {
prefixRouteKeys: true,
})
......@@ -1303,8 +1303,8 @@ export default async function build(
...pageKeys.pages,
...(pageKeys.app ?? []),
])
const dynamicRoutes: Array<ReturnType<typeof pageToRoute>> = []
const staticRoutes: typeof dynamicRoutes = []
const dynamicRoutes: Array<ManifestRoute> = []
const staticRoutes: Array<ManifestRoute> = []
for (const route of sortedRoutes) {
if (isDynamicRoute(route)) {
......@@ -2025,12 +2025,14 @@ export default async function build(
if (!isDynamic) {
staticPaths.set(originalAppPath, [
{
params: {},
pathname: page,
encodedPathname: page,
fallbackRouteParams: undefined,
fallbackRouteParams: [],
fallbackMode:
workerResult.prerenderFallbackMode,
fallbackRootParams: undefined,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
])
isStatic = true
......@@ -2061,8 +2063,6 @@ export default async function build(
`"getStaticProps" is not yet supported fully with "experimental-edge", detected on ${page}`
)
}
// TODO: add handling for statically rendering edge
// pages and allow edge with Prerender outputs
workerResult.isStatic = false
workerResult.hasStaticProps = false
}
......@@ -2188,7 +2188,7 @@ export default async function build(
runtime: pageRuntime,
pageDuration: undefined,
ssgPageDurations: undefined,
hasEmptyPrelude: undefined,
hasEmptyStaticShell: undefined,
})
})
})
......@@ -2607,6 +2607,7 @@ export default async function build(
)
)
)
const exportApp = require('../export')
.default as typeof import('../export').default
......@@ -2678,9 +2679,9 @@ export default async function build(
const appConfig = appDefaultConfigs.get(originalAppPath)
const isDynamicError = appConfig?.dynamic === 'error'
const isRoutePPREnabled = appConfig
const isRoutePPREnabled: boolean = appConfig
? checkIsRoutePPREnabled(config.experimental.ppr, appConfig)
: undefined
: false
routes.forEach((route) => {
// If the route has any dynamic root segments, we need to skip
......@@ -2700,6 +2701,8 @@ export default async function build(
_isDynamicError: isDynamicError,
_isAppDir: true,
_isRoutePPREnabled: isRoutePPREnabled,
_doNotThrowOnEmptyStaticShell:
!route.throwOnEmptyStaticShell,
}
})
})
......@@ -2780,6 +2783,31 @@ export default async function build(
// If there was no result, there's nothing more to do.
if (!exportResult) return
const getFallbackMode = (route: PrerenderedRoute) => {
const hasEmptyStaticShell = exportResult.byPath.get(
route.pathname
)?.hasEmptyStaticShell
// If the route has an empty static shell and is not configured to
// throw on empty static shell, then we should use the blocking
// static render mode.
if (
hasEmptyStaticShell &&
!route.throwOnEmptyStaticShell &&
route.fallbackMode === FallbackMode.PRERENDER
) {
return FallbackMode.BLOCKING_STATIC_RENDER
}
// If the route has no fallback mode, then we should use the
// `NOT_FOUND` fallback mode.
if (!route.fallbackMode) {
return FallbackMode.NOT_FOUND
}
return route.fallbackMode
}
const getCacheControl = (
exportPath: string,
defaultRevalidate: Revalidate = false
......@@ -2953,7 +2981,7 @@ export default async function build(
const {
metadata = {},
hasEmptyPrelude,
hasEmptyStaticShell,
hasPostponed,
} = exportResult.byPath.get(route.pathname) ?? {}
......@@ -2965,7 +2993,7 @@ export default async function build(
pageInfos.set(route.pathname, {
...(pageInfos.get(route.pathname) as PageInfo),
hasPostponed,
hasEmptyPrelude,
hasEmptyStaticShell,
initialCacheControl: cacheControl,
})
......@@ -2973,7 +3001,7 @@ export default async function build(
pageInfos.set(page, {
...(pageInfos.get(page) as PageInfo),
hasPostponed,
hasEmptyPrelude,
hasEmptyStaticShell,
initialCacheControl: cacheControl,
})
......@@ -3035,13 +3063,15 @@ export default async function build(
// prerendered routes.
if (!isRoutePPREnabled) {
dynamicRoutes.push({
params: {},
pathname: page,
encodedPathname: page,
fallbackRouteParams: undefined,
fallbackRouteParams: [],
fallbackMode:
fallbackModes.get(originalAppPath) ??
FallbackMode.NOT_FOUND,
fallbackRootParams: undefined,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
})
}
......@@ -3090,8 +3120,7 @@ export default async function build(
hasPostponed: isRoutePPREnabled,
})
const fallbackMode =
route.fallbackMode ?? FallbackMode.NOT_FOUND
const fallbackMode = getFallbackMode(route)
// When the route is configured to serve a prerender, we should
// use the cache control from the export result. If it can't be
......@@ -3133,7 +3162,9 @@ export default async function build(
fallbackExpire: fallbackCacheControl?.expire,
fallbackStatus: meta.status,
fallbackHeaders: meta.headers,
fallbackRootParams: route.fallbackRootParams,
fallbackRootParams: fallback
? route.fallbackRootParams
: undefined,
fallbackSourceRoute: route.fallbackRouteParams?.length
? page
: undefined,
......
import { FallbackMode } from '../../lib/fallback'
import {
assignErrorIfEmpty,
filterUniqueRootParamsCombinations,
filterUniqueParams,
} from './app'
import type { PrerenderedRoute } from './types'
describe('assignErrorIfEmpty', () => {
it('should assign throwOnEmptyStaticShell false for a static route', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: {},
pathname: '/',
encodedPathname: '/',
fallbackRouteParams: [],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
]
assignErrorIfEmpty(prerenderedRoutes, [])
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(true)
})
it('should assign throwOnEmptyStaticShell to the prerendered routes', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: {},
pathname: '/[id]',
encodedPathname: '/[id]',
fallbackRouteParams: ['id'],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { id: '1' },
pathname: '/1',
encodedPathname: '/1',
fallbackRouteParams: [],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
]
assignErrorIfEmpty(prerenderedRoutes, ['id'])
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(true)
})
it('should handle more complex routes', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: {},
pathname: '/[id]/[name]',
encodedPathname: '/[id]/[name]',
fallbackRouteParams: ['id', 'name'],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { id: '1' },
pathname: '/1/[name]',
encodedPathname: '/1/[name]',
fallbackRouteParams: ['name'],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { id: '1', name: 'test' },
pathname: '/1/test',
encodedPathname: '/1/test',
fallbackRouteParams: [],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { id: '2', name: 'test' },
pathname: '/2/test',
encodedPathname: '/2/test',
fallbackRouteParams: [],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { id: '2' },
pathname: '/2/[name]',
encodedPathname: '/2/[name]',
fallbackRouteParams: ['name'],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
]
assignErrorIfEmpty(prerenderedRoutes, ['id', 'name'])
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[2].throwOnEmptyStaticShell).toBe(true)
expect(prerenderedRoutes[3].throwOnEmptyStaticShell).toBe(true)
expect(prerenderedRoutes[4].throwOnEmptyStaticShell).toBe(false)
})
})
describe('filterUniqueParams', () => {
it('should filter out duplicate parameters', () => {
const params = [
{ id: '1', name: 'test' },
{ id: '1', name: 'test' },
{ id: '2' },
]
const unique = filterUniqueParams(['id', 'name'], params)
expect(unique).toEqual([{ id: '1', name: 'test' }, { id: '2' }])
})
it('should handle more complex routes', () => {
const params = [
{ id: '1', name: 'test', age: '10' },
{ id: '1', name: 'test', age: '20' },
{ id: '2', name: 'test', age: '10' },
]
const unique = filterUniqueParams(['id', 'name', 'age'], params)
expect(unique).toEqual([
{ id: '1', name: 'test', age: '10' },
{ id: '1', name: 'test', age: '20' },
{ id: '2', name: 'test', age: '10' },
])
})
})
describe('filterUniqueRootParamsCombinations', () => {
it('should return only the root parameters', () => {
const params = [
{ id: '1', name: 'test' },
{ id: '1', name: 'test' },
{ id: '2', name: 'test' },
]
const unique = filterUniqueRootParamsCombinations(['id'], params)
expect(unique).toEqual([{ id: '1' }, { id: '2' }])
})
})
import type { ParamValue, Params } from '../../server/request/params'
import type { AppPageModule } from '../../server/route-modules/app-page/module'
import type { AppSegment } from '../segment-config/app/app-segments'
import type { StaticPathsResult } from './types'
import type { PrerenderedRoute, StaticPathsResult } from './types'
import path from 'path'
import path from 'node:path'
import { AfterRunner } from '../../server/after/run-with-after'
import { createWorkStore } from '../../server/async-storage/work-store'
import { FallbackMode } from '../../lib/fallback'
......@@ -52,39 +52,26 @@ function areParamValuesEqual(a: ParamValue, b: ParamValue) {
* @param routeParams - The list of parameters to filter.
* @returns The list of unique parameters.
*/
function filterUniqueParams(
export function filterUniqueParams(
routeParamKeys: readonly string[],
routeParams: readonly Params[]
): Params[] {
const unique: Params[] = []
for (const params of routeParams) {
let i = 0
for (; i < unique.length; i++) {
const item = unique[i]
let j = 0
for (; j < routeParamKeys.length; j++) {
const key = routeParamKeys[j]
// If the param is not the same, then we need to break out of the loop.
paramsLoop: for (const params of routeParams) {
uniqueLoop: for (const item of unique) {
for (const key of routeParamKeys) {
// If the param is not the same, then we need to check the next item
if (!areParamValuesEqual(item[key], params[key])) {
break
continue uniqueLoop
}
}
// If we got to the end of the paramKeys array, then it means that we
// found a duplicate. Skip it.
if (j === routeParamKeys.length) {
break
}
}
// If we didn't get to the end of the unique array, then it means that we
// found a duplicate. Skip it.
if (i < unique.length) {
continue
// If we got here, then all params matched and we found a duplicate
continue paramsLoop
}
// If we got here, then we checked all items and found no duplicates
unique.push(params)
}
......@@ -117,36 +104,29 @@ function filterUniqueParams(
* @param routeParams - The list of parameters to filter.
* @returns The list of combinations of root params.
*/
function filterRootParamsCombinations(
export function filterUniqueRootParamsCombinations(
rootParamKeys: readonly string[],
routeParams: readonly Params[]
): Params[] {
const combinations: Params[] = []
for (const params of routeParams) {
paramsLoop: for (const params of routeParams) {
const combination: Params = {}
// Collect all root params. As soon as we don't find a root param, break.
let i = 0
for (; i < rootParamKeys.length; i++) {
const key = rootParamKeys[i]
for (const key of rootParamKeys) {
if (params[key]) {
combination[key] = params[key]
} else {
break
// Skip this combination if we don't have all root params
continue paramsLoop
}
}
// If we didn't find all root params, skip this combination. We only want to
// generate combinations that have all root params.
if (i < rootParamKeys.length) {
continue
}
combinations.push(combination)
}
return combinations
return filterUniqueParams(rootParamKeys, combinations)
}
/**
......@@ -243,6 +223,50 @@ function validateParams(
return valid
}
/**
* Assigns the throwOnEmptyStaticShell property to each of the prerendered routes.
*
* @param prerenderedRoutes - The prerendered routes.
* @param routeParamKeys - The keys of the route parameters.
*/
export function assignErrorIfEmpty(
prerenderedRoutes: readonly PrerenderedRoute[],
routeParamKeys: readonly string[]
) {
// If we're rendering a more specific route, then we don't need to error
// if the route is empty.
for (const prerenderedRoute of prerenderedRoutes) {
let throwOnEmptyStaticShell: boolean = true
// If the route has fallbackRouteParams, then we need to check if the
// route is a more specific route.
const { fallbackRouteParams, params } = prerenderedRoute
if (fallbackRouteParams && fallbackRouteParams.length > 0) {
siblingLoop: for (const other of prerenderedRoutes) {
// Skip the current route.
if (other === prerenderedRoute) continue
for (const key of routeParamKeys) {
// If the key is a fallback route param, then we can skip it, because
// it always matches.
if (fallbackRouteParams.includes(key)) {
throwOnEmptyStaticShell = false
break siblingLoop
}
// If the param value is not equal, then we can break out of the loop
// because the route is not a more specific route.
if (!areParamValuesEqual(params[key], other.params[key])) {
continue siblingLoop
}
}
}
}
prerenderedRoute.throwOnEmptyStaticShell = throwOnEmptyStaticShell
}
}
/**
* Builds the static paths for an app using `generateStaticParams`.
*
......@@ -396,6 +420,8 @@ export async function buildAppStaticPaths({
}
)
await afterRunner.executeAfter()
let lastDynamicSegmentHadGenerateStaticParams = false
for (const segment of segments) {
// Check to see if there are any missing params for segments that have
......@@ -470,11 +496,12 @@ export async function buildAppStaticPaths({
// Discover all unique combinations of the rootParams so we can generate
// shells for each of them if they're available.
routeParams.unshift(
...filterRootParamsCombinations(rootParamKeys, routeParams)
...filterUniqueRootParamsCombinations(rootParamKeys, routeParams)
)
result.prerenderedRoutes ??= []
result.prerenderedRoutes.push({
params: {},
pathname: page,
encodedPathname: page,
fallbackRouteParams: routeParamKeys,
......@@ -486,6 +513,8 @@ export async function buildAppStaticPaths({
: fallbackMode
: FallbackMode.NOT_FOUND,
fallbackRootParams: rootParamKeys,
// This is set later after all the routes have been processed.
throwOnEmptyStaticShell: true,
})
}
......@@ -503,7 +532,7 @@ export async function buildAppStaticPaths({
let pathname: string = page
let encodedPathname: string = page
const fallbackRouteParams: string[] = []
let fallbackRouteParams: string[] = []
for (const key of routeParamKeys) {
if (fallbackRouteParams.length > 0) {
......@@ -550,6 +579,7 @@ export async function buildAppStaticPaths({
result.prerenderedRoutes ??= []
result.prerenderedRoutes.push({
params,
pathname: normalizePathname(pathname),
encodedPathname: normalizePathname(encodedPathname),
fallbackRouteParams,
......@@ -561,11 +591,16 @@ export async function buildAppStaticPaths({
: fallbackMode
: FallbackMode.NOT_FOUND,
fallbackRootParams,
// This is set later after all the routes have been processed.
throwOnEmptyStaticShell: true,
})
})
}
await afterRunner.executeAfter()
// Now we have to set the throwOnEmptyStaticShell for each of the routes.
if (result.prerenderedRoutes && dynamicIO) {
assignErrorIfEmpty(result.prerenderedRoutes, routeParamKeys)
}
return result
}
......@@ -98,8 +98,8 @@ export async function buildPagesStaticPaths({
entry = `/${defaultLocale}${entry}`
}
const result = _routeMatcher(cleanedEntry)
if (!result) {
const params = _routeMatcher(cleanedEntry)
if (!params) {
throw new Error(
`The provided path \`${cleanedEntry}\` does not match the page: \`${page}\`.`
)
......@@ -109,6 +109,7 @@ export async function buildPagesStaticPaths({
// encoded so we decode the segments ensuring we only escape path
// delimiters
prerenderedRoutes.push({
params,
pathname: entry
.split('/')
.map((segment) =>
......@@ -119,6 +120,7 @@ export async function buildPagesStaticPaths({
fallbackRouteParams: undefined,
fallbackMode: parseStaticPathsResult(staticPathsResult.fallback),
fallbackRootParams: undefined,
throwOnEmptyStaticShell: undefined,
})
}
// For the object-provided path, we must make sure it specifies all
......@@ -196,6 +198,7 @@ export async function buildPagesStaticPaths({
const curLocale = entry.locale || defaultLocale || ''
prerenderedRoutes.push({
params,
pathname: normalizePathname(
`${curLocale ? `/${curLocale}` : ''}${
curLocale && builtPage === '/' ? '' : builtPage
......@@ -209,6 +212,7 @@ export async function buildPagesStaticPaths({
fallbackRouteParams: undefined,
fallbackMode: parseStaticPathsResult(staticPathsResult.fallback),
fallbackRootParams: undefined,
throwOnEmptyStaticShell: undefined,
})
}
})
......
import type { FallbackMode } from '../../lib/fallback'
import type { Params } from '../../server/request/params'
type StaticPrerenderedRoute = {
pathname: string
encodedPathname: string
fallbackRouteParams: undefined
fallbackMode: FallbackMode | undefined
fallbackRootParams: undefined
readonly params: Params
readonly pathname: string
readonly encodedPathname: string
readonly fallbackRouteParams: undefined
readonly fallbackMode: FallbackMode | undefined
readonly fallbackRootParams: undefined
/**
* When enabled, the route will be rendered with diagnostics enabled which
* will error the build if the route that is generated is empty.
*/
throwOnEmptyStaticShell: undefined
}
type FallbackPrerenderedRoute = {
pathname: string
encodedPathname: string
fallbackRouteParams: readonly string[]
fallbackMode: FallbackMode | undefined
fallbackRootParams: readonly string[]
readonly params: Params
readonly pathname: string
readonly encodedPathname: string
readonly fallbackRouteParams: readonly string[]
readonly fallbackMode: FallbackMode | undefined
readonly fallbackRootParams: readonly string[]
/**
* When enabled, the route will be rendered with diagnostics enabled which
* will error the build if the route that is generated is empty.
*/
throwOnEmptyStaticShell: boolean
}
export type PrerenderedRoute = StaticPrerenderedRoute | FallbackPrerenderedRoute
......
......@@ -353,7 +353,7 @@ export interface PageInfo {
pageDuration: number | undefined
ssgPageDurations: number[] | undefined
runtime: ServerRuntime
hasEmptyPrelude?: boolean
hasEmptyStaticShell?: boolean
hasPostponed?: boolean
isDynamicAppRoute?: boolean
}
......@@ -528,8 +528,9 @@ export async function printTreeView(
symbol = 'ƒ'
} else if (pageInfo?.isRoutePPREnabled) {
if (
// If the page has an empty prelude, then it's equivalent to a dynamic page
pageInfo?.hasEmptyPrelude ||
// If the page has an empty static shell, then it's equivalent to a
// dynamic page
pageInfo?.hasEmptyStaticShell ||
// ensure we don't mark dynamic paths that postponed as being dynamic
// since in this case we're able to partially prerender it
(pageInfo.isDynamicAppRoute && !pageInfo.hasPostponed)
......
......@@ -652,8 +652,8 @@ async function exportAppImpl(
info.metadata = result.metadata
}
if (typeof result.hasEmptyPrelude !== 'undefined') {
info.hasEmptyPrelude = result.hasEmptyPrelude
if (typeof result.hasEmptyStaticShell !== 'undefined') {
info.hasEmptyStaticShell = result.hasEmptyStaticShell
}
if (typeof result.hasPostponed !== 'undefined') {
......
......@@ -232,7 +232,7 @@ export async function exportAppPage(
}
// Writing static HTML to a file.
fileWriter.append(htmlFilepath, html ?? '')
fileWriter.append(htmlFilepath, html)
const isParallelRoute = /\/@\w+/.test(page)
const isNonSuccessfulStatusCode = res.statusCode > 300
......@@ -268,7 +268,7 @@ export async function exportAppPage(
return {
// Only include the metadata if the environment has next support.
metadata: hasNextSupport ? meta : undefined,
hasEmptyPrelude: Boolean(postponed) && html === '',
hasEmptyStaticShell: Boolean(postponed) && html === '',
hasPostponed: Boolean(postponed),
cacheControl,
fetchMetrics,
......
......@@ -70,7 +70,7 @@ export type ExportRouteResult =
cacheControl: CacheControl
metadata?: Partial<RouteMetadata>
ssgNotFound?: boolean
hasEmptyPrelude?: boolean
hasEmptyStaticShell?: boolean
hasPostponed?: boolean
fetchMetrics?: FetchMetrics
}
......@@ -135,9 +135,9 @@ export type ExportAppResult = {
*/
metadata?: Partial<RouteMetadata>
/**
* If the page has an empty prelude when using PPR.
* If the page has an empty static shell when using PPR.
*/
hasEmptyPrelude?: boolean
hasEmptyStaticShell?: boolean
/**
* If the page has postponed when using PPR.
*/
......
......@@ -109,6 +109,10 @@ async function exportPageImpl(
// result, we just want to use it to error the build if there's a problem.
_isProspectiveRender: isProspectiveRender = false,
// Configure the rendering of the page not to throw if an empty static shell
// is generated while rendering using PPR.
_doNotThrowOnEmptyStaticShell: doNotThrowOnEmptyStaticShell = false,
// Pull the original query out.
query: originalQuery = {},
} = pathMap
......@@ -267,6 +271,7 @@ async function exportPageImpl(
// If it's static, then it won't affect anything.
// If it's dynamic, then it can be handled when request hits the route.
serveStreamingMetadata: true,
doNotThrowOnEmptyStaticShell,
experimental: {
...input.renderOpts.experimental,
isRoutePPREnabled,
......@@ -590,7 +595,7 @@ async function exportPage(
cacheControl: result.cacheControl,
metadata: result.metadata,
ssgNotFound: result.ssgNotFound,
hasEmptyPrelude: result.hasEmptyPrelude,
hasEmptyStaticShell: result.hasEmptyStaticShell,
hasPostponed: result.hasPostponed,
turborepoAccessTraceResult: turborepoAccessTraceResult.serialize(),
fetchMetrics: result.fetchMetrics,
......
......@@ -132,7 +132,7 @@ import {
createDynamicValidationState,
getFirstDynamicReason,
trackAllowedDynamicAccess,
throwIfDisallowedEmptyShell,
throwIfDisallowedEmptyStaticShell,
consumeDynamicAccess,
type DynamicAccess,
} from './dynamic-rendering'
......@@ -2550,8 +2550,11 @@ async function spawnDynamicValidationInDev(
function LogDynamicValidation() {
try {
if (preludeIsEmpty) {
throwIfDisallowedEmptyShell(
// If we've disabled throwing on empty static shell, then we don't need to
// track any dynamic access that occurs above the suspense boundary because
// we'll do so in the route shell.
if (preludeIsEmpty && !ctx.renderOpts.doNotThrowOnEmptyStaticShell) {
throwIfDisallowedEmptyStaticShell(
route,
dynamicValidation,
serverDynamicTracking,
......@@ -3085,8 +3088,11 @@ async function prerenderToStream(
const { prelude, preludeIsEmpty } =
await processPrelude(unprocessedPrelude)
if (preludeIsEmpty) {
throwIfDisallowedEmptyShell(
// If we've disabled throwing on empty static shell, then we don't need to
// track any dynamic access that occurs above the suspense boundary because
// we'll do so in the route shell.
if (preludeIsEmpty && !ctx.renderOpts.doNotThrowOnEmptyStaticShell) {
throwIfDisallowedEmptyStaticShell(
workStore.route,
dynamicValidation,
serverDynamicTracking,
......@@ -3568,9 +3574,12 @@ async function prerenderToStream(
}
}
if (preludeIsEmpty) {
// If we've disabled throwing on empty static shell, then we don't need to
// track any dynamic access that occurs above the suspense boundary because
// we'll do so in the route shell.
if (preludeIsEmpty && !ctx.renderOpts.doNotThrowOnEmptyStaticShell) {
// We don't have a shell because the root errored when we aborted.
throwIfDisallowedEmptyShell(
throwIfDisallowedEmptyStaticShell(
workStore.route,
dynamicValidation,
serverDynamicTracking,
......
......@@ -647,7 +647,7 @@ function createErrorWithComponentStack(
return error
}
export function throwIfDisallowedEmptyShell(
export function throwIfDisallowedEmptyStaticShell(
route: string,
dynamicValidation: DynamicValidationState,
serverDynamic: DynamicTrackingState,
......@@ -688,7 +688,7 @@ export function throwIfDisallowedEmptyShell(
// blocked the root. We would have captured these during the prerender
// and can log them here and then terminate the build/validating render
const dynamicErrors = dynamicValidation.dynamicErrors
if (dynamicErrors.length) {
if (dynamicErrors.length > 0) {
for (let i = 0; i < dynamicErrors.length; i++) {
console.error(dynamicErrors[i])
}
......
......@@ -262,6 +262,13 @@ export interface RenderOptsPartial {
reactMaxHeadersLength: number | undefined
isStaticGeneration?: boolean
/**
* When true, the page will be rendered using the static rendering to detect
* any dynamic API's that would have stopped the page from being fully
* statically generated.
*/
doNotThrowOnEmptyStaticShell?: boolean
}
export type RenderOpts = LoadComponentsReturnType<AppPageModule> &
......
......@@ -41,6 +41,7 @@ const zExportMap: zod.ZodType<ExportPathMap> = z.record(
_isDynamicError: z.boolean().optional(),
_isRoutePPREnabled: z.boolean().optional(),
_isProspectiveRender: z.boolean().optional(),
_doNotThrowOnEmptyStaticShell: z.boolean().optional(),
})
)
......
......@@ -719,6 +719,15 @@ export type ExportPathMap = {
* @internal
*/
_isProspectiveRender?: boolean
/**
* When true, it indicates that the diagnostic render for this page is
* disabled. This is only used when the app has `experimental.ppr` and
* `experimental.dynamicIO` enabled.
*
* @internal
*/
_doNotThrowOnEmptyStaticShell?: boolean
}
}
......
export default async function Page({ params }) {
const { slug } = await params
return <div data-testid={`hello-${slug}`}>Hello /{slug}</div>
}
export async function generateStaticParams() {
return [{ slug: 'foo' }]
}
import { Suspense } from 'react'
export default function Layout({ children }) {
return (
<html>
<Suspense>
<body>{children}</body>
</Suspense>
</html>
)
}
import { nextTestSetup } from 'e2e-utils'
describe('empty-fallback-shells', () => {
const { next, isNextDeploy } = nextTestSetup({
files: __dirname,
})
it('should start and not postpone the response', async () => {
const res = await next.fetch('/world')
const html = await res.text()
expect(html).toContain('hello-world')
if (isNextDeploy) {
expect(res.headers.get('x-matched-path')).toBe('/[slug]')
}
// If we didn't use the fallback shell, then we didn't postpone the response
// and therefore shouldn't have sent the postponed header.
expect(res.headers.get('x-nextjs-postponed')).not.toBe('1')
})
})
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
dynamicIO: true,
ppr: true,
},
}
module.exports = nextConfig
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