Unverified Commit 1c5f64b9 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[Cache Components] Runtime prefetching (#81088)

Initial implementation of runtime prefetching.

A "runtime prefetch" is a more complete version of a static prefetch
(i.e. the one that a link does by default), rendered on demand, and not
cached server-side. It will render the server part of the page
dynamically, allowing the usage of
- `params` and `searchParams`
- `cookies()`
- `"use cache: private"` (these are omitted from static prerenders)
- `"use cache"` with a short expire time (these are omitted from static
prerenders)

The result may be partial (in the PPR sense). It will exclude any parts
of the page that depend on
- uncached IO
- `connection()`, `headers()`
This allows the client router to cache the result, because it has a
well-defined stale time. Note that public caches with a stale time below
a certain fixed treshold will also be excluded, because it wouldn't make
sense to keep them around in the router cache if we need to throw them
away soon after getting them.

With this PR, `<Link prefetch={true}>` changes meaning
if `clientSegmentCache` + `cacheComponents` are enabled. It will now
initiate a runtime prefetch instead of a "full" prefetch, which included
everything that a navigation request would. Full prefetches can be done
via `<Link prefetch="unstable_forceStale">`. If only one of the two
flags is on, the behavior of `<Link prefetch={true}>` is unchanged from
how it currently works.

I've split the changes up into separate commits for ease of review:
1. Introducing the new workUnitStore type
2. Server - handling the prefetch header and rendering
3. Client - Link and segment cache changes

### Implementation notes

The client router sends `next-router-prefetch: 2` to signal that it
wants a runtime prefetch (as opposed to the old `next-router-prefetch:
1`, which is used for static prefetches).

> NOTE: this builder change is required for this to work on vercel
https://github.com/vercel/vercel/pull/13547. It was released in
`vercel@44.6.5`

Somewhat confusingly, in order to to avoid existing static prefetch
codepaths, we need the server to _not_ treat this as "a prefetch
request". Instead, we want to mostly treat this like we would a
navigation request, and render dynamically. This means that:
- `isPrefetchRequest` (from `parseRequestHeaders` in `app-render`) will
be `false`
- `getRequestMeta(req, 'isPrefetchRSCRequest')` won't be set

This is a bit ugly but it works for now. I'll try to clean it up in the
future.

We render a payload of the same shape as a navigation request (including
omitting shared layouts, as instructed by the `Next-Router-State-Tree`
header). But unlike a navigation request, we do a cache-components-style
prerender at runtime in order to exclude uncached/sync IO.

This prerender uses a new workUnitStore type, `'prerender-runtime'`.
This store type changes the behavior of `cookies()`, `params`,
`searchParams`, `"use cache: private"`, `next/root-params`, and others.
Unlike a static prerender, if we detect a bad uncached/sync IO usage, we
just log an error (instead of throwing it and erroring) and respond with
whatever we managed to render up until the render was aborted, in hopes
that we can still return something useful to the client. This request is
happening at runtime, so we should try to handle errors gracefully.

We track whether or not the prerender has any dynamic holes, and if it
does, set `x-nextjs-postponed: 1` on the response. This tells the client
router if we still need to fetch more data when navigating, or if we can
skip it because we already have a complete page. Ideally, we'd track
this information per-segment for better reuse on the client side, but
that's not in scope for this PR.

We also set the `x-nextjs-staletime` header on the response to tell the
client router how long it should keep this prefetch in the cache. Note
that this does not affect `Cache-Control`, which should still be the
same as a dynamic navigation request to prevent it from being cached by
anything other than the client router.
This may be improved in the future if it turns out we can safely set an
appropriate `Cache-Control: private, ...` that also accounts for e.g.
changing cookie values, but i'm erring on the side of caution for now.
parent 4b0f7465
......@@ -764,5 +764,11 @@
"763": "\\`unstable_rootParams\\` must not be used within a client component. Next.js should be preventing it from being included in client components statically, but did not in this case.",
"764": "Missing workStore in %s",
"765": "Route %s used %s inside a Route Handler. Support for this API in Route Handlers is planned for a future version of Next.js.",
"766": "%s was used inside a Server Action. This is not supported. Functions from 'next/root-params' can only be called in the context of a route."
"766": "%s was used inside a Server Action. This is not supported. Functions from 'next/root-params' can only be called in the context of a route.",
"767": "A runtime prerender store should not be used for a route handler.",
"768": "createPrerenderSearchParamsForClientPage should not be called in a runtime prerender.",
"769": "createSearchParamsFromClient should not be called in a runtime prerender.",
"770": "createParamsFromClient should not be called in a runtime prerender.",
"771": "\\`%s\\` was called during a runtime prerender. Next.js should be preventing %s from being included in server components statically, but did not in this case.",
"772": "FetchStrategy.PPRRuntime should never be used when `experimental.clientSegmentCache` is disabled"
}
......@@ -192,7 +192,7 @@ export async function handler(
*/
const isPrefetchRSCRequest =
getRequestMeta(req, 'isPrefetchRSCRequest') ??
Boolean(req.headers[NEXT_ROUTER_PREFETCH_HEADER])
req.headers[NEXT_ROUTER_PREFETCH_HEADER] === '1' // exclude runtime prefetches, which use '2'
// NOTE: Don't delete headers[RSC] yet, it still needs to be used in renderToHTML later
......
......@@ -61,6 +61,7 @@ export default function Form({
}
}
// TODO(runtime-ppr): allow runtime prefetches in Form
const prefetch =
prefetchProp === false || prefetchProp === null ? prefetchProp : null
......
......@@ -20,7 +20,10 @@ import {
import { isLocalURL } from '../../shared/lib/router/utils/is-local-url'
import { dispatchNavigateAction } from '../components/app-router-instance'
import { errorOnce } from '../../shared/lib/utils/error-once'
import { FetchStrategy } from '../components/segment-cache'
import {
FetchStrategy,
type PrefetchTaskFetchStrategy,
} from '../components/segment-cache'
type Url = string | UrlObject
type RequiredKeys<T> = {
......@@ -151,10 +154,10 @@ type InternalLinkProps = {
* </Link>
* ```
*/
prefetch?: boolean | 'auto' | null
prefetch?: boolean | 'auto' | null | 'unstable_forceStale'
/**
* (unstable) Switch to a dynamic prefetch on hover. Effectively the same as
* (unstable) Switch to a full prefetch on hover. Effectively the same as
* updating the prefetch prop to `true` in a mouse event.
*/
unstable_dynamicOnHover?: boolean
......@@ -356,18 +359,12 @@ export default function LinkComponent(
const router = React.useContext(AppRouterContext)
const prefetchEnabled = prefetchProp !== false
/**
* The possible states for prefetch are:
* - null: this is the default "auto" mode, where we will prefetch partially if the link is in the viewport
* - true: we will prefetch if the link is visible and prefetch the full page, not just partially
* - false: we will not prefetch if in the viewport at all
* - 'unstable_dynamicOnHover': this starts in "auto" mode, but switches to "full" when the link is hovered
*/
const fetchStrategy =
prefetchProp === null || prefetchProp === 'auto'
? // We default to PPR. We'll discover whether or not the route supports it with the initial prefetch.
prefetchProp !== false
? getFetchStrategyFromPrefetchProp(prefetchProp)
: // TODO: it makes no sense to assign a fetchStrategy when prefetching is disabled.
FetchStrategy.PPR
: FetchStrategy.Full
if (process.env.NODE_ENV !== 'production') {
function createPropError(args: {
......@@ -470,11 +467,12 @@ export default function LinkComponent(
if (
props[key] != null &&
valType !== 'boolean' &&
props[key] !== 'auto'
props[key] !== 'auto' &&
props[key] !== 'unstable_forceStale'
) {
throw createPropError({
key,
expected: '`boolean | "auto"`',
expected: '`boolean | "auto" | "unstable_forceStale"`',
actual: valType,
})
}
......@@ -745,3 +743,41 @@ const LinkStatusContext = createContext<
export const useLinkStatus = () => {
return useContext(LinkStatusContext)
}
function getFetchStrategyFromPrefetchProp(
prefetchProp: Exclude<LinkProps['prefetch'], undefined | false>
): PrefetchTaskFetchStrategy {
if (
process.env.__NEXT_CACHE_COMPONENTS &&
process.env.__NEXT_CLIENT_SEGMENT_CACHE
) {
// In the new implementation:
// - `prefetch={true}` is a runtime prefetch
// (includes cached IO + params + cookies, with dynamic holes for uncached IO).
// - `unstable_forceStale` is a "full" prefetch
// (forces inclusion of all dynamic data, i.e. the old behavior of `prefetch={true}`)
if (prefetchProp === true) {
return FetchStrategy.PPRRuntime
}
if (prefetchProp === 'unstable_forceStale') {
return FetchStrategy.Full
}
// `null` or `"auto"`: this is the default "auto" mode, where we will prefetch partially if the link is in the viewport.
// This will also include invalid prop values that don't match the types specified here.
// (although those should've been filtered out by prop validation in dev)
prefetchProp satisfies null | 'auto'
// In `clientSegmentCache`, we default to PPR, and we'll discover whether or not the route supports it with the initial prefetch.
// If we're not using `clientSegmentCache`, this will be converted into a `PrefetchKind.AUTO`.
return FetchStrategy.PPR
} else {
return prefetchProp === null || prefetchProp === 'auto'
? // In `clientSegmentCache`, we default to PPR, and we'll discover whether or not the route supports it with the initial prefetch.
// If we're not using `clientSegmentCache`, this will be converted into a `PrefetchKind.AUTO`.
FetchStrategy.PPR
: // In the old implementation without runtime prefetches, `prefetch={true}` forces all dynamic data to be prefetched.
// To preserve backwards-compatibility, anything other than `false`, `null`, or `"auto"` results in a full prefetch.
// (although invalid values should've been filtered out by prop validation in dev)
FetchStrategy.Full
}
}
......@@ -329,6 +329,8 @@ export const publicAppRouterInstance: AppRouterInstance = {
const actionQueue = getAppRouterActionQueue()
const prefetchKind = options?.kind ?? PrefetchKind.AUTO
// We don't currently offer a way to issue a runtime prefetch via `router.prefetch()`.
// This will be possible when we update its API to not take a PrefetchKind.
let fetchStrategy: PrefetchTaskFetchStrategy
switch (prefetchKind) {
case PrefetchKind.AUTO: {
......
......@@ -12,6 +12,7 @@ export function bailoutToClientRendering(reason: string): void | never {
if (workUnitStore) {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-runtime':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
......
......@@ -17,6 +17,7 @@ import {
} from './segment-cache'
import { startTransition } from 'react'
import { PrefetchKind } from './router-reducer/router-reducer-types'
import { InvariantError } from '../../shared/lib/invariant-error'
type LinkElement = HTMLAnchorElement | SVGAElement
......@@ -264,7 +265,7 @@ export function onNavigationIntent(
process.env.__NEXT_DYNAMIC_ON_HOVER &&
unstable_upgradeToDynamicPrefetch
) {
// Switch to a full, dynamic prefetch
// Switch to a full prefetch
instance.fetchStrategy = FetchStrategy.Full
}
rescheduleLinkPrefetch(instance, PrefetchPriority.Intent)
......@@ -378,6 +379,13 @@ function prefetchWithOldCacheImplementation(instance: PrefetchableInstance) {
prefetchKind = PrefetchKind.FULL
break
}
case FetchStrategy.PPRRuntime: {
// We can only get here if Client Segment Cache is off, and in that case
// it shouldn't be possible for a link to request a runtime prefetch.
throw new InvariantError(
'FetchStrategy.PPRRuntime should never be used when `experimental.clientSegmentCache` is disabled'
)
}
default: {
instance.fetchStrategy satisfies never
// Unreachable, but otherwise typescript will consider the variable unassigned
......
......@@ -24,6 +24,7 @@ function hasFallbackRouteParams(): boolean {
return fallbackParams ? fallbackParams.size > 0 : false
case 'prerender-legacy':
case 'request':
case 'prerender-runtime':
case 'cache':
case 'private-cache':
case 'unstable-cache':
......
......@@ -55,7 +55,7 @@ export type RequestHeaders = {
[RSC_HEADER]?: '1'
[NEXT_ROUTER_STATE_TREE_HEADER]?: string
[NEXT_URL]?: string
[NEXT_ROUTER_PREFETCH_HEADER]?: '1'
[NEXT_ROUTER_PREFETCH_HEADER]?: '1' | '2'
[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER]?: string
'x-deployment-id'?: string
[NEXT_HMR_REFRESH_HEADER]?: '1'
......
......@@ -414,7 +414,9 @@ export function getSegmentKeypathForTask(
// the cache key, because the search params are treated as dynamic data. The
// cache entry is valid for all possible search param values.
const isDynamicTask =
task.fetchStrategy === FetchStrategy.Full || !route.isPPREnabled
task.fetchStrategy === FetchStrategy.Full ||
task.fetchStrategy === FetchStrategy.PPRRuntime ||
!route.isPPREnabled
return isDynamicTask && path.endsWith('/' + PAGE_SEGMENT_KEY)
? [path, route.renderedSearch]
: [path]
......@@ -639,11 +641,21 @@ export function upsertSegmentEntry(
// this function and confirming it's the same as `existingEntry`.
const existingEntry = readExactSegmentCacheEntry(now, keypath)
if (existingEntry !== null) {
if (candidateEntry.isPartial && !existingEntry.isPartial) {
// Don't replace a full segment with a partial one. A case where this
// might happen is if the existing segment was fetched via
// <Link prefetch={true}>.
// Don't replace a more specific segment with a less-specific one. A case where this
// might happen is if the existing segment was fetched via
// `<Link prefetch={true}>`.
if (
// We fetched the new segment using a different, less specific fetch strategy
// than the segment we already have in the cache, so it can't have more content.
(candidateEntry.fetchStrategy !== existingEntry.fetchStrategy &&
!canNewFetchStrategyProvideMoreContent(
existingEntry.fetchStrategy,
candidateEntry.fetchStrategy
)) ||
// The existing entry isn't partial, but the new one is.
// (TODO: can this be true if `candidateEntry.fetchStrategy >= existingEntry.fetchStrategy`?)
(!existingEntry.isPartial && candidateEntry.isPartial)
) {
// We're going to leave the entry on the owner's `revalidating` field
// so that it doesn't get revalidated again unnecessarily. Downgrade the
// Fulfilled entry to Rejected and null out the data so it can be garbage
......@@ -655,6 +667,7 @@ export function upsertSegmentEntry(
rejectedEntry.rsc = null
return null
}
// Evict the existing entry from the cache.
deleteSegmentFromCache(existingEntry, keypath)
}
......@@ -1355,7 +1368,10 @@ export async function fetchSegmentOnCacheMiss(
export async function fetchSegmentPrefetchesUsingDynamicRequest(
task: PrefetchTask,
route: FulfilledRouteCacheEntry,
fetchStrategy: FetchStrategy.LoadingBoundary | FetchStrategy.Full,
fetchStrategy:
| FetchStrategy.LoadingBoundary
| FetchStrategy.PPRRuntime
| FetchStrategy.Full,
dynamicRequestTree: FlightRouterState,
spawnedEntries: Map<string, PendingSegmentCacheEntry>
): Promise<PrefetchSubtaskResult<null> | null> {
......@@ -1370,13 +1386,26 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
if (nextUrl !== null) {
headers[NEXT_URL] = nextUrl
}
// Only set the prefetch header if we're not doing a "full" prefetch. We
// omit the prefetch header from a full prefetch because it's essentially
// just a navigation request that happens ahead of time — it should include
// all the same data in the response.
if (fetchStrategy !== FetchStrategy.Full) {
headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'
switch (fetchStrategy) {
case FetchStrategy.Full: {
// We omit the prefetch header from a full prefetch because it's essentially
// just a navigation request that happens ahead of time — it should include
// all the same data in the response.
break
}
case FetchStrategy.PPRRuntime: {
headers[NEXT_ROUTER_PREFETCH_HEADER] = '2'
break
}
case FetchStrategy.LoadingBoundary: {
headers[NEXT_ROUTER_PREFETCH_HEADER] = '1'
break
}
default: {
fetchStrategy satisfies never
}
}
try {
const response = await fetchPrefetchResponse(url, headers)
if (!response || !response.ok || !response.body) {
......@@ -1425,9 +1454,13 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
prefetchStream
) as Promise<NavigationFlightResponse>)
// Since we did not set the prefetch header, the response from the server
// will never contain dynamic holes.
const isResponsePartial = false
const isResponsePartial =
fetchStrategy === FetchStrategy.PPRRuntime
? // A runtime prefetch may have holes.
!!response.headers.get(NEXT_DID_POSTPONE_HEADER)
: // Full and LoadingBoundary prefetches cannot have holes.
// (even if we did set the prefetch header, we only use this codepath for non-PPR-enabled routes)
false
// Aside from writing the data into the cache, this function also returns
// the entries that were fulfilled, so we can streamingly update their sizes
......@@ -1455,7 +1488,10 @@ export async function fetchSegmentPrefetchesUsingDynamicRequest(
function writeDynamicTreeResponseIntoCache(
now: number,
task: PrefetchTask,
fetchStrategy: FetchStrategy.LoadingBoundary | FetchStrategy.Full,
fetchStrategy:
| FetchStrategy.LoadingBoundary
| FetchStrategy.PPRRuntime
| FetchStrategy.Full,
response: RSCResponse,
serverData: NavigationFlightResponse,
entry: PendingRouteCacheEntry,
......@@ -1553,7 +1589,10 @@ function rejectSegmentEntriesIfStillPending(
function writeDynamicRenderResponseIntoCache(
now: number,
task: PrefetchTask,
fetchStrategy: FetchStrategy.LoadingBoundary | FetchStrategy.Full,
fetchStrategy:
| FetchStrategy.LoadingBoundary
| FetchStrategy.PPRRuntime
| FetchStrategy.Full,
response: RSCResponse,
serverData: NavigationFlightResponse,
isResponsePartial: boolean,
......@@ -1661,7 +1700,10 @@ function writeDynamicRenderResponseIntoCache(
function writeSeedDataIntoCache(
now: number,
task: PrefetchTask,
fetchStrategy: FetchStrategy.LoadingBoundary | FetchStrategy.Full,
fetchStrategy:
| FetchStrategy.LoadingBoundary
| FetchStrategy.PPRRuntime
| FetchStrategy.Full,
route: FulfilledRouteCacheEntry,
staleAt: number,
seedData: CacheNodeSeedData,
......@@ -1855,3 +1897,31 @@ function createPromiseWithResolvers<T>(): PromiseWithResolvers<T> {
})
return { resolve: resolve!, reject: reject!, promise }
}
/**
* Checks whether the new fetch strategy is likely to provide more content than the old one.
*
* Generally, when an app uses dynamic data, a "more specific" fetch strategy is expected to provide more content:
* - `LoadingBoundary` only provides static layouts
* - `PPR` can provide shells for each segment (even for segments that use dynamic data)
* - `PPRRuntime` can additionally include content that uses searchParams, params, or cookies
* - `Full` includes all the content, even if it uses dynamic data
*
* However, it's possible that a more specific fetch strategy *won't* give us more content if:
* - a segment is fully static
* (then, `PPR`/`PPRRuntime`/`Full` will all yield equivalent results)
* - providing searchParams/params/cookies doesn't reveal any more content, e.g. because of an `await connection()`
* (then, `PPR` and `PPRRuntime` will yield equivalent results, only `Full` will give us more)
* Because of this, when comparing two segments, we should also check if the existing segment is partial.
* If it's not partial, then there's no need to prefetch it again, even using a "more specific" strategy.
* There's currently no way to know if `PPRRuntime` will yield more data that `PPR`, so we have to assume it will.
*
* Also note that, in practice, we don't expect to be comparing `LoadingBoundary` to `PPR`/`PPRRuntime`,
* because a non-PPR-enabled route wouldn't ever use the latter strategies. It might however use `Full`.
*/
export function canNewFetchStrategyProvideMoreContent(
currentStrategy: FetchStrategy,
newStrategy: FetchStrategy
): boolean {
return currentStrategy < newStrategy
}
......@@ -142,9 +142,13 @@ export const enum PrefetchPriority {
}
export const enum FetchStrategy {
PPR,
Full,
LoadingBoundary,
// Deliberately ordered so we can easily compare two segments
// and determine if one segment is "more specific" than another
// (i.e. if it's likely that it contains more data)
LoadingBoundary = 0,
PPR = 1,
PPRRuntime = 2,
Full = 3,
}
/**
......@@ -153,4 +157,7 @@ export const enum FetchStrategy {
* until we complete the initial tree prefetch request, so we use `PPR` to signal both cases
* and adjust it based on the route when actually fetching.
* */
export type PrefetchTaskFetchStrategy = FetchStrategy.PPR | FetchStrategy.Full
export type PrefetchTaskFetchStrategy =
| FetchStrategy.PPR
| FetchStrategy.PPRRuntime
| FetchStrategy.Full
......@@ -82,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' | null | 'unstable_forceStale'
/**
* 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.
......
......@@ -300,6 +300,7 @@ async function createComponentTreeInternal(
if (workUnitStore) {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-runtime':
case 'prerender-legacy':
case 'prerender-ppr':
if (workUnitStore.revalidate > defaultRevalidate) {
......
......@@ -230,6 +230,7 @@ export function trackDynamicDataInDynamicRender(workUnitStore: WorkUnitStore) {
// A private cache scope is already dynamic by definition.
return
case 'prerender':
case 'prerender-runtime':
case 'prerender-legacy':
case 'prerender-ppr':
case 'prerender-client':
......@@ -335,6 +336,21 @@ export function abortAndThrowOnSynchronousRequestDataAccess(
)
}
/**
* Use this function when dynamically prerendering with dynamicIO.
* We don't want to error, because it's better to return something
* (and we've already aborted the render at the point where the sync dynamic error occured),
* but we should log an error server-side.
* @internal
*/
export function warnOnSyncDynamicError(dynamicTracking: DynamicTrackingState) {
if (dynamicTracking.syncDynamicErrorWithStack) {
// the server did something sync dynamic, likely
// leading to an early termination of the prerender.
console.error(dynamicTracking.syncDynamicErrorWithStack)
}
}
// For now these implementations are the same so we just reexport
export const trackSynchronousRequestDataAccessInDev =
trackSynchronousPlatformIOAccessInDev
......@@ -519,6 +535,7 @@ export function createHangingInputAbortSignal(
): AbortSignal | undefined {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-runtime':
const controller = new AbortController()
if (workUnitStore.cacheSignal) {
......@@ -599,6 +616,10 @@ export function useDynamicRouteParams(expression: string) {
}
break
}
case 'prerender-runtime':
throw new InvariantError(
`\`${expression}\` was called during a runtime prerender. Next.js should be preventing ${expression} from being included in server components statically, but did not in this case.`
)
case 'cache':
case 'private-cache':
throw new InvariantError(
......
......@@ -260,6 +260,7 @@ export async function decryptActionBoundArgs(
switch (workUnitStore?.type) {
case 'prerender':
case 'prerender-runtime':
// Explicitly don't close the stream here (until prerendering is
// complete) so that hanging promises are not rejected.
if (workUnitStore.renderSignal.aborted) {
......
......@@ -71,6 +71,7 @@ export function useFlightStream<T>(
flightResponses.set(flightStream, responseOnNextTick)
return responseOnNextTick
case 'prerender':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
......
......@@ -82,15 +82,34 @@ export interface RequestStore extends CommonWorkUnitStore {
export type PrerenderStoreModern =
| PrerenderStoreModernClient
| PrerenderStoreModernServer
| PrerenderStoreModernRuntime
export interface PrerenderStoreModernClient extends PrerenderStoreModernCommon {
/** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */
export type StaticPrerenderStoreModern = Exclude<
PrerenderStoreModern,
PrerenderStoreModernRuntime
>
export interface PrerenderStoreModernClient
extends PrerenderStoreModernCommon,
StaticPrerenderStoreCommon {
readonly type: 'prerender-client'
}
export interface PrerenderStoreModernServer extends PrerenderStoreModernCommon {
export interface PrerenderStoreModernServer
extends PrerenderStoreModernCommon,
StaticPrerenderStoreCommon {
readonly type: 'prerender'
}
export interface PrerenderStoreModernRuntime
extends PrerenderStoreModernCommon {
readonly type: 'prerender-runtime'
readonly cookies: RequestStore['cookies']
readonly draftMode: RequestStore['draftMode']
}
export interface RevalidateStore {
// Collected revalidate times and tags for this document during the prerender.
revalidate: number // in seconds. 0 means dynamic. INFINITE_CACHE and higher means never revalidate.
......@@ -139,20 +158,6 @@ interface PrerenderStoreModernCommon
readonly rootParams: Params
/**
* The set of unknown route parameters. Accessing these will be tracked as
* a dynamic access.
*/
readonly fallbackRouteParams: FallbackRouteParams | null
/**
* When true, the page is prerendered as a fallback shell, while allowing any
* dynamic accesses to result in an empty shell. This is the case when there
* are also routes prerendered with a more complete set of params.
* Prerendering those routes would catch any invalid dynamic accesses.
*/
readonly allowEmptyStaticShell: boolean
/**
* A mutable resume data cache for this prerender.
*/
......@@ -179,6 +184,22 @@ interface PrerenderStoreModernCommon
readonly captureOwnerStack: undefined | (() => string | null)
}
interface StaticPrerenderStoreCommon {
/**
* The set of unknown route parameters. Accessing these will be tracked as
* a dynamic access.
*/
readonly fallbackRouteParams: FallbackRouteParams | null
/**
* When true, the page is prerendered as a fallback shell, while allowing any
* dynamic accesses to result in an empty shell. This is the case when there
* are also routes prerendered with a more complete set of params.
* Prerendering those routes would catch any invalid dynamic accesses.
*/
readonly allowEmptyStaticShell: boolean
}
export interface PrerenderStorePPR
extends CommonWorkUnitStore,
RevalidateStore {
......@@ -210,6 +231,12 @@ export type PrerenderStore =
| PrerenderStorePPR
| PrerenderStoreModern
// /** Like `PrerenderStoreModern`, but only including static prerenders (i.e. not runtime prerenders) */
export type StaticPrerenderStore = Exclude<
PrerenderStore,
PrerenderStoreModernRuntime
>
export interface CommonCacheStore
extends Omit<CommonWorkUnitStore, 'implicitTags'> {
/**
......@@ -289,6 +316,7 @@ export function getPrerenderResumeDataCache(
): PrerenderResumeDataCache | null {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-runtime':
case 'prerender-ppr':
return workUnitStore.prerenderResumeDataCache
case 'prerender-client':
......@@ -313,6 +341,7 @@ export function getRenderResumeDataCache(
case 'request':
return workUnitStore.renderResumeDataCache
case 'prerender':
case 'prerender-runtime':
case 'prerender-client':
if (workUnitStore.renderResumeDataCache) {
// If we are in a prerender, we might have a render resume data cache
......@@ -343,6 +372,7 @@ export function getHmrRefreshHash(
case 'cache':
case 'private-cache':
case 'prerender':
case 'prerender-runtime':
return workUnitStore.hmrRefreshHash
case 'request':
return workUnitStore.cookies.get(NEXT_HMR_REFRESH_HASH_COOKIE)?.value
......@@ -359,6 +389,56 @@ export function getHmrRefreshHash(
return undefined
}
export function isHmrRefresh(
workStore: WorkStore,
workUnitStore: WorkUnitStore
): boolean {
if (workStore.dev) {
switch (workUnitStore.type) {
case 'cache':
case 'private-cache':
case 'request':
return workUnitStore.isHmrRefresh ?? false
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
return false
}
export function getServerComponentsHmrCache(
workStore: WorkStore,
workUnitStore: WorkUnitStore
): ServerComponentsHmrCache | undefined {
if (workStore.dev) {
switch (workUnitStore.type) {
case 'cache':
case 'private-cache':
case 'request':
return workUnitStore.serverComponentsHmrCache
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
return undefined
}
/**
* Returns a draft mode provider only if draft mode is enabled.
*/
......@@ -371,6 +451,7 @@ export function getDraftModeProviderForCacheScope(
case 'cache':
case 'private-cache':
case 'unstable-cache':
case 'prerender-runtime':
case 'request':
return workUnitStore.draftMode
case 'prerender':
......@@ -392,6 +473,7 @@ export function getCacheSignal(
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
return workUnitStore.cacheSignal
case 'prerender-ppr':
case 'prerender-legacy':
......
......@@ -2015,16 +2015,26 @@ export default abstract class Server<
) {
const headers = req.headers
const isPrefetchRSCRequest =
headers[NEXT_ROUTER_PREFETCH_HEADER] ||
getRequestMeta(req, 'isPrefetchRSCRequest')
const prefetchHeaderValue = headers[NEXT_ROUTER_PREFETCH_HEADER]
const routerPrefetch =
prefetchHeaderValue !== undefined
? // We only recognize '1' and '2'. Strip all other values here.
prefetchHeaderValue === '1' || prefetchHeaderValue === '2'
? 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'
: undefined
const segmentPrefetchRSCRequest =
headers[NEXT_ROUTER_SEGMENT_PREFETCH_HEADER] ||
getRequestMeta(req, 'segmentPrefetchRSCRequest')
const expectedHash = computeCacheBustingSearchParam(
isPrefetchRSCRequest ? '1' : '0',
routerPrefetch,
segmentPrefetchRSCRequest,
headers[NEXT_ROUTER_STATE_TREE_HEADER],
headers[NEXT_URL]
......
......@@ -370,6 +370,7 @@ export function createPatchedFetcher(
if (workUnitStore) {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-runtime':
// TODO: Stop accumulating tags in client prerender. (fallthrough)
case 'prerender-client':
case 'prerender-ppr':
......@@ -412,6 +413,7 @@ export function createPatchedFetcher(
break
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
......@@ -552,6 +554,7 @@ export function createPatchedFetcher(
if (hasNoExplicitCacheConfig && workUnitStore !== undefined) {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-runtime':
// While we don't want to do caching in the client scope we know the
// fetch will be dynamic for cacheComponents so we may as well avoid the
// call here. (fallthrough)
......@@ -668,6 +671,7 @@ export function createPatchedFetcher(
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
if (cacheSignal) {
cacheSignal.endRead()
cacheSignal = null
......@@ -721,6 +725,7 @@ export function createPatchedFetcher(
break
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
......@@ -840,6 +845,7 @@ export function createPatchedFetcher(
switch (workUnitStore?.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
return createCachedPrerenderResponse(
res,
cacheKey,
......@@ -912,6 +918,7 @@ export function createPatchedFetcher(
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
// We sometimes use the cache to dedupe fetches that do not
// specify a cache configuration. In these cases we want to
// make sure we still exclude them from prerenders if
......@@ -1013,6 +1020,7 @@ export function createPatchedFetcher(
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
if (cacheSignal) {
cacheSignal.endRead()
cacheSignal = null
......@@ -1052,6 +1060,7 @@ export function createPatchedFetcher(
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
return makeHangingPromise<Response>(
workUnitStore.renderSignal,
'fetch()'
......
......@@ -141,6 +141,7 @@ function patchConsoleMethodDEV(methodName: InterceptableConsoleMethod): void {
switch (workUnitStore?.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
originalMethod.apply(this, dimConsoleCall(methodName, args))
break
case 'prerender-ppr':
......
......@@ -20,7 +20,8 @@ export function io(expression: string, type: ApiType) {
}
switch (workUnitStore.type) {
case 'prerender': {
case 'prerender':
case 'prerender-runtime': {
const prerenderSignal = workUnitStore.controller.signal
if (prerenderSignal.aborted === false) {
......
......@@ -53,7 +53,7 @@ export function connection(): Promise<void> {
}
case 'private-cache': {
// It might not be intuitive to throw for private caches as well, but
// we don't consider dynamic prefetches as "actual requests" (in the
// we don't consider runtime prefetches as "actual requests" (in the
// navigation sense), despite allowing them to read cookies.
const error = new Error(
`Route ${workStore.route} used "connection" inside "use cache: private". The \`connection()\` function is used to indicate the subsequent code must only run when there is an actual navigation request, but caches must be able to be produced before a navigation request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
......@@ -68,6 +68,7 @@ export function connection(): Promise<void> {
)
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
// We return a promise that never resolves to allow the prerender to
// stall at this point.
return makeHangingPromise(
......
......@@ -114,6 +114,7 @@ export function cookies(): Promise<ReadonlyRequestCookies> {
workStore,
workUnitStore
)
case 'prerender-runtime':
case 'private-cache':
return makeUntrackedExoticCookies(workUnitStore.cookies)
case 'request':
......@@ -470,6 +471,7 @@ function syncIODev(route: string | undefined, expression: string) {
break
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
......
......@@ -55,6 +55,7 @@ export function draftMode(): Promise<DraftMode> {
}
switch (workUnitStore.type) {
case 'prerender-runtime':
case 'request':
return createOrGetCachedDraftMode(workUnitStore.draftMode, workStore)
......@@ -62,8 +63,8 @@ export function draftMode(): Promise<DraftMode> {
case 'private-cache':
case 'unstable-cache':
// Inside of `"use cache"` or `unstable_cache`, draft mode is available if
// the outmost work unit store is a request store, and if draft mode is
// enabled.
// the outmost work unit store is a request store (or a runtime prerender),
// and if draft mode is enabled.
const draftModeProvider = getDraftModeProviderForCacheScope(
workStore,
workUnitStore
......@@ -257,6 +258,7 @@ function syncIODev(route: string | undefined, expression: string) {
break
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
......@@ -322,7 +324,9 @@ function trackDynamicDraftMode(expression: string, constructorOpt: Function) {
throw new Error(
`Route ${workStore.route} used "${expression}" inside a function cached with "unstable_cache(...)". The enabled status of draftMode can be read in caches but you must not enable or disable draftMode inside a cache. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
case 'prerender': {
case 'prerender':
case 'prerender-runtime': {
const error = new Error(
`Route ${workStore.route} used ${expression} without first calling \`await connection()\`. See more info here: https://nextjs.org/docs/messages/next-prerender-sync-headers`
)
......
......@@ -101,6 +101,7 @@ export function headers(): Promise<ReadonlyHeaders> {
)
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
......@@ -119,6 +120,7 @@ export function headers(): Promise<ReadonlyHeaders> {
if (workUnitStore) {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-runtime':
return makeHangingHeaders(workUnitStore)
case 'prerender-client':
const exportName = '`headers`'
......@@ -433,6 +435,7 @@ function syncIODev(route: string | undefined, expression: string) {
break
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
......
......@@ -10,10 +10,10 @@ import {
import {
workUnitAsyncStorage,
type PrerenderStore,
type PrerenderStorePPR,
type PrerenderStoreLegacy,
type PrerenderStoreModern,
type StaticPrerenderStoreModern,
type StaticPrerenderStore,
} from '../app-render/work-unit-async-storage.external'
import { InvariantError } from '../../shared/lib/invariant-error'
import {
......@@ -74,6 +74,10 @@ export function createParamsFromClient(
throw new InvariantError(
'createParamsFromClient should not be called in cache contexts.'
)
case 'prerender-runtime':
throw new InvariantError(
'createParamsFromClient should not be called in a runtime prerender.'
)
case 'request':
break
default:
......@@ -106,6 +110,7 @@ export function createServerParamsForRoute(
throw new InvariantError(
'createServerParamsForRoute should not be called in cache contexts.'
)
case 'prerender-runtime':
case 'request':
break
default:
......@@ -133,6 +138,7 @@ export function createServerParamsForServerSegment(
throw new InvariantError(
'createServerParamsForServerSegment should not be called in cache contexts.'
)
case 'prerender-runtime':
case 'request':
break
default:
......@@ -171,6 +177,7 @@ export function createPrerenderParamsForClientSegment(
)
case 'prerender-ppr':
case 'prerender-legacy':
case 'prerender-runtime':
case 'request':
break
default:
......@@ -186,7 +193,7 @@ export function createPrerenderParamsForClientSegment(
function createPrerenderParams(
underlyingParams: Params,
workStore: WorkStore,
prerenderStore: PrerenderStore
prerenderStore: StaticPrerenderStore
): Promise<Params> {
switch (prerenderStore.type) {
case 'prerender':
......@@ -291,7 +298,7 @@ const fallbackParamsProxyHandler: ProxyHandler<Promise<Params>> = {
function makeHangingParams(
underlyingParams: Params,
prerenderStore: PrerenderStoreModern
prerenderStore: StaticPrerenderStoreModern
): Promise<Params> {
const cachedParams = CachedParams.get(underlyingParams)
if (cachedParams) {
......@@ -578,6 +585,7 @@ function syncIODev(
break
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
......
......@@ -7,7 +7,7 @@ import {
import {
workUnitAsyncStorage,
type PrerenderStore,
type StaticPrerenderStore,
} from '../app-render/work-unit-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils'
import { InvariantError } from '../../shared/lib/invariant-error'
......@@ -35,6 +35,8 @@ export function createServerPathnameForMetadata(
throw new InvariantError(
'createServerPathnameForMetadata should not be called in cache contexts.'
)
case 'prerender-runtime':
case 'request':
break
default:
......@@ -47,7 +49,7 @@ export function createServerPathnameForMetadata(
function createPrerenderPathname(
underlyingPathname: string,
workStore: WorkStore,
prerenderStore: PrerenderStore
prerenderStore: StaticPrerenderStore
): Promise<string> {
switch (prerenderStore.type) {
case 'prerender-client':
......
......@@ -9,9 +9,9 @@ import {
} from '../app-render/work-async-storage.external'
import {
workUnitAsyncStorage,
type PrerenderStore,
type PrerenderStoreLegacy,
type PrerenderStorePPR,
type StaticPrerenderStore,
} from '../app-render/work-unit-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils'
import type { FallbackRouteParams } from './fallback-params'
......@@ -56,6 +56,7 @@ export async function unstable_rootParams(): Promise<Params> {
workUnitStore
)
case 'private-cache':
case 'prerender-runtime':
case 'request':
return Promise.resolve(workUnitStore.rootParams)
default:
......@@ -66,7 +67,7 @@ export async function unstable_rootParams(): Promise<Params> {
function createPrerenderRootParams(
underlyingParams: Params,
workStore: WorkStore,
prerenderStore: PrerenderStore
prerenderStore: StaticPrerenderStore
): Promise<Params> {
switch (prerenderStore.type) {
case 'prerender-client': {
......@@ -245,6 +246,7 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
)
}
case 'private-cache':
case 'prerender-runtime':
case 'request': {
break
}
......@@ -258,7 +260,7 @@ export function getRootParam(paramName: string): Promise<ParamValue> {
function createPrerenderRootParamPromise(
paramName: string,
workStore: WorkStore,
prerenderStore: PrerenderStore,
prerenderStore: StaticPrerenderStore,
apiName: string
): Promise<ParamValue> {
switch (prerenderStore.type) {
......
......@@ -11,10 +11,10 @@ import {
import {
workUnitAsyncStorage,
type PrerenderStore,
type PrerenderStoreLegacy,
type PrerenderStorePPR,
type PrerenderStoreModern,
type StaticPrerenderStore,
} from '../app-render/work-unit-async-storage.external'
import { InvariantError } from '../../shared/lib/invariant-error'
import { makeHangingPromise } from '../dynamic-rendering-utils'
......@@ -72,6 +72,10 @@ export function createSearchParamsFromClient(
case 'prerender-ppr':
case 'prerender-legacy':
return createPrerenderSearchParams(workStore, workUnitStore)
case 'prerender-runtime':
throw new InvariantError(
'createSearchParamsFromClient should not be called in a runtime prerender.'
)
case 'cache':
case 'private-cache':
case 'unstable-cache':
......@@ -109,6 +113,7 @@ export function createServerSearchParamsForServerPage(
throw new InvariantError(
'createServerSearchParamsForServerPage should not be called in cache contexts.'
)
case 'prerender-runtime':
case 'request':
break
default:
......@@ -135,6 +140,10 @@ export function createPrerenderSearchParamsForClientPage(
// We're prerendering in a mode that aborts (cacheComponents) and should stall
// the promise to ensure the RSC side is considered dynamic
return makeHangingPromise(workUnitStore.renderSignal, '`searchParams`')
case 'prerender-runtime':
throw new InvariantError(
'createPrerenderSearchParamsForClientPage should not be called in a runtime prerender.'
)
case 'cache':
case 'private-cache':
case 'unstable-cache':
......@@ -157,7 +166,7 @@ export function createPrerenderSearchParamsForClientPage(
function createPrerenderSearchParams(
workStore: WorkStore,
prerenderStore: PrerenderStore
prerenderStore: StaticPrerenderStore
): Promise<SearchParams> {
if (workStore.forceStatic) {
// When using forceStatic we override all other logic and always just return an empty
......@@ -803,6 +812,7 @@ function syncIODev(
break
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
......
......@@ -1189,6 +1189,10 @@ function trackDynamic(
throw new InvariantError(
'A client prerender store should not be used for a route handler.'
)
case 'prerender-runtime':
throw new InvariantError(
'A runtime prerender store should not be used for a route handler.'
)
case 'prerender-ppr':
return postponeWithTracking(
store.route,
......
......@@ -96,6 +96,7 @@ export function cacheLife(profile: CacheLifeProfiles | CacheLife): void {
switch (workUnitStore?.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
......
......@@ -13,6 +13,7 @@ export function cacheTag(...tags: string[]): void {
switch (workUnitStore?.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
......
export const DYNAMIC_EXPIRE = 300 // 5 minutes
export const DYNAMIC_PREFETCH_DYNAMIC_STALE = 30 // 30 seconds
export const RUNTIME_PREFETCH_DYNAMIC_STALE = 30 // 30 seconds
......@@ -18,6 +18,7 @@ import type { WorkStore } from '../app-render/work-async-storage.external'
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import type {
PrerenderStoreModernClient,
PrerenderStoreModernRuntime,
PrivateUseCacheStore,
RequestStore,
RevalidateStore,
......@@ -31,6 +32,8 @@ import {
workUnitAsyncStorage,
getDraftModeProviderForCacheScope,
getCacheSignal,
isHmrRefresh,
getServerComponentsHmrCache,
} from '../app-render/work-unit-async-storage.external'
import { makeHangingPromise } from '../dynamic-rendering-utils'
......@@ -46,7 +49,7 @@ import type { CacheSignal } from '../app-render/cache-signal'
import { decryptActionBoundArgs } from '../app-render/encryption'
import { InvariantError } from '../../shared/lib/invariant-error'
import { getDigestForWellKnownError } from '../app-render/create-error-handler'
import { DYNAMIC_EXPIRE, DYNAMIC_PREFETCH_DYNAMIC_STALE } from './constants'
import { DYNAMIC_EXPIRE, RUNTIME_PREFETCH_DYNAMIC_STALE } from './constants'
import { getCacheHandler } from './handlers'
import { UseCacheTimeoutError } from './use-cache-errors'
import {
......@@ -67,8 +70,10 @@ import type { CacheLife } from './cache-life'
interface PrivateCacheContext {
readonly kind: 'private'
// TODO: Add dynamic prefetching store when this exists.
readonly outerWorkUnitStore: RequestStore | PrivateUseCacheStore
readonly outerWorkUnitStore:
| RequestStore
| PrivateUseCacheStore
| PrerenderStoreModernRuntime
}
interface PublicCacheContext {
......@@ -188,8 +193,11 @@ function createUseCacheStore(
explicitStale: undefined,
tags: null,
hmrRefreshHash: getHmrRefreshHash(workStore, outerWorkUnitStore),
isHmrRefresh: outerWorkUnitStore.isHmrRefresh ?? false,
serverComponentsHmrCache: outerWorkUnitStore.serverComponentsHmrCache,
isHmrRefresh: isHmrRefresh(workStore, outerWorkUnitStore),
serverComponentsHmrCache: getServerComponentsHmrCache(
workStore,
outerWorkUnitStore
),
forceRevalidate: shouldForceRevalidate(workStore, outerWorkUnitStore),
draftMode: getDraftModeProviderForCacheScope(
workStore,
......@@ -209,6 +217,7 @@ function createUseCacheStore(
case 'request':
useCacheOrRequestStore = outerWorkUnitStore
break
case 'prerender-runtime':
case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':
......@@ -324,8 +333,8 @@ function propagateCacheLifeAndTags(
entry: CacheEntry
): void {
if (cacheContext.kind === 'private') {
switch (cacheContext.outerWorkUnitStore?.type) {
// TODO: Also propagate cache life and tags to dynamic prefetching stores.
switch (cacheContext.outerWorkUnitStore.type) {
case 'prerender-runtime':
case 'private-cache':
propagateCacheLifeAndTagsToRevalidateStore(
cacheContext.outerWorkUnitStore,
......@@ -343,6 +352,7 @@ function propagateCacheLifeAndTags(
case 'cache':
case 'private-cache':
case 'prerender':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
propagateCacheLifeAndTagsToRevalidateStore(
......@@ -489,6 +499,7 @@ async function generateCacheEntryImpl(
if (outerWorkUnitStore) {
switch (outerWorkUnitStore.type) {
case 'prerender-runtime':
case 'prerender':
// The encoded arguments might contain hanging promises. In
// this case we don't want to reject with "Error: Connection
......@@ -565,7 +576,7 @@ async function generateCacheEntryImpl(
let stream: ReadableStream<Uint8Array>
switch (outerWorkUnitStore?.type) {
// TODO: Dynamic prefetches should also use the prerender variant.
case 'prerender-runtime':
case 'prerender':
const timeoutAbortController = new AbortController()
......@@ -862,6 +873,7 @@ export function cache(
)
}
case 'request':
case 'prerender-runtime':
case 'private-cache':
cacheContext = {
kind: 'private',
......@@ -891,6 +903,7 @@ export function cache(
`${expression} must not be used within a client component. Next.js should be preventing ${expression} from being allowed in client components statically, but did not in this case.`
)
case 'prerender':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
......@@ -1032,8 +1045,8 @@ export function cache(
// need to include the cookies in the cache key. This is because we don't
// store the cache entries in a cache handler, but only in the Resume Data
// Cache (RDC). Private caches are only used during dynamic requests and
// dynamic prefetches. For dynamic requests, the RDC is immutable, so it
// does not include any private caches. For dynamic prefetches, the RDC is
// runtime prefetches. For dynamic requests, the RDC is immutable, so it
// does not include any private caches. For runtime prefetches, the RDC is
// mutable, but only lives as long as the request, so the key does not
// need to include cookies.
const cacheKeyParts: CacheKeyParts = hmrRefreshHash
......@@ -1049,6 +1062,7 @@ export function cache(
let encodedCacheKeyParts: FormData | string
switch (workUnitStore?.type) {
case 'prerender-runtime':
case 'prerender':
if (!isPageOrLayout) {
// If the "use cache" function is not a page or a layout, we need to
......@@ -1135,6 +1149,7 @@ export function cache(
workUnitStore.renderSignal,
'dynamic "use cache"'
)
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
......@@ -1147,8 +1162,31 @@ export function cache(
}
}
if (existingEntry.stale < DYNAMIC_PREFETCH_DYNAMIC_STALE) {
// TODO: Return hanging promise for dynamic prefetches.
if (existingEntry.stale < RUNTIME_PREFETCH_DYNAMIC_STALE) {
switch (workUnitStore.type) {
case 'prerender-runtime':
// In a runtime prerender, if the cache entry will become stale in less then 30 seconds,
// we consider this cache entry dynamic as it's not worth prefetching.
// It's better to leave a PPR hole that can be filled in dynamically
// with a potentially cached entry.
if (cacheSignal) {
cacheSignal.endRead()
}
return makeHangingPromise(
workUnitStore.renderSignal,
'dynamic "use cache"'
)
case 'prerender':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
case 'cache':
case 'private-cache':
case 'unstable-cache':
break
default:
workUnitStore satisfies never
}
}
}
......@@ -1192,6 +1230,7 @@ export function cache(
)
}
break
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
......@@ -1288,6 +1327,7 @@ export function cache(
workUnitStore.renderSignal,
'dynamic "use cache"'
)
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'request':
......@@ -1536,6 +1576,7 @@ function shouldForceRevalidate(
case 'cache':
case 'private-cache':
return workUnitStore.forceRevalidate
case 'prerender-runtime':
case 'prerender':
case 'prerender-client':
case 'prerender-ppr':
......@@ -1579,6 +1620,7 @@ function shouldDiscardCacheEntry(
switch (workUnitStore.type) {
case 'prerender':
return false
case 'prerender-runtime':
case 'prerender-client':
case 'prerender-ppr':
case 'prerender-legacy':
......
......@@ -298,9 +298,8 @@ export async function adapter(
onAfterTaskError: undefined,
},
requestEndedState: { ended: false },
isPrefetchRequest: request.headers.has(
NEXT_ROUTER_PREFETCH_HEADER
),
isPrefetchRequest:
request.headers.get(NEXT_ROUTER_PREFETCH_HEADER) === '1',
buildId: buildId ?? '',
previouslyRevalidatedTags: [],
})
......
......@@ -110,6 +110,7 @@ function revalidate(tags: string[], expression: string) {
`Route ${store.route} used "${expression}" inside a function cached with "unstable_cache(...)" which is unsupported. To ensure revalidation is performed consistently it must always happen outside of renders and cached functions. See more info here: https://nextjs.org/docs/app/building-your-application/rendering/static-and-dynamic#dynamic-rendering`
)
case 'prerender':
case 'prerender-runtime':
// cacheComponents Prerender
const error = new Error(
`Route ${store.route} used ${expression} without first calling \`await connection()\`.`
......
......@@ -163,6 +163,7 @@ export function unstable_cache<T extends Callback>(
case 'cache':
case 'private-cache':
case 'prerender':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
// We update the store's revalidate property if the option.revalidate is a higher precedence
......@@ -384,6 +385,7 @@ function getFetchUrlPrefix(
return `${pathname}${sortedSearch.length ? '?' : ''}${sortedSearch}`
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'cache':
......
......@@ -34,6 +34,7 @@ export function unstable_noStore() {
switch (workUnitStore.type) {
case 'prerender':
case 'prerender-client':
case 'prerender-runtime':
// unstable_noStore() is a noop in Dynamic I/O.
return
case 'prerender-ppr':
......
import { hexHash } from '../../hash'
export function computeCacheBustingSearchParam(
prefetchHeader: '1' | '0' | undefined,
prefetchHeader: '1' | '2' | '0' | undefined,
segmentPrefetchHeader: string | string[] | undefined,
stateTreeHeader: string | string[] | undefined,
nextUrlHeader: string | string[] | undefined
......
......@@ -16,13 +16,13 @@ export default async function Page(props) {
<Link href="/search-params?id=2">/search-params?id=2</Link>
</li>
<li>
<Link href="/search-params?id=3" prefetch>
/search-params?id=3 (prefetch: true)
<Link href="/search-params?id=3" prefetch="unstable_forceStale">
/search-params?id=3 (prefetch: unstable_forceStale)
</Link>
</li>
<li>
<Link href="/search-params" prefetch>
/search-params (prefetch: true)
<Link href="/search-params" prefetch="unstable_forceStale">
/search-params (prefetch: unstable_forceStale)
</Link>
</li>
<li>
......
......@@ -5,7 +5,7 @@ export default function Page() {
<ul>
<li>
<Link href="/with-middleware/search-params?id=1">
/search-params?id=1 (prefetch: true)
/search-params?id=1
</Link>
</li>
<li>
......@@ -14,12 +14,18 @@ export default function Page() {
</Link>
</li>
<li>
<Link href="/with-middleware/search-params?id=3" prefetch>
<Link
href="/with-middleware/search-params?id=3"
prefetch="unstable_forceStale"
>
/search-params?id=3 (prefetch: true)
</Link>
</li>
<li>
<Link href="/with-middleware/search-params" prefetch>
<Link
href="/with-middleware/search-params"
prefetch="unstable_forceStale"
>
/search-params (prefetch: true)
</Link>
</li>
......
......@@ -11,6 +11,8 @@ describe('segment cache (CDN cache busting)', () => {
return
}
// TODO(runtime-ppr): add tests for runtime prefetches
// To debug these tests locally, run:
// node start.mjs
//
......
'use client'
import Link from 'next/link'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
......@@ -10,7 +10,7 @@ export function LinkAccordion({
}: {
href: string
children: React.ReactNode
prefetch?: boolean
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
......
'use client'
import Link from 'next/link'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
......@@ -10,7 +10,7 @@ export function LinkAccordion({
}: {
href: string
children: React.ReactNode
prefetch?: boolean
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
......
'use client'
import Link from 'next/link'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
......@@ -10,7 +10,7 @@ export function LinkAccordion({
}: {
href: string
children: React.ReactNode
prefetch?: boolean
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
......
'use client'
import Link from 'next/link'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
......@@ -11,7 +11,7 @@ export function LinkAccordion({
}: {
href: string
children: React.ReactNode
prefetch?: boolean
prefetch?: LinkProps['prefetch']
unstable_dynamicOnHover?: boolean
}) {
const [isVisible, setIsVisible] = useState(false)
......
'use client'
import Link from 'next/link'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
......@@ -11,7 +11,7 @@ export function LinkAccordion({
}: {
href: string
children: string
prefetch?: boolean
prefetch?: LinkProps['prefetch']
id?: string
}) {
const [isVisible, setIsVisible] = useState(false)
......
......@@ -22,10 +22,10 @@ export default function MixedFetchStrategies() {
<li>
<LinkAccordion
id="ppr-enabled-prefetch-true"
prefetch={true}
prefetch="unstable_forceStale"
href="/mixed-fetch-strategies/has-loading-boundary/a/b/shared-layout/ppr-enabled"
>
Same link, but with prefetch=true
Same link, but with prefetch="unstable_forceStale"
</LinkAccordion>
</li>
</ul>
......
......@@ -285,7 +285,7 @@ describe('segment cache (incremental opt in)', () => {
)
it(
'when a link is prefetched with <Link prefetch=true>, no dynamic request ' +
'when a link is prefetched with <Link prefetch="unstable_forceStale">, no dynamic request ' +
'is made on navigation',
async () => {
let act
......@@ -324,7 +324,7 @@ describe('segment cache (incremental opt in)', () => {
)
it(
'when prefetching with prefetch=true, refetches cache entries that only ' +
'when prefetching with prefetch="unstable_forceStale", refetches cache entries that only ' +
'contain partial data',
async () => {
let act
......@@ -343,7 +343,7 @@ describe('segment cache (incremental opt in)', () => {
{ includes: 'Loading (PPR shell of shared-layout)...' }
)
// Prefetch the same link again, this time with prefetch=true to include
// Prefetch the same link again, this time with prefetch="unstable_forceStale" to include
// the dynamic data
await act(
async () => {
......@@ -370,7 +370,7 @@ describe('segment cache (incremental opt in)', () => {
// If this fails, it likely means that the partial cache entry that
// resulted from prefetching the normal link (<Link prefetch={false}>)
// was not properly re-fetched when the full link (<Link
// prefetch={true}>) was prefetched.
// prefetch='unstable_forceStale'>) was prefetched.
await browser.elementById('page-content')
},
// Assert that no network requests are initiated within this block.
......@@ -380,7 +380,7 @@ describe('segment cache (incremental opt in)', () => {
)
it(
'when prefetching with prefetch=true, refetches partial cache entries ' +
'when prefetching with prefetch="unstable_forceStale", refetches partial cache entries ' +
"even if there's already a pending PPR request",
async () => {
// This test is hard to describe succinctly because it involves a fairly
......@@ -427,7 +427,7 @@ describe('segment cache (incremental opt in)', () => {
)
// Before the previous prefetch finishes, prefetch the same link again,
// this time with prefetch=true to include the dynamic data.
// this time with prefetch="unstable_forceStale" to include the dynamic data.
await act(
async () => {
const checkbox = await browser.elementById(
......@@ -457,7 +457,7 @@ describe('segment cache (incremental opt in)', () => {
// If this fails, it likely means that the pending cache entry that
// resulted from prefetching the normal link (<Link prefetch={false}>)
// was not properly re-fetched when the full link (<Link
// prefetch={true}>) was prefetched.
// prefetch='unstable_forceStale'>) was prefetched.
await browser.elementById('page-content')
},
// Assert that no network requests are initiated within this block.
......
'use client'
import Link from 'next/link'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
......@@ -11,7 +11,7 @@ export function LinkAccordion({
}: {
href: string
children: string
prefetch?: boolean | 'unstable_forceStale' | 'auto'
prefetch?: LinkProps['prefetch']
id?: string
}) {
const [isVisible, setIsVisible] = useState(false)
......@@ -25,7 +25,6 @@ export function LinkAccordion({
id={id}
/>
{isVisible ? (
// @ts-expect-error - unstable_forceStale is not yet part of the types
<Link href={href} prefetch={prefetch}>
{children}
</Link>
......
import { Metadata } from 'next'
import { Suspense } from 'react'
import { cookies } from 'next/headers'
export async function generateMetadata(): Promise<Metadata> {
await cookies()
return {
title: 'Runtime-prefetchable title',
}
}
async function Content() {
await cookies()
return <div id="target-page">Target page</div>
}
export default function PageWithRuntimePrefetchableTitle() {
return (
<Suspense fallback="Loading...">
<Content />
</Suspense>
)
}
......@@ -5,16 +5,38 @@ export default function Page() {
<>
<ul>
<li>
<LinkAccordion prefetch={true} href="/page-with-dynamic-head">
Page with dynamic head (prefetch=true))
<LinkAccordion
prefetch="unstable_forceStale"
href="/page-with-dynamic-head"
>
Page with dynamic head (prefetch=unstable_forceStale)
</LinkAccordion>
</li>
<li>
<LinkAccordion
prefetch={true}
prefetch="unstable_forceStale"
href="/rewrite-to-page-with-dynamic-head"
>
Rewrite to page with dynamic head (prefetch=true)
Rewrite to page with dynamic head (prefetch=unstable_forceStale)
</LinkAccordion>
</li>
</ul>
<hr />
<ul>
<li>
<LinkAccordion
prefetch="unstable_forceStale"
href="/page-with-runtime-prefetchable-head"
>
Page with runtime-prefetchable head (prefetch=true)
</LinkAccordion>
</li>
<li>
<LinkAccordion
prefetch="unstable_forceStale"
href="/rewrite-to-page-with-runtime-prefetchable-head"
>
Rewrite to page with runtime-prefetchable head (prefetch=true)
</LinkAccordion>
</li>
</ul>
......
......@@ -12,6 +12,10 @@ const nextConfig = {
source: '/rewrite-to-page-with-dynamic-head',
destination: '/page-with-dynamic-head',
},
{
source: '/rewrite-to-page-with-runtime-prefetchable-head',
destination: '/page-with-runtime-prefetchable-head',
},
]
},
}
......
......@@ -9,12 +9,9 @@ describe('segment cache (metadata)', () => {
test('disabled in development', () => {})
return
}
it(
"regression: prefetch the head if it's missing even if all other data " +
'is cached',
async () => {
let act
describe("regression: prefetch the head if it's missing even if all other data is cached", () => {
it('pages with dynamic content and dynamic metadata, using a full prefetch', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(p) {
act = createRouterAct(p)
......@@ -75,6 +72,71 @@ describe('segment cache (metadata)', () => {
const title = await browser.eval(() => document.title)
expect(title).toBe('Dynamic Title')
}, 'no-requests')
}
)
})
it('pages with runtime-prefetchable content and dynamic metadata, using a runtime prefetch', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(p) {
act = createRouterAct(p)
},
})
// Runtime-prefetch a page.
// It only uses cookies, so this should be a complete prefetch.
await act(async () => {
const checkbox = await browser.elementByCss(
'input[data-link-accordion="/page-with-runtime-prefetchable-head"]'
)
await checkbox.click()
}, [
// Because the link is prefetched with prefetch="unstable_forceStale",
// we should be able to prefetch the title, even though it's dynamic.
{
includes: 'Runtime-prefetchable title',
},
{
includes: 'Target page',
},
])
// Now runtime-prefetch a link that rewrites to the same underlying page.
await act(async () => {
const checkbox = await browser.elementByCss(
'input[data-link-accordion="/rewrite-to-page-with-runtime-prefetchable-head"]'
)
await checkbox.click()
}, [
// TODO: Ideally, this would not prefetch the dynamic title again,
// because it was already prefetched by the previous link, and both
// links resolve to the same underlying route. This is because, unlike
// segment data, we cache routes solely by their input URL, not by the
// path of the underlying route. Similarly, we don't cache metadata
// separately from the route tree. We should probably do one or both.
{
includes: 'Runtime-prefetchable title',
},
// It should not prefetch the page content again, because it was
// already cached.
{
includes: 'Target page',
block: 'reject',
},
])
// When we navigate to the page, it should not make any additional
// network requests, because both the segment data and the head were
// fully prefetched.
await act(async () => {
const link = await browser.elementByCss(
'a[href="/rewrite-to-page-with-runtime-prefetchable-head"]'
)
await link.click()
const pageContent = await browser.elementById('target-page')
expect(await pageContent.text()).toBe('Target page')
const title = await browser.eval(() => document.title)
expect(title).toBe('Runtime-prefetchable title')
}, 'no-requests')
})
})
})
'use client'
import Link from 'next/link'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
......@@ -10,7 +10,7 @@ export function LinkAccordion({
}: {
href: string
children: React.ReactNode
prefetch?: boolean
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
......
'use client'
import Link, { LinkProps } from 'next/link'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
......
import Link from 'next/link'
import { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body style={{ fontFamily: 'monospace' }}>
<Header />
{children}
</body>
</html>
)
}
function Header() {
return (
<header>
<Link href="/" prefetch={false}>
Home
</Link>
</header>
)
}
import { DebugLinkAccordion } from '../components/link-accordion'
import { unstable_cacheLife } from 'next/cache'
export default async function Page() {
'use cache'
unstable_cacheLife('minutes')
return (
<main>
<h2>shared layout prefetching - layout with cookies and dynamic data</h2>
<ul>
<li>
<DebugLinkAccordion href="/shared-layout/one" prefetch={true} />
</li>
<li>
<DebugLinkAccordion
href="/shared-layout/one"
prefetch={'unstable_forceStale'}
/>
</li>
</ul>
<ul>
<li>
<DebugLinkAccordion href="/shared-layout/two" prefetch={'auto'} />
</li>
<li>
<DebugLinkAccordion href="/shared-layout/two" prefetch={true} />
</li>
<li>
<DebugLinkAccordion
href="/shared-layout/two"
prefetch={'unstable_forceStale'}
/>
</li>
</ul>
<h2>shared layout prefetching - layout with cookies</h2>
<ul>
<li>
<DebugLinkAccordion
href="/runtime-prefetchable-layout/one"
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href="/runtime-prefetchable-layout/two"
prefetch={'auto'}
/>
</li>
<li>
<DebugLinkAccordion
href="/runtime-prefetchable-layout/two"
prefetch={'unstable_forceStale'}
/>
</li>
</ul>
</main>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../shared'
export default async function Layout({ children }) {
return (
<main>
<div>
<h2>Shared layout</h2>
<DebugRenderKind />
<p id="shared-layout-description">
This shared layout uses cookies and no uncached IO, so it should be
completely runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</div>
<hr />
{children}
</main>
)
}
async function RuntimePrefetchable() {
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value-layout">{`Cookie from layout: ${cookieValue}`}</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay } from '../../shared'
import { cookies } from 'next/headers'
export default function Page() {
return (
<main>
<h1 style={{ color: 'yellow' }}>Page one</h1>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</main>
)
}
async function RuntimePrefetchable() {
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value-page">{`Cookie from page: ${cookieValue}`}</div>
{/*
TODO: a runtime-prefetched layout that had no holes itself will still be considered partial
if any other segment in the response is partial, because we don't track partiality per-segment,
so if we want to test that full prefetches can reuse layouts from runtime prefetches,
the whole page needs to be dynamically prerenderable.
*/}
{/* <Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense> */}
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, uncachedIO } from '../../shared'
import { cookies } from 'next/headers'
export default function Page() {
return (
<main>
<h1 style={{ color: 'green' }}>Page two</h1>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</main>
)
}
async function RuntimePrefetchable() {
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value-page">{`Cookie from page: ${cookieValue}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function Dynamic() {
await uncachedIO()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content-page">Dynamic content from page two</div>
</div>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../shared'
import { connection } from 'next/server'
export default async function Layout({ children }) {
return (
<main>
<div>
<h2>Shared layout</h2>
<DebugRenderKind />
<p id="shared-layout-description">
This shared layout uses cookies and some uncached IO, so parts of it
should be runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</div>
<hr />
{children}
</main>
)
}
async function RuntimePrefetchable() {
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value-layout">{`Cookie from layout: ${cookieValue}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content-layout">Dynamic content from layout</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, uncachedIO } from '../../shared'
import { cookies } from 'next/headers'
export default function Page() {
return (
<main>
<h1 style={{ color: 'yellow' }}>Page one</h1>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</main>
)
}
async function RuntimePrefetchable() {
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value-page">{`Cookie from page: ${cookieValue}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function Dynamic() {
await uncachedIO()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content-page">Dynamic content from page one</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, uncachedIO } from '../../shared'
import { cookies } from 'next/headers'
export default function Page() {
return (
<main>
<h1 style={{ color: 'green' }}>Page two</h1>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</main>
)
}
async function RuntimePrefetchable() {
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value-page">{`Cookie from page: ${cookieValue}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function Dynamic() {
await uncachedIO()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content-page">Dynamic content from page two</div>
</div>
)
}
import { unstable_cacheLife } from 'next/cache'
import { setTimeout } from 'timers/promises'
export async function uncachedIO() {
await setTimeout(500)
}
export async function cachedDelay(time: number, cacheBuster?: any) {
'use cache'
unstable_cacheLife('minutes')
console.log('cachedDelay', time, cacheBuster)
await setTimeout(time)
}
export function DebugRenderKind() {
const { workUnitAsyncStorage } =
require('next/dist/server/app-render/work-unit-async-storage.external') as typeof import('next/dist/server/app-render/work-unit-async-storage.external')
const workUnitStore = workUnitAsyncStorage.getStore()!
return (
<div>
workUnitStore.type: {workUnitStore.type}
{(() => {
switch (workUnitStore.type) {
case 'prerender':
return '(static prefetch)'
case 'prerender-runtime':
return '(runtime prefetch)'
default:
return null
}
})()}
</div>
)
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { ComponentProps, useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
data-prefetch={getPrefetchKind(prefetch)}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
export function DebugLinkAccordion({
href,
prefetch,
}: Omit<ComponentProps<typeof LinkAccordion>, 'children'>) {
const prefetchKind = getPrefetchKind(prefetch)
return (
<LinkAccordion href={href} prefetch={prefetch} data-prefetch={prefetch}>
{href} ({prefetchKind})
</LinkAccordion>
)
}
function getPrefetchKind(prefetch: LinkProps['prefetch']) {
switch (prefetch) {
case false:
return 'disabled'
case undefined:
case null:
case 'auto':
return 'auto'
case true:
return 'runtime'
case 'unstable_forceStale':
return 'full'
default:
prefetch satisfies never
}
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: { cacheComponents: true, clientSegmentCache: true },
productionBrowserSourceMaps: true,
}
export default nextConfig
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
import { unstable_cacheLife } from 'next/cache'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p id="intro">
This page uses a short-lived private cache (staleTime &lt;
RUNTIME_PREFETCH_DYNAMIC_STALE, which is 30s), which should not be
included in a runtime prefetch
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading...</div>}>
<CachedButShortLived />
</Suspense>
</main>
)
}
async function CachedButShortLived() {
'use cache: private'
unstable_cacheLife({
stale: 5,
// the rest of the settings don't matter for private caches,
// because they are not persisted server-side
})
await cachedDelay(500, [__filename])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
Short-lived cached content
<div id="cached-value">{Date.now()}</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
import { unstable_cacheLife } from 'next/cache'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p id="intro">
This page uses a short-lived public cache (expire &lt; DYNAMIC_EXPIRE,
5min), which should not be included in a static prefetch, but should be
included in a runtime prefetch, because it has a long enough stale time
(&gt; RUNTIME_PREFETCH_DYNAMIC_STALE, 30s)
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading...</div>}>
<ShortLivedCache />
</Suspense>
</main>
)
}
async function ShortLivedCache() {
'use cache'
unstable_cacheLife({
stale: 60, // > RUNTIME_PREFETCH_DYNAMIC_STALE
revalidate: 2 * 60,
expire: 3 * 60, // < DYNAMIC_EXPIRE
})
await cachedDelay(500, [__filename])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
Short-lived cached content
<div id="cached-value">{Date.now()}</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
import { unstable_cacheLife } from 'next/cache'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p id="intro">
This page uses a short-lived public cache (expire &lt; DYNAMIC_EXPIRE,
5min), which should not be included in a static prefetch, and should
also not be included in a runtime prefetch, because it has a short
enough stale time (&lt; RUNTIME_PREFETCH_DYNAMIC_STALE, 30s)
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading...</div>}>
<ShortLivedCache />
</Suspense>
</main>
)
}
async function ShortLivedCache() {
'use cache'
unstable_cacheLife({
stale: 20, // < RUNTIME_PREFETCH_DYNAMIC_STALE
revalidate: 2 * 60,
expire: 3 * 60, // < DYNAMIC_EXPIRE
})
await cachedDelay(500, [__filename])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
Short-lived cached content
<div id="cached-value">{Date.now()}</div>
</div>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
import { ErrorBoundary } from '../../../../components/error-boundary'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p id="intro">
This page errors after a cookies call, so we should only see the error
in a runtime prefetch or a navigation (and not during prerendering /
prefetching)
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<ErrorBoundary>
<One />
</ErrorBoundary>
</Suspense>
</main>
)
}
async function One(): Promise<never> {
const cookieStore = await cookies()
await cachedDelay(500, ['/cookies', cookieStore.get('user-agent')?.value])
throw new Error('Kaboom')
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p id="intro">
This page performs sync IO after a cookies() call, so we should only see
the error in a runtime prefetch or a navigation (and not during
prerendering / prefetching)
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<One />
</Suspense>
</main>
)
}
async function One() {
const cookieStore = await cookies()
await cachedDelay(500, ['/cookies', cookieStore.get('user-agent')?.value])
return <div id="timestamp">Timestamp: {Date.now()}</div>
}
export default async function Page() {
return (
<main>
<h1>Fully static</h1>
<p id="intro">Hello from a fully static page!</p>
<p>
{new Array({ length: 1000 })
.fill(null)
.map(() => 'Lorem ipsum dolor sit amet.')}
</p>
</main>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p>
This page uses cookies and no uncached IO, So it should be completely
prefetchable with a runtime prefetch.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</main>
)
}
async function RuntimePrefetchable() {
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value">{`Cookie: ${cookieValue}`}</div>
</div>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p>
This page uses cookies and some uncached IO, so parts of it should be
runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
<form
action={async (formData: FormData) => {
'use server'
const cookieStore = await cookies()
const cookieValue = formData.get('cookie') as string | null
if (cookieValue) {
cookieStore.set('testCookie', cookieValue)
}
}}
>
<input type="text" name="cookie" />
<button type="submit">Update cookie</button>
</form>
</main>
)
}
async function RuntimePrefetchable() {
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value">{`Cookie: ${cookieValue}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server'
type Params = { id: string }
export default async function Page({ params }: { params: Promise<Params> }) {
return (
<main>
<DebugRenderKind />
<p>
This page uses params and some uncached IO, so parts of it should be
runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable params={params} />
</Suspense>
</main>
)
}
async function RuntimePrefetchable({ params }: { params: Promise<Params> }) {
const { id } = await params
await cachedDelay(500, [__filename, id])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="param-value">{`Param: ${id}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server'
type AnySearchParams = { [key: string]: string | string[] | undefined }
export default async function Page({
searchParams,
}: {
searchParams: Promise<AnySearchParams>
}) {
return (
<main>
<DebugRenderKind />
<p>
This page uses search params and some uncached IO, so parts of it should
be runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable searchParams={searchParams} />
</Suspense>
</main>
)
}
async function RuntimePrefetchable({
searchParams,
}: {
searchParams: Promise<AnySearchParams>
}) {
const { searchParam } = await searchParams
await cachedDelay(500, [__filename, searchParam])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="search-param-value">{`Search param: ${searchParam}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p>
This page uses cookies (from a private cache) and no uncached IO, So it
should be completely prefetchable with a runtime prefetch.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</main>
)
}
async function RuntimePrefetchable() {
const cookieValue = await privateCache()
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value">{`Cookie: ${cookieValue}`}</div>
</div>
)
}
async function privateCache() {
'use cache: private'
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return cookieValue
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p>
This page uses cookies (from inside a private cache) and some uncached
IO, so parts of it should be runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
<form
action={async (formData: FormData) => {
'use server'
const cookieStore = await cookies()
const cookieValue = formData.get('cookie') as string | null
if (cookieValue) {
cookieStore.set('testCookie', cookieValue)
}
}}
>
<input type="text" name="cookie" />
<button type="submit">Update cookie</button>
</form>
</main>
)
}
async function RuntimePrefetchable() {
const cookieValue = await privateCache()
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="cookie-value">{`Cookie: ${cookieValue}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function privateCache() {
'use cache: private'
const cookieStore = await cookies()
const cookieValue = cookieStore.get('testCookie')?.value ?? null
await cachedDelay(500, [__filename, cookieValue])
return cookieValue
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p>
This page uses Date.now (in a private cache) and some uncached IO, so
parts of it should be runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable />
</Suspense>
</main>
)
}
async function RuntimePrefetchable() {
const now = await privateCache()
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="timestamp">{`Timestamp: ${now}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function privateCache() {
'use cache: private'
const now = Date.now()
await cachedDelay(500, [__filename])
return now
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server'
type Params = { id: string }
export default async function Page({ params }: { params: Promise<Params> }) {
return (
<main>
<DebugRenderKind />
<p>
This page uses params (passed to a private cache) and some uncached IO,
so parts of it should be runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable params={params} />
</Suspense>
</main>
)
}
async function RuntimePrefetchable({ params }: { params: Promise<Params> }) {
const id = await privateCache(params)
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="param-value">{`Param: ${id}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function privateCache(params: Promise<Params>) {
'use cache: private'
const { id } = await params
await cachedDelay(500, [__filename, id])
return id
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server'
type AnySearchParams = { [key: string]: string | string[] | undefined }
export default async function Page({
searchParams,
}: {
searchParams: Promise<AnySearchParams>
}) {
return (
<main>
<DebugRenderKind />
<p>
This page uses search params (passed to a private cache) and some
uncached IO, so parts of it should be runtime-prefetchable.
</p>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 1...</div>}>
<RuntimePrefetchable searchParams={searchParams} />
</Suspense>
</main>
)
}
async function RuntimePrefetchable({
searchParams,
}: {
searchParams: Promise<AnySearchParams>
}) {
const searchParam = await privateCache(searchParams)
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="search-param-value">{`Search param: ${searchParam}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function privateCache(searchParams: Promise<AnySearchParams>) {
'use cache: private'
const { searchParam } = await searchParams
await cachedDelay(500, [__filename, searchParam])
return searchParam
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import Link from 'next/link'
import { ReactNode } from 'react'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html>
<body style={{ fontFamily: 'monospace' }}>
<Header />
{children}
</body>
</html>
)
}
function Header() {
return (
<header>
<Link href="/" prefetch={false}>
Home
</Link>
</header>
)
}
import { DebugLinkAccordion } from '../../components/link-accordion'
export default async function Page() {
return (
<main>
<h1>Home</h1>
<h2>directly in a page</h2>
<ul>
<li>
cookies + dynamic content
<ul>
<li>
<DebugLinkAccordion href="/in-page/cookies" prefetch={true} />
</li>
</ul>
</li>
<li>
search params + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/in-page/search-params?searchParam=123"
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href="/in-page/search-params?searchParam=456"
prefetch={true}
/>
</li>
</ul>
</li>
<li>
dynamic params + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/in-page/dynamic-params/123"
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href="/in-page/dynamic-params/456"
prefetch={true}
/>
</li>
</ul>
</li>
<li>
only cookies
<ul>
<li>
<DebugLinkAccordion
href="/in-page/cookies-only"
prefetch={true}
/>
</li>
</ul>
</li>
</ul>
<h2>
<code>use cache: private</code>
</h2>
<ul>
<li>
cookies in private cache + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/in-private-cache/cookies"
prefetch={true}
/>
</li>
</ul>
</li>
<li>
dynamic params in private cache + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/in-private-cache/dynamic-params/123"
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href="/in-private-cache/dynamic-params/456"
prefetch={true}
/>
</li>
</ul>
</li>
<li>
search params in private cache + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/in-private-cache/search-params?searchParam=123"
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href="/in-private-cache/search-params?searchParam=456"
prefetch={true}
/>
</li>
</ul>
</li>
<li>
only cookies in private cache
<ul>
<li>
<DebugLinkAccordion
href="/in-private-cache/cookies-only"
prefetch={true}
/>
</li>
</ul>
</li>
<li>
Date.now() in private cache
<ul>
<li>
<DebugLinkAccordion
href="/in-private-cache/date-now"
prefetch={true}
/>
</li>
</ul>
</li>
</ul>
<h2>short-lived caches</h2>
<ul>
<li>
private, short stale
<ul>
<li>
<DebugLinkAccordion
href="/caches/private-short-stale"
prefetch={'auto'}
/>
</li>
<li>
<DebugLinkAccordion
href="/caches/private-short-stale"
prefetch={true}
/>
</li>
</ul>
</li>
<li>
public, short expire, long enough stale
<ul>
<li>
<DebugLinkAccordion
href="/caches/public-short-expire-long-stale"
prefetch={'auto'}
/>
</li>
<li>
<DebugLinkAccordion
href="/caches/public-short-expire-long-stale"
prefetch={true}
/>
</li>
</ul>
</li>
<li>
public, short expire, short stale
<ul>
<li>
<DebugLinkAccordion
href="/caches/public-short-expire-short-stale"
prefetch={'auto'}
/>
</li>
<li>
<DebugLinkAccordion
href="/caches/public-short-expire-short-stale"
prefetch={true}
/>
</li>
</ul>
</li>
</ul>
<h2>misc</h2>
<ul>
<li>
<DebugLinkAccordion href="/fully-static" prefetch={true} />
</li>
</ul>
<h2>errors</h2>
<ul>
<li>
<DebugLinkAccordion
href="/errors/error-after-cookies"
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href="/errors/sync-io-after-cookies"
prefetch={true}
/>
</li>
</ul>
</main>
)
}
import { unstable_cacheLife } from 'next/cache'
import { setTimeout } from 'timers/promises'
export async function uncachedIO() {
await setTimeout(500)
}
export async function cachedDelay(time: number, cacheBuster?: any) {
'use cache'
unstable_cacheLife('minutes')
console.log('cachedDelay', time, cacheBuster)
await setTimeout(time)
}
export function DebugRenderKind() {
const { workUnitAsyncStorage } =
require('next/dist/server/app-render/work-unit-async-storage.external') as typeof import('next/dist/server/app-render/work-unit-async-storage.external')
const workUnitStore = workUnitAsyncStorage.getStore()!
return (
<div>
workUnitStore.type: {workUnitStore.type}
{(() => {
switch (workUnitStore.type) {
case 'prerender':
return '(static prefetch)'
case 'prerender-runtime':
return '(runtime prefetch)'
default:
return null
}
})()}
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server'
import { lang } from 'next/root-params'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p>
This page uses root params and some uncached IO. Root params should
always be available in static prerenders, so a runtime prefetch should
have them too.
</p>
<StaticallyPrefetchable />
</main>
)
}
async function StaticallyPrefetchable() {
const currentLang = await lang()
await cachedDelay(500, [__filename, currentLang])
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="root-param-value">{`Lang: ${currentLang}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server'
import { lang } from 'next/root-params'
export default async function Page() {
return (
<main>
<DebugRenderKind />
<p>
This page uses root params (inside a private cache) and some uncached
IO. Private caches are only rendered during runtime prefetches and
navigation requests, so they won't be part of a static prefetch, but
they should be part of a runtime prefetch.
</p>
<Suspense fallback="Loading 1...">
<DynamicallyPrefetchable />
</Suspense>
</main>
)
}
async function DynamicallyPrefetchable() {
const currentLang = await privateCache()
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
<div id="root-param-value">{`Lang: ${currentLang}`}</div>
<Suspense fallback={<div style={{ color: 'grey' }}>Loading 2...</div>}>
<Dynamic />
</Suspense>
</div>
)
}
async function privateCache() {
'use cache: private'
const currentLang = await lang()
await cachedDelay(500, [__filename, currentLang])
return currentLang
}
async function Dynamic() {
await uncachedIO()
await connection()
return (
<div style={{ border: '1px solid tomato', padding: '1em' }}>
<div id="dynamic-content">Dynamic content</div>
</div>
)
}
import Link from 'next/link'
import { lang } from 'next/root-params'
import { ReactNode } from 'react'
export default async function RootLayout({
children,
}: {
children: ReactNode
}) {
const currentLang = await lang()
return (
<html lang={currentLang}>
<body style={{ fontFamily: 'monospace' }}>
<Header />
{children}
</body>
</html>
)
}
async function Header() {
const currentLang = await lang()
return (
<header>
<Link href={`/with-root-param/${currentLang}`} prefetch={false}>
Home (for lang: {currentLang})
</Link>
</header>
)
}
export function generateStaticParams() {
return [{ lang: 'en' }]
}
import { lang } from 'next/root-params'
import { DebugLinkAccordion } from '../../../components/link-accordion'
export default async function Page() {
const currentLang = await lang()
const otherLang = currentLang === 'en' ? 'de' : 'en'
return (
<main>
<h1>Home - with root param ({currentLang})</h1>
<h2>directly in a page</h2>
<ul>
<li>
root params + dynamic content
<ul>
<li>
<DebugLinkAccordion
href={`/with-root-param/${currentLang}/in-page/root-params`}
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href={`/with-root-param/${otherLang}/in-page/root-params`}
prefetch={true}
/>
</li>
</ul>
</li>
</ul>
<h2>
<code>use cache: private</code>
</h2>
<ul>
<li>
root params + dynamic content
<ul>
<li>
<DebugLinkAccordion
href={`/with-root-param/${currentLang}/in-private-cache/root-params`}
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href={`/with-root-param/${otherLang}/in-private-cache/root-params`}
prefetch={true}
/>
</li>
</ul>
</li>
</ul>
</main>
)
}
'use client'
import React from 'react'
export class ErrorBoundary extends React.Component<{
children: React.ReactNode
}> {
state = { error: null }
static getDerivedStateFromError(error) {
return { error }
}
render() {
if (this.state.error) {
return (
<div id="error-boundary">
Error boundary: {this.state.error.message}
</div>
)
}
return this.props.children
}
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { ComponentProps, useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
data-prefetch={getPrefetchKind(prefetch)}
/>
{isVisible ? (
<Link href={href} prefetch={prefetch}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
export function DebugLinkAccordion({
href,
prefetch,
}: Omit<ComponentProps<typeof LinkAccordion>, 'children'>) {
const prefetchKind = getPrefetchKind(prefetch)
return (
<LinkAccordion href={href} prefetch={prefetch} data-prefetch={prefetch}>
{href} ({prefetchKind})
</LinkAccordion>
)
}
function getPrefetchKind(prefetch: LinkProps['prefetch']) {
switch (prefetch) {
case false:
return 'disabled'
case undefined:
case null:
case 'auto':
return 'auto'
case true:
return 'runtime'
case 'unstable_forceStale':
return 'full'
default:
prefetch satisfies never
}
}
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: { cacheComponents: true, clientSegmentCache: true },
productionBrowserSourceMaps: true,
}
export default nextConfig
......@@ -10,16 +10,17 @@ export default function RefetchOnNewBaseTreeLayout({
<div style={{ backgroundColor: 'lightgray', padding: '1rem' }}>
<p>
This demonstrates what happens when a link is prefetched using{' '}
<code>{'prefetch={true}'}</code> and the URL changes. Next.js should
re-prefetch the link in case the delta between the base tree and the
target tree has changed.
<code>{'prefetch="unstable_forceStale"'}</code> and the URL changes.
Next.js should re-prefetch the link in case the delta between the base
tree and the target tree has changed.
</p>
<p>
Everything in this gray section is part of a shared layout. The links
below are prefetched using <code>{'prefetch={true}'}</code>. If the
first loaded page is "/refetch-on-new-base-tree/a", the prefetch for
this link will be empty, because there's no delta between the base
tree and the target tree.
below are prefetched using{' '}
<code>{'prefetch="unstable_forceStale"'}</code>. If the first loaded
page is "/refetch-on-new-base-tree/a", the prefetch for this link will
be empty, because there's no delta between the base tree and the
target tree.
</p>
<p>
However, if you then navigate to page B, we should re-prefetch the
......@@ -48,10 +49,16 @@ export default function RefetchOnNewBaseTreeLayout({
because it was fully prefetched.
</li>
</ul>
<LinkAccordion prefetch={true} href="/refetch-on-new-base-tree/a">
<LinkAccordion
prefetch="unstable_forceStale"
href="/refetch-on-new-base-tree/a"
>
Page A
</LinkAccordion>
<LinkAccordion prefetch={true} href="/refetch-on-new-base-tree/b">
<LinkAccordion
prefetch="unstable_forceStale"
href="/refetch-on-new-base-tree/b"
>
Page B
</LinkAccordion>
</div>
......
'use client'
import Link from 'next/link'
import Link, { type LinkProps } from 'next/link'
import Form from 'next/form'
import { useEffect, useState } from 'react'
import { useRouter } from 'next/navigation'
......@@ -12,7 +12,7 @@ export function LinkAccordion({
}: {
href: string
children: React.ReactNode
prefetch?: boolean
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
......@@ -92,6 +92,9 @@ export function ManualPrefetchLinkAccordion({
)
}
type Router = ReturnType<typeof useRouter>
type PrefetchOptions = Parameters<Router['prefetch']>[1]
function ManualPrefetchLink({
href,
children,
......@@ -109,8 +112,8 @@ function ManualPrefetchLink({
let didUnmount = false
const pollPrefetch = () => {
if (!didUnmount) {
// @ts-expect-error: onInvalidate is not yet part of public types
router.prefetch(href, {
kind: 'auto' as PrefetchOptions['kind'],
onInvalidate: pollPrefetch,
})
}
......
......@@ -272,7 +272,7 @@ describe('segment cache (revalidation)', () => {
includes: 'Page B content',
},
// Page A's content should not be prefetched because we're already on that
// page. When prefetching with `prefetch={true}`, we only prefetch the
// page. When prefetching with `prefetch='unstable_forceStale'`, we only prefetch the
// delta between the current route and the target route.
{
includes: 'Page A content',
......
......@@ -163,10 +163,19 @@ export function createRouterAct(
const originalResponse = await page.request.fetch(request, {
maxRedirects: 0,
})
// WORKAROUND:
// intercepting responses with 'Transfer-Encoding: chunked' (used for streaming)
// seems to be problematic sometimes, making the browser error with `net::ERR_INCOMPLETE_CHUNKED_ENCODING`.
// In particular, this seems to happen when blocking a streaming navigation response. (but not always)
// Playwright buffers the whole body anyway, so we can remove the header to sidestep this.
const headers = originalResponse.headers()
delete headers['transfer-encoding']
resolve({
text: await originalResponse.text(),
body: await originalResponse.body(),
headers: originalResponse.headers(),
headers,
status: originalResponse.status(),
})
}),
......
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