Unverified Commit 6866b944 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Keep never-prerenderable params out of self-hosted shells (#98612)

With Cache Components enabled and Partial Prefetching disabled, blocking
prerenders in `next start` could cache params that no
`generateStaticParams` result supplies. For `/[top]/[bottom]`, where
only `top` is supplied, this included `bottom` in the static HTML and
created a separate cache entry for each bottom value.

Adapter deployments already enforce this rule. The legacy Vercel builder
has a known limitation that the existing prerender tests explicitly
exclude.

#95872 established that these params must remain dynamic. #96297 later
put self-hosted eligibility-based shell keys and fallback-param
selection behind the `partialPrefetching` flag, alongside automatic
fallback upgrades. #98512 then made resumes honor the parameter set
recorded by the selected prerender. That did not create the invalid
prerenders, but allowed their over-resolved params to enter Cached
Navigations.

The RSC test added in #98512 did not account for that known
legacy-builder limitation and consequently failed in this [canary deploy
run](https://github.com/vercel/next.js/actions/runs/34659100427/job/103469344769).

For `next start`, shell keys and unresolved params now follow GSP
eligibility even when upgrades are disabled. Cache writes, revalidation,
and navigation RDC reads use the same key, including shared shells that
cannot be completed further. Routes whose params are all prerenderable
retain their existing keys when Partial Prefetching is disabled.
Automatic upgrade triggers remain gated.

The aforementioned `cached-navigations` tests now separate cold RSC
navigation from initial HTML and assert eligibility independently of the
observed response. Added coverage checks shell sharing, explicit
revalidation, and generated optional paths. Legacy-builder failures are
documented with expected-failure gates; its implementation remains
unchanged.

Verified by running the [full deploy test
matrix](https://github.com/vercel/next.js/actions/runs/34771777150)
against this PR.
parent c70b96b3
......@@ -573,6 +573,15 @@ export function createAppPageEntrypoint({
const remainingPrerenderableParams =
prerenderInfo?.remainingPrerenderableParams ?? []
const remainingFallbackRouteParams = nextConfig.cacheComponents
? (prerenderInfo?.fallbackRouteParams?.filter(
(param) =>
!remainingPrerenderableParams.some(
(prerenderableParam) =>
prerenderableParam.paramName === param.paramName
)
) ?? [])
: []
// Concrete optional routes like `/optional-catchall` can still match their
// generic shell entry (eg /optional-catchall/[[...slug]]) in the prerender manifest.
// If the omitted param already resolved to a real prerendered path, keep serving that concrete result.
......@@ -586,11 +595,11 @@ export function createAppPageEntrypoint({
prerenderInfo?.fallback === null &&
(prerenderInfo.fallbackRootParams?.length ?? 0) > 0
// SSG writes and navigation RDC reads use the same completed-shell key.
// Completion uses the matched shell rather than the fully resolved
// pathname. A request for `/prefix/c/foo` can complete
// `/prefix/[one]/[two]` to `/prefix/c/[two]`. This avoids creating an entry
// for every value of `two`.
// SSG writes and navigation RDC reads use the same shell key. Completion
// uses the matched shell rather than the fully resolved pathname. A request
// for `/prefix/c/foo` can complete `/prefix/[one]/[two]` to
// `/prefix/c/[two]`. This avoids creating an entry for every value of
// `two`.
//
// The completed-shell key also applies when unresolved root params require
// a blocking render. A source shell cannot be shared across root branches.
......@@ -603,12 +612,16 @@ export function createAppPageEntrypoint({
? prerenderInfo.fallback
: prerenderMatch.source
: null
let completedShellCacheKey: string | null = null
let shellCacheKey: string | null = null
if (
nextConfig.partialPrefetching &&
nextConfig.cacheComponents &&
// Never-prerenderable params must stay out of the key even when Partial
// Prefetching is disabled.
(nextConfig.partialPrefetching ||
remainingFallbackRouteParams.length > 0) &&
fallbackPathname &&
prerenderInfo?.fallbackRouteParams?.length &&
remainingPrerenderableParams.length > 0
!hasOmittedConcreteFallbackParam
) {
const cacheKey = buildCompletedShellCacheKey(
fallbackPathname,
......@@ -616,14 +629,16 @@ export function createAppPageEntrypoint({
params
)
// Only a more complete shell gets a separate cache entry.
if (cacheKey !== fallbackPathname) {
completedShellCacheKey = cacheKey
if (
cacheKey !== fallbackPathname ||
remainingFallbackRouteParams.length > 0
) {
shellCacheKey = cacheKey
}
}
let ssgCacheKey: string | null = null
let usesCompletedShellCacheKey = false
let usesShellCacheKey = false
if (
!isDraftMode &&
isSSG &&
......@@ -632,19 +647,14 @@ export function createAppPageEntrypoint({
!hasPostponedState &&
!isDynamicRSCRequest
) {
if (
// Partial fallback shells are only specialized per request when Partial
// Prefetching is enabled, mirroring the `partialFallback` flag the
// adapter emits for deployments. When it's disabled we fall through to
// the normal ISR cache key (`resolvedPathname`) so the shell stays
// shared, matching the behavior before the `partialFallbacks` config
// flag was removed.
nextConfig.partialPrefetching &&
fallbackPathname &&
prerenderInfo?.fallbackRouteParams?.length
) {
ssgCacheKey = completedShellCacheKey
usesCompletedShellCacheKey = completedShellCacheKey !== null
if (shellCacheKey !== null) {
// Normal fallback serving uses the source shell's separate cache
// lookup. Explicit revalidation skips that path, so it must write the
// source key here even when no params can be completed.
if (shellCacheKey !== fallbackPathname || isOnDemandRevalidate) {
ssgCacheKey = shellCacheKey
usesShellCacheKey = true
}
} else {
ssgCacheKey = resolvedPathname
}
......@@ -709,17 +719,6 @@ export function createAppPageEntrypoint({
const isWrappedByNextServer = Boolean(
routerServerContext?.isWrappedByNextServer
)
const remainingFallbackRouteParams =
nextConfig.partialPrefetching && remainingPrerenderableParams.length > 0
? (prerenderInfo?.fallbackRouteParams?.filter(
(param) =>
!remainingPrerenderableParams.some(
(prerenderableParam) =>
prerenderableParam.paramName === param.paramName
)
) ?? [])
: []
const render404 = async () => {
// TODO: should route-module itself handle rendering the 404
if (routerServerContext?.render404) {
......@@ -1371,8 +1370,7 @@ export function createAppPageEntrypoint({
// from entering an infinite loop of revalidations.
!forceStaticRender
) {
const incrementalCacheKey =
completedShellCacheKey ?? resolvedPathname
const incrementalCacheKey = shellCacheKey ?? resolvedPathname
const incrementalCacheEntry = await incrementalCache.get(
incrementalCacheKey,
{
......@@ -1539,8 +1537,8 @@ export function createAppPageEntrypoint({
// The platform strips never-prerenderable param values before
// calling the origin.
!isMinimalMode &&
(usesCompletedShellCacheKey ||
(forceStaticRender && completedShellCacheKey !== null)) &&
(usesShellCacheKey ||
(forceStaticRender && shellCacheKey !== null)) &&
remainingFallbackRouteParams.length > 0
? createOpaqueFallbackRouteParams(
remainingFallbackRouteParams
......
......@@ -88,11 +88,6 @@ export function createOpaqueFallbackRouteParams(
* exactly that shape. Any other shell may be empty, and a request completes it
* with the params that `generateStaticParams` can still supply. Only the params
* that completion never resolves stay deferred.
*
* `next start` without `partialPrefetching` keys ISR entries by the full
* pathname, so such an entry resolves every param. A cold staged render then
* defers params that the entry resolves, so its static stage contains less
* content. A resume reads the recorded set from the entry's postponed state.
*/
export function getStagedFallbackParams(route: {
fallbackRouteParams: readonly FallbackRouteParam[] | undefined
......
export default function Loading() {
return (
<div id="two-fallback" data-fallback>
loading two...
</div>
)
}
export default async function Page({
params,
}: {
params: Promise<{ one: string; two: string }>
}) {
const { two } = await params
return <div id="two">{two}</div>
}
import type { ReactNode } from 'react'
export function generateStaticParams() {
return [{ one: 'b' }]
}
export default async function Layout({
children,
params,
}: {
children: ReactNode
params: Promise<{ one: string }>
}) {
const { one } = await params
return (
<div>
<div id="one" data-rendered-at={performance.now()}>
{one}
</div>
{children}
</div>
)
}
export function generateStaticParams() {
return [{ parts: [] }, { parts: ['named'] }]
}
export default async function Page({
params,
}: {
params: Promise<{ parts?: string[] }>
}) {
const { parts } = await params
return (
<div id="optional" data-rendered-at={performance.now()}>
{parts?.join('/')}
</div>
)
}
export default function Loading() {
return (
<div id="two-fallback" data-fallback>
<div id="two-fallback" data-fallback data-rendered-at={performance.now()}>
loading two...
</div>
)
......
......@@ -25,7 +25,11 @@ export default async function LayoutWrapper(props) {
return (
<Suspense
fallback={
<div id="one-fallback" data-fallback>
<div
id="one-fallback"
data-fallback
data-rendered-at={performance.now()}
>
loading one...
</div>
}
......
import type { NextApiRequest, NextApiResponse } from 'next'
export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const pathParam = req.query['path']
if (!pathParam) {
return res.status(400).send(`Missing required query param "path"`)
}
const paths = Array.isArray(pathParam) ? pathParam : [pathParam]
try {
await Promise.all(paths.map((path) => res.revalidate(path)))
return res.json({ revalidated: true })
} catch (err) {
console.error(err)
return res.status(500).send(`Error revalidating ${paths}`)
}
}
......@@ -405,33 +405,56 @@ describe('cached navigations', () => {
)
})
it.each([
{ source: 'dynamic RSC', top: 't2' },
{ source: 'initial HTML with partial resume', top: 't3' },
])(
'caches a required fallback shell from $source for repeated navigations',
async ({ source, top }) => {
const route = `/required-fallback-params/${top}/b1`
const startDate = Date.now()
let bottomIsStatic = false
let page: Playwright.Page
let initialDocument: Promise<Playwright.Response>
const browser = await next.browser(
source === 'dynamic RSC' ? `/fallback-params-hub/${top}/start` : route,
{
async beforePageLoad(p: Playwright.Page) {
page = p
await page.clock.install()
await page.clock.setFixedTime(startDate)
initialDocument = page.waitForResponse((response) =>
response.request().isNavigationRequest()
)
},
}
// The legacy Vercel builder incorrectly prerenders params omitted from
// generateStaticParams.
// @gate !deploy || adapter
it('caches only eligible params from a cold RSC navigation for repeated navigations', async () => {
const top = 't2'
const route = `/required-fallback-params/${top}/b1`
const startDate = Date.now()
let page: Playwright.Page
const browser = await next.browser(`/fallback-params-hub/${top}/start`, {
async beforePageLoad(p: Playwright.Page) {
page = p
await page.clock.install()
await page.clock.setFixedTime(startDate)
},
})
const act = createRouterAct(page)
await act(
async () => {
await browser
.elementByCss(`input[data-link-accordion="${route}"]`)
.click()
await browser.elementByCss(`a[href="${route}"]`).click()
},
{ includes: 'Dynamic content' }
)
expect(await browser.elementById('top').text()).toBe(`Top: ${top}`)
expect(await browser.elementById('bottom').text()).toBe('Bottom: b1')
expect(await browser.elementById('dynamic-content').text()).toBe(
'Dynamic content'
)
for (const [index, step] of ['a', 'b'].entries()) {
const hub = `/fallback-params-hub/${top}/${step}`
await act(
async () => {
await browser
.elementByCss(`input[data-link-accordion="${hub}"]`)
.click()
await browser.elementByCss(`a[href="${hub}"]`).click()
},
{ includes: `Fallback params hub ${step}` }
)
expect(await browser.elementByCss('h1').text()).toBe(
`Fallback params hub ${step}`
)
const act = createRouterAct(page)
await page.clock.setFixedTime(startDate + (index + 1) * 60_000)
if (source === 'dynamic RSC') {
await act(async () => {
await act(
async () => {
await browser
......@@ -439,79 +462,112 @@ describe('cached navigations', () => {
.click()
await browser.elementByCss(`a[href="${route}"]`).click()
},
{ includes: 'Dynamic content' }
{ includes: 'Dynamic content', block: true }
)
} else {
// Inspect the document that populated this browser's cache, not a
// separate prefetch or a later request after the shell was cached.
const html = await (await initialDocument).text()
const [shell, resume] = html.split('<!-- PPR_BOUNDARY_SENTINEL -->')
expect(resume).toBeDefined()
const $ = cheerio.load(shell)
expect($('#top').text()).toBe(`Top: ${top}`)
bottomIsStatic = $('#bottom').length > 0
expect($('#bottom-boundary').text()).toBe(
bottomIsStatic ? 'Bottom: b1' : 'Loading bottom...'
expect(await browser.elementById('top').text()).toBe(`Top: ${top}`)
expect(await browser.elementById('bottom-boundary').text()).toBe(
'Loading bottom...'
)
expect($('#connection-boundary').text()).toBe('Loading connection...')
expect(resume).toContain('id="dynamic-content"')
}
expect(await browser.elementById('connection-boundary').text()).toBe(
'Loading connection...'
)
})
expect(await browser.elementById('top').text()).toBe(`Top: ${top}`)
expect(await browser.elementById('bottom').text()).toBe('Bottom: b1')
expect(await browser.elementById('dynamic-content').text()).toBe(
'Dynamic content'
)
}
})
for (const [index, step] of ['a', 'b'].entries()) {
const hub = `/fallback-params-hub/${top}/${step}`
// The legacy Vercel builder incorrectly prerenders params omitted from
// generateStaticParams.
// @gate !deploy || adapter
it('caches only eligible params from an initial HTML on-demand prerender for repeated navigations', async () => {
const top = 't3'
const route = `/required-fallback-params/${top}/b1`
const startDate = Date.now()
let page: Playwright.Page
let initialDocument: Promise<Playwright.Response>
const browser = await next.browser(route, {
async beforePageLoad(p: Playwright.Page) {
page = p
await page.clock.install()
await page.clock.setFixedTime(startDate)
initialDocument = page.waitForResponse((response) =>
response.request().isNavigationRequest()
)
},
})
const act = createRouterAct(page)
// Inspect the document that populated this browser's cache, not a separate
// prefetch or a later request after the shell was cached.
const response = await initialDocument
expect(response.status()).toBe(200)
const html = await response.text()
const [shell, resume] = html.split('<!-- PPR_BOUNDARY_SENTINEL -->')
expect(resume).toBeDefined()
const $ = cheerio.load(shell)
expect($('#top').text()).toBe(`Top: ${top}`)
expect($('#bottom').length).toBe(0)
expect($('#bottom-boundary').text()).toBe('Loading bottom...')
expect($('#dynamic-content').length).toBe(0)
expect($('#connection-boundary').text()).toBe('Loading connection...')
expect(resume).toContain('id="bottom"')
expect(resume).toContain('id="dynamic-content"')
expect(await browser.elementById('top').text()).toBe(`Top: ${top}`)
expect(await browser.elementById('bottom').text()).toBe('Bottom: b1')
expect(await browser.elementById('dynamic-content').text()).toBe(
'Dynamic content'
)
for (const [index, step] of ['a', 'b'].entries()) {
const hub = `/fallback-params-hub/${top}/${step}`
await act(
async () => {
await browser
.elementByCss(`input[data-link-accordion="${hub}"]`)
.click()
await browser.elementByCss(`a[href="${hub}"]`).click()
},
{ includes: `Fallback params hub ${step}` }
)
expect(await browser.elementByCss('h1').text()).toBe(
`Fallback params hub ${step}`
)
await page.clock.setFixedTime(startDate + (index + 1) * 60_000)
await act(async () => {
await act(
async () => {
await browser
.elementByCss(`input[data-link-accordion="${hub}"]`)
.elementByCss(`input[data-link-accordion="${route}"]`)
.click()
await browser.elementByCss(`a[href="${hub}"]`).click()
await browser.elementByCss(`a[href="${route}"]`).click()
},
{ includes: `Fallback params hub ${step}` }
{ includes: 'Dynamic content', block: true }
)
expect(await browser.elementByCss('h1').text()).toBe(
`Fallback params hub ${step}`
)
await page.clock.setFixedTime(startDate + (index + 1) * 60_000)
await act(async () => {
await act(
async () => {
await browser
.elementByCss(`input[data-link-accordion="${route}"]`)
.click()
await browser.elementByCss(`a[href="${route}"]`).click()
},
{ includes: 'Dynamic content', block: true }
)
// Hydration retains the static content of its actual prerender. A
// cold dynamic RSC render retains the required shell's unresolved
// bottom param.
expect(await browser.elementByCss('main').text()).toContain(
`Top: ${top}`
)
expect(await browser.elementById('bottom-boundary').text()).toBe(
bottomIsStatic ? 'Bottom: b1' : 'Loading bottom...'
)
expect(await browser.elementById('connection-boundary').text()).toBe(
'Loading connection...'
)
})
expect(await browser.elementById('top').text()).toBe(`Top: ${top}`)
expect(await browser.elementById('bottom').text()).toBe('Bottom: b1')
expect(await browser.elementById('dynamic-content').text()).toBe(
'Dynamic content'
expect(await browser.elementById('bottom-boundary').text()).toBe(
'Loading bottom...'
)
}
expect(await browser.elementById('connection-boundary').text()).toBe(
'Loading connection...'
)
})
expect(await browser.elementById('top').text()).toBe(`Top: ${top}`)
expect(await browser.elementById('bottom').text()).toBe('Bottom: b1')
expect(await browser.elementById('dynamic-content').text()).toBe(
'Dynamic content'
)
}
)
})
it('caches a fully static on-demand param for repeated navigations', async () => {
const route = '/fully-static-params/t4'
......
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