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
import {
RSC_HEADER,
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_PREFETCH_STATIC,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_INSTANT_TEST_COOKIE,
NEXT_IS_PRERENDER_HEADER,
......@@ -315,7 +316,8 @@ export function createAppPageEntrypoint({
*/
const 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
......@@ -477,7 +479,8 @@ export function createAppPageEntrypoint({
typeof req.headers.cookie === 'string' &&
req.headers.cookie.includes(NEXT_INSTANT_TEST_COOKIE + '=') &&
(!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
// prerender manifest and this is an app page.
......
......@@ -132,10 +132,12 @@ type InternalLinkProps = {
* Prefetching is only enabled in production.
*
* - 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
* - 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.
* - In the **Pages Router**:
* - `true` (default): Prefetches the route and data in the background on viewport or hover.
......@@ -150,7 +152,7 @@ type InternalLinkProps = {
* </Link>
* ```
*/
prefetch?: boolean | 'auto' | null
prefetch?: boolean | 'auto' | 'shell' | 'prefetch' | 'navigation' | null
/**
* (unstable) Switch to a full prefetch on hover. Effectively the same as
......@@ -376,12 +378,24 @@ export default function LinkComponent(
const router = React.useContext(AppRouterContext)
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.
const prefetchStage =
prefetchProp === true ? AppStage.Prefetch : AppStage.Shell
let prefetchStage: AppStage
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') {
function createPropError(args: {
......@@ -484,11 +498,15 @@ export default function LinkComponent(
if (
props[key] != null &&
valType !== 'boolean' &&
props[key] !== 'auto'
props[key] !== 'auto' &&
props[key] !== 'shell' &&
props[key] !== 'prefetch' &&
props[key] !== 'navigation'
) {
throw createPropError({
key,
expected: '`boolean | "auto"`',
expected:
'`boolean | "auto" | "shell" | "prefetch" | "navigation"`',
actual: valType,
})
}
......@@ -685,6 +703,17 @@ export default function LinkComponent(
if (e.defaultPrevented) {
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(
e,
formattedHref,
......
......@@ -5,6 +5,15 @@ export const ACTION_HEADER = 'next-action' as const
// 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_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.
// 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
......
......@@ -261,10 +261,11 @@ export function navigateToKnownRoute(
process.env.NODE_ENV !== 'production' &&
process.env.__NEXT_CACHE_COMPONENTS
) {
// Warn when navigating via a `<Link prefetch={true}>` to a route that has
// not opted into Partial Prefetching. Such a link does a legacy "full"
// prefetch that includes the route's dynamic data, defeating the
// static/dynamic split that Cache Components provides.
// Warn when navigating via a link that asks for more than the shell, like
// `<Link prefetch={true}>`, to a route that has not opted into Partial
// Prefetching. Such a link does a legacy "full" prefetch that includes the
// 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
// where we don't prefetch, the warning only appears when you actually
......@@ -288,7 +289,7 @@ export function navigateToKnownRoute(
if (ownerStack === undefined) {
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.'
)
} else if (ownerStack !== null) {
......
......@@ -31,17 +31,22 @@ export function prefetchRoute(href: string, options?: PrefetchOptions): void {
}
const prefetchKind = options?.kind ?? 'auto'
// We don't currently offer a way to issue a runtime prefetch via `router.prefetch()`.
let prefetchStage: AppStage
switch (prefetchKind) {
case 'auto': {
case 'auto':
case 'shell': {
prefetchStage = AppStage.Shell
break
}
case 'full': {
case 'full':
case 'prefetch': {
prefetchStage = AppStage.Prefetch
break
}
case 'navigation': {
prefetchStage = AppStage.Navigation
break
}
default: {
prefetchKind satisfies never
// Despite typescript thinking that this can't happen,
......
......@@ -14,6 +14,10 @@ import type {
import {
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,
NEXT_ROUTER_STATE_TREE_HEADER,
NEXT_RSC_UNION_QUERY,
......@@ -103,7 +107,11 @@ export type RequestHeaders = {
[RSC_HEADER]?: '1'
[NEXT_ROUTER_STATE_TREE_HEADER]?: 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
'x-deployment-id'?: string
[NEXT_HMR_REFRESH_HEADER]?: '1'
......
......@@ -141,11 +141,18 @@ export interface ServerPatchAction {
* 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.
* - `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 {
AUTO = 'auto',
FULL = 'full',
SHELL = 'shell',
PREFETCH = 'prefetch',
NAVIGATION = 'navigation',
}
export interface PushRef {
......
......@@ -880,21 +880,24 @@ function pingRootRouteTree(
// 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
// paths). Otherwise, we go up to the prefetch stage. This is the only
// place we look at the phase. Everything below just uses the stage.
const walkStage =
task.phase === PrefetchPhase.Shell
? AppStage.Shell
: AppStage.Prefetch
// Under Partial Prefetching, a link asking for the shell is done
// after the Shell phase.
if (
walkStage !== AppStage.Shell &&
walkCanUseRuntimeRequests(route) &&
task.prefetchStage === AppStage.Shell
) {
return PrefetchTaskExitStatus.Done
// paths). Otherwise, we go up to the stage the link asked for. This is
// the only place we look at the phase. Everything below just uses the
// stage. (What each segment needs at that stage is
// getWalkCompleteness.)
let walkStage: AppStage
if (task.phase === PrefetchPhase.Shell) {
walkStage = AppStage.Shell
} else if (walkCanUseRuntimeRequests(route)) {
if (task.prefetchStage === AppStage.Shell) {
// A link asking for the shell is done after the Shell phase.
return PrefetchTaskExitStatus.Done
}
walkStage = task.prefetchStage
} else {
// 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
......@@ -1145,7 +1148,7 @@ function getWalkCompleteness(route: FulfilledRouteCacheEntry): Completeness {
* `walkCanUseRuntimeRequests` is true.
* */
function shouldSegmentAttemptStaticRequest(
walkStage: AppStage.Shell | AppStage.Prefetch,
walkStage: AppStage,
tree: RouteTree<any>
): boolean {
const { prefetchHints } = tree
......@@ -1154,6 +1157,8 @@ function shouldSegmentAttemptStaticRequest(
return (prefetchHints & PrefetchHint.ShouldAttemptStaticShell) !== 0
case AppStage.Prefetch:
return (prefetchHints & PrefetchHint.ShouldAttemptStaticPrefetch) !== 0
case AppStage.Navigation:
return (prefetchHints & PrefetchHint.ShouldAttemptStaticNavigation) !== 0
default:
walkStage satisfies never
return false
......@@ -1203,7 +1208,7 @@ function isShellEntryEligibleForStaticAttempt(
map: CacheMap<SegmentCacheEntry>,
entry: SegmentCacheEntry,
tree: RouteTree<null>,
walkStage: AppStage.Shell | AppStage.Prefetch
walkStage: AppStage
): boolean {
if (walkStage === AppStage.Shell) {
// A shell prefetch never tries a static request for a shell entry. The
......@@ -1214,7 +1219,7 @@ function isShellEntryEligibleForStaticAttempt(
if (entry.stage !== AppStage.Shell) {
return false
}
if (!shouldSegmentAttemptStaticRequest(AppStage.Prefetch, tree)) {
if (!shouldSegmentAttemptStaticRequest(walkStage, tree)) {
return false
}
const revalidatingEntry = readOrCreateRevalidatingSegmentEntry(
......@@ -1283,7 +1288,7 @@ function pingSharedPartOfCacheComponentsTree(
newTree: RouteTree<null>,
parentBundle: SegmentBundle | null,
// The stage this pass prefetches up to (see pingRootRouteTree).
walkStage: AppStage.Shell | AppStage.Prefetch
walkStage: AppStage
): PrefetchTaskExitStatus.InProgress | PrefetchTaskExitStatus.Done {
if (!doesRouteStructureMatch(currentTree, newTree)) {
// We're entering the part of the target route that doesn't exist on the
......@@ -1401,7 +1406,7 @@ function pingNewPartOfCacheComponentsTree(
tree: RouteTree<null>,
parentBundle: SegmentBundle | null,
// The stage this pass prefetches up to (see pingRootRouteTree).
walkStage: AppStage.Shell | AppStage.Prefetch
walkStage: AppStage
): PrefetchTaskExitStatus.InProgress | PrefetchTaskExitStatus.Done {
const accumulation = pingSegmentInCacheComponentsTree(
now,
......@@ -1491,7 +1496,7 @@ function pingSegmentInCacheComponentsTree(
tree: RouteTree<null>,
parentBundle: SegmentBundle | null,
// The stage this pass prefetches up to (see pingRootRouteTree).
walkStage: AppStage.Shell | AppStage.Prefetch
walkStage: AppStage
): { bundle: SegmentBundle | null; needsRuntimeRequest: boolean } | null {
// Constant for the whole pass; recomputed here only because the walk is
// recursive and the check is cheap.
......@@ -2046,7 +2051,7 @@ function pingRuntimePrefetches(
spawnedRuntimePrefetches: Set<SegmentRequestKey>,
spawnedEntries: Map<SegmentRequestKey, PendingSegmentCacheEntry>,
// The walk's stage, which the runtime request runs at.
stage: AppStage.Shell | AppStage.Prefetch
stage: AppStage
): FlightRouterState {
// Construct a request tree (FlightRouterState) for a runtime prefetch. If
// a segment is part of the runtime prefetch, the tree is constructed by
......@@ -2116,7 +2121,7 @@ function pingSegmentBundle(
tree: RouteTree<null>,
segments: SegmentBundle,
// 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
// (finishStaticBundleOnRuntimeBailout). The finish exists only to fetch
// data the batched runtime request won't cover — Empty entries in the
......@@ -2383,10 +2388,9 @@ function accumulateSegmentBundle(
route: FulfilledRouteCacheEntry,
tree: RouteTree<null>,
parentBundle: SegmentBundle | null,
// The stage this pass prefetches up to (see pingRootRouteTree). Usually
// Prefetch. During the Shell phase it's Shell, and the entries are keyed at
// the shell vary paths.
walkStage: AppStage.Shell | AppStage.Prefetch,
// The stage this pass prefetches up to (see pingRootRouteTree). During the
// Shell phase it's Shell, and the entries are keyed at the shell vary paths.
walkStage: AppStage,
// False when finishing a chain on a runtime-prefetch bailout; see
// pingSegmentBundle.
spawnRevalidations: boolean
......@@ -2514,7 +2518,7 @@ function finishStaticBundleOnRuntimeBailout(
// The same walk stage the parent bundle was accumulated with.
// Any needs-runtime signal from finishing the bundle is dropped: the
// caller is already deopting this subtree to a runtime prefetch.
walkStage: AppStage.Shell | AppStage.Prefetch
walkStage: AppStage
): void {
const bundle = accumulateSegmentBundle(
now,
......
......@@ -73,7 +73,8 @@ type InternalLinkProps = {
*
* 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.
* - `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.
*
* In Pages Router:
......@@ -81,7 +82,7 @@ type InternalLinkProps = {
* - `false`: Prefetching will not happen when entering the viewport, but will still happen on hover.
* @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.
* When `false` `href` has to include the locale as the default behavior is disabled.
......@@ -450,11 +451,15 @@ const Link = React.forwardRef<HTMLAnchorElement, LinkPropsReal>(
if (
props[key] != null &&
valType !== 'boolean' &&
props[key] !== 'auto'
props[key] !== 'auto' &&
props[key] !== 'shell' &&
props[key] !== 'prefetch' &&
props[key] !== 'navigation'
) {
throw createPropError({
key,
expected: '`boolean | "auto"`',
expected:
'`boolean | "auto" | "shell" | "prefetch" | "navigation"`',
actual: valType,
})
}
......
......@@ -82,6 +82,7 @@ import {
NEXT_ROUTER_STALE_TIME_HEADER,
NEXT_URL,
} from '../../client/components/app-router-headers'
import { AppStage } from '../../client/components/segment-cache/types'
import { createMetadataContext } from '../../lib/metadata/metadata-context'
import {
createRequestStore as createRequestStoreFromInputs,
......@@ -1475,7 +1476,8 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
async function generateRuntimePrefetchResult(
ctx: AppRenderContext,
requestStore: RequestStore,
isShellPrefetch: boolean
// The stage the runtime prefetch asks for.
stage: AppStage
): Promise<RenderResult> {
const { workStore, renderOpts, htmlRequestId, requestId } = ctx
const {
......@@ -1520,12 +1522,24 @@ async function generateRuntimePrefetchResult(
requestStore.resumeDataCache ?? undefined
)
const mode: RuntimePrerenderMode = isShellPrefetch
? { type: 'session-shell-only' }
: {
let mode: RuntimePrerenderMode
switch (stage) {
case AppStage.Shell:
mode = { type: 'session-shell-only' }
break
case AppStage.Prefetch:
mode = {
type: 'rewindable-session-shell',
stageByteLengthsDeferred: createPromiseWithResolvers(),
}
break
case AppStage.Navigation:
mode = {
type: 'navigation',
stageByteLengthsDeferred: createPromiseWithResolvers(),
}
break
}
await prospectiveRuntimeServerPrerender(
ctx,
......@@ -1553,9 +1567,9 @@ async function generateRuntimePrefetchResult(
// A runtime shell render stops at the shell stage, so the shell ends
// at the end of the response.
stageByteLengthsPromise:
mode.type === 'rewindable-session-shell'
? mode.stageByteLengthsDeferred.promise
: Promise.resolve([]),
mode.type === 'session-shell-only'
? Promise.resolve([])
: mode.stageByteLengthsDeferred.promise,
}),
prerenderResumeDataCache,
rootParams,
......@@ -2943,8 +2957,7 @@ async function renderAppPage(
isHmrRefresh,
isPrefetchRequest,
isRSCRequest,
isRuntimePrefetchRequest,
isAppShellPrefetchRequest,
runtimePrefetchStage,
isRouteTreePrefetchRequest,
} = parsedRequestHeaders
const isPossibleActionRequest = ctx.isPossibleServerAction
......@@ -2989,8 +3002,7 @@ async function renderAppPage(
!cacheComponents &&
!isPossibleActionRequest &&
!isPrefetchRequest &&
!isRuntimePrefetchRequest &&
!isAppShellPrefetchRequest &&
runtimePrefetchStage === null &&
!isRouteTreePrefetchRequest
? setIsrStatus
: undefined
......@@ -3007,12 +3019,12 @@ async function renderAppPage(
// MARK: RSC request
if (isRSCRequest) {
if (isRuntimePrefetchRequest) {
if (runtimePrefetchStage !== null) {
// MARK: RSC runtimePrefetch
return generateRuntimePrefetchResult(
ctx,
requestStore,
isAppShellPrefetchRequest
runtimePrefetchStage
)
} else {
if (
......@@ -9823,8 +9835,9 @@ async function prerenderToStream(
// 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)
// List where the shell ends, if new chunks were emitted after
// unblocking link data or navigation().
// If anything was emitted after the shell, list where the shell
// ends. Then, if anything was emitted after `navigation()` resolved,
// list where the prefetch stage ends.
// NOTE: we must capture this *before* resolving staleTime/varyParams,
// which always emit new static chunks.
const stageByteLengths: Array<number> = []
......@@ -9837,6 +9850,16 @@ async function prerenderToStream(
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
......@@ -9901,10 +9924,11 @@ async function prerenderToStream(
const {
shouldAttemptStaticShell: shellIsStatic,
shouldAttemptStaticPrefetch: prefetchIsStatic,
shouldAttemptStaticNavigation: navigationIsStatic,
} = prerenderDataTracking
const label = (isStatic: boolean) => (isStatic ? 'static' : 'runtime')
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(
......@@ -11188,12 +11212,14 @@ async function collectSegmentData(
const {
shouldAttemptStaticShell = false,
shouldAttemptStaticPrefetch = false,
shouldAttemptStaticNavigation = false,
} = prerenderDataTracking ?? {}
if (
prefetchInlining ||
shouldAttemptStaticShell ||
shouldAttemptStaticPrefetch
shouldAttemptStaticPrefetch ||
shouldAttemptStaticNavigation
) {
// Build time: compute fresh hints and store in metadata for the
// manifest. When prefetch inlining is disabled there are no sizes to
......@@ -11207,7 +11233,8 @@ async function collectSegmentData(
serverConsumerManifest,
prefetchInlining,
shouldAttemptStaticShell,
shouldAttemptStaticPrefetch
shouldAttemptStaticPrefetch,
shouldAttemptStaticNavigation
)
metadata.prefetchHints = hints
} else {
......
......@@ -99,6 +99,10 @@ import {
NEXT_REQUEST_ID_HEADER,
NEXT_RSC_UNION_QUERY,
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_URL,
NEXT_ROUTER_STATE_TREE_HEADER,
......@@ -678,7 +682,7 @@ export default abstract class Server<
// Mark the request as a router prefetch request.
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
addRequestMeta(req, 'isRSCRequest', true)
......@@ -705,7 +709,9 @@ export default abstract class Server<
} else if (isRSCRequestHeader(req.headers[RSC_HEADER])) {
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)
const segmentPrefetchRSCRequest =
......@@ -2431,17 +2437,18 @@ export default abstract class Server<
const prefetchHeaderValue = headers[NEXT_ROUTER_PREFETCH_HEADER]
const routerPrefetch =
prefetchHeaderValue !== undefined
? // We only recognize '1', '2', and '3'. Strip all other values here.
prefetchHeaderValue === '1' ||
prefetchHeaderValue === '2' ||
prefetchHeaderValue === '3'
? // We only recognize the values we send. Strip all others here.
prefetchHeaderValue === NEXT_ROUTER_PREFETCH_STATIC ||
prefetchHeaderValue === NEXT_ROUTER_PREFETCH_RUNTIME_PREFETCH ||
prefetchHeaderValue === NEXT_ROUTER_PREFETCH_RUNTIME_SHELL ||
prefetchHeaderValue === NEXT_ROUTER_PREFETCH_RUNTIME_NAVIGATION
? prefetchHeaderValue
: undefined
: // For runtime prefetches, we always perform a dynamic request,
// 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.
getRequestMeta(req, 'isPrefetchRSCRequest')
? '1'
? NEXT_ROUTER_PREFETCH_STATIC
: undefined
const segmentPrefetchRSCRequest =
......
......@@ -28,6 +28,7 @@ import type { ParsedRequestHeaders } from './parse-request-headers'
import type { ServerActionRequestMetadata } from '../../lib/server-action-request-meta'
import {
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_PREFETCH_STATIC,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_ROUTER_STATE_TREE_HEADER,
NEXT_URL,
......@@ -152,7 +153,7 @@ export class AppPageRouteModule extends RouteModule<
// Mark the request as a router prefetch request.
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
addRequestMeta(req, 'isRSCRequest', true)
......
......@@ -2,6 +2,7 @@ import type { IncomingMessage } from 'http'
import {
NEXT_ROUTER_PREFETCH_HEADER,
NEXT_ROUTER_PREFETCH_STATIC,
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
RSC_HEADER,
} from '../../../client/components/app-router-headers'
......@@ -31,7 +32,8 @@ export function applyAppPageRscRequestMetaFromHeaders(
addRequestMeta(req as IncomingMessage, 'isRSCRequest', true)
const isPrefetchRequest =
getHeaderValue(req.headers[NEXT_ROUTER_PREFETCH_HEADER]) === '1'
getHeaderValue(req.headers[NEXT_ROUTER_PREFETCH_HEADER]) ===
NEXT_ROUTER_PREFETCH_STATIC
if (!isPrefetchRequest) {
return
}
......
......@@ -8,7 +8,12 @@ import {
NEXT_ROUTER_SEGMENT_PREFETCH_HEADER,
NEXT_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'
import { AppStage } from '../../../client/components/segment-cache/types'
import { isRSCRequestHeader } from '../../lib/is-rsc-request'
import { getScriptNonceFromHeaders } from '../../app-render/get-script-nonce-from-header'
import { parseAndValidateFlightRouterState } from '../../app-render/parse-and-validate-flight-router-state'
......@@ -28,13 +33,13 @@ export interface ParsedRequestHeaders {
*/
readonly flightRouterState: FlightRouterState | undefined
readonly isPrefetchRequest: boolean
readonly isRuntimePrefetchRequest: boolean
/**
* App Shell prefetch: a runtime prefetch that the server renders with
* params omitted (any `await params` hangs forever). Produces the
* param-independent shell of the route. Implies isRuntimePrefetchRequest.
* The stage a runtime prefetch asks for, or null if this isn't a runtime
* prefetch. A runtime prefetch of the shell is rendered with params omitted
* (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 isHmrRefresh: boolean
readonly isRSCRequest: boolean
......@@ -53,16 +58,26 @@ export function parseRequestHeaders(
// runtime prefetch requests are *not* treated as prefetch requests
// (TODO: this is confusing, we should refactor this to express this better)
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 &&
(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
......@@ -107,8 +122,7 @@ export function parseRequestHeaders(
return {
flightRouterState,
isPrefetchRequest,
isRuntimePrefetchRequest,
isAppShellPrefetchRequest,
runtimePrefetchStage,
isRouteTreePrefetchRequest,
isHmrRefresh,
isRSCRequest,
......
......@@ -25,7 +25,7 @@ export interface NavigateOptions {
}
export interface PrefetchOptions {
kind?: 'auto' | 'full'
kind?: 'auto' | 'full' | 'shell' | 'prefetch' | 'navigation'
onInvalidate?: () => void
}
......
......@@ -293,14 +293,16 @@ export const enum PrefetchHint {
// does not propagate.
ShouldAttemptStaticShell = 0b100000000000000,
ShouldAttemptStaticPrefetch = 0b1000000000000000,
ShouldAttemptStaticNavigation = 0b10000000000000000,
// This dynamic segment only accepts build-time parameter values. Kept on
// the affected node, without propagating or copying it to other segments.
// Until the client knows the allowed values, any such node prevents route
// 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
// 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
export const StaticAttemptHints =
PrefetchHint.ShouldAttemptStaticShell |
PrefetchHint.ShouldAttemptStaticPrefetch
PrefetchHint.ShouldAttemptStaticPrefetch |
PrefetchHint.ShouldAttemptStaticNavigation
/**
* The subset of PrefetchHint bits that propagate upward from a child segment to
......@@ -531,18 +534,19 @@ type NavigationFlightResponseBase = {
* TransportSegmentData). */
s?: AsyncIterable<number>
/**
* stageByteLengths - The byte offset where each stage ends, in stage order
* starting with the shell. A stage is listed only when a later stage added
* bytes; an unlisted stage ends at the end of the response, and so does the
* last stage, which is never listed. Absent when the response wasn't
* staged.
* stageByteLengths - Where each stage ends in the response, in bytes,
* indexed by AppStage: first the shell, then the prefetch stage. We only
* list a stage if a later stage added more bytes. Otherwise the stage ends
* at the end of the response, like the navigation stage always does.
* 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.
* The shell prefix is the shell variant of every segment (param-dependent
* content reduced to still-pending references). In a per-segment prefetch
* response the offsets are the segment response's own, measured against a
* staged decode of the page. The resolution row flushes past every offset,
* so a truncated decode reads it as pending, which is harmless.
* If you decode the response up to one of these offsets, you get the
* response as it was at the end of that stage. We use the shell's prefix
* as the shell for every segment. We only decode the prefetch stage's
* prefix to read its `u`, to find out whether anything up to that point
* read runtime data. A per-segment prefetch response lists its own
* 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>>
/**
......
......@@ -23,7 +23,7 @@ export function createLinkPrefetchPartialError(pathname: string): Error {
`This will lead to slower, more expensive prefetches.\n\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` +
` - [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` +
`Learn more: https://nextjs.org/docs/messages/instant-link-prefetch-partial`
)
......
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 textEncoder = new TextEncoder()
......@@ -22,7 +28,13 @@ function normalizeCacheBustingInput(
}
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,
stateTreeHeader: string | string[] | undefined,
nextUrlHeader: string | string[] | undefined
......@@ -58,7 +70,13 @@ async function computeCacheBustingSearchParamFromInput(
}
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,
stateTreeHeader: string | string[] | undefined,
nextUrlHeader: string | string[] | undefined
......@@ -77,7 +95,13 @@ export async function computeCacheBustingSearchParam(
}
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,
stateTreeHeader: string | string[] | undefined,
nextUrlHeader: string | string[] | undefined
......
......@@ -2,8 +2,13 @@ import { LinkAccordion } from '../components/link-accordion'
export default function Page() {
return (
<LinkAccordion unstable_dynamicOnHover href="/dynamic">
Dynamic page
</LinkAccordion>
<>
<LinkAccordion unstable_dynamicOnHover href="/dynamic">
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', () => {
await link.click()
}, '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() {
Partially static page (prefetch=true)
</LinkAccordion>
</li>
<li>
<LinkAccordion
href="/partially-static"
prefetch="navigation"
id="partially-static-navigation"
>
Partially static page (prefetch=navigation)
</LinkAccordion>
</li>
</ul>
)
}
......@@ -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 () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
......
import Link from 'next/link'
import { LinkAccordion } from '../../components/link-accordion'
import { PrefetchButton } from '../../components/prefetch-button'
export default function Page() {
return (
......@@ -147,6 +148,20 @@ export default function Page() {
Runtime navigation post "speculative-1" (prefetch=true)
</LinkAccordion>
</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>
<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', () => {
'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()', () => {
......
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 type * as Playwright from 'playwright'
import {
......@@ -67,9 +67,7 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
)
// we only care about the static hints, inlining is not relevant.
const hintsMask =
PrefetchHint.ShouldAttemptStaticShell |
PrefetchHint.ShouldAttemptStaticPrefetch
const hintsMask = StaticAttemptHints
// The page awaits static params, so:
// - the shell can be static (ShouldAttemptStaticShell hint set),
......@@ -81,16 +79,16 @@ describe('Partial prefetching with static params and ISR fallbacks', () => {
)
).toMatchInlineSnapshot(`
{
"hints": "ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch | ...",
"hints": "ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch | ShouldAttemptStaticNavigation | ...",
"slots": {
"children": {
"hints": "ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch | ...",
"hints": "ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch | ShouldAttemptStaticNavigation | ...",
"slots": {
"children": {
"hints": "ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch | ...",
"hints": "ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch | ShouldAttemptStaticNavigation | ...",
"slots": {
"children": {
"hints": "ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch | ...",
"hints": "ShouldAttemptStaticShell | ShouldAttemptStaticPrefetch | ShouldAttemptStaticNavigation | ...",
"slots": null,
},
},
......
......@@ -55,6 +55,14 @@ export default function Page() {
Param 1 (prefetch=true)
</LinkAccordion>
</li>
<li>
<LinkAccordion
href="/params-used-after-navigation/1"
prefetch="navigation"
>
Param 1 (prefetch=navigation)
</LinkAccordion>
</li>
<li>
<Link href="/params-used-after-navigation/2" prefetch={false}>
Param 2 (unprefetched)
......@@ -105,6 +113,19 @@ export default function Page() {
Uses runtime APIs after navigation()
</LinkAccordion>
</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>
<LinkAccordion href="/uses-navigation-static">
Uses navigation() on a static page
......@@ -274,6 +295,16 @@ export default function Page() {
(prefetch=true)
</LinkAccordion>
</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>
<LinkAccordion href="/ensure-static/prefetch/uses-cookies">
Page with <code>ensureStatic = "prefetch"</code> that uses cookies
......@@ -288,6 +319,15 @@ export default function Page() {
(prefetch=true)
</LinkAccordion>
</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>
<h2>ensureStatic = "navigation"</h2>
......@@ -304,6 +344,14 @@ export default function Page() {
prerendered param 1 (prefetch=true)
</LinkAccordion>
</li>
<li>
<LinkAccordion
href="/ensure-static/navigation/prerendered-1"
prefetch="navigation"
>
prerendered param 1 (prefetch="navigation")
</LinkAccordion>
</li>
<li>
<LinkAccordion
href="/ensure-static/navigation/not-prerendered-1"
......@@ -312,11 +360,20 @@ export default function Page() {
not-prerendered param 1 (prefetch=true)
</LinkAccordion>
</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 */}
<DynamicLinkAccordion
hrefPattern="/ensure-static/navigation/not-prerendered-{counter}"
placeholder="{counter}"
initialCount={2}
initialCount={3}
/>
</main>
)
......
......@@ -25,16 +25,16 @@ export default async function Page() {
async function Navigation() {
// 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()
return (
<>
<div id="navigation-content">Navigation content</div>
<Suspense
fallback={<p id="dynamic-loading">Loading dynamic content...</p>}
fallback={<p id="runtime-loading">Loading runtime content...</p>}
>
<DynamicContent />
<RuntimeContent />
</Suspense>
</>
)
......@@ -46,7 +46,7 @@ async function shortStaleCache() {
return Date.now()
}
async function DynamicContent() {
async function RuntimeContent() {
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 { waitForNoRedbox } from 'next-test-utils'
describe('next-link', () => {
const { next, isNextDev } = nextTestSetup({
......@@ -36,7 +37,7 @@ describe('next-link', () => {
if (isNextDev) {
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.",
"environmentLabel": null,
"label": "Runtime Error",
......@@ -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'
// - 'runtime': dynamic prefetch requests, issued by
// `fetchSegmentPrefetchesUsingRuntimeRequest` in the client. These carry a
// 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
// (no prefetch header) — send the same headers as plain prefetches and
// navigations respectively, so they cannot be demonstrably classified and
......@@ -37,6 +38,7 @@ const APP_SHELL_PREFETCH_VALUE = '3'
// prefetches. Expectations that specify a `kind` never claim these.
const NEXT_ROUTER_SEGMENT_PREFETCH_HEADER = 'next-router-segment-prefetch'
const PPR_RUNTIME_PREFETCH_VALUE = '2'
const NAVIGATION_RUNTIME_PREFETCH_VALUE = '4'
type ResponseKind = 'static' | 'runtime'
......@@ -92,9 +94,9 @@ type ExpectedResponseConfig = {
* the kind of prefetch request that produced them: 'static' matches only
* per-segment static prefetches (those with a `next-router-segment-prefetch`
* request header), and 'runtime' matches only dynamic prefetch requests
* (those with a `next-router-prefetch` header value of '2' (PPRRuntime) or
* '3' (RuntimeShell)). If omitted, any router response can satisfy the
* expectation. Note that App Shell (RuntimeShell) responses are excluded
* (those with a `next-router-prefetch` header value of '2' (up to the
* prefetch stage), '3' (the shell), or '4' (up to the navigation stage)).
* 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
* should match an App Shell response additionally requires passing
* `includeAppShellRequests: true` to `createRouterAct`.
......@@ -339,7 +341,9 @@ export function createRouterAct(
kind = 'static'
} else if (
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'
}
......
......@@ -17,6 +17,9 @@ export default function Page() {
router.prefetch('/about')
router.prefetch('/about', { kind: 'auto' })
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.push('/redirect')
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