Unverified Commit cf4d3ae8 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

partial fallbacks: only upgrade shells with remaining prerenderable params (#91158)

Partial fallback upgrading is currently too broad. Any PPR fallback shell can be treated as upgradeable, including routes with no `generateStaticParams` and shells that are already as specific as prerendering can make them.

In practice, that means we preserve `allowQuery` and enable background promotion for shells that should remain as partial fallbacks. That broadens the feature beyond the medium-cardinality case it was meant for and makes the build output imply per-param upgradeability when there are no prerenderable params left to fill.

This PR teaches static-path generation to compute `remainingPrerenderableParams` for each fallback shell: the unresolved pathname params that can still be filled by `generateStaticParams` in that branch. We then use that signal to gate partial fallback behavior.

With this change:

- `partialFallback` is only emitted for shells that still have prerenderable params remaining
- `allowQuery` with params is only preserved for those shells

Effectively, this limits partial fallback upgrading to shells that can still be made more specific by prerendering.
parent 68dade46
......@@ -37,6 +37,7 @@ import {
CACHE_ONE_YEAR_SECONDS,
HTML_CONTENT_TYPE_HEADER,
JSON_CONTENT_TYPE_HEADER,
NEXT_QUERY_PARAM_PREFIX,
NEXT_RESUME_HEADER,
} from '../../lib/constants'
......@@ -1591,6 +1592,7 @@ export async function handleBuildComplete({
fallbackStatus,
fallbackSourceRoute,
fallbackRootParams,
remainingPrerenderableParams,
allowHeader,
dataRoute,
renderingMode,
......@@ -1602,19 +1604,32 @@ export async function handleBuildComplete({
const isAppPage = Boolean(appOutputMap[srcRoute])
const meta = await getAppRouteMeta(dynamicRoute, isAppPage)
const allowQuery = Object.values(
const routeKeys =
routesManifest.dynamicRoutes.find(
(item) => item.page === dynamicRoute
)?.routeKeys || {}
)
const allowQuery = Object.values(routeKeys)
const partialFallbacksEnabled =
config.experimental.partialFallbacks === true
const partialFallback =
partialFallbacksEnabled &&
isAppPage &&
remainingPrerenderableParams !== undefined &&
remainingPrerenderableParams.length > 0 &&
renderingMode === RenderingMode.PARTIALLY_STATIC &&
typeof fallback === 'string' &&
Boolean(meta.postponed)
// Today, consumers of this build output can only upgrade a fallback shell
// when all remaining route params become concrete in the upgraded entry.
// They cannot yet represent intermediate shells like `/[foo]/[bar] -> /foo/[bar]`,
// because we do not emit which fallback params should remain deferred after
// the upgrade. Until that contract exists, only emit `partialFallback` for
// the conservative case where the upgraded entry can become fully concrete.
const canEmitPartialFallback =
partialFallback &&
fallbackRootParams?.length === 0 &&
allowQuery.length === remainingPrerenderableParams?.length
let htmlAllowQuery = allowQuery
// We only want to vary on the shell contents if there is a fallback
......@@ -1632,12 +1647,18 @@ export async function handleBuildComplete({
// RSC shell.
else if (meta.postponed) {
// If there's postponed fallback content, we usually collapse to a shared shell (`[]`).
// For opt-in partial fallbacks in cache components, keep route
// allowQuery so fallback shells can be upgraded per-param instead
// of sharing one cache key.
// For opt-in partial fallbacks in cache components, keep only the
// params that can still complete this shell.
const remainingPrerenderableQueryKeys = new Set(
(remainingPrerenderableParams ?? []).map(
(param) => `${NEXT_QUERY_PARAM_PREFIX}${param.paramName}`
)
)
htmlAllowQuery =
partialFallback && routesManifest.rsc.clientParamParsing
? allowQuery
canEmitPartialFallback && routesManifest.rsc.clientParamParsing
? Object.values(routeKeys).filter((routeKey) =>
remainingPrerenderableQueryKeys.has(routeKey)
)
: []
}
}
......@@ -1683,7 +1704,7 @@ export async function handleBuildComplete({
allowQuery: htmlAllowQuery,
allowHeader,
renderingMode,
partialFallback: partialFallback || undefined,
partialFallback: canEmitPartialFallback || undefined,
bypassFor: isAppPage ? experimentalBypassFor : undefined,
bypassToken: prerenderManifest.preview.previewModeId,
},
......
......@@ -294,6 +294,13 @@ export interface DynamicPrerenderManifestRoute {
experimentalBypassFor?: RouteHas[]
fallback: Fallback
/**
* The unresolved fallback route params that can still be specialized into a
* more specific prerendered shell because their segments export
* `generateStaticParams`.
*/
remainingPrerenderableParams?: readonly FallbackRouteParam[]
/**
* When defined, it describes the revalidation configuration for the fallback
* route.
......@@ -2067,6 +2074,8 @@ export default async function build(
defaultLocale: config.i18n?.defaultLocale,
nextConfigOutput: config.output,
pprConfig: config.experimental.ppr,
partialFallbacksEnabled:
config.experimental.partialFallbacks === true,
cacheLifeProfiles: config.cacheLife,
buildId,
clientAssetToken:
......@@ -2294,6 +2303,8 @@ export default async function build(
cacheMaxMemorySize: config.cacheMaxMemorySize,
nextConfigOutput: config.output,
pprConfig: config.experimental.ppr,
partialFallbacksEnabled:
config.experimental.partialFallbacks === true,
cacheLifeProfiles: config.cacheLife,
buildId,
clientAssetToken:
......@@ -3423,6 +3434,8 @@ export default async function build(
prerenderManifest.dynamicRoutes[route.pathname] = {
experimentalPPR: isRoutePPREnabled,
remainingPrerenderableParams:
route.remainingPrerenderableParams,
renderingMode: isAppPPREnabled
? isRoutePPREnabled
? RenderingMode.PARTIALLY_STATIC
......
import { FallbackMode } from '../../lib/fallback'
import type { Params } from '../../server/request/params'
import {
assignErrorIfEmpty,
assignStaticShellMetadata,
generateAllParamCombinations,
calculateFallbackMode,
filterUniqueParams,
......@@ -11,7 +11,26 @@ import type { PrerenderedRoute } from './types'
import type { WorkStore } from '../../server/app-render/work-async-storage.external'
import type { AppSegment } from '../segment-config/app/app-segments'
describe('assignErrorIfEmpty', () => {
function pathnameSegments(
...segments: Array<string | [string, boolean]>
): Array<{
paramName: string
hasGenerateStaticParams: boolean
}> {
return segments.map((segment) =>
Array.isArray(segment)
? {
paramName: segment[0],
hasGenerateStaticParams: segment[1],
}
: {
paramName: segment,
hasGenerateStaticParams: false,
}
)
}
describe('assignStaticShellMetadata', () => {
it('should assign throwOnEmptyStaticShell true for a static route with no children', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
......@@ -25,7 +44,7 @@ describe('assignErrorIfEmpty', () => {
},
]
assignErrorIfEmpty(prerenderedRoutes, [])
assignStaticShellMetadata(prerenderedRoutes, [], true)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(true)
})
......@@ -57,7 +76,7 @@ describe('assignErrorIfEmpty', () => {
},
]
assignErrorIfEmpty(prerenderedRoutes, [{ paramName: 'id' }])
assignStaticShellMetadata(prerenderedRoutes, pathnameSegments('id'), true)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(true)
......@@ -131,10 +150,11 @@ describe('assignErrorIfEmpty', () => {
},
]
assignErrorIfEmpty(prerenderedRoutes, [
{ paramName: 'id' },
{ paramName: 'name' },
])
assignStaticShellMetadata(
prerenderedRoutes,
pathnameSegments('id', 'name'),
true
)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(false)
......@@ -188,23 +208,71 @@ describe('assignErrorIfEmpty', () => {
},
]
assignErrorIfEmpty(prerenderedRoutes, [
{ paramName: 'id' },
{ paramName: 'name' },
{ paramName: 'extra' },
])
assignStaticShellMetadata(
prerenderedRoutes,
pathnameSegments('id', ['name', true], 'extra'),
true
)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[2].throwOnEmptyStaticShell).toBe(true)
expect(prerenderedRoutes[0].remainingPrerenderableParams).toEqual([
{
paramName: 'name',
paramType: 'dynamic',
},
])
expect(prerenderedRoutes[1].remainingPrerenderableParams).toEqual([
{
paramName: 'name',
paramType: 'dynamic',
},
])
expect(prerenderedRoutes[2].remainingPrerenderableParams).toBeUndefined()
})
it('should handle empty input', () => {
const prerenderedRoutes: PrerenderedRoute[] = []
assignErrorIfEmpty(prerenderedRoutes, [])
assignStaticShellMetadata(prerenderedRoutes, [], true)
expect(prerenderedRoutes).toEqual([])
})
it('should skip remaining prerenderable params when partial fallbacks are disabled', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: {},
pathname: '/[id]',
encodedPathname: '/[id]',
fallbackRouteParams: [
{
paramName: 'id',
paramType: 'dynamic',
},
],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { id: '1' },
pathname: '/1',
encodedPathname: '/1',
fallbackRouteParams: [],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
]
assignStaticShellMetadata(prerenderedRoutes, pathnameSegments('id'), false)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(true)
expect(prerenderedRoutes[0].remainingPrerenderableParams).toBeUndefined()
expect(prerenderedRoutes[1].remainingPrerenderableParams).toBeUndefined()
})
it('should handle blog/[slug] not throwing when concrete routes exist (from docs example)', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
......@@ -241,7 +309,7 @@ describe('assignErrorIfEmpty', () => {
},
]
assignErrorIfEmpty(prerenderedRoutes, [{ paramName: 'slug' }])
assignStaticShellMetadata(prerenderedRoutes, pathnameSegments('slug'), true)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false) // Should not throw - has concrete children
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(true) // Should throw - concrete route
......@@ -293,10 +361,11 @@ describe('assignErrorIfEmpty', () => {
},
]
assignErrorIfEmpty(prerenderedRoutes, [
{ paramName: 'id' },
{ paramName: 'slug' },
])
assignStaticShellMetadata(
prerenderedRoutes,
pathnameSegments('id', 'slug'),
true
)
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false) // Should not throw - has children
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(false) // Should not throw - has children
......@@ -374,11 +443,11 @@ describe('assignErrorIfEmpty', () => {
},
]
assignErrorIfEmpty(prerenderedRoutes, [
{ paramName: 'category' },
{ paramName: 'subcategory' },
{ paramName: 'item' },
])
assignStaticShellMetadata(
prerenderedRoutes,
pathnameSegments('category', 'subcategory', 'item'),
true
)
// All except the last one should not throw on empty static shell
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
......@@ -414,15 +483,126 @@ describe('assignErrorIfEmpty', () => {
},
]
assignErrorIfEmpty(prerenderedRoutes, [
{ paramName: 'locale' },
{ paramName: 'segments' },
])
assignStaticShellMetadata(
prerenderedRoutes,
pathnameSegments('locale', 'segments'),
true
)
// The route with more fallback params should not throw on empty static shell
expect(prerenderedRoutes[0].throwOnEmptyStaticShell).toBe(false)
expect(prerenderedRoutes[1].throwOnEmptyStaticShell).toBe(true)
})
it('should specialize only unresolved params backed by generateStaticParams', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: {},
pathname: '/[one]/[two]',
encodedPathname: '/[one]/[two]',
fallbackRouteParams: [
{
paramName: 'one',
paramType: 'dynamic',
},
{
paramName: 'two',
paramType: 'dynamic',
},
],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { one: 'b' },
pathname: '/b/[two]',
encodedPathname: '/b/[two]',
fallbackRouteParams: [
{
paramName: 'two',
paramType: 'dynamic',
},
],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
]
assignStaticShellMetadata(
prerenderedRoutes,
pathnameSegments(['one', true], 'two'),
true
)
expect(prerenderedRoutes[0].remainingPrerenderableParams).toEqual([
{
paramName: 'one',
paramType: 'dynamic',
},
])
expect(prerenderedRoutes[1].remainingPrerenderableParams).toBeUndefined()
})
it('should stop specializing once it reaches a purely dynamic param', () => {
const prerenderedRoutes: PrerenderedRoute[] = [
{
params: {},
pathname: '/[one]/[two]/[three]',
encodedPathname: '/[one]/[two]/[three]',
fallbackRouteParams: [
{
paramName: 'one',
paramType: 'dynamic',
},
{
paramName: 'two',
paramType: 'dynamic',
},
{
paramName: 'three',
paramType: 'dynamic',
},
],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
{
params: { one: 'a' },
pathname: '/a/[two]/[three]',
encodedPathname: '/a/[two]/[three]',
fallbackRouteParams: [
{
paramName: 'two',
paramType: 'dynamic',
},
{
paramName: 'three',
paramType: 'dynamic',
},
],
fallbackMode: FallbackMode.NOT_FOUND,
fallbackRootParams: [],
throwOnEmptyStaticShell: true,
},
]
assignStaticShellMetadata(
prerenderedRoutes,
pathnameSegments(['one', true], 'two', ['three', true]),
true
)
expect(prerenderedRoutes[0].remainingPrerenderableParams).toEqual([
{
paramName: 'one',
paramType: 'dynamic',
},
])
expect(prerenderedRoutes[1].remainingPrerenderableParams).toBeUndefined()
})
})
describe('filterUniqueParams', () => {
......
......@@ -406,22 +406,26 @@ interface TrieNode {
}
/**
* Assigns the throwOnEmptyStaticShell property to each of the prerendered routes.
* Assigns static shell metadata to each prerendered route.
* This function uses a Trie data structure to efficiently determine whether each route
* should throw an error when its static shell is empty.
* should throw an error when its static shell is empty and whether a fallback shell
* can still be completed into a more specific prerendered shell.
*
* A route should not throw on empty static shell if it has child routes in the Trie. For example,
* if we have two routes, `/blog/first-post` and `/blog/[slug]`, the route for
* `/blog/[slug]` should not throw because `/blog/first-post` is a more specific concrete route.
*
* @param prerenderedRoutes - The prerendered routes.
* @param pathnameSegments - The keys of the route parameters.
* @param pathnameSegments - The pathname params and whether each one is still
* prerenderable via generateStaticParams.
*/
export function assignErrorIfEmpty(
export function assignStaticShellMetadata(
prerenderedRoutes: readonly PrerenderedRoute[],
pathnameSegments: ReadonlyArray<{
readonly paramName: string
}>
readonly hasGenerateStaticParams: boolean
}>,
computeRemainingPrerenderableParams: boolean
): void {
// If there are no routes to process, exit early.
if (prerenderedRoutes.length === 0) {
......@@ -470,7 +474,10 @@ export function assignErrorIfEmpty(
if (!childNode) {
// If the child node doesn't exist, create a new one and add it to
// the current node's children.
childNode = { children: new Map(), routes: [] }
childNode = {
children: new Map(),
routes: [],
}
currentNode.children.set(valueKey, childNode)
}
// Move deeper into the Trie to the `childNode` for the next parameter.
......@@ -537,6 +544,45 @@ export function assignErrorIfEmpty(
} else {
route.throwOnEmptyStaticShell = true // Should throw on empty static shell.
}
if (
computeRemainingPrerenderableParams &&
route.fallbackRouteParams &&
route.fallbackRouteParams.length > 0
) {
const fallbackRouteParamsByName = new Map(
route.fallbackRouteParams.map((param) => [param.paramName, param])
)
const remainingPrerenderableParams: FallbackRouteParam[] = []
// Only unresolved pathname params that can still be filled by
// generateStaticParams belong here. Once we hit an unresolved param
// that is purely dynamic, the rest of the shell also stays dynamic
// and cannot be completed into a more specific prerendered shell.
for (const segment of pathnameSegments) {
if (route.params.hasOwnProperty(segment.paramName)) {
continue
}
if (!segment.hasGenerateStaticParams) {
break
}
const fallbackRouteParam = fallbackRouteParamsByName.get(
segment.paramName
)
if (!fallbackRouteParam) {
break
}
remainingPrerenderableParams.push(fallbackRouteParam)
}
route.remainingPrerenderableParams =
remainingPrerenderableParams.length > 0
? remainingPrerenderableParams
: undefined
}
}
}
......@@ -696,6 +742,7 @@ export async function buildAppStaticPaths({
nextConfigOutput,
ComponentMod,
isRoutePPREnabled = false,
partialFallbacksEnabled = false,
buildId,
rootParamKeys,
}: {
......@@ -718,6 +765,7 @@ export async function buildAppStaticPaths({
nextConfigOutput: 'standalone' | 'export' | undefined
ComponentMod: AppPageModule | AppRouteModule
isRoutePPREnabled: boolean
partialFallbacksEnabled?: boolean
buildId: string
rootParamKeys: readonly string[]
}): Promise<StaticPathsResult> {
......@@ -780,6 +828,18 @@ export async function buildAppStaticPaths({
store,
isRoutePPREnabled
)
const generatedParamNames = new Set<string>()
for (const params of routeParams) {
for (const paramName of Object.keys(params)) {
generatedParamNames.add(paramName)
}
}
const prerenderablePathSegments = pathnameRouteParamSegments.map(
(segment) => ({
paramName: segment.paramName,
hasGenerateStaticParams: generatedParamNames.has(segment.paramName),
})
)
await afterRunner.executeAfter()
......@@ -1000,7 +1060,11 @@ export async function buildAppStaticPaths({
// Now we have to set the throwOnEmptyStaticShell for each of the routes.
if (prerenderedRoutes && cacheComponents) {
assignErrorIfEmpty(prerenderedRoutes, pathnameRouteParamSegments)
assignStaticShellMetadata(
prerenderedRoutes,
prerenderablePathSegments,
partialFallbacksEnabled
)
}
return { fallbackMode, prerenderedRoutes }
......
......@@ -9,6 +9,7 @@ type StaticPrerenderedRoute = {
readonly fallbackRouteParams: undefined
readonly fallbackMode: FallbackMode | undefined
readonly fallbackRootParams: undefined
remainingPrerenderableParams?: undefined
/**
* When enabled, the route will be rendered with diagnostics enabled which
......@@ -42,6 +43,7 @@ type FallbackPrerenderedRoute = {
readonly fallbackRouteParams: readonly FallbackRouteParam[]
readonly fallbackMode: FallbackMode | undefined
readonly fallbackRootParams: readonly string[]
remainingPrerenderableParams?: readonly FallbackRouteParam[]
/**
* When enabled, the route will be rendered with diagnostics enabled which
......
......@@ -992,6 +992,10 @@ export async function handler(
if (
!isMinimalMode &&
isRoutePPREnabled &&
// Match the build-time contract: only fallback shells that can
// still be completed with prerenderable params should upgrade.
prerenderInfo?.remainingPrerenderableParams !== undefined &&
prerenderInfo.remainingPrerenderableParams.length > 0 &&
nextConfig.experimental.partialFallbacks === true &&
ssgCacheKey &&
incrementalCache &&
......
......@@ -667,6 +667,7 @@ export async function isPageStatic({
cacheHandlers,
cacheLifeProfiles,
pprConfig,
partialFallbacksEnabled,
buildId,
clientAssetToken,
sriEnabled,
......@@ -694,6 +695,7 @@ export async function isPageStatic({
}
nextConfigOutput: 'standalone' | 'export' | undefined
pprConfig: ExperimentalPPRConfig | undefined
partialFallbacksEnabled: boolean
buildId: string
clientAssetToken: string
sriEnabled: boolean
......@@ -857,6 +859,7 @@ export async function isPageStatic({
ComponentMod,
nextConfigOutput,
isRoutePPREnabled,
partialFallbacksEnabled,
buildId,
rootParamKeys,
}))
......
......@@ -799,6 +799,8 @@ export default class DevServer extends Server {
pathname,
config: {
pprConfig: this.nextConfig.experimental.ppr,
partialFallbacks:
this.nextConfig.experimental.partialFallbacks === true,
configFileName,
cacheComponents: Boolean(this.nextConfig.cacheComponents),
},
......
......@@ -30,6 +30,7 @@ import { parseAppRoute } from '../../shared/lib/router/routes/app'
type RuntimeConfig = {
pprConfig: ExperimentalPPRConfig | undefined
partialFallbacks: boolean
configFileName: string
cacheComponents: boolean
}
......@@ -147,6 +148,7 @@ export async function loadStaticPaths({
ComponentMod: components.ComponentMod,
nextConfigOutput,
isRoutePPREnabled,
partialFallbacksEnabled: config.partialFallbacks,
buildId,
authInterrupts,
rootParamKeys,
......
......@@ -90,6 +90,49 @@ describe('PrerenderManifestMatcher', () => {
expect(result).toBe(route)
})
it('should match unknown root branches against the generic source shell', () => {
const generatedRootRoute = createMockDynamicRoute({
fallbackSourceRoute: '/root-gsp/[lang]/[slug]',
routeRegex: '^/root-gsp/en/([^/]+?)(?:/)?$',
fallbackRootParams: [],
fallbackRouteParams: [
{
paramName: 'slug',
paramType: 'dynamic',
},
],
})
const genericRootRoute = createMockDynamicRoute({
fallbackSourceRoute: '/root-gsp/[lang]/[slug]',
routeRegex: '^/root-gsp/([^/]+?)/([^/]+?)(?:/)?$',
fallbackRootParams: ['lang'],
fallbackRouteParams: [
{
paramName: 'lang',
paramType: 'dynamic',
},
{
paramName: 'slug',
paramType: 'dynamic',
},
],
})
const manifest = createMockPrerenderManifest({
'/root-gsp/en/[slug]': generatedRootRoute,
'/root-gsp/[lang]/[slug]': genericRootRoute,
})
const matcher = new PrerenderManifestMatcher(
'/root-gsp/[lang]/[slug]',
manifest
)
expect(matcher.match('/root-gsp/en/two')).toBe(generatedRootRoute)
expect(matcher.match('/root-gsp/fr/two')).toBe(genericRootRoute)
})
})
describe('no match scenarios', () => {
......
export default function Loading() {
return (
<div id="fallback" data-fallback>
loading...
</div>
)
}
import { Suspense } from 'react'
async function Dynamic() {
await new Promise((resolve) => setTimeout(resolve, 1000))
return <div id="agent">Custom Data</div>
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return (
<div>
<div id="slug" data-slug={slug}>
{slug}
</div>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
......@@ -28,4 +28,24 @@ describe('partial-fallback-shell-upgrade', () => {
expect($('#fallback').length).toBe(0)
})
})
it('should not upgrade a route shell when no params were prerendered', async () => {
const pathname = '/no-gsp/two'
const start = Date.now()
await retry(
async () => {
const $ = await next.render$(pathname)
expect($('#fallback').text()).toBe('loading...')
expect($('#slug').closest('[hidden]').length).toBe(1)
if (Date.now() - start < 5000) {
throw new Error('continue polling fallback shell')
}
},
6000,
500,
'no-gsp fallback shell should remain unupgraded'
)
})
})
import { nextTestSetup } from 'e2e-utils'
import type { NextAdapter } from 'next'
describe('adapter-partial-fallback', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('should emit partial fallback metadata when infra can upgrade the shell', async () => {
const { outputs }: Parameters<NextAdapter['onBuildComplete']>[0] =
await next.readJSON('build-complete.json')
const withGspPrerender = outputs.prerenders.find(
(output) => output.pathname === '/with-gsp/[slug]'
)
const withoutGspPrerender = outputs.prerenders.find(
(output) => output.pathname === '/without-gsp/[slug]'
)
const genericPrefixPrerender = outputs.prerenders.find(
(output) => output.pathname === '/prefix/[one]/[two]'
)
const generatedPrefixPrerender = outputs.prerenders.find(
(output) => output.pathname === '/prefix/b/[two]'
)
const genericDashedPrerender = outputs.prerenders.find(
(output) => output.pathname === '/dashed/[my-slug]/[two]'
)
const generatedDashedPrerender = outputs.prerenders.find(
(output) => output.pathname === '/dashed/b/[two]'
)
expect(withGspPrerender).toBeDefined()
expect(withoutGspPrerender).toBeDefined()
expect(genericPrefixPrerender).toBeDefined()
expect(generatedPrefixPrerender).toBeDefined()
expect(genericDashedPrerender).toBeDefined()
expect(generatedDashedPrerender).toBeDefined()
expect(withGspPrerender.config.partialFallback).toBe(true)
expect(withGspPrerender.config.allowQuery).toEqual(['nxtPslug'])
expect(withoutGspPrerender.config.partialFallback).toBeUndefined()
expect(withoutGspPrerender.config.allowQuery).toEqual([])
expect(genericPrefixPrerender.config.partialFallback).toBeUndefined()
expect(genericPrefixPrerender.config.allowQuery).toEqual([])
expect(generatedPrefixPrerender.config.partialFallback).toBeUndefined()
expect(generatedPrefixPrerender.config.allowQuery).toEqual([])
expect(genericDashedPrerender.config.partialFallback).toBeUndefined()
expect(genericDashedPrerender.config.allowQuery).toEqual([])
expect(generatedDashedPrerender.config.partialFallback).toBeUndefined()
expect(generatedDashedPrerender.config.allowQuery).toEqual([])
})
})
export default function Loading() {
return <div>loading...</div>
}
import { Suspense } from 'react'
async function Dynamic() {
await new Promise((resolve) => setTimeout(resolve, 1000))
return <div>Custom Data</div>
}
export default async function Page({
params,
}: {
params: Promise<{ 'my-slug': string; two: string }>
}) {
const { 'my-slug': mySlug, two } = await params
return (
<div>
<div>
{mySlug}:{two}
</div>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
import type { ReactNode } from 'react'
export function generateStaticParams() {
return [{ 'my-slug': 'b' }]
}
export default function Layout({ children }: { children: ReactNode }) {
return <>{children}</>
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function Page() {
return <p>adapter partial fallback fixture</p>
}
export default function Loading() {
return <div>loading...</div>
}
import { Suspense } from 'react'
async function Dynamic() {
await new Promise((resolve) => setTimeout(resolve, 1000))
return <div>Custom Data</div>
}
export default async function Page({
params,
}: {
params: Promise<{ one: string; two: string }>
}) {
const { one, two } = await params
return (
<div>
<div>
{one}:{two}
</div>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
import type { ReactNode } from 'react'
export function generateStaticParams() {
return [{ one: 'b' }]
}
export default function Layout({ children }: { children: ReactNode }) {
return <>{children}</>
}
export default function Loading() {
return <div>loading...</div>
}
import { Suspense } from 'react'
async function Dynamic() {
await new Promise((resolve) => setTimeout(resolve, 1000))
return <div>Custom Data</div>
}
export function generateStaticParams() {
return [{ slug: 'one' }]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return (
<div>
<div>{slug}</div>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
export default function Loading() {
return <div>loading...</div>
}
import { Suspense } from 'react'
async function Dynamic() {
await new Promise((resolve) => setTimeout(resolve, 1000))
return <div>Custom Data</div>
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
return (
<div>
<div>{slug}</div>
<Suspense fallback={<div>Loading...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
import fs from 'fs/promises'
/** @type {import('next').NextAdapter } */
export default {
name: 'adapter-partial-fallback',
async onBuildComplete(ctx) {
await fs.writeFile('build-complete.json', JSON.stringify(ctx, null, 2))
},
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
experimental: {
adapterPath: require.resolve('./my-adapter.mjs'),
partialFallbacks: 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