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

fix: fully static pages should emit & serve static rsc payloads (#89202)

This restores fast navigations to fully static PPR routes in Cache
Components, even when prefetch hasn’t completed or `prefetch={false}` is
used. In legacy versions of PPR, the `prefetchDataRoute` entries would
be populated with `.prefetch.rsc` values containing static RSC payloads.
This regressed in cache components, and the only static RSC payloads
were in the `.segments` directory. However, when Next.js triggers a
regular RSC request (non-prefetch), either because the prefetch hadn't
completed yet or `prefetch={false}` was configured, we'd route to the
empty fallback and trigger a function invocation.

This restores old behavior of emitting a `.rsc` file for a fully static
route. This information technically also exists in the `.segments`
directory, but it's split into parts, and it's now routed to unless
explicitly done so via the `next-router-segment-prefetch` header. In
addition to emitting the route, this also ensures we set
`prefetchDataRoute` to point to this. This is how the Vercel adapter
knows the file to serve.

An e2e regression test now asserts that `prefetch={false}` navigation
does not wait for a dynamic render. The deploy test will be unblocked
once https://github.com/vercel/vercel/pull/14770 lands.
parent 0e457e95
......@@ -1233,6 +1233,7 @@ export async function handleBuildComplete({
initialHeaders,
initialStatus,
dataRoute,
prefetchDataRoute,
renderingMode,
allowHeader,
experimentalBypassFor,
......@@ -1404,13 +1405,22 @@ export async function handleBuildComplete({
)
let postponed = meta.postponed
const dataRouteToUse =
renderingMode === RenderingMode.PARTIALLY_STATIC &&
prefetchDataRoute
? prefetchDataRoute
: dataRoute
if (isAppPage) {
// When experimental PPR is enabled, we expect that the data
// that should be served as a part of the prerender should
// be from the prefetch data route. If this isn't enabled
// for ppr, the only way to get the data is from the data
// route.
dataFilePath = path.join(appDistDir, dataRoute)
dataFilePath = path.join(
appDistDir,
(dataRouteToUse ?? dataRoute)?.replace(/^\//, '')
)
}
if (
......
......@@ -3311,6 +3311,7 @@ export default async function build(
metadata = {},
hasEmptyStaticShell,
hasPostponed,
hasStaticRsc,
} = exportResult.byPath.get(route.pathname) ?? {}
const cacheControl = getCacheControl(
......@@ -3342,6 +3343,10 @@ export default async function build(
} else {
dataRoute = path.posix.join(`${normalizedRoute}${RSC_SUFFIX}`)
}
const prefetchDataRoute =
isRoutePPREnabled && dataRoute && hasStaticRsc
? dataRoute
: undefined
const meta = collectMeta(metadata)
const status =
......@@ -3363,7 +3368,7 @@ export default async function build(
initialExpireSeconds: cacheControl.expire,
srcRoute: page,
dataRoute,
prefetchDataRoute: undefined,
prefetchDataRoute,
allowHeader: ALLOWED_HEADERS,
}
} else {
......
......@@ -381,8 +381,17 @@ export async function handler(
// If PPR is enabled, and this is a RSC request (but not a prefetch), then
// we can use this fact to only generate the flight data for the request
// because we can't cache the HTML (as it's also dynamic).
const staticPrefetchDataRoute =
prerenderManifest.routes[resolvedPathname]?.prefetchDataRoute
let isDynamicRSCRequest =
isRoutePPREnabled && isRSCRequest && !isPrefetchRSCRequest
isRoutePPREnabled &&
isRSCRequest &&
!isPrefetchRSCRequest &&
// If generated at build time, treat the RSC request as static
// so we can serve the prebuilt .rsc without a dynamic render.
// Only do this for routes that have a concrete prefetchDataRoute.
!staticPrefetchDataRoute
// During a PPR revalidation, the RSC request is not dynamic if we do not have the postponed data.
// We only attach the postponed data during a resume. If there's no postponed data, then it must be a revalidation.
......
......@@ -836,6 +836,10 @@ async function exportAppImpl(
info.hasPostponed = result.hasPostponed
}
if (typeof result.hasStaticRsc !== 'undefined') {
info.hasStaticRsc = result.hasStaticRsc
}
if (typeof result.fetchMetrics !== 'undefined') {
info.fetchMetrics = result.fetchMetrics
}
......
......@@ -130,6 +130,8 @@ export async function exportAppPage(
// If page data isn't available, it means that the page couldn't be rendered
// properly so long as we don't have unknown route params. When a route doesn't
// have unknown route params, there will not be any flight data.
let hasStaticRsc = false
if (!flightData) {
if (
!fallbackRouteParams ||
......@@ -139,12 +141,18 @@ export async function exportAppPage(
throw new Error(`Invariant: failed to get page data for ${path}`)
}
} else {
// If PPR is enabled, we want to emit a segment prefetch files
// instead of the standard rsc. This is because the standard rsc will
// contain the dynamic data. We do this if any routes have PPR enabled so
// that the cache read/write is the same.
if (!renderOpts.experimental.isRoutePPREnabled) {
// Writing the RSC payload to a file if we don't have PPR enabled.
const hasFallbackParams =
fallbackRouteParams != null && fallbackRouteParams.size > 0
const shouldWriteRsc =
!renderOpts.experimental.isRoutePPREnabled ||
(!postponed && !hasFallbackParams)
hasStaticRsc = shouldWriteRsc
// With PPR enabled, we normally skip writing .rsc because it may contain
// dynamic data. However, for fully static outputs (no postponed state and
// no fallback params), we can safely emit the route .rsc to support
// static navigations.
if (shouldWriteRsc) {
fileWriter.append(
htmlFilepath.replace(/\.html$/, RSC_SUFFIX),
flightData
......@@ -226,6 +234,7 @@ export async function exportAppPage(
},
hasEmptyStaticShell: Boolean(postponed) && html === '',
hasPostponed: Boolean(postponed),
hasStaticRsc,
cacheControl,
fetchMetrics,
renderResumeDataCache: renderResumeDataCache
......
......@@ -69,6 +69,7 @@ export type ExportRouteResult =
ssgNotFound?: boolean
hasEmptyStaticShell?: boolean
hasPostponed?: boolean
hasStaticRsc?: boolean
fetchMetrics?: FetchMetrics
renderResumeDataCache?: string
}
......@@ -145,6 +146,10 @@ export type ExportAppResult = {
* If the page has postponed when using PPR.
*/
hasPostponed?: boolean
/**
* If the page emitted a static RSC payload.
*/
hasStaticRsc?: boolean
fetchMetrics?: FetchMetrics
}
......
......@@ -230,7 +230,10 @@ export default class FileSystemCache implements CacheHandler {
}
let rscData: Buffer | undefined
if (!ctx.isFallback && !ctx.isRoutePPREnabled) {
if (
!ctx.isFallback &&
(!ctx.isRoutePPREnabled || meta?.postponed == null)
) {
rscData = await this.fs.readFile(
this.getFilePath(
`${key}${RSC_SUFFIX}`,
......
export async function generateStaticParams() {
return [{ slug: 'alpha' }]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
'use cache'
const { slug } = await params
await new Promise((resolve) => setTimeout(resolve, 2000))
return <div id="slug">Hi {slug}</div>
}
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>{children}</body>
</html>
)
}
import Link from 'next/link'
export default function Page() {
return (
<div id="home">
home{' '}
<Link href="/alpha" prefetch={false}>
alpha
</Link>
</div>
)
}
module.exports = {
cacheComponents: true,
}
import { nextTestSetup } from 'e2e-utils'
describe('static-rsc-cache-components', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
it('is skipped', () => {})
return
}
it('navigates to prerendered route without waiting for dynamic render', async () => {
const browser = await next.browser('/')
// Track elapsed time across the client navigation.
await browser.eval(`window.__navStart = performance.now()`)
const link = await browser.elementByCss('a[href="/alpha"]')
await link.click()
const slug = await browser.elementById('slug')
expect(await slug.innerText()).toBe('Hi alpha')
const elapsed = await browser.eval(`performance.now() - window.__navStart`)
// The page has an intentional 2s delay in the Server Component.
// If this were a dynamic render, navigation would take ~2s+.
expect(elapsed).toBeLessThan(1500)
})
})
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