Unverified Commit f5af2845 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Add global config to enable Partial Prefetching (#94448)

Adds a global config option called `partialPrefetching` that changes the
behavior of `<Link prefetch={true}>`.

When Partial Prefetching is enabled, only Cache Components are included
in a prefetch response. Dynamic data is omitted. This is the same idea
as Partial Prerendering for initial page loads, now applied to client
navigations.

In the initial Cache Components release, Partial Prefetching was enabled
for any Link that did not explicitly set a `prefetch` prop. However, if
the `prefetch` prop was set to `true`, then the Link retained the old
behavior where the _entire_ page was prefetched, including dynamic data.
This was to ease the migration path for existing apps that already
relied on dynamic data being included in the prefetch.

For new apps that have Cache Components enabled from the start, it's
suggested to also enable `partialPrefetching`.

This PR also adds a per-segment opt-in: a route segment can set
`unstable_prefetch = 'partial'` to enable Partial Prefetching just for
that segment, so apps can migrate gradually before enabling it globally.

<!-- NEXT_JS_LLM_PR -->
parent 70149d7a
...@@ -1302,5 +1302,6 @@ ...@@ -1302,5 +1302,6 @@
"1301": "Cannot determine late/early stage before starting the render", "1301": "Cannot determine late/early stage before starting the render",
"1302": "Attempted to advance to stage %s but the render is limited to %s", "1302": "Attempted to advance to stage %s but the render is limited to %s",
"1303": "Route \"%s\": A Client Component used \\`%s\\` outside of \\`<Suspense>\\`.\\n\\nThis prevents the route from being prerendered because the value is only available at runtime.\\n\\nWays to fix this:\\n - [stream] Wrap the Client Component in \\`<Suspense fallback={...}>\\`\\n https://nextjs.org/docs/messages/next-prerender-client-hook#wrap-the-client-component-in-suspense", "1303": "Route \"%s\": A Client Component used \\`%s\\` outside of \\`<Suspense>\\`.\\n\\nThis prevents the route from being prerendered because the value is only available at runtime.\\n\\nWays to fix this:\\n - [stream] Wrap the Client Component in \\`<Suspense fallback={...}>\\`\\n https://nextjs.org/docs/messages/next-prerender-client-hook#wrap-the-client-component-in-suspense",
"1304": "Route \"%s\": A Client Component used \\`%s\\` outside of \\`<Suspense>\\`.\\n\\nThis prevents the route from being prerendered because the value is only available at runtime.\\n\\nWays to fix this:\\n - [stream] Wrap the Client Component in \\`<Suspense fallback={...}>\\`\\n https://nextjs.org/docs/messages/next-prerender-client-hook#wrap-the-client-component-in-suspense\\n - [prerender] If the dynamic params are known, prerender them with \\`generateStaticParams\\`\\n https://nextjs.org/docs/messages/next-prerender-client-hook#prerender-known-dynamic-params" "1304": "Route \"%s\": A Client Component used \\`%s\\` outside of \\`<Suspense>\\`.\\n\\nThis prevents the route from being prerendered because the value is only available at runtime.\\n\\nWays to fix this:\\n - [stream] Wrap the Client Component in \\`<Suspense fallback={...}>\\`\\n https://nextjs.org/docs/messages/next-prerender-client-hook#wrap-the-client-component-in-suspense\\n - [prerender] If the dynamic params are known, prerender them with \\`generateStaticParams\\`\\n https://nextjs.org/docs/messages/next-prerender-client-hook#prerender-known-dynamic-params",
"1305": "\\`partialPrefetching\\` requires \\`cacheComponents\\` to be enabled. Please update your %s accordingly."
} }
...@@ -38,18 +38,14 @@ const InstantConfigSchema = z.union([ ...@@ -38,18 +38,14 @@ const InstantConfigSchema = z.union([
const PrefetchSchema = z.enum([ const PrefetchSchema = z.enum([
'auto', 'auto',
'partial',
'force-disabled', 'force-disabled',
'force-static',
'force-runtime', 'force-runtime',
]) ])
export type Instant = InstantConfig | true | false export type Instant = InstantConfig | true | false
export type Prefetch = export type Prefetch = 'auto' | 'partial' | 'force-disabled' | 'force-runtime'
| 'auto'
| 'force-disabled'
| 'force-static'
| 'force-runtime'
export type InstantConfigForTypeCheckInternal = __GenericInstantConfig | Instant export type InstantConfigForTypeCheckInternal = __GenericInstantConfig | Instant
// the __GenericInstantConfig type is used to avoid type widening issues with // the __GenericInstantConfig type is used to avoid type widening issues with
...@@ -137,9 +133,13 @@ const AppSegmentConfigSchema = z.object({ ...@@ -137,9 +133,13 @@ const AppSegmentConfigSchema = z.object({
unstable_instant: InstantConfigSchema.optional(), unstable_instant: InstantConfigSchema.optional(),
/** /**
* Controls runtime prefetching for this segment. * Controls prefetching for this segment.
* 'static' is a noop (default behavior). * - 'auto' (default) is a noop.
* 'runtime' enables runtime prefetching. * - 'partial' enables Partial Prefetching. Only Cache Components are
* prefetched, not dynamic ones.
* - 'force-runtime' is a superset of 'partial' and prefetches using a
* runtime request, instead of a static one.
* - 'force-disabled' disables prefetching for the segment.
*/ */
unstable_prefetch: PrefetchSchema.optional(), unstable_prefetch: PrefetchSchema.optional(),
...@@ -195,7 +195,7 @@ export function parseAppSegmentConfig( ...@@ -195,7 +195,7 @@ export function parseAppSegmentConfig(
} }
case 'unstable_prefetch': { case 'unstable_prefetch': {
return { return {
message: `Invalid unstable_prefetch value ${JSON.stringify(ctx.data)} on "${route}", must be "auto", "force-disabled", "force-static", or "force-runtime".`, message: `Invalid unstable_prefetch value ${JSON.stringify(ctx.data)} on "${route}", must be "auto", "partial", "force-disabled", or "force-runtime".`,
} }
} }
case 'unstable_dynamicStaleTime': { case 'unstable_dynamicStaleTime': {
...@@ -258,9 +258,13 @@ export type AppSegmentConfig = { ...@@ -258,9 +258,13 @@ export type AppSegmentConfig = {
unstable_instant?: Instant unstable_instant?: Instant
/** /**
* Controls runtime prefetching for this segment. * Controls prefetching for this segment.
* 'static' is a noop (default behavior). * - 'auto' (default) is a noop.
* 'runtime' enables runtime prefetching. * - 'partial' enables Partial Prefetching. Only Cache Components are
* prefetched, not dynamic ones.
* - 'force-runtime' is a superset of 'partial' and prefetches using a
* runtime request, instead of a static one.
* - 'force-disabled' disables prefetching for the segment.
*/ */
unstable_prefetch?: Prefetch unstable_prefetch?: Prefetch
......
...@@ -745,7 +745,7 @@ function pingRootRouteTree( ...@@ -745,7 +745,7 @@ function pingRootRouteTree(
// We don't need to do this for runtime prefetches, because those are only available in // We don't need to do this for runtime prefetches, because those are only available in
// `cacheComponents`, where every route is PPR. // `cacheComponents`, where every route is PPR.
let fetchStrategy: FetchStrategy let fetchStrategy: FetchStrategy
if (tree.prefetchHints & PrefetchHint.SubtreeHasInstant) { if (tree.prefetchHints & PrefetchHint.SubtreeHasPartialPrefetching) {
// If `instant` is defined anywhere on the target route, ignore the // If `instant` is defined anywhere on the target route, ignore the
// fetch strategy and switch to unified strategy used by Cache // fetch strategy and switch to unified strategy used by Cache
// Components (called `PPR` for now, will likely be renamed). // Components (called `PPR` for now, will likely be renamed).
......
...@@ -482,6 +482,7 @@ async function exportAppImpl( ...@@ -482,6 +482,7 @@ async function exportAppImpl(
distDir, distDir,
basePath: nextConfig.basePath, basePath: nextConfig.basePath,
cacheComponents: nextConfig.cacheComponents ?? false, cacheComponents: nextConfig.cacheComponents ?? false,
partialPrefetching: nextConfig.partialPrefetching,
validationLevel: nextConfig.experimental.instantInsights.validationLevel, validationLevel: nextConfig.experimental.instantInsights.validationLevel,
trailingSlash: nextConfig.trailingSlash, trailingSlash: nextConfig.trailingSlash,
locales: i18n?.locales, locales: i18n?.locales,
......
...@@ -2252,6 +2252,7 @@ async function getRSCPayload( ...@@ -2252,6 +2252,7 @@ async function getRSCPayload(
hints, hints,
prefetchInliningEnabled, prefetchInliningEnabled,
ctx.renderOpts.cacheComponents, ctx.renderOpts.cacheComponents,
ctx.renderOpts.partialPrefetching,
workStore.isStaticGeneration, workStore.isStaticGeneration,
ctx.renderOpts.isBuildTimePrerendering ?? false, ctx.renderOpts.isBuildTimePrerendering ?? false,
getDynamicParamFromSegment, getDynamicParamFromSegment,
...@@ -2458,6 +2459,7 @@ async function getErrorRSCPayload( ...@@ -2458,6 +2459,7 @@ async function getErrorRSCPayload(
errorHints, errorHints,
errorPrefetchInliningEnabled, errorPrefetchInliningEnabled,
ctx.renderOpts.cacheComponents, ctx.renderOpts.cacheComponents,
ctx.renderOpts.partialPrefetching,
workStore.isStaticGeneration, workStore.isStaticGeneration,
ctx.renderOpts.isBuildTimePrerendering ?? false, ctx.renderOpts.isBuildTimePrerendering ?? false,
getDynamicParamFromSegment, getDynamicParamFromSegment,
......
...@@ -13,6 +13,7 @@ async function createFlightRouterStateFromLoaderTreeImpl( ...@@ -13,6 +13,7 @@ async function createFlightRouterStateFromLoaderTreeImpl(
hintTree: PrefetchHints | null, hintTree: PrefetchHints | null,
prefetchInliningEnabled: boolean, prefetchInliningEnabled: boolean,
cacheComponents: boolean, cacheComponents: boolean,
partialPrefetching: boolean | undefined,
isStaticGeneration: boolean, isStaticGeneration: boolean,
isBuildTimePrerendering: boolean, isBuildTimePrerendering: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
...@@ -28,14 +29,17 @@ async function createFlightRouterStateFromLoaderTreeImpl( ...@@ -28,14 +29,17 @@ async function createFlightRouterStateFromLoaderTreeImpl(
{}, {},
] ]
// Load the layout or page module to check for unstable_instant/unstable_prefetch config // Load the layout or page module to check for unstable_instant/unstable_prefetch
// config. When a segment doesn't export unstable_prefetch, it defaults to
// 'partial' if the app has opted into partial prefetching globally via the
// `partialPrefetching` config in next.config.js.
const mod = layout ? await layout[0]() : page ? await page[0]() : undefined const mod = layout ? await layout[0]() : page ? await page[0]() : undefined
const instantConfig = mod const instantConfig = mod
? (mod as AppSegmentConfig).unstable_instant ? (mod as AppSegmentConfig).unstable_instant
: undefined : undefined
const prefetchConfig = mod const prefetchConfig =
? (mod as AppSegmentConfig).unstable_prefetch (mod ? (mod as AppSegmentConfig).unstable_prefetch : undefined) ??
: undefined (partialPrefetching ? 'partial' : undefined)
let prefetchHints = 0 let prefetchHints = 0
// Union in the precomputed build-time hints (e.g. segment inlining // Union in the precomputed build-time hints (e.g. segment inlining
...@@ -92,10 +96,12 @@ async function createFlightRouterStateFromLoaderTreeImpl( ...@@ -92,10 +96,12 @@ async function createFlightRouterStateFromLoaderTreeImpl(
instantConfig === true || instantConfig === true ||
(typeof instantConfig === 'object' && instantConfig !== null) (typeof instantConfig === 'object' && instantConfig !== null)
) { ) {
prefetchHints |= PrefetchHint.SubtreeHasInstant prefetchHints |= PrefetchHint.SubtreeHasPartialPrefetching
} }
if (prefetchConfig === 'force-disabled') { if (prefetchConfig === 'partial') {
prefetchHints |= PrefetchHint.SubtreeHasPartialPrefetching
} else if (prefetchConfig === 'force-disabled') {
prefetchHints |= PrefetchHint.PrefetchDisabled prefetchHints |= PrefetchHint.PrefetchDisabled
} else if (prefetchConfig === 'force-runtime') { } else if (prefetchConfig === 'force-runtime') {
prefetchHints |= PrefetchHint.HasRuntimePrefetch prefetchHints |= PrefetchHint.HasRuntimePrefetch
...@@ -117,6 +123,7 @@ async function createFlightRouterStateFromLoaderTreeImpl( ...@@ -117,6 +123,7 @@ async function createFlightRouterStateFromLoaderTreeImpl(
childHintNode, childHintNode,
prefetchInliningEnabled, prefetchInliningEnabled,
cacheComponents, cacheComponents,
partialPrefetching,
isStaticGeneration, isStaticGeneration,
isBuildTimePrerendering, isBuildTimePrerendering,
getDynamicParamFromSegment, getDynamicParamFromSegment,
...@@ -127,7 +134,7 @@ async function createFlightRouterStateFromLoaderTreeImpl( ...@@ -127,7 +134,7 @@ async function createFlightRouterStateFromLoaderTreeImpl(
if (child[4] !== undefined) { if (child[4] !== undefined) {
prefetchHints |= prefetchHints |=
child[4] & child[4] &
(PrefetchHint.SubtreeHasInstant | (PrefetchHint.SubtreeHasPartialPrefetching |
PrefetchHint.SubtreeHasLoadingBoundary | PrefetchHint.SubtreeHasLoadingBoundary |
PrefetchHint.SubtreeHasRuntimePrefetch) PrefetchHint.SubtreeHasRuntimePrefetch)
// If a child has a loading boundary (either directly or in its subtree), // If a child has a loading boundary (either directly or in its subtree),
...@@ -165,6 +172,7 @@ export async function createFlightRouterStateFromLoaderTree( ...@@ -165,6 +172,7 @@ export async function createFlightRouterStateFromLoaderTree(
hintTree: PrefetchHints | null, hintTree: PrefetchHints | null,
prefetchInliningEnabled: boolean, prefetchInliningEnabled: boolean,
cacheComponents: boolean, cacheComponents: boolean,
partialPrefetching: boolean | undefined,
isStaticGeneration: boolean, isStaticGeneration: boolean,
isBuildTimePrerendering: boolean, isBuildTimePrerendering: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment, getDynamicParamFromSegment: GetDynamicParamFromSegment,
...@@ -176,6 +184,7 @@ export async function createFlightRouterStateFromLoaderTree( ...@@ -176,6 +184,7 @@ export async function createFlightRouterStateFromLoaderTree(
hintTree, hintTree,
prefetchInliningEnabled, prefetchInliningEnabled,
cacheComponents, cacheComponents,
partialPrefetching,
isStaticGeneration, isStaticGeneration,
isBuildTimePrerendering, isBuildTimePrerendering,
getDynamicParamFromSegment, getDynamicParamFromSegment,
...@@ -189,6 +198,7 @@ export async function createRouteTreePrefetch( ...@@ -189,6 +198,7 @@ export async function createRouteTreePrefetch(
hintTree: PrefetchHints | null, hintTree: PrefetchHints | null,
prefetchInliningEnabled: boolean, prefetchInliningEnabled: boolean,
cacheComponents: boolean, cacheComponents: boolean,
partialPrefetching: boolean | undefined,
isStaticGeneration: boolean, isStaticGeneration: boolean,
isBuildTimePrerendering: boolean, isBuildTimePrerendering: boolean,
getDynamicParamFromSegment: GetDynamicParamFromSegment getDynamicParamFromSegment: GetDynamicParamFromSegment
...@@ -203,6 +213,7 @@ export async function createRouteTreePrefetch( ...@@ -203,6 +213,7 @@ export async function createRouteTreePrefetch(
hintTree, hintTree,
prefetchInliningEnabled, prefetchInliningEnabled,
cacheComponents, cacheComponents,
partialPrefetching,
isStaticGeneration, isStaticGeneration,
isBuildTimePrerendering, isBuildTimePrerendering,
getDynamicParamFromSegment, getDynamicParamFromSegment,
......
...@@ -97,6 +97,7 @@ export interface RenderOptsPartial { ...@@ -97,6 +97,7 @@ export interface RenderOptsPartial {
err?: Error | null err?: Error | null
basePath: string basePath: string
cacheComponents: boolean cacheComponents: boolean
partialPrefetching?: NextConfigComplete['partialPrefetching']
validationLevel: ValidationLevel validationLevel: ValidationLevel
trailingSlash: boolean trailingSlash: boolean
images: ImageConfigComplete images: ImageConfigComplete
......
...@@ -64,6 +64,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -64,6 +64,7 @@ export async function walkTreeWithFlightRouterState({
} = ctx } = ctx
const prefetchInliningEnabled = Boolean(experimental.prefetchInlining) const prefetchInliningEnabled = Boolean(experimental.prefetchInlining)
const cacheComponents = ctx.renderOpts.cacheComponents const cacheComponents = ctx.renderOpts.cacheComponents
const partialPrefetching = ctx.renderOpts.partialPrefetching
const isStaticGeneration = workStore.isStaticGeneration const isStaticGeneration = workStore.isStaticGeneration
const isBuildTimePrerendering = const isBuildTimePrerendering =
ctx.renderOpts.isBuildTimePrerendering ?? false ctx.renderOpts.isBuildTimePrerendering ?? false
...@@ -163,6 +164,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -163,6 +164,7 @@ export async function walkTreeWithFlightRouterState({
hintTree, hintTree,
prefetchInliningEnabled, prefetchInliningEnabled,
cacheComponents, cacheComponents,
partialPrefetching,
isStaticGeneration, isStaticGeneration,
isBuildTimePrerendering, isBuildTimePrerendering,
getDynamicParamFromSegment getDynamicParamFromSegment
...@@ -172,6 +174,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -172,6 +174,7 @@ export async function walkTreeWithFlightRouterState({
hintTree, hintTree,
prefetchInliningEnabled, prefetchInliningEnabled,
cacheComponents, cacheComponents,
partialPrefetching,
isStaticGeneration, isStaticGeneration,
isBuildTimePrerendering, isBuildTimePrerendering,
getDynamicParamFromSegment, getDynamicParamFromSegment,
...@@ -203,6 +206,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -203,6 +206,7 @@ export async function walkTreeWithFlightRouterState({
hintTree, hintTree,
prefetchInliningEnabled, prefetchInliningEnabled,
cacheComponents, cacheComponents,
partialPrefetching,
isStaticGeneration, isStaticGeneration,
isBuildTimePrerendering, isBuildTimePrerendering,
getDynamicParamFromSegment getDynamicParamFromSegment
...@@ -212,6 +216,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -212,6 +216,7 @@ export async function walkTreeWithFlightRouterState({
hintTree, hintTree,
prefetchInliningEnabled, prefetchInliningEnabled,
cacheComponents, cacheComponents,
partialPrefetching,
isStaticGeneration, isStaticGeneration,
isBuildTimePrerendering, isBuildTimePrerendering,
getDynamicParamFromSegment, getDynamicParamFromSegment,
...@@ -244,6 +249,7 @@ export async function walkTreeWithFlightRouterState({ ...@@ -244,6 +249,7 @@ export async function walkTreeWithFlightRouterState({
hintTree, hintTree,
prefetchInliningEnabled, prefetchInliningEnabled,
cacheComponents, cacheComponents,
partialPrefetching,
isStaticGeneration, isStaticGeneration,
isBuildTimePrerendering, isBuildTimePrerendering,
getDynamicParamFromSegment, getDynamicParamFromSegment,
...@@ -376,6 +382,7 @@ export async function createFullTreeFlightDataForNavigation({ ...@@ -376,6 +382,7 @@ export async function createFullTreeFlightDataForNavigation({
hintTreeForInitialRender, hintTreeForInitialRender,
Boolean(experimental.prefetchInlining), Boolean(experimental.prefetchInlining),
ctx.renderOpts.cacheComponents, ctx.renderOpts.cacheComponents,
ctx.renderOpts.partialPrefetching,
workStoreForInitialRender.isStaticGeneration, workStoreForInitialRender.isStaticGeneration,
ctx.renderOpts.isBuildTimePrerendering ?? false, ctx.renderOpts.isBuildTimePrerendering ?? false,
getDynamicParamFromSegment, getDynamicParamFromSegment,
......
...@@ -568,6 +568,7 @@ export default abstract class Server< ...@@ -568,6 +568,7 @@ export default abstract class Server<
// `htmlLimitedBots` is passed to server as serialized config in string format // `htmlLimitedBots` is passed to server as serialized config in string format
htmlLimitedBots: this.nextConfig.htmlLimitedBots, htmlLimitedBots: this.nextConfig.htmlLimitedBots,
cacheComponents: this.nextConfig.cacheComponents ?? false, cacheComponents: this.nextConfig.cacheComponents ?? false,
partialPrefetching: this.nextConfig.partialPrefetching,
validationLevel: validationLevel:
this.nextConfig.experimental.instantInsights.validationLevel, this.nextConfig.experimental.instantInsights.validationLevel,
experimental: { experimental: {
......
...@@ -766,6 +766,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -766,6 +766,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
.optional(), .optional(),
pageExtensions: z.array(z.string()).min(1).optional(), pageExtensions: z.array(z.string()).min(1).optional(),
instrumentationClientInject: z.array(z.string()).optional(), instrumentationClientInject: z.array(z.string()).optional(),
partialPrefetching: z.boolean().optional(),
poweredByHeader: z.boolean().optional(), poweredByHeader: z.boolean().optional(),
productionBrowserSourceMaps: z.boolean().optional(), productionBrowserSourceMaps: z.boolean().optional(),
reactCompiler: z.union([ reactCompiler: z.union([
......
...@@ -1774,6 +1774,18 @@ export interface NextConfig { ...@@ -1774,6 +1774,18 @@ export interface NextConfig {
*/ */
cacheComponents?: boolean cacheComponents?: boolean
/**
* Opts the whole app into Partial Prefetching: `<Link prefetch={true}>`
* prefetches only the static parts of a route, never its dynamic data.
* When `true`, the default segment-level `unstable_prefetch` becomes
* `'partial'`; per-segment `unstable_prefetch` exports still win. Requires
* `cacheComponents: true`.
*
* When `false` or omitted, this does nothing (the legacy behavior, where
* dynamic data is included in the prefetch).
*/
partialPrefetching?: boolean
cacheLife?: { cacheLife?: {
[profile: string]: { [profile: string]: {
// How long the client can cache a value without checking with the server. // How long the client can cache a value without checking with the server.
...@@ -2101,6 +2113,7 @@ export interface NextConfigRuntime { ...@@ -2101,6 +2113,7 @@ export interface NextConfigRuntime {
distDir: NextConfigComplete['distDir'] distDir: NextConfigComplete['distDir']
cacheComponents: NextConfigComplete['cacheComponents'] cacheComponents: NextConfigComplete['cacheComponents']
partialPrefetching: NextConfigComplete['partialPrefetching']
agentRules: NextConfigComplete['agentRules'] agentRules: NextConfigComplete['agentRules']
htmlLimitedBots: NextConfigComplete['htmlLimitedBots'] htmlLimitedBots: NextConfigComplete['htmlLimitedBots']
assetPrefix: NextConfigComplete['assetPrefix'] assetPrefix: NextConfigComplete['assetPrefix']
...@@ -2259,6 +2272,7 @@ export function getNextConfigRuntime( ...@@ -2259,6 +2272,7 @@ export function getNextConfigRuntime(
distDir: config.distDir, distDir: config.distDir,
cacheComponents: config.cacheComponents, cacheComponents: config.cacheComponents,
partialPrefetching: config.partialPrefetching,
agentRules: config.agentRules, agentRules: config.agentRules,
htmlLimitedBots: config.htmlLimitedBots, htmlLimitedBots: config.htmlLimitedBots,
assetPrefix: config.assetPrefix, assetPrefix: config.assetPrefix,
......
...@@ -527,6 +527,12 @@ function assignDefaultsAndValidate( ...@@ -527,6 +527,12 @@ function assignDefaultsAndValidate(
) )
} }
if (result.partialPrefetching && !result.cacheComponents) {
throw new Error(
`\`partialPrefetching\` requires \`cacheComponents\` to be enabled. Please update your ${configFileName} accordingly.`
)
}
if (result.experimental.appShells) { if (result.experimental.appShells) {
// App Shells is tested in combination with the experimental flags it // App Shells is tested in combination with the experimental flags it
// expects to ship alongside. All of these are on track to become // expects to ship alongside. All of these are on track to become
......
...@@ -159,12 +159,13 @@ const API_DOCS: Record< ...@@ -159,12 +159,13 @@ const API_DOCS: Record<
unstable_prefetch: { unstable_prefetch: {
description: `Controls prefetching behavior for this segment. This configuration is currently under development and will change.`, description: `Controls prefetching behavior for this segment. This configuration is currently under development and will change.`,
link: '(docs coming soon)', link: '(docs coming soon)',
type: `"auto" | "force-disabled" | "force-static" | "force-runtime"`, type: `"auto" | "partial" | "force-disabled" | "force-runtime"`,
options: { options: {
auto: 'Default. Framework decides based on instant validation and segment configuration. You do not need to set this explicitly.', auto: 'Default. Framework decides based on instant validation and segment configuration. You do not need to set this explicitly.',
partial: 'Enables Partial Prefetching for this segment.',
'force-disabled': 'Never prefetch this segment.', 'force-disabled': 'Never prefetch this segment.',
'force-static': 'Always prefetch this segment statically.', 'force-runtime':
'force-runtime': 'Always prefetch this segment at runtime.', 'Prefetch this segment with a runtime server request so it can access session data, such as cookies.',
}, },
insertText: `unstable_prefetch = 'force-runtime';`, insertText: `unstable_prefetch = 'force-runtime';`,
}, },
......
...@@ -184,10 +184,11 @@ export const enum PrefetchHint { ...@@ -184,10 +184,11 @@ export const enum PrefetchHint {
// This segment has a runtime prefetch enabled (via unstable_instant with // This segment has a runtime prefetch enabled (via unstable_instant with
// prefetch: 'runtime'). Per-segment only, does not propagate to ancestors. // prefetch: 'runtime'). Per-segment only, does not propagate to ancestors.
HasRuntimePrefetch = 0b00001, HasRuntimePrefetch = 0b00001,
// This segment or one of its descendants has an instant config defined // This segment or one of its descendants opts into Partial Prefetching.
// (any truthy unstable_instant, regardless of prefetch mode). Propagates // Currently set when a truthy unstable_instant config is present on any
// upward so the root segment reflects the entire subtree. // segment in the subtree (regardless of prefetch mode). Propagates upward
SubtreeHasInstant = 0b00010, // so the root segment reflects the entire subtree.
SubtreeHasPartialPrefetching = 0b00010,
// This segment itself has a loading.tsx boundary. // This segment itself has a loading.tsx boundary.
SegmentHasLoadingBoundary = 0b00100, SegmentHasLoadingBoundary = 0b00100,
// A descendant segment (but not this one) has a loading.tsx boundary. // A descendant segment (but not this one) has a loading.tsx boundary.
......
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { LinkAccordion } from '../components/link-accordion'
export default function Page() {
return (
<main>
<h1>Home</h1>
<ul>
<li>
<LinkAccordion href="/target-page" prefetch={true}>
/target-page
</LinkAccordion>
</li>
</ul>
</main>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
export default function Page() {
return (
<main>
<div id="static-content">Static content</div>
<Suspense fallback={<div>Loading dynamic...</div>}>
<Dynamic />
</Suspense>
</main>
)
}
async function Dynamic() {
await connection()
return <div id="dynamic-content">Dynamic content</div>
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
partialPrefetching: true,
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
describe('partial prefetching config', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
it('is skipped', () => {})
return
}
it('does not prefetch dynamic data, even when <Link prefetch={true}>', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
// Reveal the link to trigger its prefetch. The Link has prefetch={true},
// and the target page has no per-segment config, so the behavior is
// determined by the global Next.js config. Because Partial Prefetching is
// enabled, the prefetch should include static content, but NOT
// dynamic data.
await act(async () => {
const linkToggle = await browser.elementByCss(
'input[data-link-accordion="/target-page"]'
)
await linkToggle.click()
}, [
{ includes: 'Static content' },
{ includes: 'Dynamic content', block: 'reject' },
])
})
})
import { Suspense } from 'react'
import { connection } from 'next/server'
// No per-segment config. This is the control: with neither the global
// `partialPrefetching` flag nor a segment-level opt-in, a `prefetch={true}`
// link does a full prefetch that includes dynamic data.
export default function Page() {
return (
<main>
<div id="static-content">Default static</div>
<Suspense fallback={<div>Loading dynamic...</div>}>
<Dynamic />
</Suspense>
</main>
)
}
async function Dynamic() {
await connection()
return <div id="dynamic-content">Default dynamic</div>
}
import { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { LinkAccordion } from '../components/link-accordion'
export default function Page() {
return (
<main>
<h1>Home</h1>
<ul>
<li>
<LinkAccordion href="/default-route" prefetch={true}>
/default-route
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/partial-route" prefetch={true}>
/partial-route
</LinkAccordion>
</li>
</ul>
</main>
)
}
import { Suspense } from 'react'
import { connection } from 'next/server'
// Opts this route into partial prefetching at the segment level, without the
// global `partialPrefetching` flag. A `prefetch={true}` link should prefetch
// the static shell but never the dynamic data.
export const unstable_prefetch = 'partial'
export default function Page() {
return (
<main>
<div id="static-content">Partial static</div>
<Suspense fallback={<div>Loading dynamic...</div>}>
<Dynamic />
</Suspense>
</main>
)
}
async function Dynamic() {
await connection()
return <div id="dynamic-content">Partial dynamic</div>
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
cacheComponents: true,
}
module.exports = nextConfig
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from 'router-act'
describe('partial prefetching segment config', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
it('is skipped', () => {})
return
}
it('includes dynamic data in the prefetch when the route has no partial prefetching config', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
// Reveal the link to trigger its prefetch. The Link has prefetch={true},
// the target route has no per-segment config, and this app does NOT enable
// partial prefetching globally. So the legacy behavior applies: the
// prefetch is a full prefetch that includes dynamic data.
//
// This is the control case. It's the first place we assert the "dynamic IS
// prefetched" direction, which proves the opt-in case below is meaningful.
await act(
async () => {
const linkToggle = await browser.elementByCss(
'input[data-link-accordion="/default-route"]'
)
await linkToggle.click()
},
{ includes: 'Default dynamic' }
)
})
it('does not prefetch dynamic data for a route with unstable_prefetch = "partial"', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
// Reveal the link to trigger its prefetch. The Link has prefetch={true},
// and the target route opts into partial prefetching via
// `export const unstable_prefetch = 'partial'`. So the prefetch should
// include the static shell, but NOT the dynamic data — even though the
// global config does not enable partial prefetching.
await act(async () => {
const linkToggle = await browser.elementByCss(
'input[data-link-accordion="/partial-route"]'
)
await linkToggle.click()
}, [
{ includes: 'Partial static' },
{ includes: 'Partial dynamic', block: 'reject' },
])
})
})
...@@ -84,8 +84,8 @@ describe('prefetch={true} with instant route', () => { ...@@ -84,8 +84,8 @@ describe('prefetch={true} with instant route', () => {
const act = createRouterAct(page) const act = createRouterAct(page)
// The layout has unstable_instant but the page does not. The // The layout has unstable_instant but the page does not. The
// SubtreeHasInstant bit should propagate up from the layout, so // SubtreeHasPartialPrefetching bit should propagate up from the layout,
// prefetch={true} on the Link should still be downgraded. // so prefetch={true} on the Link should still be downgraded.
await act(async () => { await act(async () => {
const linkToggle = await browser.elementByCss( const linkToggle = await browser.elementByCss(
'input[data-link-accordion="/layout-instant"]' 'input[data-link-accordion="/layout-instant"]'
......
...@@ -223,4 +223,32 @@ describe('config', () => { ...@@ -223,4 +223,32 @@ describe('config', () => {
expect(config.turbopack.root).toBe(config.outputFileTracingRoot) expect(config.turbopack.root).toBe(config.outputFileTracingRoot)
}) })
}) })
describe('partialPrefetching config', () => {
it('Should throw when `partialPrefetching` is set without `cacheComponents`', async () => {
await expect(async () => {
await loadConfig(PHASE_DEVELOPMENT_SERVER, '<rootDir>-no-cc', {
customConfig: {
partialPrefetching: true,
},
})
}).rejects.toThrow(
/`partialPrefetching` requires `cacheComponents` to be enabled/
)
})
it('Should accept `partialPrefetching: true` when `cacheComponents` is enabled', async () => {
const config = await loadConfig(
PHASE_DEVELOPMENT_SERVER,
'<rootDir>-cc',
{
customConfig: {
cacheComponents: true,
partialPrefetching: true,
},
}
)
expect(config.partialPrefetching).toBe(true)
})
})
}) })
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