Unverified Commit 3cdb56c2 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

[PPF] unstable_prefetch() (#97622)

Implements `unstable_prefetch()`, which is intended for use in
`partialPrefetching`. `await unstable_prefetch()` excludes content from
the app shell -- it will only be available when using `prefetch={true}`
(speculative prefetch) or during navigations.

As a rule of thumb, `unstable_prefetch()` resolves whenever static
`params` would:
- in a static prerender
  - but NOT the app shell extracted from it, which is param-less
- in a runtime prefetch (`prefetch={true}`)
  - but NOT a runtime app shell, which is param-less

Note that `prefetch()` is URL data, so using it in an App Shell without
Suspense will trigger an instant insight.

### Implementation notes

`prefetch()` is treated like URL data, so it resolves in the
`PrefetchStatic/PrefetchRuntime` stages added in #96908. The
implementation is basically analogous to `unstable_navigation()` except
using different stages. i've considered abstracting them into one
implementation, but decided against that for now, we can deduplicate
later.

Error messages about URL data have not been updated to mention it yet --
we will do that as a follow up, along with docs.

`await prefetch()` does not count as a runtime data access, meaning that
it won't affect the static prefetch hint for a route. however `await
prefetch(); await cookies()` does deopt the route, because using a
speculative runtime prefetch would reveal more content. Note that this
may cause us to unnecessarily deopt a shell to runtime even if only the
speculative part of the content would be improved by a runtime request;
this is not a new issue, but it's something we should optimize.
parent 55b26f96
......@@ -1483,5 +1483,12 @@
"1482": "Route %s used \\`unstable_navigation()\\` inside \\`after()\\` while rendering. The \\`unstable_navigation()\\` function is used to indicate the subsequent code must only run during an actual navigation, but \\`after()\\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after",
"1483": "Route %s used \\`unstable_navigation()\\` inside \"use cache: private\". This is not currently supported. Instead, move the \"use cache\" directive to a function that's called below \\`await unstable_navigation()\\`, so that the cached content is deferred to the navigation without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"1484": "Route %s used \\`unstable_navigation()\\` inside \"use cache\". This is not currently supported. Instead, move the \"use cache\" directive to a function that's called below \\`await unstable_navigation()\\`, so that the cached content is deferred to the navigation without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"1485": "\"unstable_prefetch() is not implemented yet.\""
"1485": "\"unstable_prefetch() is not implemented yet.\"",
"1486": "Route %s used \\`unstable_prefetch()\\` inside \"use cache\". This is not currently supported. Instead, move the \"use cache\" directive to a function that's called below \\`await unstable_prefetch()\\`, so that the cached content is deferred to the prefetch without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache",
"1487": "`unstable_prefetch` must not be used within a Client Component. Next.js should be preventing `unstable_prefetch` from being included in Client Components statically, but did not in this case.",
"1488": "Route %s used \\`unstable_prefetch()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without a prefetch. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context",
"1489": "Route %s used \\`unstable_prefetch()\\` inside a function cached with \\`unstable_cache()\\`. The \\`unstable_prefetch()\\` function is used to indicate the subsequent code must not run in the app shell, but \\`unstable_cache()\\` caches must be able to be produced before a prefetch, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache",
"1490": "Route %s used \\`unstable_prefetch()\\` inside \\`after()\\` while rendering. The \\`unstable_prefetch()\\` function is used to indicate the subsequent code must not run in the app shell, but \\`after()\\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after",
"1491": "Route %s used \\`unstable_prefetch()\\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents",
"1492": "Route %s used \\`unstable_prefetch()\\` inside \"use cache: private\". This is not currently supported. Instead, move the \"use cache\" directive to a function that's called below \\`await unstable_prefetch()\\`, so that the cached content is deferred to the prefetch without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache"
}
......@@ -5,6 +5,7 @@ import {
} from '../app-render/work-unit-async-storage.external'
import {
applyOwnerStack,
RENDER_STAGES_BY_DATA_KIND,
trackIncompatibleShellContent,
} from '../dynamic-rendering-utils'
import { isRequestApiAllowedInCurrentPhase } from './utils'
......@@ -24,7 +25,128 @@ import { RenderStage } from '../app-render/staged-rendering'
* content below `await unstable_prefetch()` remains fully cacheable.
*/
export function unstable_prefetch(): Promise<void> {
throw new Error('"unstable_prefetch() is not implemented yet."')
const workStore = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore()
if (!workStore || !workUnitStore) {
const callingExpression = 'unstable_prefetch'
throwForMissingRequestStore(callingExpression)
}
if (!process.env.__NEXT_CACHE_COMPONENTS) {
throw new Error(
`Route ${workStore.route} used \`unstable_prefetch()\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`
)
}
if (!isRequestApiAllowedInCurrentPhase(workUnitStore)) {
throw new Error(
`Route ${workStore.route} used \`unstable_prefetch()\` inside \`after()\` while rendering. The \`unstable_prefetch()\` function is used to indicate the subsequent code must not run in the app shell, but \`after()\` executes after the request, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/after`
)
}
switch (workUnitStore.type) {
case 'prerender': {
// Content below `prefetch()` is excluded from the shell, but it's
// deliberately included in the static output (and thus in static
// prefetches), so we only delay it until the static prefetch stage.
const { stagedRendering } = workUnitStore
if (!stagedRendering) {
// Prospective prerender
return Promise.resolve(undefined)
} else {
// Final prerender
return stagedRendering.delayUntilStage(
RENDER_STAGES_BY_DATA_KIND.staticLinkData,
'unstable_prefetch',
undefined
)
}
}
case 'prerender-runtime': {
// In a shell render, prefetch() doesn't resolve, because it doesn't reach
// `Runtime`. It'll resolve in a runtime prefetch, and in a runtime
// prerender produced during a navigation.
// Note that this does not mark the subtree as dynamic -- content guarded by
// prefetch() is still considered cacheable.
const { stagedRendering } = workUnitStore
if (!stagedRendering) {
// Prospective prerender
return Promise.resolve(undefined)
} else {
// Final prerender
return stagedRendering.delayUntilStage(
RENDER_STAGES_BY_DATA_KIND.runtimeLinkData,
'unstable_prefetch',
undefined
)
}
}
case 'request': {
const { stagedRendering } = workUnitStore
if (stagedRendering) {
// We can either recover a static shell or a runtime shell, but not both.
trackIncompatibleShellContent(workUnitStore)
const stage = workUnitStore.needsAppShell
? RENDER_STAGES_BY_DATA_KIND.runtimeLinkData // Match the timing of 'prerender-runtime'.
: RENDER_STAGES_BY_DATA_KIND.staticLinkData // Match the timing of 'prerender'.
return stagedRendering.delayUntilStage(
stage,
'unstable_prefetch',
undefined
)
}
return Promise.resolve(undefined)
}
case 'cache': {
const error = new Error(
`Route ${workStore.route} used \`unstable_prefetch()\` inside "use cache". This is not currently supported. Instead, move the "use cache" directive to a function that's called below \`await unstable_prefetch()\`, so that the cached content is deferred to the prefetch without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
Error.captureStackTrace(error, unstable_prefetch)
applyOwnerStack(error)
workStore.invalidDynamicUsageError ??= error
throw error
}
case 'private-cache': {
const error = new Error(
`Route ${workStore.route} used \`unstable_prefetch()\` inside "use cache: private". This is not currently supported. Instead, move the "use cache" directive to a function that's called below \`await unstable_prefetch()\`, so that the cached content is deferred to the prefetch without caching the stage boundary itself. See more info here: https://nextjs.org/docs/messages/next-request-in-use-cache`
)
Error.captureStackTrace(error, unstable_prefetch)
applyOwnerStack(error)
workStore.invalidDynamicUsageError ??= error
throw error
}
case 'unstable-cache': {
throw new Error(
`Route ${workStore.route} used \`unstable_prefetch()\` inside a function cached with \`unstable_cache()\`. The \`unstable_prefetch()\` function is used to indicate the subsequent code must not run in the app shell, but \`unstable_cache()\` caches must be able to be produced before a prefetch, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache`
)
}
case 'generate-static-params': {
throw new Error(
`Route ${workStore.route} used \`unstable_prefetch()\` inside \`generateStaticParams\`. This is not supported because \`generateStaticParams\` runs at build time without a prefetch. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`
)
}
case 'prerender-client':
case 'validation-client': {
const exportName = '`unstable_prefetch`'
throw new InvariantError(
`${exportName} must not be used within a Client Component. Next.js should be preventing ${exportName} from being included in Client Components statically, but did not in this case.`
)
}
case 'prerender-legacy': {
// NOTE: Should not be reachable, because we don't use this mode in cacheComponents,
// which we require at the top
throw new Error(
`Route ${workStore.route} used \`unstable_prefetch()\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents`
)
}
default: {
workUnitStore satisfies never
return Promise.resolve(undefined)
}
}
}
/**
......
......@@ -341,6 +341,19 @@ export function runDevWarmupTests({
assertLog(logs, `after params`, 'Prefetch')
assertLog(logs, `after searchParams`, 'Prefetch')
assertLog(
logs,
`after prefetch`,
// Same as navigation() below: static prerender timing on initial
// load, app-shell timing for a client nav when there's a runtime
// prefetch.
isInitialLoad
? 'Prerender'
: partialPrefetching || hasRuntimePrefetch
? 'Prefetch'
: 'Prerender'
)
assertLog(
logs,
`after navigation`,
......
import { cookies, headers } from 'next/headers'
import { CachedData } from '../../data-fetching'
import { connection } from 'next/server'
import { unstable_navigation as navigation } from 'next/cache'
import {
unstable_navigation as navigation,
unstable_prefetch,
} from 'next/cache'
import { Suspense } from 'react'
export const instant = true
......@@ -23,6 +26,7 @@ export default function Page({ params, searchParams }) {
<LogAfter label="headers" api={() => headers()} />
<LogAfter label="params" api={() => params} />
<LogAfter label="searchParams" api={() => searchParams} />
<LogAfter label="prefetch" api={() => unstable_prefetch()} />
<LogAfter label="navigation" api={() => navigation()} />
{/* Dynamic */}
......
import { cookies, headers } from 'next/headers'
import { CachedData } from '../../data-fetching'
import { connection } from 'next/server'
import { unstable_navigation as navigation } from 'next/cache'
import {
unstable_navigation as navigation,
unstable_prefetch,
} from 'next/cache'
import { Suspense } from 'react'
const CACHE_KEY = __dirname + '/__PAGE__'
......@@ -20,6 +23,7 @@ export default function Page({ params, searchParams }) {
<LogAfter label="headers" api={() => headers()} />
<LogAfter label="params" api={() => params} />
<LogAfter label="searchParams" api={() => searchParams} />
<LogAfter label="prefetch" api={() => unstable_prefetch()} />
<LogAfter label="navigation" api={() => navigation()} />
{/* Dynamic */}
......
import { Instant } from 'next'
import { unstable_prefetch } from 'next/cache'
export const instant: Instant = {
level: 'experimental-error',
}
export const prefetch = 'partial'
export default async function Page() {
return (
<main>
<p>
This page is missing a suspense around prefetch(), so we can't render a
shell.
</p>
<PrefetchContent />
</main>
)
}
async function PrefetchContent() {
await unstable_prefetch()
return <div>{`Prefetch content`}</div>
}
......@@ -44,6 +44,12 @@ export default async function Page() {
<li>
<DebugLinks href="/shells/valid-navigation-with-suspense" />
</li>
<li>
<DebugLinks href="/shells/invalid-prefetch-without-suspense" />
</li>
<li>
<DebugLinks href="/shells/valid-prefetch-with-suspense" />
</li>
</ul>
</main>
)
......
import { Instant } from 'next'
import { unstable_prefetch } from 'next/cache'
import { Suspense } from 'react'
export const instant: Instant = {
level: 'experimental-error',
}
export const prefetch = 'partial'
export default async function Page() {
return (
<main>
<p>
This page has a suspense around prefetch(), so we can render a shell and
should have no validation errors.
</p>
<Suspense>
<PrefetchContent />
</Suspense>
</main>
)
}
async function PrefetchContent() {
await unstable_prefetch()
return <div>{`Prefetch content`}</div>
}
import { Instant } from 'next'
import { unstable_prefetch } from 'next/cache'
export const instant: Instant = {
level: 'experimental-error',
}
export default async function Page() {
return (
<main>
<p>
This page is missing a suspense around prefetch(), but that's allowed if
we're not in partialPrefetching and aren't rendering App Shells.
</p>
<PrefetchContent />
</main>
)
}
async function PrefetchContent() {
await unstable_prefetch()
return <div>{`Prefetch content`}</div>
}
......@@ -54,6 +54,9 @@ export default async function Page() {
<li>
<DebugLinks href="/suspense-in-root/sync-io/sync-io-after-navigation" />
</li>
<li>
<DebugLinks href="/suspense-in-root/sync-io/sync-io-after-prefetch" />
</li>
<li>
<DebugLinks href="/suspense-in-root/sync-io/sync-io-after-cookies-in-generate-metadata" />
</li>
......@@ -305,6 +308,9 @@ export default async function Page() {
<li>
<DebugLinks href="/suspense-in-root/non-app-shell/valid-unguarded-navigation" />
</li>
<li>
<DebugLinks href="/suspense-in-root/non-app-shell/valid-unguarded-prefetch" />
</li>
</ul>
<h2>Blocking await attribution</h2>
......
import { unstable_prefetch } from 'next/cache'
import { Suspense } from 'react'
export const instant = { level: 'experimental-error' }
export default async function Page() {
return (
<main>
<p>
This page uses sync IO after awaiting prefetch():
{/*
In partialPrefetching, prefetch() is not allowed in shells,
so we need a Suspense.
Before partialPrefetching everything is static, so we could skip it,
but that's not relevant to this test.
*/}
<Suspense>
<SyncIOAfterPrefetch />
</Suspense>
</p>
</main>
)
}
async function SyncIOAfterPrefetch() {
await unstable_prefetch()
return Date.now()
}
......@@ -970,6 +970,80 @@ export function registerHeadAndReportingTests(
}
})
it('invalid - unguarded prefetch() in a shell', async () => {
if (isNextDev) {
const browser = await navigateTo(
'/shells/invalid-prefetch-without-suspense'
)
await expect(browser).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Instant Validation",
"source": "app/shells/(default)/invalid-prefetch-without-suspense/page.tsx (4:33) @ instant
> 4 | export const instant: Instant = {
| ^",
"stack": [
"instant app/shells/(default)/invalid-prefetch-without-suspense/page.tsx (4:33)",
"Set.forEach <anonymous>",
],
},
],
"code": "E1439",
"description": "Next.js encountered URL data outside of Suspense.",
"environmentLabel": "Server",
"label": "Instant",
"source": "app/shells/(default)/invalid-prefetch-without-suspense/page.tsx (23:26) @ PrefetchContent
> 23 | await unstable_prefetch()
| ^",
"stack": [
"PrefetchContent app/shells/(default)/invalid-prefetch-without-suspense/page.tsx (23:26)",
"Page app/shells/(default)/invalid-prefetch-without-suspense/page.tsx (17:7)",
],
}
`)
} else {
const result = await prerender(
'/shells/(default)/invalid-prefetch-without-suspense'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/shells/invalid-prefetch-without-suspense": Next.js encountered URL data during prerendering or a navigation.
\`params\` or \`searchParams\` accessed outside of \`<Suspense>\` may prevent the navigation from being instant, leading to a slower user experience.
Ways to fix this:
- [stream] Provide a placeholder with \`<Suspense fallback={...}>\` around the data access
- [block] Set \`export const instant = false\` to allow a blocking route
Learn more: https://nextjs.org/docs/messages/instant-shell-url-data
at main (<anonymous>)
at body (<anonymous>)
at html (<anonymous>)
Build-time instant validation failed for route "/shells/invalid-prefetch-without-suspense".
To get a more detailed stack trace and pinpoint the issue, try one of the following:
- Start the app in development mode by running \`next dev\`, then open "/shells/invalid-prefetch-without-suspense" in your browser to investigate the error.
- Rerun the production build with \`next build --debug-prerender\` to generate better stack traces.
Stopping prerender due to instant validation errors."
`)
expect(result.exitCode).toBe(1)
}
})
it('valid - prefetch() with suspense in a shell', async () => {
if (isNextDev) {
const browser = await navigateTo(
'/shells/valid-prefetch-with-suspense'
)
await expectNoDevValidationErrors(browser, await browser.url())
} else {
const result = await prerender(
'/shells/(default)/valid-prefetch-with-suspense'
)
expectNoBuildValidationErrors(result)
}
})
it('valid - unguarded root param', async () => {
if (isNextDev) {
const browser = await navigateTo(
......@@ -1026,6 +1100,19 @@ export function registerHeadAndReportingTests(
expectNoBuildValidationErrors(result)
}
})
it('valid - unguarded prefetch', async () => {
if (isNextDev) {
const browser = await navigateTo(
'/suspense-in-root/non-app-shell/valid-unguarded-prefetch'
)
await expectNoDevValidationErrors(browser, await browser.url())
} else {
const result = await prerender(
'/suspense-in-root/non-app-shell/valid-unguarded-prefetch'
)
expectNoBuildValidationErrors(result)
}
})
})
}
......
......@@ -134,6 +134,65 @@ export function registerSyncIoAndBlockingTests(
}
})
it('sync IO after prefetch()', async () => {
if (isNextDev) {
const browser = await navigateTo(
'/suspense-in-root/sync-io/sync-io-after-prefetch'
)
await expect(browser).toDisplayCollapsedRedbox(`
{
"code": "E1432",
"description": "Next.js encountered the unstable value Date.now() while prerendering.",
"environmentLabel": "Server",
"label": "Blocking Route",
"source": "app/suspense-in-root/sync-io/sync-io-after-prefetch/page.tsx (27:15) @ SyncIOAfterPrefetch
> 27 | return Date.now()
| ^",
"stack": [
"SyncIOAfterPrefetch app/suspense-in-root/sync-io/sync-io-after-prefetch/page.tsx (27:15)",
"Page app/suspense-in-root/sync-io/sync-io-after-prefetch/page.tsx (18:11)",
],
}
`)
} else {
const result = await prerender(
'/suspense-in-root/sync-io/sync-io-after-prefetch'
)
// `await prefetch()` resolves during a static prerender, so
// we hit the sync IO there and error before reaching instant validation.
expect(
getPrerenderOutput(result.cliOutput, {
isMinified: true,
})
).toMatchInlineSnapshot(`
"Error: Route "/suspense-in-root/sync-io/sync-io-after-prefetch": Next.js encountered the unstable value \`Date.now()\` while prerendering.
This value can change between renders, so it must be either prerendered or computed later.
Ways to fix this:
- [dynamic] Render at request time by adding a dynamic data access (e.g. \`await connection()\`) before this call
- [cache] Prerender and cache the value with \`"use cache"\`
- [client] Render the value on the client with \`"use client"\`
- [measure] If the value is for telemetry, use a timing API such as \`performance.now()\`
Learn more: https://nextjs.org/docs/messages/blocking-prerender-current-time
at a (app/suspense-in-root/sync-io/sync-io-after-prefetch/page.tsx:27:15)
25 | async function SyncIOAfterPrefetch() {
26 | await unstable_prefetch()
> 27 | return Date.now()
| ^
28 | }
29 |
To get a more detailed stack trace and pinpoint the issue, try one of the following:
- Start the app in development mode by running \`next dev\`, then open "/suspense-in-root/sync-io/sync-io-after-prefetch" in your browser to investigate the error.
- Rerun the production build with \`next build --debug-prerender\` to generate better stack traces.
Error occurred prerendering page "/suspense-in-root/sync-io/sync-io-after-prefetch". Read more: https://nextjs.org/docs/messages/prerender-error
Export encountered an error on /suspense-in-root/sync-io/sync-io-after-prefetch/page: /suspense-in-root/sync-io/sync-io-after-prefetch, exiting the build."
`)
expect(result.exitCode).toBe(1)
}
})
it('sync IO after cache with session data input', async () => {
if (isNextDev) {
const browser = await navigateTo(
......
......@@ -75,6 +75,9 @@ describe('cached navigations - global partialPrefetching', () => {
expect(await browser.elementById('navigation-boundary').text()).toContain(
'Navigation content'
)
expect(await browser.elementById('prefetch-boundary').text()).toContain(
'Prefetch content'
)
// Only connection() shows a Suspense fallback — it's truly dynamic.
expect(await browser.elementById('connection-boundary').text()).toBe(
......
import { cookies, headers } from 'next/headers'
import { connection } from 'next/server'
import { unstable_navigation as navigation } from 'next/cache'
import {
unstable_navigation as navigation,
unstable_prefetch,
} from 'next/cache'
import { Suspense } from 'react'
// Note: intentionally no `export const prefetch` and no `instant` config. This
......@@ -40,6 +43,11 @@ export default async function Page({
<NavigationContent />
</Suspense>
</div>
<div id="prefetch-boundary">
<Suspense fallback={<p>Loading prefetch...</p>}>
<PrefetchContent />
</Suspense>
</div>
</main>
)
}
......@@ -79,3 +87,8 @@ async function NavigationContent() {
await navigation()
return <p>Navigation content</p>
}
async function PrefetchContent() {
await unstable_prefetch()
return <p>Prefetch content</p>
}
......@@ -148,6 +148,35 @@ export default function Page() {
</LinkAccordion>
</li>
</ul>
<h2>Prefetch posts</h2>
<ul>
<li>
<LinkAccordion href="/static-prefetch/1">
Static prefetch post 1
</LinkAccordion>
</li>
<li>
<Link href="/static-prefetch/2" prefetch={false}>
Static prefetch post 2 (unprefetched)
</Link>
</li>
<li>
<LinkAccordion href="/runtime-prefetch/1">
Runtime prefetch post 1
</LinkAccordion>
</li>
<li>
<Link href="/runtime-prefetch/2" prefetch={false}>
Runtime prefetch post 2 (unprefetched)
</Link>
</li>
<li>
<LinkAccordion href="/runtime-prefetch/speculative-1" prefetch={true}>
Runtime prefetch post "speculative-1" (prefetch=true)
</LinkAccordion>
</li>
</ul>
</main>
)
}
import { Suspense } from 'react'
import { unstable_prefetch } from 'next/cache'
import { cookies } from 'next/headers'
import { connection } from 'next/server'
type Params = { id: string }
export const prefetch = 'partial'
export default async function Page({ params }: { params: Promise<Params> }) {
return (
<main>
<Suspense fallback={<p id="prefetch-loading">Loading prefetch...</p>}>
<PrefetchData />
</Suspense>
{/* The fallback is the App Shell — the part of the page that
doesn't depend on params. */}
<Suspense fallback={<p id="shell">App shell for prefetch</p>}>
<ParamsDependent params={params} />
</Suspense>
</main>
)
}
async function PrefetchData() {
await cookies() // Makes sure this page uses a runtime prefetch
await unstable_prefetch() // Exclude the contents below from runtime app shells
return <div id="prefetch-content">Prefetch content</div>
}
async function ParamsDependent({ params }: { params: Promise<Params> }) {
const { id } = await params
return (
<>
<p id="param-value">{`Post ${id}`}</p>
<Suspense
fallback={<p id="dynamic-loading">Loading dynamic content...</p>}
>
<Dynamic id={id} />
</Suspense>
</>
)
}
async function Dynamic({ id }: { id: string }) {
await connection()
return <p id="dynamic-content">{`Post body for ${id}`}</p>
}
import { Suspense } from 'react'
import { unstable_prefetch } from 'next/cache'
import { connection } from 'next/server'
export async function generateStaticParams() {
return [{ id: '1' }, { id: '2' }]
}
type Params = { id: string }
export const prefetch = 'partial'
export default async function Page({ params }: { params: Promise<Params> }) {
return (
<main>
<Suspense fallback={<p id="shell">App shell for prefetch</p>}>
<ParamsDependent params={params} />
</Suspense>
<Suspense fallback={<p id="prefetch-loading">Loading prefetch...</p>}>
<PrefetchData />
</Suspense>
</main>
)
}
async function PrefetchData() {
await unstable_prefetch() // Exclude the contents below from the shell
return <div id="prefetch-content">Prefetch content</div>
}
async function ParamsDependent({ params }: { params: Promise<Params> }) {
// Make sure the static prefetch varies on params so that the client router
// has to extract a static shell from it when navigating to another param value.
// If the static prefetch doesn't vary on params, it'll be used instead of
// the app shell
const { id } = await params
return (
<>
<p id="param-value">{`Post ${id}`}</p>
<Suspense
fallback={<p id="dynamic-loading">Loading dynamic content...</p>}
>
<Dynamic id={id} />
</Suspense>
</>
)
}
async function Dynamic({ id }: { id: string }) {
await connection()
return <p id="dynamic-content">{`Post body for ${id}`}</p>
}
......@@ -591,6 +591,180 @@ describe('App Shell prefetching', () => {
})
})
describe('prefetch()', () => {
it('excludes prefetch() from a static App Shell', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Caches the App Shell for /static-prefetch/[id].
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/static-prefetch/1"]')
.click()
}, [{ includes: 'App shell for prefetch', kind: 'static' }])
await act(async () => {
// /static-prefetch/2 was never prefetched, so the router falls back to
// the cached App Shell.
await browser.elementByCss('a[href="/static-prefetch/2"]').click()
expect(await browser.elementById('shell').text()).toEqual(
'App shell for prefetch'
)
// prefetch()-gated content is not part of the App Shell.
expect(await browser.locator('#prefetch-content').count()).toBe(0)
expect(await browser.elementByCss('#prefetch-loading').text()).toBe(
'Loading prefetch...'
)
})
expect(await browser.elementById('prefetch-content').text()).toEqual(
'Prefetch content'
)
expect(await browser.elementById('dynamic-content').text()).toEqual(
'Post body for 2'
)
})
it('excludes prefetch() from a runtime App Shell', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// Caches the App Shell for /runtime-prefetch/[id]. The route reads
// request data, so its static-attempt hint is unset and the prefetch
// deopts to a runtime shell.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/runtime-prefetch/1"]')
.click()
}, [
{ includes: 'App shell for prefetch', kind: 'runtime' },
{ includes: 'param-value', block: 'reject' }, // Only a shell, no URL data.
])
await act(async () => {
// /runtime-prefetch/2 was never prefetched, so the router falls back to
// the cached App Shell.
await browser.elementByCss('a[href="/runtime-prefetch/2"]').click()
expect(await browser.elementById('shell').text()).toEqual(
'App shell for prefetch'
)
// prefetch()-gated content is not part of the App Shell.
expect(await browser.locator('#prefetch-content').count()).toBe(0)
expect(await browser.elementByCss('#prefetch-loading').text()).toBe(
'Loading prefetch...'
)
})
expect(await browser.elementById('prefetch-content').text()).toEqual(
'Prefetch content'
)
expect(await browser.elementById('dynamic-content').text()).toEqual(
'Post body for 2'
)
})
it('includes prefetch() in a static prefetch', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/static-prefetch/1"]')
.click()
}, [{ includes: 'App shell for prefetch', kind: 'static' }])
await act(async () => {
// Navigate to the prefetched route.
await browser.elementByCss('a[href="/static-prefetch/1"]').click()
expect(await browser.elementById('param-value').text()).toEqual(
'Post 1'
)
// prefetch()-gated content resolves in a static prefetch.
expect(await browser.locator('#prefetch-loading').count()).toBe(0)
expect(await browser.elementByCss('#prefetch-content').text()).toBe(
'Prefetch content'
)
// Dynamic content is not included.
expect(await browser.locator('#dynamic-content').count()).toBe(0)
expect(await browser.elementByCss('#dynamic-loading').text()).toBe(
'Loading dynamic content...'
)
})
expect(await browser.elementById('dynamic-content').text()).toEqual(
'Post body for 1'
)
})
it('includes prefetch() in a speculative runtime prefetch', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// The Shell phase's runtime App Shell request, then the Speculative
// phase's per-link runtime prefetch (the link opts in with
// `prefetch={true}`).
await act(async () => {
await browser
.elementByCss(
'input[data-link-accordion="/runtime-prefetch/speculative-1"]'
)
.click()
}, [
{ includes: 'App shell for prefetch', kind: 'runtime' }, // Shell
{ includes: 'Post speculative-1', kind: 'runtime' }, // Speculative
])
await act(async () => {
// Navigate to the prefetched route.
await browser
.elementByCss('a[href="/runtime-prefetch/speculative-1"]')
.click()
expect(await browser.elementById('param-value').text()).toEqual(
'Post speculative-1'
)
// Unlike navigation(), prefetch() resolves in a speculative runtime
// prefetch.
expect(await browser.locator('#prefetch-loading').count()).toBe(0)
expect(await browser.elementByCss('#prefetch-content').text()).toBe(
'Prefetch content'
)
// Dynamic content is not included.
expect(await browser.locator('#dynamic-content').count()).toBe(0)
expect(await browser.elementByCss('#dynamic-loading').text()).toBe(
'Loading dynamic content...'
)
})
expect(await browser.elementById('dynamic-content').text()).toEqual(
'Post body for speculative-1'
)
})
})
describe('root params', () => {
it('includes root params in a runtime App Shell', async () => {
let page: Playwright.Page
......
import { Suspense } from 'react'
import { unstable_navigation as navigation } from 'next/cache'
import {
unstable_navigation as navigation,
unstable_prefetch,
} from 'next/cache'
type Params = { slug: string }
......@@ -30,6 +33,11 @@ export default function Page({ params }: { params: Promise<Params> }) {
>
<NavigationContent />
</Suspense>
<Suspense
fallback={<p id="prefetch-loading">Loading prefetch content...</p>}
>
<PrefetchContent />
</Suspense>
</main>
)
}
......@@ -43,3 +51,8 @@ async function NavigationContent() {
await navigation()
return <p id="navigation-content">Navigation content</p>
}
async function PrefetchContent() {
await unstable_prefetch()
return <p id="prefetch-content">Prefetch content</p>
}
......@@ -35,6 +35,16 @@ export default function Page() {
Uses navigation() on a static page
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/uses-runtime-after-prefetch">
Uses runtime APIs after prefetch()
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/uses-prefetch-static">
Uses prefetch() on a static page
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/dynamic-param/one">
Dynamic param one
......
import { Suspense } from 'react'
import { unstable_prefetch } from 'next/cache'
export default function Page() {
return (
<main>
<Suspense fallback={<p id="prefetch-loading">Loading prefetch...</p>}>
<PrefetchContent />
</Suspense>
</main>
)
}
async function PrefetchContent() {
await unstable_prefetch()
return <p id="page-content">Fully static page content (with prefetch())</p>
}
// A page that calls cookies and headers after awaiting `unstable_prefetch()`.
// Unlike `navigation()`, `prefetch()` doesn't stop runtime-data tracking — the
// reads below it still count — so the tree hint stays unset and this route
// can't be prefetched statically.
import { cookies, headers } from 'next/headers'
import { unstable_prefetch } from 'next/cache'
import { Suspense } from 'react'
export default async function Page() {
return (
<main>
<p id="page-content">Runtime APIs called after prefetch()</p>
<Suspense
fallback={<p id="prefetch-loading">Loading prefetch content...</p>}
>
<Prefetch />
</Suspense>
</main>
)
}
async function Prefetch() {
await unstable_prefetch()
return (
<>
<div id="prefetch-content">Prefetch content</div>
<Suspense
fallback={<p id="runtime-loading">Loading runtime content...</p>}
>
<RuntimeContent />
</Suspense>
</>
)
}
async function RuntimeContent() {
await Promise.all([cookies(), headers()])
return <p id="runtime-content">Runtime content</p>
}
......@@ -144,6 +144,41 @@ describe('static App Shell prefetch attempt', () => {
}, 'no-requests')
})
it('prefetches a fully static route that uses prefetch() with static requests only, then navigates instantly from cache', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
// prefetch() resolves during a static prerender, and the route accesses no
// runtime data, so the static attempt is sufficient.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/uses-prefetch-static"]')
.click()
}, [
{
includes: 'Fully static page content (with prefetch())',
kind: 'static',
},
{
includes: 'Fully static page content (with prefetch())',
kind: 'runtime',
block: 'reject',
},
])
await act(async () => {
await browser.elementByCss('a[href="/uses-prefetch-static"]').click()
expect(await browser.elementById('page-content').text()).toBe(
'Fully static page content (with prefetch())'
)
}, 'no-requests')
})
it('goes straight to a runtime shell prefetch when the shell reads cookies (hint unset)', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
......@@ -335,6 +370,35 @@ describe('static App Shell prefetch attempt', () => {
)
})
it('goes straight to a runtime shell prefetch for a partial segment that calls runtime APIs after prefetch() (hint unset)', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
beforePageLoad(p: Playwright.Page) {
page = p
},
})
const act = createRouterAct(page, { includeAppShellRequests: true })
await act(async () => {
await browser
.elementByCss(
'input[data-link-accordion="/uses-runtime-after-prefetch"]'
)
.click()
}, [
// Unlike navigation(), prefetch() doesn't stop runtime-data tracking, so
// the cookies()/headers() reads below it leave the tree hint unset and
// the shell arrives in a runtime response.
{ includes: 'Runtime APIs called after prefetch()', kind: 'runtime' },
// No static attempt precedes it.
{
includes: 'Runtime APIs called after prefetch()',
kind: 'static',
block: 'reject',
},
])
})
it('reuses the static App Shell across different param values of a dynamic route', async () => {
let page: Playwright.Page
const browser = await next.browser('/', {
......@@ -405,6 +469,9 @@ describe('static App Shell prefetch attempt', () => {
expect(await browser.elementById('navigation-loading').text()).toBe(
'Loading navigation content...'
)
expect(await browser.elementById('prefetch-loading').text()).toBe(
'Loading prefetch content...'
)
},
// The param content arrives with the navigation response.
{ includes: 'Dynamic param content: two' }
......
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