Unverified Commit 824fcd63 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Opt Partial Prefetching routes into the runtime stage of Cached Navs (#95097)

In #95064 we added a global opt-in to the runtime stage of Cached
Navigations: setting `cachedNavigations: 'allow-runtime'` makes every
route runtime-cache, on top of the existing per-segment `prefetch =
'allow-runtime'`. This extends the opt-in: a `prefetch` config of
`'partial'`, `'unstable_eager'`, or `'allow-runtime'` all enable Partial
Prefetching for a route, and a route already doing PPR-style partial
prefetching should also runtime-cache its navigations. The next-config
`partialPrefetching`, which enables Partial Prefetching globally, opts
every route in as well.

Both runtime-prefetch spawn gates in `app-render.tsx` now broaden their
condition to include `partialPrefetching` and any segment `prefetch`
that enables Partial Prefetching, via a new
`anySegmentHasPartialPrefetchingEnabled` helper. The narrower callers
that gate metadata staging and the dev reveal stage keep using
`anySegmentHasRuntimePrefetchEnabled`, since they specifically concern
routes the client runtime-prefetches (`'allow-runtime'`), not partial
ones.

Because `partialPrefetching` has no default and is not auto-enabled by
`cacheComponents`, apps that do not set it are unaffected.

Tests add `prefetch = 'partial'` and `prefetch = 'unstable_eager'`
routes to the existing `default` fixture and a new `partial-prefetching`
fixture for the global config, each asserting the route runtime-caches
its request-derived content on a second navigation without a per-segment
`prefetch = 'allow-runtime'` export.
parent f96ff7c7
...@@ -264,6 +264,7 @@ import { ...@@ -264,6 +264,7 @@ import {
} from './staged-rendering' } from './staged-rendering'
import { import {
anySegmentHasRuntimePrefetchEnabled, anySegmentHasRuntimePrefetchEnabled,
anySegmentHasPartialPrefetchingEnabled,
isPageAllowedToBlock, isPageAllowedToBlock,
anySegmentNeedsInstantValidationInDev, anySegmentNeedsInstantValidationInDev,
anySegmentNeedsInstantValidationInBuild, anySegmentNeedsInstantValidationInBuild,
...@@ -980,16 +981,18 @@ async function generateStagedDynamicFlightRenderResultNode( ...@@ -980,16 +981,18 @@ async function generateStagedDynamicFlightRenderResultNode(
let runtimePrefetchStream: ReadableStream<Uint8Array> | undefined let runtimePrefetchStream: ReadableStream<Uint8Array> | undefined
// Check if this route should runtime-cache its navigation: either a segment // Check if this route should runtime-cache its navigation. This happens when
// opted in via `prefetch = 'allow-runtime'`, or the global // Partial Prefetching is enabled for the route, either per segment (a
// `cachedNavigations: 'allow-runtime'` flag forces it for every route. If so, // `prefetch` of 'partial', 'unstable_eager', or 'allow-runtime') or globally
// we piggyback on the dynamic render to fill caches and then spawn a final // (the `partialPrefetching` config), or when the `cachedNavigations:
// runtime prerender whose result stream is embedded in the RSC payload. This // 'allow-runtime'` flag forces it for every route. If so, we piggyback on the
// is gated because it adds extra server processing and increases the response // dynamic render to fill caches and then spawn a final runtime prerender
// payload size. // whose result stream is embedded in the RSC payload. This is gated because
// it adds extra server processing and increases the response payload size.
if ( if (
experimental.cachedNavigations === 'allow-runtime' || experimental.cachedNavigations === 'allow-runtime' ||
(await anySegmentHasRuntimePrefetchEnabled(loaderTree)) Boolean(renderOpts.partialPrefetching) ||
(await anySegmentHasPartialPrefetchingEnabled(loaderTree))
) { ) {
// Create a mutable cache that gets filled during the dynamic render. // Create a mutable cache that gets filled during the dynamic render.
const prerenderResumeDataCache = createPrerenderResumeDataCache() const prerenderResumeDataCache = createPrerenderResumeDataCache()
...@@ -3529,12 +3532,15 @@ async function renderToStream( ...@@ -3529,12 +3532,15 @@ async function renderToStream(
// If the route should runtime-cache its navigation, spawn a runtime // If the route should runtime-cache its navigation, spawn a runtime
// prerender after the resume render fills caches. The result is // prerender after the resume render fills caches. The result is
// embedded in the initial RSC payload so the client can cache // embedded in the initial RSC payload so the client can cache
// runtime-prefetchable content during hydration. This is enabled either // runtime-prefetchable content during hydration. This is enabled when
// per segment via `prefetch = 'allow-runtime'`, or globally via the // Partial Prefetching is on for the route, either per segment (a
// `cachedNavigations: 'allow-runtime'` flag. // `prefetch` of 'partial', 'unstable_eager', or 'allow-runtime') or
// globally (the `partialPrefetching` config), or when the
// `cachedNavigations: 'allow-runtime'` flag forces it for every route.
if ( if (
cachedNavigations === 'allow-runtime' || cachedNavigations === 'allow-runtime' ||
(await anySegmentHasRuntimePrefetchEnabled(tree)) Boolean(renderOpts.partialPrefetching) ||
(await anySegmentHasPartialPrefetchingEnabled(tree))
) { ) {
const prerenderResumeDataCache = createPrerenderResumeDataCache() const prerenderResumeDataCache = createPrerenderResumeDataCache()
requestStore.resumeDataCache = prerenderResumeDataCache requestStore.resumeDataCache = prerenderResumeDataCache
......
...@@ -76,6 +76,42 @@ export async function anySegmentHasRuntimePrefetchEnabled( ...@@ -76,6 +76,42 @@ export async function anySegmentHasRuntimePrefetchEnabled(
return false return false
} }
/**
* Like `anySegmentHasRuntimePrefetchEnabled`, but matches any `prefetch` config
* that enables Partial Prefetching for the segment: 'partial',
* 'unstable_eager', or 'allow-runtime'. A route with Partial Prefetching
* enabled also runtime-caches its navigations, so this gates the runtime
* prefetch spawn.
*/
export async function anySegmentHasPartialPrefetchingEnabled(
tree: LoaderTree
): Promise<boolean> {
const { mod: layoutOrPageMod } = await getLayoutOrPageModule(tree)
const prefetchConfig = layoutOrPageMod
? (layoutOrPageMod as AppSegmentConfig).prefetch
: undefined
if (
prefetchConfig === 'partial' ||
prefetchConfig === 'unstable_eager' ||
prefetchConfig === 'allow-runtime'
) {
return true
}
const { parallelRoutes } = parseLoaderTree(tree)
for (const parallelRouteKey in parallelRoutes) {
const parallelRoute = parallelRoutes[parallelRouteKey]
const hasChildPartialPrefetching =
await anySegmentHasPartialPrefetchingEnabled(parallelRoute)
if (hasChildPartialPrefetching) {
return true
}
}
return false
}
export async function isPageAllowedToBlock(tree: LoaderTree): Promise<boolean> { export async function isPageAllowedToBlock(tree: LoaderTree): Promise<boolean> {
const { mod: layoutOrPageMod } = await getLayoutOrPageModule(tree) const { mod: layoutOrPageMod } = await getLayoutOrPageModule(tree)
......
import path from 'path'
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
// The `partial-prefetching` fixture enables Partial Prefetching globally via
// the next-config `partialPrefetching: true`, which opts every route into
// runtime Cached Navigations even without a per-segment `prefetch` config.
describe('cached navigations - global partialPrefetching', () => {
const { next, isNextDev } = nextTestSetup({
files: path.join(__dirname, 'partial-prefetching'),
})
if (isNextDev) {
it('is skipped', () => {})
return
}
it('runtime-caches a route that has no per-segment prefetch config', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
async beforePageLoad(p: Playwright.Page) {
page = p
await page.clock.install()
},
})
const act = createRouterAct(page)
// First navigation to /runtime-prefetchable — a route that reads request
// data but does NOT export any `prefetch` config. The link uses
// prefetch={false}, so this is a plain navigation with no prefetch.
await act(
async () => {
await browser.elementByCss('a[href="/runtime-prefetchable"]').click()
},
{ includes: 'Dynamic content' }
)
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
// Navigate back to home
await browser.back()
expect(await browser.elementByCss('h1').text()).toBe('Home')
// Second navigation — under the global `partialPrefetching` config, the
// request-derived content (searchParams, cookies, headers) was
// runtime-cached from the first navigation and shows instantly, even with
// the dynamic request blocked. Only the truly dynamic connection() content
// needs a server request.
await act(async () => {
await act(
async () => {
await browser.elementByCss('a[href="/runtime-prefetchable"]').click()
},
{
includes: 'Dynamic content',
block: true,
}
)
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
expect(
await browser.elementById('search-params-boundary').text()
).toContain('Search params:')
expect(await browser.elementById('cookies-boundary').text()).toContain(
'Cookie:'
)
expect(await browser.elementById('headers-boundary').text()).toContain(
'Header:'
)
// Only connection() shows a Suspense fallback — it's truly dynamic.
expect(await browser.elementById('connection-boundary').text()).toBe(
'Loading connection...'
)
})
// After unblocking, the dynamic content resolves too.
expect(await browser.elementById('connection-boundary').text()).toContain(
'Dynamic content'
)
})
})
...@@ -990,4 +990,76 @@ describe('cached navigations', () => { ...@@ -990,4 +990,76 @@ describe('cached navigations', () => {
expect(barContent).not.toContain('foo') expect(barContent).not.toContain('foo')
}) })
}) })
// A `prefetch` config that enables Partial Prefetching ('partial',
// 'unstable_eager', or 'allow-runtime') also opts the route into runtime
// Cached Navigations, even though this fixture does not set the global
// `cachedNavigations: 'allow-runtime'` flag. Contrast with
// `partially-static`, which has no `prefetch` config and only gets static
// caching.
async function expectRuntimeCachedOnSecondNavigation(route: string) {
let page: Playwright.Page
const browser = await next.browser('/', {
async beforePageLoad(p: Playwright.Page) {
page = p
await page.clock.install()
},
})
const act = createRouterAct(page)
// First navigation — full dynamic request, no prefetch.
await act(
async () => {
await browser.elementByCss(`a[href="${route}"]`).click()
},
{ includes: 'Dynamic content' }
)
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
// Navigate back to home.
await browser.back()
expect(await browser.elementByCss('h1').text()).toBe('Home')
// Second navigation — the request-derived content was runtime-cached from
// the first navigation and shows instantly even with the dynamic request
// blocked. Only connection() needs a server request.
await act(async () => {
await act(
async () => {
await browser.elementByCss(`a[href="${route}"]`).click()
},
{ includes: 'Dynamic content', block: true }
)
expect(await browser.elementById('cached-content').text()).toContain(
'Cached content'
)
expect(
await browser.elementById('search-params-boundary').text()
).toContain('Search params:')
expect(await browser.elementById('cookies-boundary').text()).toContain(
'Cookie:'
)
expect(await browser.elementById('headers-boundary').text()).toContain(
'Header:'
)
expect(await browser.elementById('connection-boundary').text()).toBe(
'Loading connection...'
)
})
expect(await browser.elementById('connection-boundary').text()).toContain(
'Dynamic content'
)
}
it('runtime-caches a route with prefetch = "partial"', async () => {
await expectRuntimeCachedOnSecondNavigation('/prefetch-partial')
})
it('runtime-caches a route with prefetch = "unstable_eager"', async () => {
await expectRuntimeCachedOnSecondNavigation('/prefetch-eager')
})
}) })
...@@ -33,6 +33,16 @@ export default function Home() { ...@@ -33,6 +33,16 @@ export default function Home() {
Go to runtime-prefetchable page Go to runtime-prefetchable page
</Link> </Link>
</li> </li>
<li>
<Link href="/prefetch-partial" prefetch={false}>
Go to prefetch=partial page
</Link>
</li>
<li>
<Link href="/prefetch-eager" prefetch={false}>
Go to prefetch=unstable_eager page
</Link>
</li>
</ul> </ul>
</main> </main>
) )
......
import { RuntimeContent } from '../../components/runtime-content'
// `prefetch = 'unstable_eager'` enables Partial Prefetching, which also opts
// the route into runtime Cached Navigations.
export const prefetch = 'unstable_eager'
export default async function Page({
searchParams,
}: {
searchParams: Promise<{ q?: string }>
}) {
return <RuntimeContent searchParams={searchParams} />
}
import { RuntimeContent } from '../../components/runtime-content'
// `prefetch = 'partial'` enables Partial Prefetching, which also opts the route
// into runtime Cached Navigations.
export const prefetch = 'partial'
export default async function Page({
searchParams,
}: {
searchParams: Promise<{ q?: string }>
}) {
return <RuntimeContent searchParams={searchParams} />
}
import { cookies, headers } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
// A page body with a static (`'use cache'`) block, request-derived content
// (searchParams/cookies/headers) that resolves at the runtime stage, and a
// truly dynamic `connection()` boundary. Shared by the routes that exercise the
// per-segment `prefetch` opt-ins for runtime Cached Navigations.
export function RuntimeContent({
searchParams,
}: {
searchParams: Promise<{ q?: string }>
}) {
return (
<main>
<CachedContent />
<div id="search-params-boundary">
<Suspense fallback={<p>Loading search params...</p>}>
<SearchParamsContent searchParams={searchParams} />
</Suspense>
</div>
<div id="cookies-boundary">
<Suspense fallback={<p>Loading cookies...</p>}>
<CookiesContent />
</Suspense>
</div>
<div id="headers-boundary">
<Suspense fallback={<p>Loading headers...</p>}>
<HeadersContent />
</Suspense>
</div>
<div id="connection-boundary">
<Suspense fallback={<p>Loading connection...</p>}>
<ConnectionContent />
</Suspense>
</div>
</main>
)
}
async function CachedContent() {
'use cache'
return <p id="cached-content">Cached content</p>
}
async function SearchParamsContent({
searchParams,
}: {
searchParams: Promise<{ q?: string }>
}) {
const { q } = await searchParams
return <p>Search params: {q ?? 'none'}</p>
}
async function CookiesContent() {
const cookieStore = await cookies()
const value = cookieStore.get('testCookie')?.value ?? 'none'
return <p>Cookie: {value}</p>
}
async function HeadersContent() {
const headerStore = await headers()
const value = headerStore.get('x-test-header') ?? 'none'
return <p>Header: {value}</p>
}
async function ConnectionContent() {
await connection()
return <p>Dynamic content</p>
}
import Link from 'next/link'
import { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body>
<nav>
<Link href="/" prefetch={false}>
Home
</Link>
</nav>
{children}
</body>
</html>
)
}
import Link from 'next/link'
export default function Home() {
return (
<main>
<h1>Home</h1>
<h2>
Links with <code>prefetch=false</code>
</h2>
<ul>
<li>
<Link href="/runtime-prefetchable" prefetch={false}>
Go to runtime-prefetchable page
</Link>
</li>
</ul>
</main>
)
}
import { cookies, headers } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
// Note: intentionally no `export const prefetch` and no `instant` config. This
// route gets runtime-cached purely because of the global `partialPrefetching`
// config in next.config.ts.
export default async function Page({
searchParams,
}: {
searchParams: Promise<{ q?: string }>
}) {
return (
<main>
<CachedContent />
<div id="search-params-boundary">
<Suspense fallback={<p>Loading search params...</p>}>
<SearchParamsContent searchParams={searchParams} />
</Suspense>
</div>
<div id="cookies-boundary">
<Suspense fallback={<p>Loading cookies...</p>}>
<CookiesContent />
</Suspense>
</div>
<div id="headers-boundary">
<Suspense fallback={<p>Loading headers...</p>}>
<HeadersContent />
</Suspense>
</div>
<div id="connection-boundary">
<Suspense fallback={<p>Loading connection...</p>}>
<ConnectionContent />
</Suspense>
</div>
</main>
)
}
async function CachedContent() {
'use cache'
return <p id="cached-content">Cached content</p>
}
async function SearchParamsContent({
searchParams,
}: {
searchParams: Promise<{ q?: string }>
}) {
const { q } = await searchParams
return <p>Search params: {q ?? 'none'}</p>
}
async function CookiesContent() {
const cookieStore = await cookies()
const value = cookieStore.get('testCookie')?.value ?? 'none'
return <p>Cookie: {value}</p>
}
async function HeadersContent() {
const headerStore = await headers()
const value = headerStore.get('x-test-header') ?? 'none'
return <p>Header: {value}</p>
}
async function ConnectionContent() {
await connection()
return <p>Dynamic content</p>
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
productionBrowserSourceMaps: true,
// Enabling Partial Prefetching globally opts every route into runtime Cached
// Navigations, even without a per-segment `prefetch` config.
// `cachedNavigations` is left at its default (`true`, the static stage), so
// the runtime stage here comes solely from `partialPrefetching`.
partialPrefetching: true,
experimental: {
prefetchInlining: false,
exposeTestingApiInProductionBuild: true,
optimisticRouting: true,
useOffline: true,
varyParams: true,
},
}
export default 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