Unverified Commit 9cd05eae authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Implement runtime prefetching via segment opt-in (#83072)

Follow-up to #82905.

When prefetching a link, we should perform a runtime prefetch for any
segment that

- has runtime prefetching enabled
- is not a shared layout

or

- is a child of a segment that meets the above criteria.

Anything that doesn't meet those criteria will be prefetched statically,
i.e. the behavior before this PR. In other words, we disregard the
`prefetch` config of shared layouts when deciding whether to perform a
runtime prefetch.

This means if you opt into runtime prefetching in a layout, navigating
to a page inside that layout for the first time will perform a runtime
prefetch, but navigating across multiple pages inside that layout will
be static (until/unless there's a child that has also opted into runtime
prefetching).

For example, given a route structure like `/store/[id]`, where
`/store/layout.tsx` has runtime prefetching enabled, but
`/store/[id]/page.tsx` does not:

- A Link from `/home` to `/store/1` results in a **runtime prefetch**
- A Link from `/store/1` to `/store/2` results in a **static prefetch**

If we didn't make this distinction, then opting into prefetching in a
layout would override the config of everything inside it.

(However, the most common pattern will be to set this config at the page
level, where the distinction doesn't matter, since there are no child
segments.)

---------
Co-authored-by: 's avatarJanka Uryga <lolzatu2@gmail.com>
parent d3bc0371
......@@ -121,6 +121,12 @@ export type RouteTree = {
// this value is disregarded, because in that model `loading.tsx` is treated
// like any other Suspense boundary.)
hasLoadingBoundary: HasLoadingBoundary
// Indicates whether this route has a runtime prefetch that we can request.
// This is determined by the server; it's not purely a user configuration
// because the server may determine that a route is fully static and doesn't
// need runtime prefetching regardless of the configuration.
hasRuntimePrefetch: boolean
}
type RouteCacheEntryShared = {
......@@ -147,10 +153,10 @@ type RouteCacheEntryShared = {
* Rejected depending on the response from the server.
*/
export const enum EntryStatus {
Empty,
Pending,
Fulfilled,
Rejected,
Empty = 0,
Pending = 1,
Fulfilled = 2,
Rejected = 3,
}
type PendingRouteCacheEntry = RouteCacheEntryShared & {
......@@ -431,8 +437,8 @@ export function readRouteCacheEntry(
return readExactRouteCacheEntry(now, key.href, key.nextUrl)
}
export function getSegmentKeypathForTask(
task: PrefetchTask,
export function getSegmentKeypath(
fetchStrategy: FetchStrategy,
route: FulfilledRouteCacheEntry,
cacheKey: SegmentCacheKey
): Prefix<SegmentCacheKeypath> {
......@@ -443,11 +449,11 @@ export function getSegmentKeypathForTask(
// If we're fetching using PPR, we do not need to include the search params in
// 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 ||
task.fetchStrategy === FetchStrategy.PPRRuntime ||
const isDynamic =
fetchStrategy === FetchStrategy.Full ||
fetchStrategy === FetchStrategy.PPRRuntime ||
!route.isPPREnabled
return isDynamicTask && cacheKey.endsWith('/' + PAGE_SEGMENT_KEY)
return isDynamic && cacheKey.endsWith('/' + PAGE_SEGMENT_KEY)
? [cacheKey, route.renderedSearch]
: [cacheKey]
}
......@@ -481,7 +487,7 @@ export function readSegmentCacheEntry(
// is the common case because PPR/static prerenders always treat search params
// as dynamic.
//
// See corresponding logic in `getSegmentKeypathForTask`.
// See corresponding logic in `getSegmentKeypath`.
const entryWithoutSearchParams = readExactSegmentCacheEntry(now, [cacheKey])
return entryWithoutSearchParams
}
......@@ -744,11 +750,11 @@ export function requestOptimisticRouteCacheEntry(
*/
export function readOrCreateSegmentCacheEntry(
now: number,
task: PrefetchTask,
fetchStrategy: FetchStrategy,
route: FulfilledRouteCacheEntry,
cacheKey: SegmentCacheKey
): SegmentCacheEntry {
const keypath = getSegmentKeypathForTask(task, route, cacheKey)
const keypath = getSegmentKeypath(fetchStrategy, route, cacheKey)
const existingEntry = readExactSegmentCacheEntry(now, keypath)
if (existingEntry !== null) {
return existingEntry
......@@ -1158,6 +1164,7 @@ function convertTreePrefetchToRouteTree(
// This field is only relevant to dynamic routes. For a PPR/static route,
// there's always some partial loading state we can fetch.
hasLoadingBoundary: HasLoadingBoundary.SegmentHasLoadingBoundary,
hasRuntimePrefetch: prefetch.hasRuntimePrefetch,
}
}
......@@ -1251,6 +1258,10 @@ function convertFlightRouterStateToRouteTree(
flightRouterState[5] !== undefined
? flightRouterState[5]
: HasLoadingBoundary.SubtreeHasNoLoadingBoundary,
// Non-static tree responses are only used by apps that haven't adopted
// Cache Components. So this is always false.
hasRuntimePrefetch: false,
}
}
......@@ -2036,7 +2047,7 @@ function writeSeedDataIntoCache(
// There's no matching entry. Attempt to create a new one.
const possiblyNewEntry = readOrCreateSegmentCacheEntry(
now,
task,
fetchStrategy,
route,
cacheKey
)
......@@ -2065,7 +2076,7 @@ function writeSeedDataIntoCache(
)
upsertSegmentEntry(
now,
getSegmentKeypathForTask(task, route, cacheKey),
getSegmentKeypath(fetchStrategy, route, cacheKey),
newEntry
)
}
......
......@@ -359,7 +359,7 @@ function readRenderSnapshotFromCache(
)
// We don't need this information in a render snapshot, so this can just be a placeholder.
const shouldUseRuntimePrefetch = false
const hasRuntimePrefetch = false
return {
flightRouterState: [
......@@ -375,7 +375,7 @@ function readRenderSnapshotFromCache(
childSeedDatas,
loading,
isPartial,
shouldUseRuntimePrefetch,
hasRuntimePrefetch,
],
}
}
......
......@@ -51,7 +51,7 @@ export type TreePrefetch = {
}
/** Whether this segment should be fetched using a runtime prefetch */
shouldUseRuntimePrefetch: boolean
hasRuntimePrefetch: boolean
// Extra fields that only exist so we can reconstruct a FlightRouterState on
// the client. We may be able to unify TreePrefetch and FlightRouterState
......@@ -281,7 +281,7 @@ function collectSegmentDataImpl(
slotMetadata[parallelRouteKey] = childTree
}
const shouldUseRuntimePrefetch = seedData !== null ? seedData[5] : false
const hasRuntimePrefetch = seedData !== null ? seedData[5] : false
if (seedData !== null) {
// Spawn a task to write the segment data to a new Flight stream.
......@@ -324,7 +324,7 @@ function collectSegmentDataImpl(
// case there's a bug and we need to revert.
// TODO: Remove once clientParamParsing is enabled everywhere.
paramKey: isClientParamParsingEnabled ? null : paramKey,
shouldUseRuntimePrefetch,
hasRuntimePrefetch,
slots: slotMetadata,
isRootLayout: route[4] === true,
}
......
......@@ -229,7 +229,7 @@ async function createComponentTreeInternal(
? (layoutOrPageMod as AppSegmentConfig).unstable_prefetch
: undefined
/** Whether this segment should use a runtime prefetch instead of a static prefetch. */
const shouldUseRuntimePrefetch = prefetchConfig === 'unstable_runtime'
const hasRuntimePrefetch = prefetchConfig === 'unstable_runtime'
const [Forbidden, forbiddenStyles] =
authInterrupts && forbidden
......@@ -704,7 +704,7 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData,
loadingData,
isPossiblyPartialResponse,
shouldUseRuntimePrefetch,
hasRuntimePrefetch,
]
}
......@@ -737,7 +737,7 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData,
loadingData,
true,
shouldUseRuntimePrefetch,
hasRuntimePrefetch,
]
}
......@@ -843,7 +843,7 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData,
loadingData,
isPossiblyPartialResponse,
shouldUseRuntimePrefetch,
hasRuntimePrefetch,
]
} else {
const SegmentComponent = Component
......@@ -1021,7 +1021,7 @@ async function createComponentTreeInternal(
parallelRouteCacheNodeSeedData,
loadingData,
isPossiblyPartialResponse,
shouldUseRuntimePrefetch,
hasRuntimePrefetch,
]
}
}
......
......@@ -229,7 +229,7 @@ export type CacheNodeSeedData = [
loading: LoadingModuleData | Promise<LoadingModuleData>,
isPartial: boolean,
/** TODO: this doesn't feel like it belongs here, because it's only used during build, in `collectSegmentData` */
shouldUseRuntimePrefetch: boolean,
hasRuntimePrefetch: boolean,
]
export type FlightDataSegment = [
......
......@@ -53,6 +53,16 @@ export default async function Page() {
/>
</li>
</ul>
<h2>shared layout prefetching - segment config</h2>
<ul>
<li>
This link deliberately doesn't specify a `prefetch` prop, because the
page has a segment-level prefetch config:
<br />
<DebugLinkAccordion href="/segment-config/runtime-prefetchable" />
</li>
</ul>
</main>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { DebugRenderKind } from '../../../shared'
// No `export const unstable_prefetch = ...` is needed, we default to static
export default async function SubLayout({ children }) {
return (
<main>
<div>
<h3>Sub-layout</h3>
<DebugRenderKind />
<p id="static-content-sub-layout">
This sub-layout uses cookies, but did not specify that it should be
runtime prefetchable, so it should be prefetched statically by
default.
</p>
<Suspense
fallback={
<div id="runtime-prefetchable-fallback-sub-layout">Loading ...</div>
}
>
<RuntimePrefetchable />
</Suspense>
</div>
<hr />
{children}
</main>
)
}
async function RuntimePrefetchable() {
await cookies()
return (
<div id="runtime-prefetchable-content-sub-layout">
Runtime-prefetchable content from sub-layout
</div>
)
}
......@@ -6,7 +6,20 @@ export const unstable_prefetch = 'unstable_runtime'
export default function Page() {
return (
<main>
<h1>A page that should use a runtime prefetch</h1>
<h1 style={{ color: 'green' }}>
A runtime-prefetchable child of a runtime-prefetchable layout
</h1>
<p id="static-content-page">
This page has two relevant parent layouts:
<br />
1. A runtime-prefetchable shared layout layout.
<br />
2. A statically-prefetchable sub-layout not shared with other pages.
<br />
<br />
We should use a runtime prefetch for it without any overrides on Link,
but its sub-layout should be prefetched statically.
</p>
<Suspense fallback="Loading...">
<RuntimePrefetchable />
</Suspense>
......@@ -16,5 +29,9 @@ export default function Page() {
async function RuntimePrefetchable() {
await cookies()
return <div>Runtime-prefetchable content</div>
return (
<div id="runtime-prefetchable-content-page">
Runtime-prefetchable content from page
</div>
)
}
import { cookies } from 'next/headers'
import { connection } from 'next/server'
import { Suspense } from 'react'
// Technically, no `export const unstable_prefetch = ...` is needed, because we default to static,
// this is just to make sure that we excercise the codepaths for it
export const unstable_prefetch = 'unstable_static'
export default function Page() {
return (
<main>
<h1 style={{ color: 'green' }}>Statically prefetchable</h1>
<p id="static-content-page">
This page is a child of a runtime-prefetchable layout that is not
configured as runtime-prefetchable. We should not use a runtime prefetch
for it.
</p>
<Suspense fallback="Loading...">
<RuntimePrefetchable />
</Suspense>
<Suspense fallback="Loading...">
<DynamicContent />
</Suspense>
</main>
)
}
async function RuntimePrefetchable() {
await cookies()
return (
<div id="runtime-prefetchable-content-page">
Runtime-prefetchable content from page
</div>
)
}
async function DynamicContent() {
await connection()
return <div id="dynamic-content-page">Dynamic Content from page</div>
}
// No `export const unstable_prefetch = ...` is needed, we default to static
export default function Page() {
return (
<main>
<h1 style={{ color: 'green' }}>Fully statically prefetchable</h1>
<p id="static-content-page">
This page is a statically-prefetchable child of a runtime-prefetchable
layout. We should not use a runtime prefetch for it.
</p>
</main>
)
}
import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { DebugRenderKind } from '../../shared'
export const unstable_prefetch = 'unstable_runtime'
export default async function Layout({ children }) {
return (
<main>
<div>
<h2>Shared layout</h2>
<DebugRenderKind />
<p id="static-content-layout">
This shared layout uses cookies and no uncached IO, so it should be
completely runtime-prefetchable.
</p>
<Suspense fallback="Loading ...">
<RuntimePrefetchable />
</Suspense>
</div>
<hr />
{children}
</main>
)
}
async function RuntimePrefetchable() {
await cookies()
return (
<div id="runtime-prefetchable-content-layout">
Runtime-prefetchable content from shared layout
</div>
)
}
import { cookies } from 'next/headers'
import { DebugLinkAccordion } from '../../../components/link-accordion'
import { Suspense } from 'react'
// No `export const unstable_prefetch = ...` is needed, we default to static
// (but see page description for more on the actual behavior)
export default function Page() {
return (
<main>
<h1>Child of a runtime prefetchable layout</h1>
<div>
<p>
When this page is prefetched from outside of the{' '}
<code>/segment-config/runtime-prefetchable</code> segment, the page
contents will be runtime-prefetched (despite this segment not being
marked as runtime-prefetchable) because the parent layout is marked as
runtime-prefetchable.
</p>
<Suspense fallback="Loading...">
<RuntimePrefetchable />
</Suspense>
</div>
<ul>
<li>
A page that shares some layouts with this page, and should use a
static prefetch:
<br />
<DebugLinkAccordion href="/segment-config/runtime-prefetchable/configured-as-static" />
</li>
<li>
A page that shares some layouts with this page, and should use a
runtime prefetch:
<br />
<DebugLinkAccordion href="/segment-config/runtime-prefetchable/configured-as-runtime" />
</li>
<li>
A page that shares some layouts with this page, and has a fully static
page segment
<br />
<DebugLinkAccordion href="/segment-config/runtime-prefetchable/fully-static" />
</li>
</ul>
</main>
)
}
async function RuntimePrefetchable() {
await cookies()
return (
<div id="runtime-prefetchable-content-page">
Runtime-prefetchable content from page
</div>
)
}
import { nextTestSetup } from 'e2e-utils'
import { Playwright as NextBrowser } from '../../../../lib/next-webdriver'
import type * as Playwright from 'playwright'
import { createRouterAct } from '../router-act'
......@@ -534,7 +535,15 @@ describe('layout sharing in non-static prefetches', () => {
`input[data-prefetch="auto"][data-link-accordion="/runtime-prefetchable-layout/two"]`
)
await linkToggle.click()
})
}, [
// Should not fetch the shared layout, because that was already prefetched
{
includes: 'Shared layout',
block: 'reject',
},
// Should fetch the static part of page two
{ includes: 'Page two' },
])
// Navigate to page two. We need to request the page segment dynamically, but the shared layout should be cached.
await act(async () => {
......@@ -566,6 +575,204 @@ describe('layout sharing in non-static prefetches', () => {
'Dynamic content from page two'
)
})
describe('segment-level prefetch config', () => {
const clientNavigateToSegmentConfigPage = async (
browser: NextBrowser,
act: ReturnType<typeof createRouterAct>
) => {
// Reveal the link to trigger a (automatic) runtime prefetch for the segment-config entrypoint page
await act(async () => {
const linkToggle = await browser.elementByCss(
`input[data-link-accordion="/segment-config/runtime-prefetchable"]`
)
await linkToggle.click()
}, [
{
includes: 'runtime-prefetchable-content-layout',
},
])
// Navigate to the segment-config entrypoint page.
// The layout is configured as runtime prefetchable, but the page is not.
// Both contain runtime-prefetchable content,
// but nothing dynamic, so we shouldn't need any extra requests.
//
// Note that the page itself doesn't specify that it should use a runtime prefetch,
// but we'll currently automatically include it in the runtime prefetch request
// that we're doing because of the layout's config.
await act(async () => {
await browser
.elementByCss(`a[href="/segment-config/runtime-prefetchable"]`)
.click()
}, 'no-requests')
}
it('does not unnecessarily use a runtime prefetch for sub-pages of runtime-prefetchable layouts', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
// First, we move from the starting page to another page that has a runtime-prefetchable layout.
await clientNavigateToSegmentConfigPage(browser, act)
// Now we're on a page that uses the runtime-prefetchable layout,
// sub-pages of the same layout that are configured as static shouldn't automatically issue a runtime prefetch.
await act(async () => {
await browser
.elementByCss(
`input[data-link-accordion="/segment-config/runtime-prefetchable/configured-as-static"]`
)
.click()
}, [
// We should not prefetch anything from the parent layout again.
{ includes: 'static-content-layout', block: 'reject' },
{ includes: 'runtime-prefetchable-content-layout', block: 'reject' },
// We should prefetch the static content for the page, but nothing more.
{ includes: 'static-content-page' },
{ includes: 'dynamic-content-page', block: 'reject' },
{ includes: 'runtime-prefetchable-content-page', block: 'reject' },
])
})
it('statically prefetches a fully-static page segment if all its runtime-prefetchable parents are available', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
// First, we move from the starting page to another page that has a runtime-prefetchable layout.
await clientNavigateToSegmentConfigPage(browser, act)
// Now we're on a page that uses the runtime-prefetchable layout,
// sub-pages of the same layout that are configured as static shouldn't automatically issue a runtime prefetch.
await act(async () => {
await browser
.elementByCss(
`input[data-link-accordion="/segment-config/runtime-prefetchable/fully-static"]`
)
.click()
}, [
// We should not prefetch anything from the parent layout again.
{ includes: 'static-content-layout', block: 'reject' },
{ includes: 'runtime-prefetchable-content-layout', block: 'reject' },
// We should prefetch the static content for the page, but nothing more.
{ includes: 'static-content-page' },
])
// The page segment is fully static, so we shouldn't need any extra requests to navigate to it.
await act(async () => {
await browser
.elementByCss(
`a[href="/segment-config/runtime-prefetchable/fully-static"]`
)
.click()
}, 'no-requests')
expect(
await (await browser.elementById('static-content-page')).isVisible()
).toBeTrue()
})
it('uses a runtime prefetch for sub-pages of runtime-prefetchable layouts if requested', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page)
// First, we move from the starting page to another page that has a runtime-prefetchable layout.
await clientNavigateToSegmentConfigPage(browser, act)
// Sub-pages of this layout that are configured as runtime-prefetchable should be prefetched as such.
// However, if the page also has a sub-layout (not shared with the current page)
// that is configured as static, that part shouldn't be runtime-prefetched.
//
// Note that this is a sub-optimal configuration -- in a real app, we'd likely want the sub-layout
// to be runtime-prefetched as well, because it contains some runtime-prefetchable content.
// However, this is deliberately set up this way to assert that we don't do a runtime prefetch unless requested.
await act(async () => {
await browser
.elementByCss(
`input[data-link-accordion="/segment-config/runtime-prefetchable/configured-as-runtime"]`
)
.click()
}, [
// We should not prefetch anything from the parent layout again.
{ includes: 'static-content-layout', block: 'reject' },
{ includes: 'runtime-prefetchable-content-layout', block: 'reject' },
{
// We should *not* prefetch the runtime parts of the sub-layout,
// because it's not configured as runtime-prefetchable.
includes: 'runtime-prefetchable-content-sub-layout',
block: 'reject',
},
// ...but we should prefetch the runtime parts of the page.
{ includes: 'runtime-prefetchable-content-page' },
{ includes: 'dynamic-content-page', block: 'reject' },
])
// Navigate to the runtime-prefetchable sub-page.
await act(async () => {
// We should be able to display what we've prefetched before the navigation request resolves.
await act(async () => {
await browser
.elementByCss(
`a[href="/segment-config/runtime-prefetchable/configured-as-runtime"]`
)
.click()
}, 'block')
// The sub-layout should show static content, but not runtime-prefetchable content.
expect(
await (
await browser.elementById('static-content-sub-layout')
).isVisible()
).toBeTrue()
expect(
await (
await browser.elementById(
'runtime-prefetchable-fallback-sub-layout'
)
).isVisible()
).toBeTrue()
// The sub-page should show static/runtime-prefetchable content.
expect(
await (await browser.elementById('static-content-page')).isVisible()
).toBeTrue()
expect(
await (
await browser.elementById('runtime-prefetchable-content-page')
).isVisible()
).toBeTrue()
})
// After the navigation, we should see the content that wasn't prefetched.
// (because the sub-layout was configured as static)
expect(
await (
await browser.elementById('runtime-prefetchable-content-sub-layout')
).isVisible()
).toBeTrue()
})
})
})
function defer(callback: () => Promise<void>) {
......
// This is technically unnecessary, because this page is static
// and a runtime prefetch won't do any better than a static one,
// but it's useful to exercise this codepath.
// In the future, this test can be used to check whether we correctly
// *skip* a runtime prefetch if a page was prerendered as static.
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() {
return (
<main>
......
......@@ -2,6 +2,8 @@ import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() {
return (
<main>
......
......@@ -3,6 +3,8 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() {
return (
<main>
......
......@@ -2,6 +2,8 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server'
export const unstable_prefetch = 'unstable_runtime'
type Params = { id: string }
export default async function Page({ params }: { params: Promise<Params> }) {
......
......@@ -2,6 +2,8 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server'
export const unstable_prefetch = 'unstable_runtime'
type AnySearchParams = { [key: string]: string | string[] | undefined }
export default async function Page({
......
......@@ -2,6 +2,8 @@ import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() {
return (
<main>
......
......@@ -3,6 +3,8 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() {
return (
<main>
......
......@@ -2,6 +2,8 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() {
return (
<main>
......
......@@ -2,6 +2,8 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server'
export const unstable_prefetch = 'unstable_runtime'
type Params = { id: string }
export default async function Page({ params }: { params: Promise<Params> }) {
......
......@@ -2,6 +2,8 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../shared'
import { connection } from 'next/server'
export const unstable_prefetch = 'unstable_runtime'
type AnySearchParams = { [key: string]: string | string[] | undefined }
export default async function Page({
......
......@@ -11,7 +11,7 @@ export default async function Page() {
cookies + dynamic content
<ul>
<li>
<DebugLinkAccordion href="/in-page/cookies" prefetch={true} />
<DebugLinkAccordion href="/in-page/cookies" />
</li>
</ul>
</li>
......@@ -20,16 +20,10 @@ export default async function Page() {
search params + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/in-page/search-params?searchParam=123"
prefetch={true}
/>
<DebugLinkAccordion href="/in-page/search-params?searchParam=123" />
</li>
<li>
<DebugLinkAccordion
href="/in-page/search-params?searchParam=456"
prefetch={true}
/>
<DebugLinkAccordion href="/in-page/search-params?searchParam=456" />
</li>
</ul>
</li>
......@@ -37,16 +31,10 @@ export default async function Page() {
dynamic params + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/in-page/dynamic-params/123"
prefetch={true}
/>
<DebugLinkAccordion href="/in-page/dynamic-params/123" />
</li>
<li>
<DebugLinkAccordion
href="/in-page/dynamic-params/456"
prefetch={true}
/>
<DebugLinkAccordion href="/in-page/dynamic-params/456" />
</li>
</ul>
</li>
......@@ -54,10 +42,7 @@ export default async function Page() {
only cookies
<ul>
<li>
<DebugLinkAccordion
href="/in-page/cookies-only"
prefetch={true}
/>
<DebugLinkAccordion href="/in-page/cookies-only" />
</li>
</ul>
</li>
......@@ -71,10 +56,7 @@ export default async function Page() {
cookies in private cache + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/in-private-cache/cookies"
prefetch={true}
/>
<DebugLinkAccordion href="/in-private-cache/cookies" />
</li>
</ul>
</li>
......@@ -82,16 +64,10 @@ export default async function Page() {
dynamic params in private cache + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/in-private-cache/dynamic-params/123"
prefetch={true}
/>
<DebugLinkAccordion href="/in-private-cache/dynamic-params/123" />
</li>
<li>
<DebugLinkAccordion
href="/in-private-cache/dynamic-params/456"
prefetch={true}
/>
<DebugLinkAccordion href="/in-private-cache/dynamic-params/456" />
</li>
</ul>
</li>
......@@ -99,16 +75,10 @@ export default async function Page() {
search params in private cache + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/in-private-cache/search-params?searchParam=123"
prefetch={true}
/>
<DebugLinkAccordion href="/in-private-cache/search-params?searchParam=123" />
</li>
<li>
<DebugLinkAccordion
href="/in-private-cache/search-params?searchParam=456"
prefetch={true}
/>
<DebugLinkAccordion href="/in-private-cache/search-params?searchParam=456" />
</li>
</ul>
</li>
......@@ -116,10 +86,7 @@ export default async function Page() {
only cookies in private cache
<ul>
<li>
<DebugLinkAccordion
href="/in-private-cache/cookies-only"
prefetch={true}
/>
<DebugLinkAccordion href="/in-private-cache/cookies-only" />
</li>
</ul>
</li>
......@@ -127,10 +94,7 @@ export default async function Page() {
Date.now() in private cache
<ul>
<li>
<DebugLinkAccordion
href="/in-private-cache/date-now"
prefetch={true}
/>
<DebugLinkAccordion href="/in-private-cache/date-now" />
</li>
</ul>
</li>
......@@ -144,10 +108,7 @@ export default async function Page() {
cookies() promise passed to public cache + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/passed-to-public-cache/cookies"
prefetch={true}
/>
<DebugLinkAccordion href="/passed-to-public-cache/cookies" />
</li>
</ul>
</li>
......@@ -155,16 +116,10 @@ export default async function Page() {
dynamic params promise passed to public cache + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/passed-to-public-cache/dynamic-params/123"
prefetch={true}
/>
<DebugLinkAccordion href="/passed-to-public-cache/dynamic-params/123" />
</li>
<li>
<DebugLinkAccordion
href="/passed-to-public-cache/dynamic-params/456"
prefetch={true}
/>
<DebugLinkAccordion href="/passed-to-public-cache/dynamic-params/456" />
</li>
</ul>
</li>
......@@ -172,16 +127,10 @@ export default async function Page() {
search params promise passed to public cache + dynamic content
<ul>
<li>
<DebugLinkAccordion
href="/passed-to-public-cache/search-params?searchParam=123"
prefetch={true}
/>
<DebugLinkAccordion href="/passed-to-public-cache/search-params?searchParam=123" />
</li>
<li>
<DebugLinkAccordion
href="/passed-to-public-cache/search-params?searchParam=456"
prefetch={true}
/>
<DebugLinkAccordion href="/passed-to-public-cache/search-params?searchParam=456" />
</li>
</ul>
</li>
......@@ -189,10 +138,7 @@ export default async function Page() {
only cookies passed to public cache (no dynamic content)
<ul>
<li>
<DebugLinkAccordion
href="/passed-to-public-cache/cookies-only"
prefetch={true}
/>
<DebugLinkAccordion href="/passed-to-public-cache/cookies-only" />
</li>
</ul>
</li>
......@@ -290,7 +236,7 @@ export default async function Page() {
<h2>misc</h2>
<ul>
<li>
<DebugLinkAccordion href="/fully-static" prefetch={true} />
<DebugLinkAccordion href="/fully-static" />
</li>
</ul>
</main>
......
......@@ -2,6 +2,8 @@ import { cookies } from 'next/headers'
import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() {
return (
<main>
......
......@@ -3,6 +3,8 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind } from '../../../shared'
import { connection } from 'next/server'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() {
return (
<main>
......
......@@ -3,6 +3,8 @@ import { cachedDelay, DebugRenderKind } from '../../../../shared'
import { connection } from 'next/server'
import { cookies } from 'next/headers'
export const unstable_prefetch = 'unstable_runtime'
type Params = { id: string }
export default async function Page({ params }: { params: Promise<Params> }) {
......
......@@ -3,6 +3,8 @@ import { cachedDelay, DebugRenderKind } from '../../../shared'
import { connection } from 'next/server'
import { cookies } from 'next/headers'
export const unstable_prefetch = 'unstable_runtime'
type AnySearchParams = { [key: string]: string | string[] | undefined }
export default async function Page({
......
......@@ -2,6 +2,9 @@ import { Suspense } from 'react'
import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server'
import { lang } from 'next/root-params'
import { cookies } from 'next/headers'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() {
return (
......@@ -12,12 +15,16 @@ export default async function Page() {
always be available in static prerenders, so a runtime prefetch should
have them too.
</p>
<StaticallyPrefetchable />
<Suspense fallback="Loading 1...">
<RuntimePrefetchable />
</Suspense>
</main>
)
}
async function StaticallyPrefetchable() {
async function RuntimePrefetchable() {
await cookies()
const currentLang = await lang()
await cachedDelay([__filename, currentLang])
return (
......
......@@ -3,6 +3,8 @@ import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server'
import { lang } from 'next/root-params'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() {
return (
<main>
......@@ -14,13 +16,13 @@ export default async function Page() {
they should be part of a runtime prefetch.
</p>
<Suspense fallback="Loading 1...">
<DynamicallyPrefetchable />
<RuntimePrefetchable />
</Suspense>
</main>
)
}
async function DynamicallyPrefetchable() {
async function RuntimePrefetchable() {
const currentLang = await privateCache()
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
......
......@@ -16,13 +16,11 @@ export default async function Page() {
<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>
......@@ -39,13 +37,11 @@ export default async function Page() {
<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>
......@@ -62,13 +58,11 @@ export default async function Page() {
<li>
<DebugLinkAccordion
href={`/with-root-param/${currentLang}/passed-to-public-cache/root-params`}
prefetch={true}
/>
</li>
<li>
<DebugLinkAccordion
href={`/with-root-param/${otherLang}/passed-to-public-cache/root-params`}
prefetch={true}
/>
</li>
</ul>
......
......@@ -3,6 +3,8 @@ import { cachedDelay, DebugRenderKind, uncachedIO } from '../../../../shared'
import { connection } from 'next/server'
import { lang } from 'next/root-params'
export const unstable_prefetch = 'unstable_runtime'
export default async function Page() {
return (
<main>
......@@ -14,13 +16,13 @@ export default async function Page() {
a hanging input.
</p>
<Suspense fallback="Loading 1...">
<DynamicallyPrefetchable />
<RuntimePrefetchable />
</Suspense>
</main>
)
}
async function DynamicallyPrefetchable() {
async function RuntimePrefetchable() {
const currentLang = await publicCache(lang())
return (
<div style={{ border: '1px solid blue', padding: '1em' }}>
......
......@@ -2,7 +2,7 @@ import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from '../router-act'
describe('<Link prefetch={true}> (runtime prefetch)', () => {
describe('runtime prefetching', () => {
const { next, isNextDev, isNextDeploy } = nextTestSetup({
files: __dirname,
})
......
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html lang="en">
<body>{children}</body>
</html>
)
}
export const unstable_prefetch = 'unstable_runtime'
export default function Layout({ children }: { children: React.ReactNode }) {
return <>{children}</>
}
import { connection } from 'next/server'
import { Suspense } from 'react'
export const unstable_prefetch = 'unstable_static'
export default function Page() {
return (
<main>
<h1>A page that should use a static prefetch</h1>
<Suspense fallback="Loading...">
<Dynamic />
</Suspense>
</main>
)
}
async function Dynamic() {
await connection()
return <div>Dynamic content</div>
}
import { connection } from 'next/server'
import { Suspense } from 'react'
// No exported prefetch value.
// export const unstable_prefetch = ...
export default function Page() {
return (
<main>
<h1>A page that should use a static prefetch</h1>
<Suspense fallback="Loading...">
<Dynamic />
</Suspense>
</main>
)
}
async function Dynamic() {
await connection()
return <div>Dynamic content</div>
}
import { LinkAccordion } from '../components/link-accordion'
export default function Page() {
return (
<main>
<ul>
<li>
<LinkAccordion href="/prefetch-static">
/prefetch-static
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/prefetch-runtime">
/prefetch-runtime
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/nested-prefetch-static">
/nested-prefetch-static
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/no-prefetch">/no-prefetch</LinkAccordion>
</li>
</ul>
</main>
)
}
import { connection } from 'next/server'
import { Suspense } from 'react'
export const unstable_prefetch = 'unstable_static'
export default function Page() {
return (
<main>
<h1>A page that should use a static prefetch</h1>
<Suspense fallback="Loading...">
<Dynamic />
</Suspense>
</main>
)
}
async function Dynamic() {
await connection()
return <div>Dynamic content</div>
}
'use client'
import Link, { type LinkProps } from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
prefetch,
}: {
href: string
children: React.ReactNode
prefetch?: LinkProps['prefetch']
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link prefetch={prefetch} href={href}>
{children}
</Link>
) : (
<>{children} (link is hidden)</>
)}
</>
)
}
import { NextConfig } from 'next'
const nextConfig: NextConfig = {
experimental: {
cacheComponents: true,
clientSegmentCache: true,
// This is automatically enabled when running with `__NEXT_EXPERIMENTAL_PPR`,
// which lets us exercise both modes.
// clientParamParsing: true,
},
}
export default nextConfig
import { nextTestSetup } from 'e2e-utils'
import {
createRequestTracker,
RequestTracker,
} from '../../../../lib/e2e-utils/request-tracker'
import {
RootTreePrefetch,
TreePrefetch,
} from 'next/dist/server/app-render/collect-segment-data'
describe('export const unstable_prefetch = ...', () => {
const { next, isNextDev } = nextTestSetup({
files: __dirname,
})
if (isNextDev) {
it('disabled in development', () => {})
return
}
// TODO: these tests aren't very good, but since the client-side part isn't implmented yet,
// asserting on what the tree prefetch response contains is the best we can do.
// They should be replaced with `act()` tests when the client-side changes are made.
async function captureTreePrefetchResponse(
requestTracker: RequestTracker,
action: () => Promise<void>
): Promise<string> {
const [, response] = await requestTracker.captureResponse(action, {
async request(req) {
const headers = req.headers()
return headers['next-router-segment-prefetch'] === '/_tree'
},
})
return response.text()
}
/** Hackily parse the first row of the RSC response. */
function parseRouteTreeFromTreePrefetchResponse(response: string) {
// Get row 0, the root object.
const rowMatch = response.match(/(?:^|\n)0:(.*?)\n/)
if (!rowMatch) {
throw new Error('Failed to find row 0 in route tree flight data')
}
// `tree` is essentially plain JSON, so it's fine to not do full RSC parsing.
const data = JSON.parse(rowMatch[1]) as RootTreePrefetch
return data.tree
}
it('does not mark for segments with prefetch: "static" as runtime-prefetchable', async () => {
const browser = await next.browser('/')
const requestTracker = createRequestTracker(browser)
// Reveal the link to trigger a runtime prefetch for one value of the dynamic param
const response = await captureTreePrefetchResponse(
requestTracker,
async () => {
const linkToggle = await browser.elementByCss(
`input[data-link-accordion="/prefetch-static"]`
)
await linkToggle.click()
}
)
expect(parseRouteTreeFromTreePrefetchResponse(response)).toEqual(
expect.objectContaining({
name: '',
shouldUseRuntimePrefetch: false,
slots: {
children: expect.objectContaining({
name: 'prefetch-static',
shouldUseRuntimePrefetch: false,
slots: {
children: expect.objectContaining({
name: '__PAGE__',
shouldUseRuntimePrefetch: false, // <-----------------
}),
},
}),
},
})
)
})
it('marks segments with prefetch: "runtime" as runtime-prefetchable', async () => {
const browser = await next.browser('/')
const requestTracker = createRequestTracker(browser)
// Reveal the link to trigger a runtime prefetch for one value of the dynamic param
const response = await captureTreePrefetchResponse(
requestTracker,
async () => {
const linkToggle = await browser.elementByCss(
`input[data-link-accordion="/prefetch-runtime"]`
)
await linkToggle.click()
}
)
expect(parseRouteTreeFromTreePrefetchResponse(response)).toEqual(
expect.objectContaining({
name: '',
shouldUseRuntimePrefetch: false,
slots: {
children: expect.objectContaining({
name: 'prefetch-runtime',
shouldUseRuntimePrefetch: false,
slots: {
children: expect.objectContaining({
name: '__PAGE__',
shouldUseRuntimePrefetch: true, // <-----------------
slots: null,
}),
},
}),
},
})
)
})
it('defaults segments to static if no config is specified', async () => {
const browser = await next.browser('/')
const requestTracker = createRequestTracker(browser)
// Reveal the link to trigger a runtime prefetch for one value of the dynamic param
const response = await captureTreePrefetchResponse(
requestTracker,
async () => {
const linkToggle = await browser.elementByCss(
`input[data-link-accordion="/no-prefetch"]`
)
await linkToggle.click()
}
)
expect(parseRouteTreeFromTreePrefetchResponse(response)).toEqual(
expect.objectContaining({
name: '',
shouldUseRuntimePrefetch: false,
slots: {
children: expect.objectContaining({
name: 'no-prefetch',
shouldUseRuntimePrefetch: false,
slots: {
children: expect.objectContaining({
name: '__PAGE__',
shouldUseRuntimePrefetch: false, // <-----------------
slots: null,
}),
},
}),
},
}) satisfies TreePrefetch
)
})
it('does not mark a "static" segment that is a child of a "runtime" segment as runtime-prefetchable', async () => {
const browser = await next.browser('/')
const requestTracker = createRequestTracker(browser)
// Reveal the link to trigger a runtime prefetch for one value of the dynamic param
const response = await captureTreePrefetchResponse(
requestTracker,
async () => {
const linkToggle = await browser.elementByCss(
`input[data-link-accordion="/nested-prefetch-static"]`
)
await linkToggle.click()
}
)
expect(parseRouteTreeFromTreePrefetchResponse(response)).toEqual(
expect.objectContaining({
name: '',
shouldUseRuntimePrefetch: false,
slots: {
children: expect.objectContaining({
name: 'nested-prefetch-static',
shouldUseRuntimePrefetch: true, // <-----------------
slots: {
children: expect.objectContaining({
name: '__PAGE__',
shouldUseRuntimePrefetch: false, // <-----------------
slots: null,
}),
},
}),
},
}) satisfies TreePrefetch
)
})
})
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