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

[PPF] unstable_navigation() (#96908)

`navigation()` is a new API that allows omitting contents from runtime
shells and runtime prefetches. Conceptually, the point is to express
that something is expensive to compute, so we shouldn't do it for
requests that may not get used (shells and prefetches). Notably, this
means that it's fine to include it in a static prerender -- it'll be
computed once and used for many requests, so it doesn't make sense to
exclude it.



## Implementation

The split in behavior across static and runtime prerenders is a
departure from how most of our APIs behave -- usually, if something
resolves statically, then it also resolves in "more complete" prerender.
Departing from this leads to some implementation complexity.

We include three new stages, used by two facets of the implementation:

```diff
export enum RenderStage {
  Before = 1,
  //
  ShellStatic = 10,
+ PrefetchStatic = 11, <------- params, prefetch()  [static prerenders]
+ NavigationStatic = 12  <------navigation()        [static prerenders]
  Static = 13, <--------------- finish accumulators [static prerenders]
  //
  ShellRuntime = 20,
  Runtime = 21, <-------------- params, prefetch() [runtime prerenders]
+ NavigationRuntime = 22, <---- navigation()       [runtime prerenders]
  //
  Dynamic = 30,
  Abandoned = 40,
}
```

### NavigationRuntime

In runtime prerenders (or dev renders that simulate them),
`navigation()` resolves in `NavigationRuntime`
We only reach this stage in 1. the embedded runtime prerender produced
for Cached Navigations and 2. during dev/prod full staged renders --
runtime shells end in `ShellRuntime`, and runtime prefetches end in
`Runtime`.

Notably, this means that content gated behind `navigation()` is included
in the embedded runtime prefetch stream.

### PrefetchStatic & NavigationStatic

This is a helper stage added before `Static`. Static prefetches still
use the `Static` stage for their output. This new stage exists so that
we can resolve static `params` (and `prefetch()` when we implement it)
which the stage is named after) separately from `navigation()`, which
resolves in `NavigationStatic`, after which the prerender ends in
`Static`. This separation is important, because during static prerenders
we track whether or not runtime APIs are used (see
`trackRuntimeDataAccessed`) to determine if a runtime shell (or runtime
prefetch) might give us more content than the static ones. However, a
runtime shell/prefethc **would not resolve navigation()**, so `await
navigation(); await cookies()` would not reveal more content, and thus
shouldn't count as a usage that prevents static optimization.
We achieve this by checking the stage inside
`trackRuntimeDataAccessedImpl` and not tracking anything if we reached
the `NavigationStatic` stage.

### Behavior of shells and validation

As noted before, `navigation()` has an incompatible resolution order
between static and runtime prerenders. In #97040, we did some groundwork
to deal with this in validation.

Static prerenders resolve `navigation()`, which means that static shells
include content gated behind navigation(). This means that Static Shell
Validation allows them.

On the other hand, App shells **do not** resolve `navigation()`. This
leads to an inconsistency for Instant Validation -- a `await
navigation()` might be fine if a page is prefetched statically, but
would become blocking as soon as the page starts using runtime data and
switches to a runtime shell. To avoid this pitfall, we pessimistically
assume that any `navigation()` _might_ be part of a runtime
shell/prefetch, so any `navigation()` unguarded by Suspense will error
in IV.

