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

Add <Link prefetch="navigation"> (#99871)

`await navigation()` prevents certain parts of a page from being
rendered as part of a Link's prefetch (`<Link prefetch={true}>`).
However, there are cases where you may wish to override that behavior
and forcibly prefetch past that boundary. For example, if you have high
confidence that the user will interact with a particular link.

This PR adds three new options for a Link's prefetch prop: `"shell"`,
`"prefetch"`, and `"navigation"`.

`"shell"` and `"prefetch"` exist mostly for consistency — a value of
`"shell"` has the same behavior as a missing prefetch prop, and
`"prefetch"` has the same behavior as `true`. It's only `"navigation"`
that introduces novel functionality.

The naming scheme intentionally mirrors the `await prefetch()` and
`await navigation()` APIs introduced in version 16.4. They correspond to
the same conceptual stages.

---------
Co-authored-by: 's avatarJanka Uryga <lolzatu2@gmail.com>
parent d06bd637
...@@ -54,6 +54,7 @@ import { getServerActionRequestMetadata } from '../../server/lib/server-action-r ...@@ -54,6 +54,7 @@ import { getServerActionRequestMetadata } from '../../server/lib/server-action-r
import { import {
RSC_HEADER, RSC_HEADER,
NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_PREFETCH_STATIC,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_INSTANT_TEST_COOKIE, NEXT_INSTANT_TEST_COOKIE,
NEXT_IS_PRERENDER_HEADER, NEXT_IS_PRERENDER_HEADER,
...@@ -315,7 +316,8 @@ export function createAppPageEntrypoint({ ...@@ -315,7 +316,8 @@ export function createAppPageEntrypoint({
*/ */
const isPrefetchRSCRequest = const isPrefetchRSCRequest =
getRequestMeta(req, 'isPrefetchRSCRequest') ?? getRequestMeta(req, 'isPrefetchRSCRequest') ??
req.headers[NEXT_ROUTER_PREFETCH_HEADER] === '1' // exclude runtime prefetches, which use '2' // Runtime prefetches use the other values, so they're excluded.
req.headers[NEXT_ROUTER_PREFETCH_HEADER] === NEXT_ROUTER_PREFETCH_STATIC
// NOTE: Don't delete headers[RSC] yet, it still needs to be used in renderToHTML later // NOTE: Don't delete headers[RSC] yet, it still needs to be used in renderToHTML later
...@@ -477,7 +479,8 @@ export function createAppPageEntrypoint({ ...@@ -477,7 +479,8 @@ export function createAppPageEntrypoint({
typeof req.headers.cookie === 'string' && typeof req.headers.cookie === 'string' &&
req.headers.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=') && req.headers.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=') &&
(!isRSCRequestHeader(req.headers[RSC_HEADER]) || (!isRSCRequestHeader(req.headers[RSC_HEADER]) ||
req.headers[NEXT_ROUTER_PREFETCH_HEADER] === '1') req.headers[NEXT_ROUTER_PREFETCH_HEADER] ===
NEXT_ROUTER_PREFETCH_STATIC)
// This page supports PPR if it is marked as being `PARTIALLY_STATIC` in the // This page supports PPR if it is marked as being `PARTIALLY_STATIC` in the
// prerender manifest and this is an app page. // prerender manifest and this is an app page.
......
...@@ -132,10 +132,12 @@ type InternalLinkProps = { ...@@ -132,10 +132,12 @@ type InternalLinkProps = {
* Prefetching is only enabled in production. * Prefetching is only enabled in production.
* *
* - In the **App Router**: * - In the **App Router**:
* - `"auto"`, `null`, `undefined` (default): Prefetch behavior depends on static vs dynamic routes: * - `"auto"`, `"shell"`, `null`, `undefined` (default): Prefetch behavior depends on static vs dynamic routes:
* - Static routes: fully prefetched * - Static routes: fully prefetched
* - Dynamic routes: partial prefetch to the nearest segment with a `loading.js` * - Dynamic routes: partial prefetch to the nearest segment with a `loading.js`
* - `true`: Always prefetch the full route and data. * - `true` or `"prefetch"`: Always prefetch the full route and data.
* - `"navigation"`: Prefetch up to where `navigation()` resolves. Without
* Partial Prefetching, this is the same as `true`.
* - `false`: Disable prefetching on both viewport and hover. * - `false`: Disable prefetching on both viewport and hover.
* - In the **Pages Router**: * - In the **Pages Router**:
* - `true` (default): Prefetches the route and data in the background on viewport or hover. * - `true` (default): Prefetches the route and data in the background on viewport or hover.
...@@ -150,7 +152,7 @@ type InternalLinkProps = { ...@@ -150,7 +152,7 @@ type InternalLinkProps = {
* </Link> * </Link>
* ``` * ```
*/ */
prefetch?: boolean | 'auto' | null prefetch?: boolean | 'auto' | 'shell' | 'prefetch' | 'navigation' | null
/** /**
* (unstable) Switch to a full prefetch on hover. Effectively the same as * (unstable) Switch to a full prefetch on hover. Effectively the same as
...@@ -376,12 +378,24 @@ export default function LinkComponent( ...@@ -376,12 +378,24 @@ export default function LinkComponent(
const router = React.useContext(AppRouterContext) const router = React.useContext(AppRouterContext)
const prefetchEnabled = prefetchProp !== false const prefetchEnabled = prefetchProp !== false
const prefetchIntent: RouterTransitionPrefetchIntent =
prefetchProp === false ? 'none' : prefetchProp === true ? 'full' : 'auto'
// TODO: it makes no sense to assign a stage when prefetching is disabled. // TODO: it makes no sense to assign a stage when prefetching is disabled.
const prefetchStage = let prefetchStage: AppStage
prefetchProp === true ? AppStage.Prefetch : AppStage.Shell switch (prefetchProp) {
case true:
case 'prefetch':
prefetchStage = AppStage.Prefetch
break
case 'navigation':
prefetchStage = AppStage.Navigation
break
case false:
case 'auto':
case 'shell':
case null:
default:
prefetchStage = AppStage.Shell
break
}
if (process.env.NODE_ENV !== 'production') { if (process.env.NODE_ENV !== 'production') {
function createPropError(args: { function createPropError(args: {
...@@ -484,11 +498,15 @@ export default function LinkComponent( ...@@ -484,11 +498,15 @@ export default function LinkComponent(
if ( if (
props[key] != null && props[key] != null &&
valType !== 'boolean' && valType !== 'boolean' &&
props[key] !== 'auto' props[key] !== 'auto' &&
props[key] !== 'shell' &&
props[key] !== 'prefetch' &&
props[key] !== 'navigation'
) { ) {
throw createPropError({ throw createPropError({
key, key,
expected: '`boolean | "auto"`', expected:
'`boolean | "auto" | "shell" | "prefetch" | "navigation"`',
actual: valType, actual: valType,
}) })
} }
...@@ -685,6 +703,17 @@ export default function LinkComponent( ...@@ -685,6 +703,17 @@ export default function LinkComponent(
if (e.defaultPrevented) { if (e.defaultPrevented) {
return return
} }
// This is only reported to `onRouterTransitionStart`, which is public
// API, so every value that asks for more than the shell is reported as
// `'full'`.
const prefetchIntent: RouterTransitionPrefetchIntent =
prefetchProp === false
? 'none'
: prefetchProp === true ||
prefetchProp === 'prefetch' ||
prefetchProp === 'navigation'
? 'full'
: 'auto'
linkClicked( linkClicked(
e, e,
formattedHref, formattedHref,
......
...@@ -5,6 +5,15 @@ export const ACTION_HEADER = 'next-action' as const ...@@ -5,6 +5,15 @@ export const ACTION_HEADER = 'next-action' as const
// prefetches, which also need to specify a particular segment. // prefetches, which also need to specify a particular segment.
export const NEXT_ROUTER_STATE_TREE_HEADER = 'next-router-state-tree' as const export const NEXT_ROUTER_STATE_TREE_HEADER = 'next-router-state-tree' as const
export const NEXT_ROUTER_PREFETCH_HEADER = 'next-router-prefetch' as const export const NEXT_ROUTER_PREFETCH_HEADER = 'next-router-prefetch' as const
// The values of NEXT_ROUTER_PREFETCH_HEADER. A static prefetch can be answered
// from the prerender. It's also how we ask for the legacy prefetch up to the
// loading boundary.
export const NEXT_ROUTER_PREFETCH_STATIC = '1' as const
// A runtime prefetch, rendered with cookies, headers and params, up to the
// stage it names.
export const NEXT_ROUTER_PREFETCH_RUNTIME_PREFETCH = '2' as const
export const NEXT_ROUTER_PREFETCH_RUNTIME_SHELL = '3' as const
export const NEXT_ROUTER_PREFETCH_RUNTIME_NAVIGATION = '4' as const
// This contains the path to the segment being prefetched. // This contains the path to the segment being prefetched.
// TODO: If we change next-router-state-tree to be a segment path, we can use // TODO: If we change next-router-state-tree to be a segment path, we can use
// that instead. Then next-router-prefetch and next-router-segment-prefetch can // that instead. Then next-router-prefetch and next-router-segment-prefetch can
......
...@@ -261,10 +261,11 @@ export function navigateToKnownRoute( ...@@ -261,10 +261,11 @@ export function navigateToKnownRoute(
process.env.NODE_ENV !== 'production' && process.env.NODE_ENV !== 'production' &&
process.env.__NEXT_CACHE_COMPONENTS process.env.__NEXT_CACHE_COMPONENTS
) { ) {
// Warn when navigating via a `<Link prefetch={true}>` to a route that has // Warn when navigating via a link that asks for more than the shell, like
// not opted into Partial Prefetching. Such a link does a legacy "full" // `<Link prefetch={true}>`, to a route that has not opted into Partial
// prefetch that includes the route's dynamic data, defeating the // Prefetching. Such a link does a legacy "full" prefetch that includes the
// static/dynamic split that Cache Components provides. // route's dynamic data, defeating the static/dynamic split that Cache
// Components provides.
// //
// This runs at navigation time (rather than prefetch time) so that, in dev // This runs at navigation time (rather than prefetch time) so that, in dev
// where we don't prefetch, the warning only appears when you actually // where we don't prefetch, the warning only appears when you actually
...@@ -288,7 +289,7 @@ export function navigateToKnownRoute( ...@@ -288,7 +289,7 @@ export function navigateToKnownRoute(
if (ownerStack === undefined) { if (ownerStack === undefined) {
console.error( console.error(
'' + '' +
'Cannot associate the "prefetch={true}" warning with a specific <Link> making it harder to find the cause of the following warning. ' + 'Cannot associate the prefetch warning with a specific <Link> making it harder to find the cause of the following warning. ' +
'This is a bug in Next.js.' 'This is a bug in Next.js.'
) )
} else if (ownerStack !== null) { } else if (ownerStack !== null) {
......
...@@ -31,17 +31,22 @@ export function prefetchRoute(href: string, options?: PrefetchOptions): void { ...@@ -31,17 +31,22 @@ export function prefetchRoute(href: string, options?: PrefetchOptions): void {
} }
const prefetchKind = options?.kind ?? 'auto' const prefetchKind = options?.kind ?? 'auto'
// We don't currently offer a way to issue a runtime prefetch via `router.prefetch()`.
let prefetchStage: AppStage let prefetchStage: AppStage
switch (prefetchKind) { switch (prefetchKind) {
case 'auto': { case 'auto':
case 'shell': {
prefetchStage = AppStage.Shell prefetchStage = AppStage.Shell
break break
} }
case 'full': { case 'full':
case 'prefetch': {
prefetchStage = AppStage.Prefetch prefetchStage = AppStage.Prefetch
break break
} }
case 'navigation': {
prefetchStage = AppStage.Navigation
break
}
default: { default: {
prefetchKind satisfies never prefetchKind satisfies never
// Despite typescript thinking that this can't happen, // Despite typescript thinking that this can't happen,
......
...@@ -14,6 +14,10 @@ import type { ...@@ -14,6 +14,10 @@ import type {
import { import {
type NEXT_ROUTER_PREFETCH_HEADER, type NEXT_ROUTER_PREFETCH_HEADER,
type NEXT_ROUTER_PREFETCH_STATIC,
type NEXT_ROUTER_PREFETCH_RUNTIME_PREFETCH,
type NEXT_ROUTER_PREFETCH_RUNTIME_SHELL,
type NEXT_ROUTER_PREFETCH_RUNTIME_NAVIGATION,
type NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, type NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_ROUTER_STATE_TREE_HEADER, NEXT_ROUTER_STATE_TREE_HEADER,
NEXT_RSC_UNION_QUERY, NEXT_RSC_UNION_QUERY,
...@@ -103,7 +107,11 @@ export type RequestHeaders = { ...@@ -103,7 +107,11 @@ export type RequestHeaders = {
[RSC_HEADER]?: '1' [RSC_HEADER]?: '1'
[NEXT_ROUTER_STATE_TREE_HEADER]?: string [NEXT_ROUTER_STATE_TREE_HEADER]?: string
[NEXT_URL]?: string [NEXT_URL]?: string
[NEXT_ROUTER_PREFETCH_HEADER]?: '1' | '2' | '3' [NEXT_ROUTER_PREFETCH_HEADER]?:
| typeof NEXT_ROUTER_PREFETCH_STATIC
| typeof NEXT_ROUTER_PREFETCH_RUNTIME_PREFETCH
| typeof NEXT_ROUTER_PREFETCH_RUNTIME_SHELL
| typeof NEXT_ROUTER_PREFETCH_RUNTIME_NAVIGATION
[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]?: string [NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]?: string
'x-deployment-id'?: string 'x-deployment-id'?: string
[NEXT_HMR_REFRESH_HEADER]?: '1' [NEXT_HMR_REFRESH_HEADER]?: '1'
......
...@@ -141,11 +141,18 @@ export interface ServerPatchAction { ...@@ -141,11 +141,18 @@ export interface ServerPatchAction {
* PrefetchKind defines the type of prefetching that should be done. * PrefetchKind defines the type of prefetching that should be done.
* - `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully. * - `auto` - if the page is dynamic, prefetch the page data partially, if static prefetch the page data fully.
* - `full` - prefetch the page data fully. * - `full` - prefetch the page data fully.
* - `shell` - the same as `auto`, named after the stage it prefetches.
* - `prefetch` - the same as `full`, named after the stage it prefetches.
* - `navigation` - prefetch up to where `navigation()` resolves. Without
* Partial Prefetching, this is the same as `full`.
*/ */
export enum PrefetchKind { export enum PrefetchKind {
AUTO = 'auto', AUTO = 'auto',
FULL = 'full', FULL = 'full',
SHELL = 'shell',
PREFETCH = 'prefetch',
NAVIGATION = 'navigation',
} }
export interface PushRef { export interface PushRef {
......
...@@ -880,21 +880,24 @@ function pingRootRouteTree( ...@@ -880,21 +880,24 @@ function pingRootRouteTree(
// Pick the stage to prefetch up to on this pass. During the Shell // Pick the stage to prefetch up to on this pass. During the Shell
// phase, we request each segment's shell (keyed at the shell vary // phase, we request each segment's shell (keyed at the shell vary
// paths). Otherwise, we go up to the prefetch stage. This is the only // paths). Otherwise, we go up to the stage the link asked for. This is
// place we look at the phase. Everything below just uses the stage. // the only place we look at the phase. Everything below just uses the
const walkStage = // stage. (What each segment needs at that stage is
task.phase === PrefetchPhase.Shell // getWalkCompleteness.)
? AppStage.Shell let walkStage: AppStage
: AppStage.Prefetch if (task.phase === PrefetchPhase.Shell) {
walkStage = AppStage.Shell
// Under Partial Prefetching, a link asking for the shell is done } else if (walkCanUseRuntimeRequests(route)) {
// after the Shell phase. if (task.prefetchStage === AppStage.Shell) {
if ( // A link asking for the shell is done after the Shell phase.
walkStage !== AppStage.Shell && return PrefetchTaskExitStatus.Done
walkCanUseRuntimeRequests(route) && }
task.prefetchStage === AppStage.Shell walkStage = task.prefetchStage
) { } else {
return PrefetchTaskExitStatus.Done // Without Partial Prefetching, only a link asking for the shell gets
// here. A static request is the only kind we can make, and it
// returns the whole prerender, so we go up to the navigation stage.
walkStage = AppStage.Navigation
} }
// The head is a one-node tree next to the route tree (see // The head is a one-node tree next to the route tree (see
...@@ -1145,7 +1148,7 @@ function getWalkCompleteness(route: FulfilledRouteCacheEntry): Completeness { ...@@ -1145,7 +1148,7 @@ function getWalkCompleteness(route: FulfilledRouteCacheEntry): Completeness {
* `walkCanUseRuntimeRequests` is true. * `walkCanUseRuntimeRequests` is true.
* */ * */
function shouldSegmentAttemptStaticRequest( function shouldSegmentAttemptStaticRequest(
walkStage: AppStage.Shell | AppStage.Prefetch, walkStage: AppStage,
tree: RouteTree<any> tree: RouteTree<any>
): boolean { ): boolean {
const { prefetchHints } = tree const { prefetchHints } = tree
...@@ -1154,6 +1157,8 @@ function shouldSegmentAttemptStaticRequest( ...@@ -1154,6 +1157,8 @@ function shouldSegmentAttemptStaticRequest(
return (prefetchHints & PrefetchHint.ShouldAttemptStaticShell) !== 0 return (prefetchHints & PrefetchHint.ShouldAttemptStaticShell) !== 0
case AppStage.Prefetch: case AppStage.Prefetch:
return (prefetchHints & PrefetchHint.ShouldAttemptStaticPrefetch) !== 0 return (prefetchHints & PrefetchHint.ShouldAttemptStaticPrefetch) !== 0
case AppStage.Navigation:
return (prefetchHints & PrefetchHint.ShouldAttemptStaticNavigation) !== 0
default: default:
walkStage satisfies never walkStage satisfies never
return false return false
...@@ -1203,7 +1208,7 @@ function isShellEntryEligibleForStaticAttempt( ...@@ -1203,7 +1208,7 @@ function isShellEntryEligibleForStaticAttempt(
map: CacheMap<SegmentCacheEntry>, map: CacheMap<SegmentCacheEntry>,
entry: SegmentCacheEntry, entry: SegmentCacheEntry,
tree: RouteTree<null>, tree: RouteTree<null>,
walkStage: AppStage.Shell | AppStage.Prefetch walkStage: AppStage
): boolean { ): boolean {
if (walkStage === AppStage.Shell) { if (walkStage === AppStage.Shell) {
// A shell prefetch never tries a static request for a shell entry. The // A shell prefetch never tries a static request for a shell entry. The
...@@ -1214,7 +1219,7 @@ function isShellEntryEligibleForStaticAttempt( ...@@ -1214,7 +1219,7 @@ function isShellEntryEligibleForStaticAttempt(
if (entry.stage !== AppStage.Shell) { if (entry.stage !== AppStage.Shell) {
return false return false
} }
if (!shouldSegmentAttemptStaticRequest(AppStage.Prefetch, tree)) { if (!shouldSegmentAttemptStaticRequest(walkStage, tree)) {
return false return false
} }
const revalidatingEntry = readOrCreateRevalidatingSegmentEntry( const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(
...@@ -1283,7 +1288,7 @@ function pingSharedPartOfCacheComponentsTree( ...@@ -1283,7 +1288,7 @@ function pingSharedPartOfCacheComponentsTree(
newTree: RouteTree<null>, newTree: RouteTree<null>,
parentBundle: SegmentBundle | null, parentBundle: SegmentBundle | null,
// The stage this pass prefetches up to (see pingRootRouteTree). // The stage this pass prefetches up to (see pingRootRouteTree).
walkStage: AppStage.Shell | AppStage.Prefetch walkStage: AppStage
): PrefetchTaskExitStatus.InProgress | PrefetchTaskExitStatus.Done { ): PrefetchTaskExitStatus.InProgress | PrefetchTaskExitStatus.Done {
if (!doesRouteStructureMatch(currentTree, newTree)) { if (!doesRouteStructureMatch(currentTree, newTree)) {
// We're entering the part of the target route that doesn't exist on the // We're entering the part of the target route that doesn't exist on the
...@@ -1401,7 +1406,7 @@ function pingNewPartOfCacheComponentsTree( ...@@ -1401,7 +1406,7 @@ function pingNewPartOfCacheComponentsTree(
tree: RouteTree<null>, tree: RouteTree<null>,
parentBundle: SegmentBundle | null, parentBundle: SegmentBundle | null,
// The stage this pass prefetches up to (see pingRootRouteTree). // The stage this pass prefetches up to (see pingRootRouteTree).
walkStage: AppStage.Shell | AppStage.Prefetch walkStage: AppStage
): PrefetchTaskExitStatus.InProgress | PrefetchTaskExitStatus.Done { ): PrefetchTaskExitStatus.InProgress | PrefetchTaskExitStatus.Done {
const accumulation = pingSegmentInCacheComponentsTree( const accumulation = pingSegmentInCacheComponentsTree(
now, now,
...@@ -1491,7 +1496,7 @@ function pingSegmentInCacheComponentsTree( ...@@ -1491,7 +1496,7 @@ function pingSegmentInCacheComponentsTree(
tree: RouteTree<null>, tree: RouteTree<null>,
parentBundle: SegmentBundle | null, parentBundle: SegmentBundle | null,
// The stage this pass prefetches up to (see pingRootRouteTree). // The stage this pass prefetches up to (see pingRootRouteTree).
walkStage: AppStage.Shell | AppStage.Prefetch walkStage: AppStage
): { bundle: SegmentBundle | null; needsRuntimeRequest: boolean } | null { ): { bundle: SegmentBundle | null; needsRuntimeRequest: boolean } | null {
// Constant for the whole pass; recomputed here only because the walk is // Constant for the whole pass; recomputed here only because the walk is
// recursive and the check is cheap. // recursive and the check is cheap.
...@@ -2046,7 +2051,7 @@ function pingRuntimePrefetches( ...@@ -2046,7 +2051,7 @@ function pingRuntimePrefetches(
spawnedRuntimePrefetches: Set<SegmentRequestKey>, spawnedRuntimePrefetches: Set<SegmentRequestKey>,
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>, spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,
// The walk's stage, which the runtime request runs at. // The walk's stage, which the runtime request runs at.
stage: AppStage.Shell | AppStage.Prefetch stage: AppStage
): FlightRouterState { ): FlightRouterState {
// Construct a request tree (FlightRouterState) for a runtime prefetch. If // Construct a request tree (FlightRouterState) for a runtime prefetch. If
// a segment is part of the runtime prefetch, the tree is constructed by // a segment is part of the runtime prefetch, the tree is constructed by
...@@ -2116,7 +2121,7 @@ function pingSegmentBundle( ...@@ -2116,7 +2121,7 @@ function pingSegmentBundle(
tree: RouteTree<null>, tree: RouteTree<null>,
segments: SegmentBundle, segments: SegmentBundle,
// The stage this pass prefetches up to (see pingRootRouteTree). // The stage this pass prefetches up to (see pingRootRouteTree).
walkStage: AppStage.Shell | AppStage.Prefetch, walkStage: AppStage,
// False when finishing an open bundle chain on a runtime-prefetch bailout // False when finishing an open bundle chain on a runtime-prefetch bailout
// (finishStaticBundleOnRuntimeBailout). The finish exists only to fetch // (finishStaticBundleOnRuntimeBailout). The finish exists only to fetch
// data the batched runtime request won't cover — Empty entries in the // data the batched runtime request won't cover — Empty entries in the
...@@ -2383,10 +2388,9 @@ function accumulateSegmentBundle( ...@@ -2383,10 +2388,9 @@ function accumulateSegmentBundle(
route: FulfilledRouteCacheEntry, route: FulfilledRouteCacheEntry,
tree: RouteTree<null>, tree: RouteTree<null>,
parentBundle: SegmentBundle | null, parentBundle: SegmentBundle | null,
// The stage this pass prefetches up to (see pingRootRouteTree). Usually // The stage this pass prefetches up to (see pingRootRouteTree). During the
// Prefetch. During the Shell phase it's Shell, and the entries are keyed at // Shell phase it's Shell, and the entries are keyed at the shell vary paths.
// the shell vary paths. walkStage: AppStage,
walkStage: AppStage.Shell | AppStage.Prefetch,
// False when finishing a chain on a runtime-prefetch bailout; see // False when finishing a chain on a runtime-prefetch bailout; see
// pingSegmentBundle. // pingSegmentBundle.
spawnRevalidations: boolean spawnRevalidations: boolean
...@@ -2514,7 +2518,7 @@ function finishStaticBundleOnRuntimeBailout( ...@@ -2514,7 +2518,7 @@ function finishStaticBundleOnRuntimeBailout(
// The same walk stage the parent bundle was accumulated with. // The same walk stage the parent bundle was accumulated with.
// Any needs-runtime signal from finishing the bundle is dropped: the // Any needs-runtime signal from finishing the bundle is dropped: the
// caller is already deopting this subtree to a runtime prefetch. // caller is already deopting this subtree to a runtime prefetch.
walkStage: AppStage.Shell | AppStage.Prefetch walkStage: AppStage
): void { ): void {
const bundle = accumulateSegmentBundle( const bundle = accumulateSegmentBundle(
now, now,
......
...@@ -73,7 +73,8 @@ type InternalLinkProps = { ...@@ -73,7 +73,8 @@ type InternalLinkProps = {
* *
* In App Router: * In App Router:
* - "auto", null, undefined (default): For statically generated pages, this will prefetch the full React Server Component data. For dynamic pages, this will prefetch up to the nearest route segment with a [`loading.js`](https://nextjs.org/docs/app/api-reference/file-conventions/loading) file. If there is no loading file, it will not fetch the full tree to avoid fetching too much data. * - "auto", null, undefined (default): For statically generated pages, this will prefetch the full React Server Component data. For dynamic pages, this will prefetch up to the nearest route segment with a [`loading.js`](https://nextjs.org/docs/app/api-reference/file-conventions/loading) file. If there is no loading file, it will not fetch the full tree to avoid fetching too much data.
* - `true`: This will prefetch the full React Server Component data for all route segments, regardless of whether they contain a segment with `loading.js`. * - `true` or `"prefetch"`: This will prefetch the full React Server Component data for all route segments, regardless of whether they contain a segment with `loading.js`.
* - `"navigation"`: This will prefetch up to where `navigation()` resolves. Without Partial Prefetching, this is the same as `true`.
* - `false`: This will not prefetch any data, even on hover. * - `false`: This will not prefetch any data, even on hover.
* *
* In Pages Router: * In Pages Router:
...@@ -81,7 +82,7 @@ type InternalLinkProps = { ...@@ -81,7 +82,7 @@ type InternalLinkProps = {
* - `false`: Prefetching will not happen when entering the viewport, but will still happen on hover. * - `false`: Prefetching will not happen when entering the viewport, but will still happen on hover.
* @defaultValue `true` (pages router) or `null` (app router) * @defaultValue `true` (pages router) or `null` (app router)
*/ */
prefetch?: boolean | 'auto' | null prefetch?: boolean | 'auto' | 'shell' | 'prefetch' | 'navigation' | null
/** /**
* The active locale is automatically prepended. `locale` allows for providing a different locale. * The active locale is automatically prepended. `locale` allows for providing a different locale.
* When `false` `href` has to include the locale as the default behavior is disabled. * When `false` `href` has to include the locale as the default behavior is disabled.
...@@ -450,11 +451,15 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>( ...@@ -450,11 +451,15 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
if ( if (
props[key] != null && props[key] != null &&
valType !== 'boolean' && valType !== 'boolean' &&
props[key] !== 'auto' props[key] !== 'auto' &&
props[key] !== 'shell' &&
props[key] !== 'prefetch' &&
props[key] !== 'navigation'
) { ) {
throw createPropError({ throw createPropError({
key, key,
expected: '`boolean | "auto"`', expected:
'`boolean | "auto" | "shell" | "prefetch" | "navigation"`',
actual: valType, actual: valType,
}) })
} }
......
...@@ -82,6 +82,7 @@ import { ...@@ -82,6 +82,7 @@ import {
NEXT_ROUTER_STALE_TIME_HEADER, NEXT_ROUTER_STALE_TIME_HEADER,
NEXT_URL, NEXT_URL,
} from '../../client/components/app-router-headers' } from '../../client/components/app-router-headers'
import { AppStage } from '../../client/components/segment-cache/types'
import { createMetadataContext } from '../../lib/metadata/metadata-context' import { createMetadataContext } from '../../lib/metadata/metadata-context'
import { import {
createRequestStore as createRequestStoreFromInputs, createRequestStore as createRequestStoreFromInputs,
...@@ -1475,7 +1476,8 @@ async function generateDynamicFlightRenderResultWithStagesInDev( ...@@ -1475,7 +1476,8 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
async function generateRuntimePrefetchResult( async function generateRuntimePrefetchResult(
ctx: AppRenderContext, ctx: AppRenderContext,
requestStore: RequestStore, requestStore: RequestStore,
isShellPrefetch: boolean // The stage the runtime prefetch asks for.
stage: AppStage
): Promise<RenderResult> { ): Promise<RenderResult> {
const { workStore, renderOpts, htmlRequestId, requestId } = ctx const { workStore, renderOpts, htmlRequestId, requestId } = ctx
const { const {
...@@ -1520,12 +1522,24 @@ async function generateRuntimePrefetchResult( ...@@ -1520,12 +1522,24 @@ async function generateRuntimePrefetchResult(
requestStore.resumeDataCache ?? undefined requestStore.resumeDataCache ?? undefined
) )
const mode: RuntimePrerenderMode = isShellPrefetch let mode: RuntimePrerenderMode
? { type: 'session-shell-only' } switch (stage) {
: { case AppStage.Shell:
mode = { type: 'session-shell-only' }
break
case AppStage.Prefetch:
mode = {
type: 'rewindable-session-shell', type: 'rewindable-session-shell',
stageByteLengthsDeferred: createPromiseWithResolvers(), stageByteLengthsDeferred: createPromiseWithResolvers(),
} }
break
case AppStage.Navigation:
mode = {
type: 'navigation',
stageByteLengthsDeferred: createPromiseWithResolvers(),
}
break
}
await prospectiveRuntimeServerPrerender( await prospectiveRuntimeServerPrerender(
ctx, ctx,
...@@ -1553,9 +1567,9 @@ async function generateRuntimePrefetchResult( ...@@ -1553,9 +1567,9 @@ async function generateRuntimePrefetchResult(
// A runtime shell render stops at the shell stage, so the shell ends // A runtime shell render stops at the shell stage, so the shell ends
// at the end of the response. // at the end of the response.
stageByteLengthsPromise: stageByteLengthsPromise:
mode.type === 'rewindable-session-shell' mode.type === 'session-shell-only'
? mode.stageByteLengthsDeferred.promise ? Promise.resolve([])
: Promise.resolve([]), : mode.stageByteLengthsDeferred.promise,
}), }),
prerenderResumeDataCache, prerenderResumeDataCache,
rootParams, rootParams,
...@@ -2943,8 +2957,7 @@ async function renderAppPage( ...@@ -2943,8 +2957,7 @@ async function renderAppPage(
isHmrRefresh, isHmrRefresh,
isPrefetchRequest, isPrefetchRequest,
isRSCRequest, isRSCRequest,
isRuntimePrefetchRequest, runtimePrefetchStage,
isAppShellPrefetchRequest,
isRouteTreePrefetchRequest, isRouteTreePrefetchRequest,
} = parsedRequestHeaders } = parsedRequestHeaders
const isPossibleActionRequest = ctx.isPossibleServerAction const isPossibleActionRequest = ctx.isPossibleServerAction
...@@ -2989,8 +3002,7 @@ async function renderAppPage( ...@@ -2989,8 +3002,7 @@ async function renderAppPage(
!cacheComponents && !cacheComponents &&
!isPossibleActionRequest && !isPossibleActionRequest &&
!isPrefetchRequest && !isPrefetchRequest &&
!isRuntimePrefetchRequest && runtimePrefetchStage === null &&
!isAppShellPrefetchRequest &&
!isRouteTreePrefetchRequest !isRouteTreePrefetchRequest
? setIsrStatus ? setIsrStatus
: undefined : undefined
...@@ -3007,12 +3019,12 @@ async function renderAppPage( ...@@ -3007,12 +3019,12 @@ async function renderAppPage(
// MARK: RSC request // MARK: RSC request
if (isRSCRequest) { if (isRSCRequest) {
if (isRuntimePrefetchRequest) { if (runtimePrefetchStage !== null) {
// MARK: RSC runtimePrefetch // MARK: RSC runtimePrefetch
return generateRuntimePrefetchResult( return generateRuntimePrefetchResult(
ctx, ctx,
requestStore, requestStore,
isAppShellPrefetchRequest runtimePrefetchStage
) )
} else { } else {
if ( if (
...@@ -9823,8 +9835,9 @@ async function prerenderToStream( ...@@ -9823,8 +9835,9 @@ async function prerenderToStream(
// which is scheduled in a (fast) immediate, so we do this in a separate task // which is scheduled in a (fast) immediate, so we do this in a separate task
// (fast immediates will be drained at the end of the task, so in the next task we know we're done flushing) // (fast immediates will be drained at the end of the task, so in the next task we know we're done flushing)
// List where the shell ends, if new chunks were emitted after // If anything was emitted after the shell, list where the shell
// unblocking link data or navigation(). // ends. Then, if anything was emitted after `navigation()` resolved,
// list where the prefetch stage ends.
// NOTE: we must capture this *before* resolving staleTime/varyParams, // NOTE: we must capture this *before* resolving staleTime/varyParams,
// which always emit new static chunks. // which always emit new static chunks.
const stageByteLengths: Array<number> = [] const stageByteLengths: Array<number> = []
...@@ -9837,6 +9850,16 @@ async function prerenderToStream( ...@@ -9837,6 +9850,16 @@ async function prerenderToStream(
collectedChunksByStage[RenderStage.ShellStatic] collectedChunksByStage[RenderStage.ShellStatic]
) )
) )
if (
collectedChunksByStage[RenderStage.NavigationStatic].length >
collectedChunksByStage[RenderStage.PrefetchStatic].length
) {
stageByteLengths.push(
getTotalByteLength(
collectedChunksByStage[RenderStage.PrefetchStatic]
)
)
}
} }
// Now that the prerendering is complete, we know the final stale // Now that the prerendering is complete, we know the final stale
...@@ -9901,10 +9924,11 @@ async function prerenderToStream( ...@@ -9901,10 +9924,11 @@ async function prerenderToStream(
const { const {
shouldAttemptStaticShell: shellIsStatic, shouldAttemptStaticShell: shellIsStatic,
shouldAttemptStaticPrefetch: prefetchIsStatic, shouldAttemptStaticPrefetch: prefetchIsStatic,
shouldAttemptStaticNavigation: navigationIsStatic,
} = prerenderDataTracking } = prerenderDataTracking
const label = (isStatic: boolean) => (isStatic ? 'static' : 'runtime') const label = (isStatic: boolean) => (isStatic ? 'static' : 'runtime')
console.log( console.log(
`Route ${workStore.route} :: hints: shell=${label(shellIsStatic)}, prefetch=${label(prefetchIsStatic)}` `Route ${workStore.route} :: hints: shell=${label(shellIsStatic)}, prefetch=${label(prefetchIsStatic)}, navigation=${label(navigationIsStatic)}`
) )
} }
await collectSegmentData( await collectSegmentData(
...@@ -11188,12 +11212,14 @@ async function collectSegmentData( ...@@ -11188,12 +11212,14 @@ async function collectSegmentData(
const { const {
shouldAttemptStaticShell = false, shouldAttemptStaticShell = false,
shouldAttemptStaticPrefetch = false, shouldAttemptStaticPrefetch = false,
shouldAttemptStaticNavigation = false,
} = prerenderDataTracking ?? {} } = prerenderDataTracking ?? {}
if ( if (
prefetchInlining || prefetchInlining ||
shouldAttemptStaticShell || shouldAttemptStaticShell ||
shouldAttemptStaticPrefetch shouldAttemptStaticPrefetch ||
shouldAttemptStaticNavigation
) { ) {
// Build time: compute fresh hints and store in metadata for the // Build time: compute fresh hints and store in metadata for the
// manifest. When prefetch inlining is disabled there are no sizes to // manifest. When prefetch inlining is disabled there are no sizes to
...@@ -11207,7 +11233,8 @@ async function collectSegmentData( ...@@ -11207,7 +11233,8 @@ async function collectSegmentData(
serverConsumerManifest, serverConsumerManifest,
prefetchInlining, prefetchInlining,
shouldAttemptStaticShell, shouldAttemptStaticShell,
shouldAttemptStaticPrefetch shouldAttemptStaticPrefetch,
shouldAttemptStaticNavigation
) )
metadata.prefetchHints = hints metadata.prefetchHints = hints
} else { } else {
......
...@@ -99,6 +99,10 @@ import { ...@@ -99,6 +99,10 @@ import {
NEXT_REQUEST_ID_HEADER, NEXT_REQUEST_ID_HEADER,
NEXT_RSC_UNION_QUERY, NEXT_RSC_UNION_QUERY,
NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_PREFETCH_STATIC,
NEXT_ROUTER_PREFETCH_RUNTIME_PREFETCH,
NEXT_ROUTER_PREFETCH_RUNTIME_SHELL,
NEXT_ROUTER_PREFETCH_RUNTIME_NAVIGATION,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_URL, NEXT_URL,
NEXT_ROUTER_STATE_TREE_HEADER, NEXT_ROUTER_STATE_TREE_HEADER,
...@@ -678,7 +682,7 @@ export default abstract class Server< ...@@ -678,7 +682,7 @@ export default abstract class Server<
// Mark the request as a router prefetch request. // Mark the request as a router prefetch request.
req.headers[RSC_HEADER] = '1' req.headers[RSC_HEADER] = '1'
req.headers[NEXT_ROUTER_PREFETCH_HEADER] = '1' req.headers[NEXT_ROUTER_PREFETCH_HEADER] = NEXT_ROUTER_PREFETCH_STATIC
req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] = segmentPath req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] = segmentPath
addRequestMeta(req, 'isRSCRequest', true) addRequestMeta(req, 'isRSCRequest', true)
...@@ -705,7 +709,9 @@ export default abstract class Server< ...@@ -705,7 +709,9 @@ export default abstract class Server<
} else if (isRSCRequestHeader(req.headers[RSC_HEADER])) { } else if (isRSCRequestHeader(req.headers[RSC_HEADER])) {
addRequestMeta(req, 'isRSCRequest', true) addRequestMeta(req, 'isRSCRequest', true)
if (req.headers[NEXT_ROUTER_PREFETCH_HEADER] === '1') { if (
req.headers[NEXT_ROUTER_PREFETCH_HEADER] === NEXT_ROUTER_PREFETCH_STATIC
) {
addRequestMeta(req, 'isPrefetchRSCRequest', true) addRequestMeta(req, 'isPrefetchRSCRequest', true)
const segmentPrefetchRSCRequest = const segmentPrefetchRSCRequest =
...@@ -2431,17 +2437,18 @@ export default abstract class Server< ...@@ -2431,17 +2437,18 @@ export default abstract class Server<
const prefetchHeaderValue = headers[NEXT_ROUTER_PREFETCH_HEADER] const prefetchHeaderValue = headers[NEXT_ROUTER_PREFETCH_HEADER]
const routerPrefetch = const routerPrefetch =
prefetchHeaderValue !== undefined prefetchHeaderValue !== undefined
? // We only recognize '1', '2', and '3'. Strip all other values here. ? // We only recognize the values we send. Strip all others here.
prefetchHeaderValue === '1' || prefetchHeaderValue === NEXT_ROUTER_PREFETCH_STATIC ||
prefetchHeaderValue === '2' || prefetchHeaderValue === NEXT_ROUTER_PREFETCH_RUNTIME_PREFETCH ||
prefetchHeaderValue === '3' prefetchHeaderValue === NEXT_ROUTER_PREFETCH_RUNTIME_SHELL ||
prefetchHeaderValue === NEXT_ROUTER_PREFETCH_RUNTIME_NAVIGATION
? prefetchHeaderValue ? prefetchHeaderValue
: undefined : undefined
: // For runtime prefetches, we always perform a dynamic request, : // For runtime prefetches, we always perform a dynamic request,
// so we don't expect the header to be stripped by an intermediate layer. // so we don't expect the header to be stripped by an intermediate layer.
// This should only happen for static prefetches, so we only handle those here. // This should only happen for static prefetches, so we only handle those here.
getRequestMeta(req, 'isPrefetchRSCRequest') getRequestMeta(req, 'isPrefetchRSCRequest')
? '1' ? NEXT_ROUTER_PREFETCH_STATIC
: undefined : undefined
const segmentPrefetchRSCRequest = const segmentPrefetchRSCRequest =
......
...@@ -28,6 +28,7 @@ import type { ParsedRequestHeaders } from './parse-request-headers' ...@@ -28,6 +28,7 @@ import type { ParsedRequestHeaders } from './parse-request-headers'
import type { ServerActionRequestMetadata } from '../../lib/server-action-request-meta' import type { ServerActionRequestMetadata } from '../../lib/server-action-request-meta'
import { import {
NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_PREFETCH_STATIC,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_ROUTER_STATE_TREE_HEADER, NEXT_ROUTER_STATE_TREE_HEADER,
NEXT_URL, NEXT_URL,
...@@ -152,7 +153,7 @@ export class AppPageRouteModule extends RouteModule< ...@@ -152,7 +153,7 @@ export class AppPageRouteModule extends RouteModule<
// Mark the request as a router prefetch request. // Mark the request as a router prefetch request.
req.headers[RSC_HEADER] = '1' req.headers[RSC_HEADER] = '1'
req.headers[NEXT_ROUTER_PREFETCH_HEADER] = '1' req.headers[NEXT_ROUTER_PREFETCH_HEADER] = NEXT_ROUTER_PREFETCH_STATIC
req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] = segmentPath req.headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] = segmentPath
addRequestMeta(req, 'isRSCRequest', true) addRequestMeta(req, 'isRSCRequest', true)
......
...@@ -2,6 +2,7 @@ import type { IncomingMessage } from 'http' ...@@ -2,6 +2,7 @@ import type { IncomingMessage } from 'http'
import { import {
NEXT_ROUTER_PREFETCH_HEADER, NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_PREFETCH_STATIC,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
RSC_HEADER, RSC_HEADER,
} from '../../../client/components/app-router-headers' } from '../../../client/components/app-router-headers'
...@@ -31,7 +32,8 @@ export function applyAppPageRscRequestMetaFromHeaders( ...@@ -31,7 +32,8 @@ export function applyAppPageRscRequestMetaFromHeaders(
addRequestMeta(req as IncomingMessage, 'isRSCRequest', true) addRequestMeta(req as IncomingMessage, 'isRSCRequest', true)
const isPrefetchRequest = const isPrefetchRequest =
getHeaderValue(req.headers[NEXT_ROUTER_PREFETCH_HEADER]) === '1' getHeaderValue(req.headers[NEXT_ROUTER_PREFETCH_HEADER]) ===
NEXT_ROUTER_PREFETCH_STATIC
if (!isPrefetchRequest) { if (!isPrefetchRequest) {
return return
} }
......
...@@ -8,7 +8,12 @@ import { ...@@ -8,7 +8,12 @@ import {
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER, NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_REQUEST_ID_HEADER, NEXT_REQUEST_ID_HEADER,
NEXT_HTML_REQUEST_ID_HEADER, NEXT_HTML_REQUEST_ID_HEADER,
NEXT_ROUTER_PREFETCH_STATIC,
NEXT_ROUTER_PREFETCH_RUNTIME_PREFETCH,
NEXT_ROUTER_PREFETCH_RUNTIME_SHELL,
NEXT_ROUTER_PREFETCH_RUNTIME_NAVIGATION,
} from '../../../client/components/app-router-headers' } from '../../../client/components/app-router-headers'
import { AppStage } from '../../../client/components/segment-cache/types'
import { isRSCRequestHeader } from '../../lib/is-rsc-request' import { isRSCRequestHeader } from '../../lib/is-rsc-request'
import { getScriptNonceFromHeaders } from '../../app-render/get-script-nonce-from-header' import { getScriptNonceFromHeaders } from '../../app-render/get-script-nonce-from-header'
import { parseAndValidateFlightRouterState } from '../../app-render/parse-and-validate-flight-router-state' import { parseAndValidateFlightRouterState } from '../../app-render/parse-and-validate-flight-router-state'
...@@ -28,13 +33,13 @@ export interface ParsedRequestHeaders { ...@@ -28,13 +33,13 @@ export interface ParsedRequestHeaders {
*/ */
readonly flightRouterState: FlightRouterState | undefined readonly flightRouterState: FlightRouterState | undefined
readonly isPrefetchRequest: boolean readonly isPrefetchRequest: boolean
readonly isRuntimePrefetchRequest: boolean
/** /**
* App Shell prefetch: a runtime prefetch that the server renders with * The stage a runtime prefetch asks for, or null if this isn't a runtime
* params omitted (any `await params` hangs forever). Produces the * prefetch. A runtime prefetch of the shell is rendered with params omitted
* param-independent shell of the route. Implies isRuntimePrefetchRequest. * (any `await params` hangs forever), so it produces the param-independent
* shell of the route.
*/ */
readonly isAppShellPrefetchRequest: boolean readonly runtimePrefetchStage: AppStage | null
readonly isRouteTreePrefetchRequest: boolean readonly isRouteTreePrefetchRequest: boolean
readonly isHmrRefresh: boolean readonly isHmrRefresh: boolean
readonly isRSCRequest: boolean readonly isRSCRequest: boolean
...@@ -53,16 +58,26 @@ export function parseRequestHeaders( ...@@ -53,16 +58,26 @@ export function parseRequestHeaders(
// runtime prefetch requests are *not* treated as prefetch requests // runtime prefetch requests are *not* treated as prefetch requests
// (TODO: this is confusing, we should refactor this to express this better) // (TODO: this is confusing, we should refactor this to express this better)
const isPrefetchRequest = const isPrefetchRequest =
isRSCRequest && headers[NEXT_ROUTER_PREFETCH_HEADER] === '1'
const isAppShellPrefetchRequest =
isRSCRequest && headers[NEXT_ROUTER_PREFETCH_HEADER] === '3'
// App Shell prefetches are a subtype of runtime prefetch — same code path,
// but with less resolved content (omitting link data)
const isRuntimePrefetchRequest =
isRSCRequest && isRSCRequest &&
(headers[NEXT_ROUTER_PREFETCH_HEADER] === '2' || isAppShellPrefetchRequest) headers[NEXT_ROUTER_PREFETCH_HEADER] === NEXT_ROUTER_PREFETCH_STATIC
let runtimePrefetchStage: AppStage | null = null
if (isRSCRequest) {
switch (headers[NEXT_ROUTER_PREFETCH_HEADER]) {
case NEXT_ROUTER_PREFETCH_RUNTIME_SHELL:
runtimePrefetchStage = AppStage.Shell
break
case NEXT_ROUTER_PREFETCH_RUNTIME_PREFETCH:
runtimePrefetchStage = AppStage.Prefetch
break
case NEXT_ROUTER_PREFETCH_RUNTIME_NAVIGATION:
runtimePrefetchStage = AppStage.Navigation
break
case undefined:
default:
break
}
}
const isHmrRefresh = headers[NEXT_HMR_REFRESH_HEADER] !== undefined const isHmrRefresh = headers[NEXT_HMR_REFRESH_HEADER] !== undefined
...@@ -107,8 +122,7 @@ export function parseRequestHeaders( ...@@ -107,8 +122,7 @@ export function parseRequestHeaders(
return { return {
flightRouterState, flightRouterState,
isPrefetchRequest, isPrefetchRequest,
isRuntimePrefetchRequest, runtimePrefetchStage,
isAppShellPrefetchRequest,
isRouteTreePrefetchRequest, isRouteTreePrefetchRequest,
isHmrRefresh, isHmrRefresh,
isRSCRequest, isRSCRequest,
......
...@@ -25,7 +25,7 @@ export interface NavigateOptions { ...@@ -25,7 +25,7 @@ export interface NavigateOptions {
} }
export interface PrefetchOptions { export interface PrefetchOptions {
kind?: 'auto' | 'full' kind?: 'auto' | 'full' | 'shell' | 'prefetch' | 'navigation'
onInvalidate?: () => void onInvalidate?: () => void
} }
......
...@@ -293,14 +293,16 @@ export const enum PrefetchHint { ...@@ -293,14 +293,16 @@ export const enum PrefetchHint {
// does not propagate. // does not propagate.
ShouldAttemptStaticShell = 0b100000000000000, ShouldAttemptStaticShell = 0b100000000000000,
ShouldAttemptStaticPrefetch = 0b1000000000000000, ShouldAttemptStaticPrefetch = 0b1000000000000000,
ShouldAttemptStaticNavigation = 0b10000000000000000,
// This dynamic segment only accepts build-time parameter values. Kept on // This dynamic segment only accepts build-time parameter values. Kept on
// the affected node, without propagating or copying it to other segments. // the affected node, without propagating or copying it to other segments.
// Until the client knows the allowed values, any such node prevents route // Until the client knows the allowed values, any such node prevents route
// prediction, even when the route's components never read the parameter. // prediction, even when the route's components never read the parameter.
IsClosedParam = 0b10000000000000000, IsClosedParam = 0b100000000000000000,
// A descendant segment (but not this one) has a closed parameter. Propagates // A descendant segment (but not this one) has a closed parameter. Propagates
// upward so route prediction can check the root instead of walking the tree. // upward so route prediction can check the root instead of walking the tree.
SubtreeHasClosedParams = 0b100000000000000000, SubtreeHasClosedParams = 0b1000000000000000000,
} }
/** /**
...@@ -325,7 +327,8 @@ export const StaticPrefetchDisabled = PrefetchHint.PrefetchDisabled ...@@ -325,7 +327,8 @@ export const StaticPrefetchDisabled = PrefetchHint.PrefetchDisabled
export const StaticAttemptHints = export const StaticAttemptHints =
PrefetchHint.ShouldAttemptStaticShell | PrefetchHint.ShouldAttemptStaticShell |
PrefetchHint.ShouldAttemptStaticPrefetch PrefetchHint.ShouldAttemptStaticPrefetch |
PrefetchHint.ShouldAttemptStaticNavigation
/** /**
* The subset of PrefetchHint bits that propagate upward from a child segment to * The subset of PrefetchHint bits that propagate upward from a child segment to
...@@ -531,18 +534,19 @@ type NavigationFlightResponseBase = { ...@@ -531,18 +534,19 @@ type NavigationFlightResponseBase = {
* TransportSegmentData). */ * TransportSegmentData). */
s?: AsyncIterable<number> s?: AsyncIterable<number>
/** /**
* stageByteLengths - The byte offset where each stage ends, in stage order * stageByteLengths - Where each stage ends in the response, in bytes,
* starting with the shell. A stage is listed only when a later stage added * indexed by AppStage: first the shell, then the prefetch stage. We only
* bytes; an unlisted stage ends at the end of the response, and so does the * list a stage if a later stage added more bytes. Otherwise the stage ends
* last stage, which is never listed. Absent when the response wasn't * at the end of the response, like the navigation stage always does.
* staged. * Absent if the response wasn't staged. Live renders only list the shell.
* *
* Decoding the response up to a stage's offset reads it as of that stage. * If you decode the response up to one of these offsets, you get the
* The shell prefix is the shell variant of every segment (param-dependent * response as it was at the end of that stage. We use the shell's prefix
* content reduced to still-pending references). In a per-segment prefetch * as the shell for every segment. We only decode the prefetch stage's
* response the offsets are the segment response's own, measured against a * prefix to read its `u`, to find out whether anything up to that point
* staged decode of the page. The resolution row flushes past every offset, * read runtime data. A per-segment prefetch response lists its own
* so a truncated decode reads it as pending, which is harmless. * offsets. The row that resolves this list always comes after every
* offset, so a prefix reads it as pending, which is fine.
*/ */
a?: Promise<Array<number>> a?: Promise<Array<number>>
/** /**
......
...@@ -23,7 +23,7 @@ export function createLinkPrefetchPartialError(pathname: string): Error { ...@@ -23,7 +23,7 @@ export function createLinkPrefetchPartialError(pathname: string): Error {
`This will lead to slower, more expensive prefetches.\n\n` + `This will lead to slower, more expensive prefetches.\n\n` +
`Ways to fix this:\n` + `Ways to fix this:\n` +
` - [upgrade] Opt into Partial Prefetching by exporting \`const prefetch = 'partial'\` from the page or layout, or by setting \`partialPrefetching: true\` in next.config to opt the whole app in\n` + ` - [upgrade] Opt into Partial Prefetching by exporting \`const prefetch = 'partial'\` from the page or layout, or by setting \`partialPrefetching: true\` in next.config to opt the whole app in\n` +
` - [disable] Remove \`prefetch={true}\` from the <Link> to use the default prefetch\n` + ` - [disable] Remove \`prefetch={true}\` or \`prefetch="navigation"\` from the <Link> to use the default prefetch\n` +
` - [ignore] Set \`export const instant = false\` to opt the route out of instant-navigation validation\n\n` + ` - [ignore] Set \`export const instant = false\` to opt the route out of instant-navigation validation\n\n` +
`Learn more: https://nextjs.org/docs/messages/instant-link-prefetch-partial` `Learn more: https://nextjs.org/docs/messages/instant-link-prefetch-partial`
) )
......
import { hexHash } from '../../hash' import { hexHash } from '../../hash'
import type {
NEXT_ROUTER_PREFETCH_STATIC,
NEXT_ROUTER_PREFETCH_RUNTIME_PREFETCH,
NEXT_ROUTER_PREFETCH_RUNTIME_SHELL,
NEXT_ROUTER_PREFETCH_RUNTIME_NAVIGATION,
} from '../../../../client/components/app-router-headers'
const CACHE_BUSTING_SEARCH_PARAM_DIGEST_BYTES = 12 const CACHE_BUSTING_SEARCH_PARAM_DIGEST_BYTES = 12
const textEncoder = new TextEncoder() const textEncoder = new TextEncoder()
...@@ -22,7 +28,13 @@ function normalizeCacheBustingInput( ...@@ -22,7 +28,13 @@ function normalizeCacheBustingInput(
} }
function createCacheBustingSearchParamInput( function createCacheBustingSearchParamInput(
prefetchHeader: '1' | '2' | '3' | '0' | undefined, prefetchHeader:
| typeof NEXT_ROUTER_PREFETCH_STATIC
| typeof NEXT_ROUTER_PREFETCH_RUNTIME_PREFETCH
| typeof NEXT_ROUTER_PREFETCH_RUNTIME_SHELL
| typeof NEXT_ROUTER_PREFETCH_RUNTIME_NAVIGATION
| '0'
| undefined,
segmentPrefetchHeader: string | string[] | undefined, segmentPrefetchHeader: string | string[] | undefined,
stateTreeHeader: string | string[] | undefined, stateTreeHeader: string | string[] | undefined,
nextUrlHeader: string | string[] | undefined nextUrlHeader: string | string[] | undefined
...@@ -58,7 +70,13 @@ async function computeCacheBustingSearchParamFromInput( ...@@ -58,7 +70,13 @@ async function computeCacheBustingSearchParamFromInput(
} }
export async function computeCacheBustingSearchParam( export async function computeCacheBustingSearchParam(
prefetchHeader: '1' | '2' | '3' | '0' | undefined, prefetchHeader:
| typeof NEXT_ROUTER_PREFETCH_STATIC
| typeof NEXT_ROUTER_PREFETCH_RUNTIME_PREFETCH
| typeof NEXT_ROUTER_PREFETCH_RUNTIME_SHELL
| typeof NEXT_ROUTER_PREFETCH_RUNTIME_NAVIGATION
| '0'
| undefined,
segmentPrefetchHeader: string | string[] | undefined, segmentPrefetchHeader: string | string[] | undefined,
stateTreeHeader: string | string[] | undefined, stateTreeHeader: string | string[] | undefined,
nextUrlHeader: string | string[] | undefined nextUrlHeader: string | string[] | undefined
...@@ -77,7 +95,13 @@ export async function computeCacheBustingSearchParam( ...@@ -77,7 +95,13 @@ export async function computeCacheBustingSearchParam(
} }
export function computeLegacyCacheBustingSearchParam( export function computeLegacyCacheBustingSearchParam(
prefetchHeader: '1' | '2' | '3' | '0' | undefined, prefetchHeader:
| typeof NEXT_ROUTER_PREFETCH_STATIC
| typeof NEXT_ROUTER_PREFETCH_RUNTIME_PREFETCH
| typeof NEXT_ROUTER_PREFETCH_RUNTIME_SHELL
| typeof NEXT_ROUTER_PREFETCH_RUNTIME_NAVIGATION
| '0'
| undefined,
segmentPrefetchHeader: string | string[] | undefined, segmentPrefetchHeader: string | string[] | undefined,
stateTreeHeader: string | string[] | undefined, stateTreeHeader: string | string[] | undefined,
nextUrlHeader: string | string[] | undefined nextUrlHeader: string | string[] | undefined
......
...@@ -2,8 +2,13 @@ import { LinkAccordion } from '../components/link-accordion' ...@@ -2,8 +2,13 @@ import { LinkAccordion } from '../components/link-accordion'
export default function Page() { export default function Page() {
return ( return (
<LinkAccordion unstable_dynamicOnHover href="/dynamic"> <>
Dynamic page <LinkAccordion unstable_dynamicOnHover href="/dynamic">
</LinkAccordion> Dynamic page
</LinkAccordion>
<LinkAccordion unstable_dynamicOnHover href="/partial">
Partial page
</LinkAccordion>
</>
) )
} }
import { Suspense } from 'react'
import { navigation } from 'next/cache'
import { cookies } from 'next/headers'
import { connection } from 'next/server'
export const prefetch = 'partial'
export default function Page() {
return (
<main>
<Suspense fallback={<p id="navigation-loading">Loading navigation...</p>}>
<Navigation />
</Suspense>
<Suspense fallback={<p id="dynamic-loading">Loading dynamic data...</p>}>
<Dynamic />
</Suspense>
</main>
)
}
async function Navigation() {
// Reading cookies means only a runtime prefetch includes this content, and
// navigation() means only a prefetch of the navigation stage does.
await cookies()
await navigation()
return <p id="navigation-content">Navigation content on partial page</p>
}
async function Dynamic() {
await connection()
return <p id="dynamic-content">Dynamic content on partial page</p>
}
...@@ -61,4 +61,56 @@ describe('dynamic on hover', () => { ...@@ -61,4 +61,56 @@ describe('dynamic on hover', () => {
await link.click() await link.click()
}, 'no-requests') }, 'no-requests')
}) })
it('with Partial Prefetching, prefetches the navigation stage on hover', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// Reveal the link. It hasn't been hovered yet, so it only gets the shell.
await act(
async () => {
await browser
.elementByCss('input[data-link-accordion="/partial"]')
.click()
await browser.elementByCss('a[href="/partial"]')
},
{ includes: 'Navigation content on partial page', block: 'reject' }
)
// Hover over the link. The route opts into Partial Prefetching, so
// instead of a full prefetch, the link sends a runtime prefetch of the
// navigation stage. It includes the content after navigation(), but not
// the dynamic content.
const link = await browser.elementByCss('a[href="/partial"]')
await act(async () => {
await link.hover()
}, [
{ includes: 'Navigation content on partial page', kind: 'runtime' },
{ includes: 'Dynamic content on partial page', block: 'reject' },
])
// The navigation shows the prefetched content right away, and only
// fetches the dynamic content.
await act(
async () => {
await link.click()
// While the navigation response is blocked (we're still in the `act`
// scope), the prefetched content is already visible.
expect(await browser.elementById('navigation-content').text()).toBe(
'Navigation content on partial page'
)
expect(await browser.elementById('dynamic-loading').text()).toBe(
'Loading dynamic data...'
)
},
{ includes: 'Dynamic content on partial page' }
)
expect(await browser.elementById('dynamic-content').text()).toBe(
'Dynamic content on partial page'
)
})
}) })
...@@ -28,6 +28,15 @@ export default function Page() { ...@@ -28,6 +28,15 @@ export default function Page() {
Partially static page (prefetch=true) Partially static page (prefetch=true)
</LinkAccordion> </LinkAccordion>
</li> </li>
<li>
<LinkAccordion
href="/partially-static"
prefetch="navigation"
id="partially-static-navigation"
>
Partially static page (prefetch=navigation)
</LinkAccordion>
</li>
</ul> </ul>
) )
} }
...@@ -227,6 +227,41 @@ describe('force stale', () => { ...@@ -227,6 +227,41 @@ describe('force stale', () => {
} }
) )
it(
'a prefetch="navigation" link does a full prefetch, like ' +
'prefetch={true}',
async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
act = createRouterAct(p)
},
})
// This route doesn't opt into Partial Prefetching, so a link that asks
// for the navigation stage gets the whole page, including the dynamic
// content.
await act(async () => {
const toggle = await browser.elementByCss(
'input[data-link-accordion="partially-static-navigation"]'
)
await toggle.click()
}, [
{ includes: 'Static layout content' },
{ includes: 'Partially static page content' },
])
// Everything was prefetched, so the navigation makes no requests.
await act(async () => {
const link = await browser.elementById('partially-static-navigation')
await link.click()
}, 'no-requests')
expect(await browser.elementById('partially-static-page').text()).toBe(
'Partially static page content'
)
}
)
it('back/forward navigations do not make requests', async () => { it('back/forward navigations do not make requests', async () => {
let act: ReturnType<typeof createRouterAct> let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', { const browser = await next.browser('/', {
......
import Link from 'next/link' import Link from 'next/link'
import { LinkAccordion } from '../../components/link-accordion' import { LinkAccordion } from '../../components/link-accordion'
import { PrefetchButton } from '../../components/prefetch-button'
export default function Page() { export default function Page() {
return ( return (
...@@ -147,6 +148,20 @@ export default function Page() { ...@@ -147,6 +148,20 @@ export default function Page() {
Runtime navigation post "speculative-1" (prefetch=true) Runtime navigation post "speculative-1" (prefetch=true)
</LinkAccordion> </LinkAccordion>
</li> </li>
<li>
<LinkAccordion
href="/runtime-navigation/speculative-2"
prefetch="navigation"
>
Runtime navigation post "speculative-2" (prefetch=navigation)
</LinkAccordion>
</li>
<li>
<PrefetchButton href="/runtime-navigation/speculative-3" />{' '}
<Link href="/runtime-navigation/speculative-3" prefetch={false}>
Runtime navigation post "speculative-3" (router.prefetch)
</Link>
</li>
</ul> </ul>
<h2>Prefetch posts</h2> <h2>Prefetch posts</h2>
......
'use client'
import { useRouter } from 'next/navigation'
type Router = ReturnType<typeof useRouter>
type PrefetchOptions = Parameters<Router['prefetch']>[1]
export function PrefetchButton({ href }: { href: string }) {
const router = useRouter()
return (
<button
data-prefetch-navigation={href}
onClick={() =>
router.prefetch(href, {
kind: 'navigation' as NonNullable<PrefetchOptions>['kind'],
})
}
>
router.prefetch({href}, {'{ kind: "navigation" }'})
</button>
)
}
...@@ -591,6 +591,110 @@ describe('App Shell prefetching', () => { ...@@ -591,6 +591,110 @@ describe('App Shell prefetching', () => {
'Post body for speculative-1' 'Post body for speculative-1'
) )
}) })
it('includes navigation() in a runtime prefetch of the navigation stage', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Reveal the LinkAccordion for /runtime-navigation/speculative-2. The
// link asks for the navigation stage, so after the shell request, the
// runtime prefetch includes the navigation-gated content.
await act(async () => {
await browser
.elementByCss(
'input[data-link-accordion="/runtime-navigation/speculative-2"]'
)
.click()
}, [
{ includes: 'App shell for navigation', kind: 'runtime' }, // Shell
{ includes: 'Navigation content', kind: 'runtime' }, // Speculative
// Dynamic content is never prefetched.
{ includes: 'Post body for speculative-2', block: 'reject' },
])
await act(async () => {
// Navigate to the prefetched route.
await browser
.elementByCss('a[href="/runtime-navigation/speculative-2"]')
.click()
// While the navigation response is blocked (we're still in the `act`
// block), the prefetched content should already be visible.
expect(await browser.elementById('param-value').text()).toEqual(
'Post speculative-2'
)
// The navigation-gated content is included.
expect(await browser.locator('#navigation-loading').count()).toBe(0)
expect(await browser.elementByCss('#navigation-content').text()).toBe(
'Navigation content'
)
// Dynamic content is not included.
expect(await browser.locator('#dynamic-content').count()).toBe(0)
expect(await browser.elementByCss('#dynamic-loading').text()).toBe(
'Loading dynamic content...'
)
})
// After the outer act unblocks the navigation, the dynamic content
// streams in.
expect(await browser.elementById('dynamic-content').text()).toEqual(
'Post body for speculative-2'
)
})
})
describe('router.prefetch()', () => {
it('includes navigation() when called with kind "navigation"', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Prefetch /runtime-navigation/speculative-3 with kind "navigation".
// Like a prefetch="navigation" link, after the shell request, the
// runtime prefetch includes the navigation-gated content.
await act(async () => {
await browser
.elementByCss(
'button[data-prefetch-navigation="/runtime-navigation/speculative-3"]'
)
.click()
}, [
{ includes: 'App shell for navigation', kind: 'runtime' }, // Shell
{ includes: 'Navigation content', kind: 'runtime' }, // Speculative
// Dynamic content is never prefetched.
{ includes: 'Post body for speculative-3', block: 'reject' },
])
await act(async () => {
await browser
.elementByCss('a[href="/runtime-navigation/speculative-3"]')
.click()
// While the navigation response is blocked, the prefetched content
// should already be visible, including the navigation-gated content.
expect(await browser.elementById('param-value').text()).toEqual(
'Post speculative-3'
)
expect(await browser.locator('#navigation-loading').count()).toBe(0)
expect(await browser.elementByCss('#navigation-content').text()).toBe(
'Navigation content'
)
expect(await browser.locator('#dynamic-content').count()).toBe(0)
})
expect(await browser.elementById('dynamic-content').text()).toEqual(
'Post body for speculative-3'
)
})
}) })
describe('prefetch()', () => { describe('prefetch()', () => {
......
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { PrefetchHint } from 'next/src/shared/lib/app-router-types' import { StaticAttemptHints } from 'next/src/shared/lib/app-router-types'
import { createRouterAct } from 'router-act' import { createRouterAct } from 'router-act'
import type * as Playwright from 'playwright' import type * as Playwright from 'playwright'
import { import {
...@@ -67,9 +67,7 @@ describe('Partial prefetching with static params and ISR fallbacks', () => { ...@@ -67,9 +67,7 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
) )
// we only care about the static hints, inlining is not relevant. // we only care about the static hints, inlining is not relevant.
const hintsMask = const hintsMask = StaticAttemptHints
PrefetchHint.ShouldAttemptStaticShell |
PrefetchHint.ShouldAttemptStaticPrefetch
// The page awaits static params, so: // The page awaits static params, so:
// - the shell can be static (ShouldAttemptStaticShell hint set), // - the shell can be static (ShouldAttemptStaticShell hint set),
...@@ -81,16 +79,16 @@ describe('Partial prefetching with static params and ISR fallbacks', () => { ...@@ -81,16 +79,16 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
) )
).toMatchInlineSnapshot(` ).toMatchInlineSnapshot(`
{ {
"hints": "ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch | ...", "hints": "ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch | ShouldAttemptStaticNavigation | ...",
"slots": { "slots": {
"children": { "children": {
"hints": "ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch | ...", "hints": "ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch | ShouldAttemptStaticNavigation | ...",
"slots": { "slots": {
"children": { "children": {
"hints": "ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch | ...", "hints": "ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch | ShouldAttemptStaticNavigation | ...",
"slots": { "slots": {
"children": { "children": {
"hints": "ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch | ...", "hints": "ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch | ShouldAttemptStaticNavigation | ...",
"slots": null, "slots": null,
}, },
}, },
......
...@@ -55,6 +55,14 @@ export default function Page() { ...@@ -55,6 +55,14 @@ export default function Page() {
Param 1 (prefetch=true) Param 1 (prefetch=true)
</LinkAccordion> </LinkAccordion>
</li> </li>
<li>
<LinkAccordion
href="/params-used-after-navigation/1"
prefetch="navigation"
>
Param 1 (prefetch=navigation)
</LinkAccordion>
</li>
<li> <li>
<Link href="/params-used-after-navigation/2" prefetch={false}> <Link href="/params-used-after-navigation/2" prefetch={false}>
Param 2 (unprefetched) Param 2 (unprefetched)
...@@ -105,6 +113,19 @@ export default function Page() { ...@@ -105,6 +113,19 @@ export default function Page() {
Uses runtime APIs after navigation() Uses runtime APIs after navigation()
</LinkAccordion> </LinkAccordion>
</li> </li>
<li>
<LinkAccordion href="/uses-runtime-after-navigation" prefetch={true}>
Uses runtime APIs after navigation() (prefetch=true)
</LinkAccordion>
</li>
<li>
<LinkAccordion
href="/uses-runtime-after-navigation"
prefetch="navigation"
>
Uses runtime APIs after navigation() (prefetch=navigation)
</LinkAccordion>
</li>
<li> <li>
<LinkAccordion href="/uses-navigation-static"> <LinkAccordion href="/uses-navigation-static">
Uses navigation() on a static page Uses navigation() on a static page
...@@ -274,6 +295,16 @@ export default function Page() { ...@@ -274,6 +295,16 @@ export default function Page() {
(prefetch=true) (prefetch=true)
</LinkAccordion> </LinkAccordion>
</li> </li>
<li>
<LinkAccordion
href="/ensure-static/shell/uses-cookies"
prefetch="navigation"
>
Page with <code>ensureStatic = "shell"</code> that uses cookies
(prefetch="navigation")
</LinkAccordion>
</li>
<li> <li>
<LinkAccordion href="/ensure-static/prefetch/uses-cookies"> <LinkAccordion href="/ensure-static/prefetch/uses-cookies">
Page with <code>ensureStatic = "prefetch"</code> that uses cookies Page with <code>ensureStatic = "prefetch"</code> that uses cookies
...@@ -288,6 +319,15 @@ export default function Page() { ...@@ -288,6 +319,15 @@ export default function Page() {
(prefetch=true) (prefetch=true)
</LinkAccordion> </LinkAccordion>
</li> </li>
<li>
<LinkAccordion
href="/ensure-static/prefetch/uses-cookies"
prefetch="navigation"
>
Page with <code>ensureStatic = "prefetch"</code> that uses cookies
(prefetch="navigation")
</LinkAccordion>
</li>
</ul> </ul>
<h2>ensureStatic = "navigation"</h2> <h2>ensureStatic = "navigation"</h2>
...@@ -304,6 +344,14 @@ export default function Page() { ...@@ -304,6 +344,14 @@ export default function Page() {
prerendered param 1 (prefetch=true) prerendered param 1 (prefetch=true)
</LinkAccordion> </LinkAccordion>
</li> </li>
<li>
<LinkAccordion
href="/ensure-static/navigation/prerendered-1"
prefetch="navigation"
>
prerendered param 1 (prefetch="navigation")
</LinkAccordion>
</li>
<li> <li>
<LinkAccordion <LinkAccordion
href="/ensure-static/navigation/not-prerendered-1" href="/ensure-static/navigation/not-prerendered-1"
...@@ -312,11 +360,20 @@ export default function Page() { ...@@ -312,11 +360,20 @@ export default function Page() {
not-prerendered param 1 (prefetch=true) not-prerendered param 1 (prefetch=true)
</LinkAccordion> </LinkAccordion>
</li> </li>
<li>
<LinkAccordion
href="/ensure-static/navigation/not-prerendered-2"
prefetch="navigation"
>
not-prerendered param 2 (prefetch=navigation)
</LinkAccordion>
</li>
{/* Used for manual testing of on-demand prerenders */} {/* Used for manual testing of on-demand prerenders */}
<DynamicLinkAccordion <DynamicLinkAccordion
hrefPattern="/ensure-static/navigation/not-prerendered-{counter}" hrefPattern="/ensure-static/navigation/not-prerendered-{counter}"
placeholder="{counter}" placeholder="{counter}"
initialCount={2} initialCount={3}
/> />
</main> </main>
) )
......
...@@ -25,16 +25,16 @@ export default async function Page() { ...@@ -25,16 +25,16 @@ export default async function Page() {
async function Navigation() { async function Navigation() {
// The runtime data tracking should end here, so the prerender // The runtime data tracking should end here, so the prerender
// shouldn't track the awaits of cookies/headers inside DynamicContent. // shouldn't track the awaits of cookies/headers inside RuntimeContent.
await navigation() await navigation()
return ( return (
<> <>
<div id="navigation-content">Navigation content</div> <div id="navigation-content">Navigation content</div>
<Suspense <Suspense
fallback={<p id="dynamic-loading">Loading dynamic content...</p>} fallback={<p id="runtime-loading">Loading runtime content...</p>}
> >
<DynamicContent /> <RuntimeContent />
</Suspense> </Suspense>
</> </>
) )
...@@ -46,7 +46,7 @@ async function shortStaleCache() { ...@@ -46,7 +46,7 @@ async function shortStaleCache() {
return Date.now() return Date.now()
} }
async function DynamicContent() { async function RuntimeContent() {
await Promise.all([cookies(), headers(), shortStaleCache()]) await Promise.all([cookies(), headers(), shortStaleCache()])
return <p id="dynamic-content">Dynamic content</p> return <p id="runtime-content">Runtime content</p>
} }
import Link from 'next/link'
export default function Hello() {
return (
<>
<Link prefetch="prefetch" href="/valid-prefetch">
Link with `prefetch="prefetch"`
</Link>
<Link prefetch="navigation" href="/valid-prefetch">
Link with `prefetch="navigation"`
</Link>
</>
)
}
import { nextTestSetup } from 'e2e-utils' import { nextTestSetup } from 'e2e-utils'
import { waitForNoRedbox } from 'next-test-utils'
describe('next-link', () => { describe('next-link', () => {
const { next, isNextDev } = nextTestSetup({ const { next, isNextDev } = nextTestSetup({
...@@ -36,7 +37,7 @@ describe('next-link', () => { ...@@ -36,7 +37,7 @@ describe('next-link', () => {
if (isNextDev) { if (isNextDev) {
await expect(browser).toDisplayRedbox(` await expect(browser).toDisplayRedbox(`
{ {
"description": "Failed prop type: The prop \`prefetch\` expects a \`boolean | "auto"\` in \`<Link>\`, but got \`string\` instead. "description": "Failed prop type: The prop \`prefetch\` expects a \`boolean | "auto" | "shell" | "prefetch" | "navigation"\` in \`<Link>\`, but got \`string\` instead.
Open your browser's console to view the Component stack trace.", Open your browser's console to view the Component stack trace.",
"environmentLabel": null, "environmentLabel": null,
"label": "Runtime Error", "label": "Runtime Error",
...@@ -58,4 +59,15 @@ describe('next-link', () => { ...@@ -58,4 +59,15 @@ describe('next-link', () => {
) )
} }
}) })
// Prop validation only runs in dev, so this can't fail in production.
// @force-gate dev
it('accepts the `prefetch` values that name a stage (dev-only)', async () => {
const browser = await next.browser('/valid-prefetch')
await waitForNoRedbox(browser)
expect(await browser.elementByCss('body').text()).toContain(
'Link with `prefetch="navigation"`'
)
})
}) })
...@@ -28,7 +28,8 @@ const APP_SHELL_PREFETCH_VALUE = '3' ...@@ -28,7 +28,8 @@ const APP_SHELL_PREFETCH_VALUE = '3'
// - 'runtime': dynamic prefetch requests, issued by // - 'runtime': dynamic prefetch requests, issued by
// `fetchSegmentPrefetchesUsingRuntimeRequest` in the client. These carry a // `fetchSegmentPrefetchesUsingRuntimeRequest` in the client. These carry a
// FlightRouterState request tree and a `next-router-prefetch` header value // FlightRouterState request tree and a `next-router-prefetch` header value
// of '2' (FetchStrategy.PPRRuntime) or '3' (FetchStrategy.RuntimeShell). // of '2' (up to the prefetch stage), '3' (the shell), or '4' (up to the
// navigation stage).
// The other strategies used by that path — LoadingBoundary ('1') and Full // The other strategies used by that path — LoadingBoundary ('1') and Full
// (no prefetch header) — send the same headers as plain prefetches and // (no prefetch header) — send the same headers as plain prefetches and
// navigations respectively, so they cannot be demonstrably classified and // navigations respectively, so they cannot be demonstrably classified and
...@@ -37,6 +38,7 @@ const APP_SHELL_PREFETCH_VALUE = '3' ...@@ -37,6 +38,7 @@ const APP_SHELL_PREFETCH_VALUE = '3'
// prefetches. Expectations that specify a `kind` never claim these. // prefetches. Expectations that specify a `kind` never claim these.
const NEXT_ROUTER_SEGMENT_PREFETCH_HEADER = 'next-router-segment-prefetch' const NEXT_ROUTER_SEGMENT_PREFETCH_HEADER = 'next-router-segment-prefetch'
const PPR_RUNTIME_PREFETCH_VALUE = '2' const PPR_RUNTIME_PREFETCH_VALUE = '2'
const NAVIGATION_RUNTIME_PREFETCH_VALUE = '4'
type ResponseKind = 'static' | 'runtime' type ResponseKind = 'static' | 'runtime'
...@@ -92,9 +94,9 @@ type ExpectedResponseConfig = { ...@@ -92,9 +94,9 @@ type ExpectedResponseConfig = {
* the kind of prefetch request that produced them: 'static' matches only * the kind of prefetch request that produced them: 'static' matches only
* per-segment static prefetches (those with a `next-router-segment-prefetch` * per-segment static prefetches (those with a `next-router-segment-prefetch`
* request header), and 'runtime' matches only dynamic prefetch requests * request header), and 'runtime' matches only dynamic prefetch requests
* (those with a `next-router-prefetch` header value of '2' (PPRRuntime) or * (those with a `next-router-prefetch` header value of '2' (up to the
* '3' (RuntimeShell)). If omitted, any router response can satisfy the * prefetch stage), '3' (the shell), or '4' (up to the navigation stage)).
* expectation. Note that App Shell (RuntimeShell) responses are excluded * If omitted, any router response can satisfy the expectation. Note that App Shell (RuntimeShell) responses are excluded
* from assertion logic by default, so a `kind: 'runtime'` expectation that * from assertion logic by default, so a `kind: 'runtime'` expectation that
* should match an App Shell response additionally requires passing * should match an App Shell response additionally requires passing
* `includeAppShellRequests: true` to `createRouterAct`. * `includeAppShellRequests: true` to `createRouterAct`.
...@@ -339,7 +341,9 @@ export function createRouterAct( ...@@ -339,7 +341,9 @@ export function createRouterAct(
kind = 'static' kind = 'static'
} else if ( } else if (
headers[NEXT_ROUTER_PREFETCH_HEADER] === PPR_RUNTIME_PREFETCH_VALUE || headers[NEXT_ROUTER_PREFETCH_HEADER] === PPR_RUNTIME_PREFETCH_VALUE ||
headers[NEXT_ROUTER_PREFETCH_HEADER] === APP_SHELL_PREFETCH_VALUE headers[NEXT_ROUTER_PREFETCH_HEADER] === APP_SHELL_PREFETCH_VALUE ||
headers[NEXT_ROUTER_PREFETCH_HEADER] ===
NAVIGATION_RUNTIME_PREFETCH_VALUE
) { ) {
kind = 'runtime' kind = 'runtime'
} }
......
...@@ -17,6 +17,9 @@ export default function Page() { ...@@ -17,6 +17,9 @@ export default function Page() {
router.prefetch('/about') router.prefetch('/about')
router.prefetch('/about', { kind: 'auto' }) router.prefetch('/about', { kind: 'auto' })
router.prefetch('/about', { kind: 'full' }) router.prefetch('/about', { kind: 'full' })
router.prefetch('/about', { kind: 'shell' })
router.prefetch('/about', { kind: 'prefetch' })
router.prefetch('/about', { kind: 'navigation' })
router.prefetch('/about', { onInvalidate() {} }) router.prefetch('/about', { onInvalidate() {} })
router.push('/redirect') router.push('/redirect')
router.push(`/blog/${'a/b'}`) router.push(`/blog/${'a/b'}`)
......
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