In practice, this is handled analogously to static params: we do a dev
render with `needsAppShell: true`, which makes `navigation()` resolve in
`NavigationRuntime`, and then we use the `ShellRuntime` stage when
validating, which means that `navigation()` will be a hole. Note that
the discriminated error message logic currently only retries errors
using the `Runtime` stage, which won't have `navigation()` resolved
either, so it will be incorrectly reported as dynamic data. This will be
improved in a follow up.
parent 2cc3694f
...@@ -1475,5 +1475,12 @@ ...@@ -1475,5 +1475,12 @@
"1474": "Invariant: cannot write an empty buffer to the image cache", "1474": "Invariant: cannot write an empty buffer to the image cache",
"1475": "Invariant: no direct app page entry found for %s", "1475": "Invariant: no direct app page entry found for %s",
"1476": "Not implemented: this behavior is not yet supported when `experimental.concurrentRouterQueue` is enabled.", "1476": "Not implemented: this behavior is not yet supported when `experimental.concurrentRouterQueue` is enabled.",
"1477": "unstable_navigation() is not implemented yet." "1477": "unstable_navigation() is not implemented yet.",
"1478": "`unstable_navigation` must not be used within a Client Component. Next.js should be preventing `unstable_navigation` from being included in Client Components statically, but did not in this case.",
"1479": "Route %s used \\`unstable_navigation()\\` inside a function cached with \\`unstable_cache()\\`. The \\`unstable_navigation()\\` function is used to indicate the subsequent code must only run during an actual navigation, but \\`unstable_cache()\\` caches must be able to be produced before a navigation, so this function is not allowed in this scope. See more info here: https://nextjs.org/docs/app/api-reference/functions/unstable_cache",
"1480": "Route %s used \\`unstable_navigation()\\` inside \\`generateStaticParams\\`. This is not supported because \\`generateStaticParams\\` runs at build time without a navigation. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context",
"1481": "Route %s used \\`unstable_navigation()\\`, which requires Cache Components to be enabled. Learn more: https://nextjs.org/docs/app/api-reference/config/next-config-js/cacheComponents",
"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"
} }
...@@ -4,14 +4,16 @@ import { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolv ...@@ -4,14 +4,16 @@ import { createPromiseWithResolvers } from '../../shared/lib/promise-with-resolv
export enum RenderStage { export enum RenderStage {
Before = 1, Before = 1,
// //
ShellStatic = 11, ShellStatic = 10,
PrefetchStatic = 11,
NavigationStatic = 12,
Static = 13, Static = 13,
// //
ShellRuntime = 21, ShellRuntime = 20,
Runtime = 23, Runtime = 21,
NavigationRuntime = 22,
// //
Dynamic = 30, Dynamic = 30,
//
Abandoned = 40, Abandoned = 40,
} }
...@@ -22,10 +24,13 @@ export type AdvanceableRenderStage = Exclude< ...@@ -22,10 +24,13 @@ export type AdvanceableRenderStage = Exclude<
export const RENDER_STAGE_ADVANCE_ORDER: AdvanceableRenderStage[] = [ export const RENDER_STAGE_ADVANCE_ORDER: AdvanceableRenderStage[] = [
RenderStage.ShellStatic, RenderStage.ShellStatic,
RenderStage.PrefetchStatic,
RenderStage.NavigationStatic,
RenderStage.Static, RenderStage.Static,
// //
RenderStage.ShellRuntime, RenderStage.ShellRuntime,
RenderStage.Runtime, RenderStage.Runtime,
RenderStage.NavigationRuntime,
// //
RenderStage.Dynamic, RenderStage.Dynamic,
] ]
......
...@@ -248,6 +248,19 @@ function trackRuntimeDataAccessedImpl( ...@@ -248,6 +248,19 @@ function trackRuntimeDataAccessedImpl(
): void { ): void {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'prerender': { case 'prerender': {
const { stagedRendering } = workUnitStore
if (
stagedRendering &&
stagedRendering.currentStage >= RenderStage.NavigationStatic
) {
// Ignore any accesses that happen after `navigation()` resolves.
// The purpose of this tracking is to judge whether a runtime prefetch
// would give us a more complete result than a static one.
// But `navigation()` wouldn't have resolved in a runtime prefetch,
// so e.g. `await navigation(); await cookies()` wouldn't have more content
// in those, and we shouldn't count it.
return
}
// Response-level flag (the payload's `u`, forwarded to segment // Response-level flag (the payload's `u`, forwarded to segment
// responses as `needsRuntimeRequest`): resolved for every kind of // responses as `needsRuntimeRequest`): resolved for every kind of
// access — a pre-upgrade fallback response must keep reporting that // access — a pre-upgrade fallback response must keep reporting that
...@@ -412,7 +425,7 @@ export function trackPromiseUsed<T>(promise: Promise<T>, onUse: () => void) { ...@@ -412,7 +425,7 @@ export function trackPromiseUsed<T>(promise: Promise<T>, onUse: () => void) {
export const RENDER_STAGES_BY_DATA_KIND = { export const RENDER_STAGES_BY_DATA_KIND = {
sessionData: RenderStage.ShellRuntime as const, sessionData: RenderStage.ShellRuntime as const,
staticLinkData: RenderStage.Static as const, staticLinkData: RenderStage.PrefetchStatic as const,
runtimeLinkData: RenderStage.Runtime as const, runtimeLinkData: RenderStage.Runtime as const,
} }
......
...@@ -61,12 +61,15 @@ export function io(expression: string, type: SyncIOApiType) { ...@@ -61,12 +61,15 @@ export function io(expression: string, type: SyncIOApiType) {
// `shouldTrackSyncInterrupt`/`syncInterruptCurrentStageWithReason` // `shouldTrackSyncInterrupt`/`syncInterruptCurrentStageWithReason`
switch (stageController.currentStage) { switch (stageController.currentStage) {
case RenderStage.ShellStatic: case RenderStage.ShellStatic:
case RenderStage.PrefetchStatic:
case RenderStage.NavigationStatic:
case RenderStage.Static: { case RenderStage.Static: {
syncIOError = createSyncIOError(workStore.route, expression, type) syncIOError = createSyncIOError(workStore.route, expression, type)
break break
} }
case RenderStage.ShellRuntime: case RenderStage.ShellRuntime:
case RenderStage.Runtime: { case RenderStage.Runtime:
case RenderStage.NavigationRuntime: {
// We're in the Runtime stage. // We're in the Runtime stage.
// We only error for Sync IO in the Runtime stage if the route has partialPrefetching enabled. // We only error for Sync IO in the Runtime stage if the route has partialPrefetching enabled.
syncIOError = createSyncIORuntimeError( syncIOError = createSyncIORuntimeError(
......
import { workAsyncStorage } from '../app-render/work-async-storage.external'
import {
throwForMissingRequestStore,
workUnitAsyncStorage,
} from '../app-render/work-unit-async-storage.external'
import {
applyOwnerStack,
trackIncompatibleShellContent,
} from '../dynamic-rendering-utils'
import { isRequestApiAllowedInCurrentPhase } from './utils'
import { InvariantError } from '../../shared/lib/invariant-error'
import { RenderStage } from '../app-render/staged-rendering'
/** /**
* This function allows you to indicate that the subsequent code should be * This function allows you to indicate that the subsequent code should be
* deferred to the actual navigation instead of rendering during a runtime * deferred to the actual navigation instead of rendering during a runtime
...@@ -13,5 +26,129 @@ ...@@ -13,5 +26,129 @@
* content below `await unstable_navigation()` remains fully cacheable. * content below `await unstable_navigation()` remains fully cacheable.
*/ */
export function unstable_navigation(): Promise<void> { export function unstable_navigation(): Promise<void> {
throw new Error('unstable_navigation() is not implemented yet.') const workStore = workAsyncStorage.getStore()
const workUnitStore = workUnitAsyncStorage.getStore()
if (!workStore || !workUnitStore) {
const callingExpression = 'unstable_navigation'
throwForMissingRequestStore(callingExpression)
}
if (!process.env.__NEXT_CACHE_COMPONENTS) {
throw new Error(
`Route ${workStore.route} used \`unstable_navigation()\`, 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_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`
)
}
switch (workUnitStore.type) {
case 'prerender': {
// Static prerenders are computed once and shared across many
// clients, so there's no per-request prefetch cost to save by
// deferring the content — it's deliberately included in the static
// output (and thus in static prefetches).
// However, it's excluded from the shell, and has to be separated from
// unstable_prefetch(), so we have to delay it.
const { stagedRendering } = workUnitStore
if (!stagedRendering) {
// Prospective prerender
return Promise.resolve(undefined)
} else {
// Final prerender
return stagedRendering.delayUntilStage(
RenderStage.NavigationStatic,
'unstable_navigation',
undefined
)
}
}
case 'prerender-runtime': {
// In a shell or runtime prefetch, navigation() doesn't resolve,
// because they don't reach `NavigationRuntime`.
// It'll only resolve in a runtime prerender produced during a navigation.
// Note that this does not mark the subtree as dynamic -- content guarded by
// navigation() is still considered cacheable.
const { stagedRendering } = workUnitStore
if (!stagedRendering) {
// Prospective prerender
return Promise.resolve(undefined)
} else {
// Final prerender
return stagedRendering.delayUntilStage(
RenderStage.NavigationRuntime,
'unstable_navigation',
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
? RenderStage.NavigationRuntime // Match the timing of 'prerender-runtime'.
: RenderStage.NavigationStatic // Match the timing of 'prerender'.
return stagedRendering.delayUntilStage(
stage,
'unstable_navigation',
undefined
)
}
return Promise.resolve(undefined)
}
case 'cache': {
const error = new Error(
`Route ${workStore.route} 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`
)
Error.captureStackTrace(error, unstable_navigation)
applyOwnerStack(error)
workStore.invalidDynamicUsageError ??= error
throw error
}
case 'private-cache': {
const error = new Error(
`Route ${workStore.route} 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`
)
Error.captureStackTrace(error, unstable_navigation)
applyOwnerStack(error)
workStore.invalidDynamicUsageError ??= error
throw error
}
case 'unstable-cache': {
throw new Error(
`Route ${workStore.route} used \`unstable_navigation()\` inside a function cached with \`unstable_cache()\`. The \`unstable_navigation()\` function is used to indicate the subsequent code must only run during an actual navigation, but \`unstable_cache()\` caches must be able to be produced before a navigation, 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_navigation()\` inside \`generateStaticParams\`. This is not supported because \`generateStaticParams\` runs at build time without a navigation. Read more: https://nextjs.org/docs/messages/next-dynamic-api-wrong-context`
)
}
case 'prerender-client':
case 'validation-client': {
const exportName = '`unstable_navigation`'
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_navigation()\`, 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({ ...@@ -341,6 +341,19 @@ export function runDevWarmupTests({
assertLog(logs, `after params`, 'Prefetch') assertLog(logs, `after params`, 'Prefetch')
assertLog(logs, `after searchParams`, 'Prefetch') assertLog(logs, `after searchParams`, 'Prefetch')
assertLog(
logs,
`after navigation`,
// For initial load, navigation() follows static prerender timing.
// For client nav, it follows app-shell timing if `partialPrefetching` is on,
// and static timing otherwise.
isInitialLoad
? 'Prerender'
: partialPrefetching || hasRuntimePrefetch
? 'Prefetch'
: 'Prerender'
)
assertLog(logs, 'after connection', 'Server') assertLog(logs, 'after connection', 'Server')
} }
......
import { cookies, headers } from 'next/headers' import { cookies, headers } from 'next/headers'
import { CachedData } from '../../data-fetching' import { CachedData } from '../../data-fetching'
import { connection } from 'next/server' import { connection } from 'next/server'
import { unstable_navigation as navigation } from 'next/cache'
import { Suspense } from 'react' import { Suspense } from 'react'
export const instant = true export const instant = true
...@@ -18,11 +19,12 @@ export default function Page({ params, searchParams }) { ...@@ -18,11 +19,12 @@ export default function Page({ params, searchParams }) {
<CachedData cacheKey={CACHE_KEY} label="page" /> <CachedData cacheKey={CACHE_KEY} label="page" />
<LogAfter label="--- dynamic stage ---" api={() => connection()} /> <LogAfter label="--- dynamic stage ---" api={() => connection()} />
{/* Runtime */}
<LogAfter label="cookies" api={() => cookies()} /> <LogAfter label="cookies" api={() => cookies()} />
<LogAfter label="headers" api={() => headers()} /> <LogAfter label="headers" api={() => headers()} />
<LogAfter label="params" api={() => params} /> <LogAfter label="params" api={() => params} />
<LogAfter label="searchParams" api={() => searchParams} /> <LogAfter label="searchParams" api={() => searchParams} />
<LogAfter label="navigation" api={() => navigation()} />
{/* Dynamic */} {/* Dynamic */}
<LogAfter label="connection" api={() => connection()} /> <LogAfter label="connection" api={() => connection()} />
</main> </main>
......
import { cookies, headers } from 'next/headers' import { cookies, headers } from 'next/headers'
import { CachedData } from '../../data-fetching' import { CachedData } from '../../data-fetching'
import { connection } from 'next/server' import { connection } from 'next/server'
import { unstable_navigation as navigation } from 'next/cache'
import { Suspense } from 'react' import { Suspense } from 'react'
const CACHE_KEY = __dirname + '/__PAGE__' const CACHE_KEY = __dirname + '/__PAGE__'
...@@ -15,11 +16,12 @@ export default function Page({ params, searchParams }) { ...@@ -15,11 +16,12 @@ export default function Page({ params, searchParams }) {
<CachedData cacheKey={CACHE_KEY} label="page" /> <CachedData cacheKey={CACHE_KEY} label="page" />
<LogAfter label="--- dynamic stage ---" api={() => connection()} /> <LogAfter label="--- dynamic stage ---" api={() => connection()} />
{/* Runtime */}
<LogAfter label="cookies" api={() => cookies()} /> <LogAfter label="cookies" api={() => cookies()} />
<LogAfter label="headers" api={() => headers()} /> <LogAfter label="headers" api={() => headers()} />
<LogAfter label="params" api={() => params} /> <LogAfter label="params" api={() => params} />
<LogAfter label="searchParams" api={() => searchParams} /> <LogAfter label="searchParams" api={() => searchParams} />
<LogAfter label="navigation" api={() => navigation()} />
{/* Dynamic */} {/* Dynamic */}
<LogAfter label="connection" api={() => connection()} /> <LogAfter label="connection" api={() => connection()} />
</main> </main>
......
import { Instant } from 'next'
import { unstable_navigation as navigation } 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 navigation(), so we can't render
a shell.
</p>
<NavigationContent />
</main>
)
}
async function NavigationContent() {
await navigation()
return <div>{`Navigation content`}</div>
}
...@@ -38,6 +38,12 @@ export default async function Page() { ...@@ -38,6 +38,12 @@ export default async function Page() {
<li> <li>
<DebugLinks href="/shells/invalid-static-with-gsp-metadata/123" /> <DebugLinks href="/shells/invalid-static-with-gsp-metadata/123" />
</li> </li>
<li>
<DebugLinks href="/shells/invalid-navigation-without-suspense" />
</li>
<li>
<DebugLinks href="/shells/valid-navigation-with-suspense" />
</li>
</ul> </ul>
</main> </main>
) )
......
import { Instant } from 'next'
import { unstable_navigation as navigation } 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 navigation(), so we can render a shell
and should have no validation errors.
</p>
<Suspense>
<NavigationContent />
</Suspense>
</main>
)
}
async function NavigationContent() {
await navigation()
return <div>{`Navigation content`}</div>
}
import { Instant } from 'next'
import { unstable_navigation as navigation } 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 navigation(), but that's allowed
if we're not in partialPrefetching and aren't rendering App Shells.
</p>
<NavigationContent />
</main>
)
}
async function NavigationContent() {
await navigation()
return <div>{`Navigation content`}</div>
}
...@@ -51,6 +51,9 @@ export default async function Page() { ...@@ -51,6 +51,9 @@ export default async function Page() {
<li> <li>
<DebugLinks href="/suspense-in-root/sync-io/sync-io-after-cookies" /> <DebugLinks href="/suspense-in-root/sync-io/sync-io-after-cookies" />
</li> </li>
<li>
<DebugLinks href="/suspense-in-root/sync-io/sync-io-after-navigation" />
</li>
<li> <li>
<DebugLinks href="/suspense-in-root/sync-io/sync-io-after-cookies-in-generate-metadata" /> <DebugLinks href="/suspense-in-root/sync-io/sync-io-after-cookies-in-generate-metadata" />
</li> </li>
...@@ -299,6 +302,9 @@ export default async function Page() { ...@@ -299,6 +302,9 @@ export default async function Page() {
<li> <li>
<DebugLinks href="/suspense-in-root/non-app-shell/valid-unguarded-static-params/123" /> <DebugLinks href="/suspense-in-root/non-app-shell/valid-unguarded-static-params/123" />
</li> </li>
<li>
<DebugLinks href="/suspense-in-root/non-app-shell/valid-unguarded-navigation" />
</li>
</ul> </ul>
<h2>Blocking await attribution</h2> <h2>Blocking await attribution</h2>
......
import { unstable_navigation as navigation } 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 navigation():
{/*
In partialPrefetching, navigation() 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>
<SyncIOAfterNavigation />
</Suspense>
</p>
</main>
)
}
async function SyncIOAfterNavigation() {
await navigation()
return Date.now()
}
...@@ -785,8 +785,6 @@ export function registerHeadAndReportingTests( ...@@ -785,8 +785,6 @@ export function registerHeadAndReportingTests(
}) })
it('invalid - unguarded static params in metadata', async () => { it('invalid - unguarded static params in metadata', async () => {
// TODO(app-shells): static params currently aren't excluded from the shell.
// This should be failing validation.
if (isNextDev) { if (isNextDev) {
const browser = await navigateTo( const browser = await navigateTo(
'/shells/invalid-static-with-gsp-metadata/123' '/shells/invalid-static-with-gsp-metadata/123'
...@@ -896,6 +894,82 @@ export function registerHeadAndReportingTests( ...@@ -896,6 +894,82 @@ export function registerHeadAndReportingTests(
} }
}) })
it('invalid - unguarded navigation() in a shell', async () => {
// TODO(cache-stages): navigation() should not be reported as uncached data.
if (isNextDev) {
const browser = await navigateTo(
'/shells/invalid-navigation-without-suspense'
)
await expect(browser).toDisplayCollapsedRedbox(`
{
"cause": [
{
"label": "Caused by: Instant Validation",
"source": "app/shells/(default)/invalid-navigation-without-suspense/page.tsx (4:33) @ instant
> 4 | export const instant: Instant = {
| ^",
"stack": [
"instant app/shells/(default)/invalid-navigation-without-suspense/page.tsx (4:33)",
"Set.forEach <anonymous>",
],
},
],
"code": "E1437",
"description": "Next.js encountered uncached data during a navigation.",
"environmentLabel": "Server",
"label": "Instant",
"source": "app/shells/(default)/invalid-navigation-without-suspense/page.tsx (23:19) @ NavigationContent
> 23 | await navigation()
| ^",
"stack": [
"NavigationContent app/shells/(default)/invalid-navigation-without-suspense/page.tsx (23:19)",
"Page app/shells/(default)/invalid-navigation-without-suspense/page.tsx (17:7)",
],
}
`)
} else {
const result = await prerender(
'/shells/(default)/invalid-navigation-without-suspense'
)
expect(extractBuildValidationError(result.cliOutput))
.toMatchInlineSnapshot(`
"Error: Route "/shells/invalid-navigation-without-suspense": Next.js encountered uncached data during prerendering or a navigation.
\`fetch(...)\` or \`connection()\` accessed outside of \`<Suspense>\` prevents the route from being prerendered or 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
- [cache] Cache the data access with \`"use cache"\` (does not apply to \`connection()\`)
- [block] Set \`export const instant = false\` to allow a blocking route
Learn more: https://nextjs.org/docs/messages/blocking-prerender-dynamic
at main (<anonymous>)
at body (<anonymous>)
at html (<anonymous>)
Build-time instant validation failed for route "/shells/invalid-navigation-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-navigation-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 - navigation() with suspense in a shell', async () => {
if (isNextDev) {
const browser = await navigateTo(
'/shells/valid-navigation-with-suspense'
)
await expectNoDevValidationErrors(browser, await browser.url())
} else {
const result = await prerender(
'/shells/(default)/valid-navigation-with-suspense'
)
expectNoBuildValidationErrors(result)
}
})
it('valid - unguarded root param', async () => { it('valid - unguarded root param', async () => {
if (isNextDev) { if (isNextDev) {
const browser = await navigateTo( const browser = await navigateTo(
...@@ -939,6 +1013,19 @@ export function registerHeadAndReportingTests( ...@@ -939,6 +1013,19 @@ export function registerHeadAndReportingTests(
expectNoBuildValidationErrors(result) expectNoBuildValidationErrors(result)
} }
}) })
it('valid - unguarded navigation', async () => {
if (isNextDev) {
const browser = await navigateTo(
'/suspense-in-root/non-app-shell/valid-unguarded-navigation'
)
await expectNoDevValidationErrors(browser, await browser.url())
} else {
const result = await prerender(
'/suspense-in-root/non-app-shell/valid-unguarded-navigation'
)
expectNoBuildValidationErrors(result)
}
})
}) })
} }
......
...@@ -2,7 +2,7 @@ import { ...@@ -2,7 +2,7 @@ import {
expectNoBuildValidationErrors, expectNoBuildValidationErrors,
extractBuildValidationError, extractBuildValidationError,
} from 'e2e-utils/instant-validation' } from 'e2e-utils/instant-validation'
import { getDeterministicOutput } from '../cache-components-errors/utils' import { getPrerenderOutput } from '../cache-components-errors/utils'
import { type InstantValidationCaseContext } from './harness.util' import { type InstantValidationCaseContext } from './harness.util'
const partialPrefetching = !!process.env.__NEXT_PARTIAL_PREFETCHING const partialPrefetching = !!process.env.__NEXT_PARTIAL_PREFETCHING
...@@ -75,6 +75,65 @@ export function registerSyncIoAndBlockingTests( ...@@ -75,6 +75,65 @@ export function registerSyncIoAndBlockingTests(
} }
}) })
it('sync IO after navigation()', async () => {
if (isNextDev) {
const browser = await navigateTo(
'/suspense-in-root/sync-io/sync-io-after-navigation'
)
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-navigation/page.tsx (27:15) @ SyncIOAfterNavigation
> 27 | return Date.now()
| ^",
"stack": [
"SyncIOAfterNavigation app/suspense-in-root/sync-io/sync-io-after-navigation/page.tsx (27:15)",
"Page app/suspense-in-root/sync-io/sync-io-after-navigation/page.tsx (18:11)",
],
}
`)
} else {
const result = await prerender(
'/suspense-in-root/sync-io/sync-io-after-navigation'
)
// `await navigation()` 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-navigation": 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-navigation/page.tsx:27:15)
25 | async function SyncIOAfterNavigation() {
26 | await navigation()
> 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-navigation" 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-navigation". Read more: https://nextjs.org/docs/messages/prerender-error
Export encountered an error on /suspense-in-root/sync-io/sync-io-after-navigation/page: /suspense-in-root/sync-io/sync-io-after-navigation, exiting the build."
`)
expect(result.exitCode).toBe(1)
}
})
it('sync IO after cache with session data input', async () => { it('sync IO after cache with session data input', async () => {
if (isNextDev) { if (isNextDev) {
const browser = await navigateTo( const browser = await navigateTo(
...@@ -113,9 +172,8 @@ export function registerSyncIoAndBlockingTests( ...@@ -113,9 +172,8 @@ export function registerSyncIoAndBlockingTests(
// defer until its args serialize, so the cache function (and the // defer until its args serialize, so the cache function (and the
// Date.now() that follows) lands in the runtime stage. // Date.now() that follows) lands in the runtime stage.
expect( expect(
getDeterministicOutput(result.cliOutput, { getPrerenderOutput(result.cliOutput, {
isMinified: true, isMinified: true,
startingLineMatch: 'Collecting page data',
}) })
).toMatchInlineSnapshot(` ).toMatchInlineSnapshot(`
"Error: Route "/suspense-in-root/sync-io/sync-io-after-cache-with-cookie-input": Next.js encountered the unstable value \`Date.now()\` while prerendering. "Error: Route "/suspense-in-root/sync-io/sync-io-after-cache-with-cookie-input": Next.js encountered the unstable value \`Date.now()\` while prerendering.
......
...@@ -72,6 +72,9 @@ describe('cached navigations - global partialPrefetching', () => { ...@@ -72,6 +72,9 @@ describe('cached navigations - global partialPrefetching', () => {
expect(await browser.elementById('headers-boundary').text()).toContain( expect(await browser.elementById('headers-boundary').text()).toContain(
'Header:' 'Header:'
) )
expect(await browser.elementById('navigation-boundary').text()).toContain(
'Navigation content'
)
// Only connection() shows a Suspense fallback — it's truly dynamic. // Only connection() shows a Suspense fallback — it's truly dynamic.
expect(await browser.elementById('connection-boundary').text()).toBe( expect(await browser.elementById('connection-boundary').text()).toBe(
......
import { cookies, headers } from 'next/headers' import { cookies, headers } from 'next/headers'
import { connection } from 'next/server' import { connection } from 'next/server'
import { unstable_navigation as navigation } from 'next/cache'
import { Suspense } from 'react' import { Suspense } from 'react'
// Note: intentionally no `export const prefetch` and no `instant` config. This // Note: intentionally no `export const prefetch` and no `instant` config. This
...@@ -34,6 +35,11 @@ export default async function Page({ ...@@ -34,6 +35,11 @@ export default async function Page({
<ConnectionContent /> <ConnectionContent />
</Suspense> </Suspense>
</div> </div>
<div id="navigation-boundary">
<Suspense fallback={<p>Loading navigation...</p>}>
<NavigationContent />
</Suspense>
</div>
</main> </main>
) )
} }
...@@ -68,3 +74,8 @@ async function ConnectionContent() { ...@@ -68,3 +74,8 @@ async function ConnectionContent() {
await connection() await connection()
return <p>Dynamic content</p> return <p>Dynamic content</p>
} }
async function NavigationContent() {
await navigation()
return <p>Navigation content</p>
}
...@@ -116,6 +116,38 @@ export default function Page() { ...@@ -116,6 +116,38 @@ export default function Page() {
</LinkAccordion> </LinkAccordion>
</li> </li>
</ul> </ul>
<h2>Navigation posts</h2>
<ul>
<li>
<LinkAccordion href="/static-navigation/1">
Static navigation post 1
</LinkAccordion>
</li>
<li>
<Link href="/static-navigation/2" prefetch={false}>
Static navigation post 2 (unprefetched)
</Link>
</li>
<li>
<LinkAccordion href="/runtime-navigation/1">
Runtime navigation post 1
</LinkAccordion>
</li>
<li>
<Link href="/runtime-navigation/2" prefetch={false}>
Runtime navigation post 2 (unprefetched)
</Link>
</li>
<li>
<LinkAccordion
href="/runtime-navigation/speculative-1"
prefetch={true}
>
Runtime navigation post "speculative-1" (prefetch=true)
</LinkAccordion>
</li>
</ul>
</main> </main>
) )
} }
import { Suspense } from 'react'
import { unstable_navigation as navigation } 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="navigation-loading">Loading navigation...</p>}>
<Navigation />
</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 navigation</p>}>
<ParamsDependent params={params} />
</Suspense>
</main>
)
}
async function Navigation() {
await cookies() // Makes sure this page uses a runtime prefetch
await navigation() // Exclude the contents below from runtime prefetching and runtime app shells
return <div id="navigation-content">Navigation 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_navigation as navigation } 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 navigation</p>}>
<ParamsDependent params={params} />
</Suspense>
<Suspense fallback={<p id="navigation-loading">Loading navigation...</p>}>
<Navigation />
</Suspense>
</main>
)
}
async function Navigation() {
await navigation() // Exclude the contents below from the shell
return <div id="navigation-content">Navigation 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>
}
...@@ -377,6 +377,220 @@ describe('App Shell prefetching', () => { ...@@ -377,6 +377,220 @@ describe('App Shell prefetching', () => {
) )
}) })
describe('navigation()', () => {
it('excludes navigation() 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 })
// Reveal the LinkAccordion for /static-navigation/1. This caches the App Shell
// for the route. The page renders a component that uses navigation(),
// which should be excluded from the shell.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/static-navigation/1"]')
.click()
}, [{ includes: 'App shell for navigation', kind: 'static' }])
await act(async () => {
// Click the link to /static-navigation/2. This link is rendered with
// prefetch={false}, so it was never prefetched. The cached App Shell
// should render immediately, before any navigation response arrives.
await browser.elementByCss('a[href="/static-navigation/2"]').click()
// While the navigation response is blocked (we're still in the `act`
// block), the cached App Shell should already be visible.
expect(await browser.elementById('shell').text()).toEqual(
'App shell for navigation'
)
// The navigation-gated content is NOT part of the App Shell, only its fallback.
expect(await browser.locator('#navigation-content').count()).toBe(0)
expect(await browser.elementByCss('#navigation-loading').text()).toBe(
'Loading navigation...'
)
})
// After the outer act unblocks the navigation, the navigation-gated
// content streams in with the navigation response, along with the
// dynamic content.
expect(await browser.elementById('navigation-content').text()).toEqual(
'Navigation content'
)
expect(await browser.elementById('dynamic-content').text()).toEqual(
'Post body for 2'
)
})
it('excludes navigation() 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 })
// Reveal the LinkAccordion for /runtime-navigation/1. This caches the App Shell
// for the route. The page renders a component that uses navigation(),
// which should be excluded from the runtime shell.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/runtime-navigation/1"]')
.click()
}, [
{ includes: 'App shell for navigation', kind: 'runtime' },
{ includes: 'param-value', block: 'reject' }, // Only a shell, no URL data.
])
await act(async () => {
// Click the link to /runtime-navigation/2. This link is rendered with
// prefetch={false}, so it was never prefetched. The cached App Shell
// should render immediately, before any navigation response arrives.
await browser.elementByCss('a[href="/runtime-navigation/2"]').click()
// While the navigation response is blocked (we're still in the `act`
// block), the cached App Shell should already be visible.
expect(await browser.elementById('shell').text()).toEqual(
'App shell for navigation'
)
// The navigation-gated content is NOT part of the App Shell, only its fallback.
expect(await browser.locator('#navigation-content').count()).toBe(0)
expect(await browser.elementByCss('#navigation-loading').text()).toBe(
'Loading navigation...'
)
})
// After the outer act unblocks the navigation, the navigation-gated
// content streams in with the navigation response, along with the
// dynamic content.
expect(await browser.elementById('navigation-content').text()).toEqual(
'Navigation content'
)
expect(await browser.elementById('dynamic-content').text()).toEqual(
'Post body for 2'
)
})
it('includes navigation() 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 })
// Reveal the LinkAccordion for /static-navigation/1,
// Triggering a static prefetch request.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/static-navigation/1"]')
.click()
}, [{ includes: 'App shell for navigation', kind: 'static' }])
await act(async () => {
// Navigate to the prefetched route.
await browser.elementByCss('a[href="/static-navigation/1"]').click()
// While the navigation response is blocked (we're still in the `act`
// block), the prefetched content should already be visible.
// Param-dependent content is visible because the params are static.
expect(await browser.elementById('param-value').text()).toEqual(
'Post 1'
)
// The navigation-gated content is included.
expect(await browser.locator('#navigation-loading').count()).toBe(0)
expect(await browser.elementByCss('#navigation-content').text()).toBe(
'Navigation content'
)
// Dynamic content is not included.
expect(await browser.locator('#dynamic-content').count()).toBe(0)
expect(await browser.elementByCss('#dynamic-loading').text()).toBe(
'Loading dynamic content...'
)
})
expect(await browser.elementById('navigation-content').text()).toEqual(
'Navigation content'
)
// After the outer act unblocks the navigation, the dynamic content streams in.
expect(await browser.elementById('dynamic-content').text()).toEqual(
'Post body for 1'
)
})
it('excludes navigation() from 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 })
// Reveal the LinkAccordion for /runtime-navigation/speculative-1,
// Triggering a shell request and then a speculative prefetch request.
// The page renders a component that uses navigation(),
// which should be excluded from both.
await act(async () => {
await browser
.elementByCss(
'input[data-link-accordion="/runtime-navigation/speculative-1"]'
)
.click()
}, [
// Two runtime responses carry the shell text, in order: the Shell
// phase's runtime App Shell request, then the Speculative phase's
// batched per-link runtime prefetch. The route reads request data,
// so its static-attempt hint is unset and the prefetch deopts to
// runtime requests — the runtime-completeness contract of Partial
// Prefetching routes.
{ includes: 'App shell for navigation', kind: 'runtime' }, // Shell
{ includes: 'Post speculative-1', kind: 'runtime' }, // Speculative
])
await act(async () => {
// Navigate to the prefetched route.
await browser
.elementByCss('a[href="/runtime-navigation/speculative-1"]')
.click()
// While the navigation response is blocked (we're still in the `act`
// block), the prefetched content should already be visible.
// Param-dependent content is visible because we used a speculative prefetch.
expect(await browser.elementById('param-value').text()).toEqual(
'Post speculative-1'
)
// The navigation-gated content is not included.
expect(await browser.locator('#navigation-content').count()).toBe(0)
expect(await browser.elementByCss('#navigation-loading').text()).toBe(
'Loading navigation...'
)
// Dynamic content is not included.
expect(await browser.locator('#dynamic-content').count()).toBe(0)
expect(await browser.elementByCss('#dynamic-loading').text()).toBe(
'Loading dynamic content...'
)
})
// After the outer act unblocks the navigation, the navigation-gated
// content streams in with the navigation response, along with the
// dynamic content.
expect(await browser.elementById('navigation-content').text()).toEqual(
'Navigation content'
)
expect(await browser.elementById('dynamic-content').text()).toEqual(
'Post body for speculative-1'
)
})
})
describe('root params', () => { describe('root params', () => {
it('includes root params in a runtime App Shell', async () => { it('includes root params in a runtime App Shell', async () => {
let page: Playwright.Page let page: Playwright.Page
......
import { Suspense } from 'react' import { Suspense } from 'react'
import { unstable_navigation as navigation } from 'next/cache'
type Params = { slug: string } type Params = { slug: string }
...@@ -24,6 +25,11 @@ export default function Page({ params }: { params: Promise<Params> }) { ...@@ -24,6 +25,11 @@ export default function Page({ params }: { params: Promise<Params> }) {
<Suspense fallback={<p id="slug-loading">Loading param content...</p>}> <Suspense fallback={<p id="slug-loading">Loading param content...</p>}>
<SlugContent params={params} /> <SlugContent params={params} />
</Suspense> </Suspense>
<Suspense
fallback={<p id="navigation-loading">Loading navigation content...</p>}
>
<NavigationContent />
</Suspense>
</main> </main>
) )
} }
...@@ -32,3 +38,8 @@ async function SlugContent({ params }: { params: Promise<Params> }) { ...@@ -32,3 +38,8 @@ async function SlugContent({ params }: { params: Promise<Params> }) {
const { slug } = await params const { slug } = await params
return <p id="slug-content">{`Dynamic param content: ${slug}`}</p> return <p id="slug-content">{`Dynamic param content: ${slug}`}</p>
} }
async function NavigationContent() {
await navigation()
return <p id="navigation-content">Navigation content</p>
}
...@@ -25,6 +25,16 @@ export default function Page() { ...@@ -25,6 +25,16 @@ export default function Page() {
<li> <li>
<LinkAccordion href="/uses-connection">Uses connection</LinkAccordion> <LinkAccordion href="/uses-connection">Uses connection</LinkAccordion>
</li> </li>
<li>
<LinkAccordion href="/uses-runtime-after-navigation">
Uses runtime APIs after navigation()
</LinkAccordion>
</li>
<li>
<LinkAccordion href="/uses-navigation-static">
Uses navigation() on a static page
</LinkAccordion>
</li>
<li> <li>
<LinkAccordion href="/dynamic-param/one"> <LinkAccordion href="/dynamic-param/one">
Dynamic param one Dynamic param one
......
import { Suspense } from 'react'
import { unstable_navigation as navigation } from 'next/cache'
export default function Page() {
return (
<main>
<Suspense fallback={<p id="navigation-loading">Loading navigation...</p>}>
<NavigationContent />
</Suspense>
</main>
)
}
async function NavigationContent() {
await navigation()
return <p id="page-content">Fully static page content (with navigation())</p>
}
// A page that calls cookies and headers, but only after awaiting `navigation()`
// which means it can still be prefetched statically.
//
// Note the Shell phase is always permitted to issue a runtime shell request,
// so the absence of one in the test is attributable to the static shell
// attempt succeeding, not to configuration forbidding runtime requests.
import { cacheLife } from 'next/dist/server/use-cache/cache-life'
import { cookies, headers } from 'next/headers'
import { unstable_navigation as navigation } from 'next/cache'
import { Suspense } from 'react'
export default async function Page() {
return (
<main>
<p id="page-content">Runtime APIs called after navigation()</p>
<Suspense
fallback={<p id="navigation-loading">Loading navigation content...</p>}
>
<Navigation />
</Suspense>
</main>
)
}
async function Navigation() {
// The runtime data tracking should end here, so the prerender
// shouldn't track the awaits of cookies/headers inside DynamicContent.
await navigation()
return (
<>
<div id="navigation-content">Navigation content</div>
<Suspense
fallback={<p id="dynamic-loading">Loading dynamic content...</p>}
>
<DynamicContent />
</Suspense>
</>
)
}
async function shortStaleCache() {
'use cache'
cacheLife({ stale: 300 - 1 }) // smaller than MIN_SHELL_STALE
return Date.now()
}
async function DynamicContent() {
await Promise.all([cookies(), headers(), shortStaleCache()])
return <p id="dynamic-content">Dynamic content</p>
}
...@@ -102,6 +102,48 @@ describe('static App Shell prefetch attempt', () => { ...@@ -102,6 +102,48 @@ describe('static App Shell prefetch attempt', () => {
}, 'no-requests') }, 'no-requests')
}) })
it('prefetches a fully static route that uses navigation() 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 })
// Reveal the LinkAccordion for /uses-navigation-static. The route accesses no
// runtime data, so its tree carries the static-prefetch hint and the
// Shell phase attempts static per-segment prefetches. The static
// responses are complete, so no runtime shell request fires.
await act(async () => {
await browser
.elementByCss('input[data-link-accordion="/uses-navigation-static"]')
.click()
}, [
// The shell content arrives in a static per-segment response...
{
includes: 'Fully static page content (with navigation())',
kind: 'static',
},
// ...and must NOT arrive in a runtime prefetch response — the
// static attempt was sufficient, so no runtime request fires.
{
includes: 'Fully static page content (with navigation())',
kind: 'runtime',
block: 'reject',
},
])
// Navigate to the prefetched route. Everything was cached by the static
// prefetch, so the navigation completes without any requests.
await act(async () => {
await browser.elementByCss('a[href="/uses-navigation-static"]').click()
expect(await browser.elementById('page-content').text()).toBe(
'Fully static page content (with navigation())'
)
}, 'no-requests')
})
it('goes straight to a runtime shell prefetch when the shell reads cookies (hint unset)', async () => { it('goes straight to a runtime shell prefetch when the shell reads cookies (hint unset)', async () => {
let page: Playwright.Page let page: Playwright.Page
const browser = await next.browser('/', { const browser = await next.browser('/', {
...@@ -232,6 +274,67 @@ describe('static App Shell prefetch attempt', () => { ...@@ -232,6 +274,67 @@ describe('static App Shell prefetch attempt', () => {
) )
}) })
it('does not fall back to a runtime shell prefetch for a partial segment that calls runtime APIs after navigation()', 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-navigation"]'
)
.click()
}, [
// In a static prerender, navigation() is allowed to resolve,
// so content behind navigation() will be part of a static prefetch.
{ includes: 'Navigation content', kind: 'static' },
// No runtime request should fire.
{
includes: 'Runtime APIs called after navigation()',
kind: 'runtime',
block: 'reject',
},
// Dynamic data should not be included.
{
includes: 'Dynamic content',
block: 'reject',
},
])
// Navigate. The prefetched shell renders instantly; the dynamic hole is
// filled by the navigation-time dynamic request, as always.
await act(
async () => {
await browser
.elementByCss('a[href="/uses-runtime-after-navigation"]')
.click()
// While the navigation response is blocked (we're still inside the
// `act` scope), the prefetched shell is already visible, with the
// loading fallback in place of the dynamic content.
expect(await browser.elementById('page-content').text()).toBe(
'Runtime APIs called after navigation()'
)
expect(await browser.elementById('navigation-content').text()).toBe(
'Navigation content'
)
expect(await browser.elementById('dynamic-loading').text()).toBe(
'Loading dynamic content...'
)
},
// The dynamic content streams in with the navigation response.
{ includes: 'Dynamic content' }
)
expect(await browser.elementById('dynamic-content').text()).toBe(
'Dynamic content'
)
})
it('reuses the static App Shell across different param values of a dynamic route', async () => { it('reuses the static App Shell across different param values of a dynamic route', async () => {
let page: Playwright.Page let page: Playwright.Page
const browser = await next.browser('/', { const browser = await next.browser('/', {
...@@ -291,13 +394,17 @@ describe('static App Shell prefetch attempt', () => { ...@@ -291,13 +394,17 @@ describe('static App Shell prefetch attempt', () => {
// While the navigation response is blocked (we're still inside the // While the navigation response is blocked (we're still inside the
// `act` scope), the reused shell is already visible, with the // `act` scope), the reused shell is already visible, with the
// loading fallback in place of the param content. // loading fallback in place of the param content and content
// behind navigation()
expect(await browser.elementById('page-content').text()).toBe( expect(await browser.elementById('page-content').text()).toBe(
'Dynamic-param page shell text' 'Dynamic-param page shell text'
) )
expect(await browser.elementById('slug-loading').text()).toBe( expect(await browser.elementById('slug-loading').text()).toBe(
'Loading param content...' 'Loading param content...'
) )
expect(await browser.elementById('navigation-loading').text()).toBe(
'Loading navigation content...'
)
}, },
// The param content arrives with the navigation response. // The param content arrives with the navigation response.
{ includes: 'Dynamic param content: two' } { 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