Unverified Commit 5ed0a5c9 authored by Aurora Scharff's avatar Aurora Scharff Committed by GitHub

dev-overlay: wire Link prefetch={true} Partial Prefetching warning into Insights (#94798)

### What?

Wires the dev-only `<Link prefetch={true}>` Partial Prefetching warning
from [#94672](https://github.com/vercel/next.js/pull/94672) into the
Instant Insights surface. Code frame, call stack, three fix cards:
**Upgrade** `prefetch = 'partial'` · **Disable** the prop · **Ignore**
with `instant = false`.

Demo:
[93-link-prefetch-without-partial](https://error-messages-overhaul-ibsl.labs.vercel.dev/scenario/93-link-prefetch-without-partial).

### How?

- Warning factored into a shared `instant-messages.ts` factory.
- New `link-prefetch-partial` overlay kind + `Instant` label +
`InstantRuntimeError` dispatcher.
- Two new fix-card groups: **Upgrade** (amber, arrow-up), **Disable**
(gray, minus).
- New `instant-link-prefetch-partial.mdx` rule page + "Auditing existing
calls" section in the adoption guide.
- Unit tests for the matcher, cards, and `isInstantNavigationError`.

### Related

- [#94818](https://github.com/vercel/next.js/pull/94818) — broader
Partial Prefetching docs cleanup. Lands independently.
- [vercel/front#73592](https://github.com/vercel/front/pull/73592) —
next-site `upgrade` + `disable` `FixGroup` values.
parent 6cc1049d
......@@ -174,7 +174,6 @@ Every insight page ends (just before `## Useful links`) with the canonical opt-o
Instant-navigation validation runs by default in [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) apps and is what surfaces this error.
- **One segment**: add [`export const instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations.
- **Layout and its children**: add `export const instant = { unstable_disableValidation: true }` to a layout. This disables validation for that layout and every segment below it.
- **Entire app**: set [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`.
See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.
......
......@@ -92,7 +92,7 @@ export default nextConfig
## Auditing existing `<Link prefetch={true}>` calls
When `partialPrefetching` is enabled, `<Link prefetch={true}>` now prefetches the App Shell plus cached content, but not dynamic data. Review each existing usage and decide whether the prop is still providing value.
When `partialPrefetching` is enabled, `<Link prefetch={true}>` now prefetches the App Shell plus cached content, but not dynamic data. Review each existing usage and decide whether the prop is still providing value. In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the dev overlay surfaces a [**link-prefetch-partial** insight](/docs/messages/instant-link-prefetch-partial) for each call that points at a route without Partial Prefetching, so you can work through them one at a time.
Previously, `<Link prefetch={true}>` also prefetched dynamic data.
......
---
title: Next.js encountered dynamic data during prefetching
kind: insight
---
During a [client-side navigation](/docs/app/glossary#client-side-navigation), a [`<Link prefetch={true}>`](/docs/app/api-reference/components/link) navigated to a route that has not enabled [Partial Prefetching](/docs/app/glossary#partial-prefetching). With [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled, `prefetch={true}` is a legacy "full" prefetch that pulls down the route's dynamic data along with its [App Shell](/docs/app/glossary#app-shell). This will lead to slower, more expensive prefetches.
Routes that opt into Partial Prefetching skip the dynamic data at prefetch time, leaving you free to choose when it loads: at navigation via [streaming](/docs/app/glossary#streaming), ahead of time via [runtime prefetching](/docs/app/guides/runtime-prefetching), or not at all. The check fires at navigation time, not prefetch time, so existing apps that have just enabled Cache Components are not flooded with warnings for every `<Link prefetch={true}>` on the page.
> **Good to know**: In [`next dev`](/docs/app/api-reference/cli/next#next-dev-options), the error overlay points at the failing component. Run `next build --debug-prerender` to get the full list of blocking routes with stack traces. When iterating on specific routes, use `next build --debug-build-paths /dashboard /settings` to rebuild only those pages.
## Ways to fix this
<FixOption
group="upgrade"
href="#opt-into-partial-prefetching"
title="Opt into Partial Prefetching"
>
Adopt Partial Prefetching for the target route so the link prefetches only the
App Shell. After adopting, layer on further prefetch optimizations.
</FixOption>
<FixOption
group="disable"
href="#use-the-default-prefetch"
title="Use the default prefetch"
>
Drop the prefetch prop from the link so it falls back to the default prefetch
behavior, which does not include dynamic data.
</FixOption>
<FixOption
group="ignore"
href="#disable-validation-on-this-route"
title="Disable validation on this route"
>
Opt the target route out of instant-navigation validation and keep the legacy
full prefetch.
</FixOption>
## Opt into Partial Prefetching
Choose this fix when the target route has an [App Shell](/docs/app/glossary#app-shell) with dynamic content below it. Opting into Partial Prefetching tells Next.js to prefetch only the App Shell and defer the dynamic data to navigation. Opt in per-route or app-wide, and from there layer on further prefetch optimizations.
### Patterns
#### Per-route opt-in
Export [`prefetch`](/docs/app/api-reference/file-conventions/route-segment-config/prefetch) from the page or layout of the route the link points at.
```jsx filename="app/dashboard/page.js"
export const prefetch = 'partial'
export default function DashboardPage() {
return <Dashboard />
}
```
#### App-wide opt-in
Set [`partialPrefetching`](/docs/app/api-reference/config/next-config-js/partialPrefetching) to `true` in `next.config` to opt the whole app in.
```js filename="next.config.js"
module.exports = {
partialPrefetching: true,
}
```
Learn more: [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching).
### Trade-off
The route's dynamic data isn't included in the prefetch. The user sees the App Shell as soon as the link enters the viewport, and the dynamic content streams in after navigation. The dynamic content arrives later than it would with a full prefetch. How much later depends on how long the dynamic data takes to fetch.
### Gotchas
- Partial Prefetching only works with [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) enabled.
- If the route doesn't have a clear App Shell (everything below the layout reads dynamic data), Partial Prefetching has nothing to prefetch and behaves the same as no prefetch. Move static content above the dynamic boundary first.
### Next steps
Opting in stops at the App Shell. To also prefetch cached parts of the route, set `prefetch={true}` on the link. If the cached content depends on request data (cookies, headers, search params), opt the route into [runtime prefetching](/docs/app/guides/runtime-prefetching). The [prefetching guide](/docs/app/guides/prefetching) covers the link-level options end to end.
## Use the default prefetch
Choose this fix when you set `prefetch={true}` to warm up a frequently-visited route and you can accept fetching the dynamic data on navigation. Remove the prop and the link uses the default prefetch strategy, which under Cache Components prefetches the cached page render and skips the dynamic data.
### Patterns
#### Remove the `prefetch` prop
```jsx filename="app/nav.js"
import Link from 'next/link'
export default function Nav() {
return <Link href="/dashboard">Dashboard</Link>
}
```
### Trade-off
The link no longer forces a full prefetch. The user gets the cached parts of the route when the link enters the viewport, and the dynamic data is fetched at navigation time. This is the default behavior under Cache Components.
### Gotchas
- Removing `prefetch={true}` does not disable prefetching. It falls back to the default. To disable prefetching entirely, use `prefetch={false}`.
- See [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching) for the full table of what each `<Link>` prop downloads under each configuration.
## Disable validation on this route
Choose this fix when you need the legacy full prefetch behavior and cannot adopt Partial Prefetching for the target route. Setting [`instant`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to `false` on the target route opts it out of instant-navigation validation and silences the warning.
### Patterns
#### Opt the route out
Add the export to the page or layout file of the target route.
```jsx filename="app/dashboard/page.js"
export const instant = false
export default function DashboardPage() {
return <Dashboard />
}
```
### Trade-off
The link continues to do a full prefetch, including dynamic data, and the warning is silenced.
### Gotchas
- `instant = false` disables all instant-navigation checks for the route, not only this one. [Blocking-route](/docs/messages/blocking-prerender-runtime) and [unrendered-segment](/docs/messages/instant-unrendered-segment) warnings, and other Insights for the route are silenced too.
## Don't want this validation?
Instant-navigation validation runs by default in [Cache Components](/docs/app/api-reference/config/next-config-js/cacheComponents) apps and surfaces this error.
- **One segment**: add [`export const instant = false`](/docs/app/api-reference/file-conventions/route-segment-config/instant) to the page or layout file. This opts out the segment itself. Child segments are still validated during client navigations.
- **Entire app**: set [`experimental.instantInsights.validationLevel`](/docs/app/api-reference/file-conventions/route-segment-config/instant#configuring-validation-defaults) to `'manual-warning'` in `next.config`. This limits validation to segments that explicitly export `instant`.
See [Ensuring instant navigations](/docs/app/guides/instant-navigation) for the full model.
## Useful links
- [Adopting Partial Prefetching](/docs/app/guides/adopting-partial-prefetching)
- [Ensuring instant navigations](/docs/app/guides/instant-navigation)
......@@ -1383,5 +1383,6 @@
"1382": "Expected a work store while caching an `ImageResponse` during prerendering.",
"1383": "Route segment config \"dynamic\" is not compatible with \\`nextConfig.cacheComponents\\`. Please remove it.",
"1384": "Invariant: Cache Components cannot be enabled in export mode",
"1385": "Route \"%s\": Next.js encountered uncached or runtime data in \\`generateViewport()\\`.\\n\\nThis prevents the page from being prerendered, leading to a slower user experience. Unlike metadata, viewport cannot be streamed behind \\`<Suspense>\\` because it affects the initial page load.\\n\\nWays to fix this:\\n - [static] Use a static viewport export instead of \\`generateViewport()\\`\\n https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#use-static-viewport\\n - [cache] For uncached data (\\`fetch\\`, database calls): cache the viewport with \\`\"use cache\"\\` in \\`generateViewport()\\` (does not apply to \\`connection()\\`)\\n https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic#cache-the-viewport-data\\n - [block] Set \\`export const instant = false\\` to silence this warning and allow a blocking route\\n https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic#allow-blocking-route"
"1385": "Route \"%s\": Next.js encountered uncached or runtime data in \\`generateViewport()\\`.\\n\\nThis prevents the page from being prerendered, leading to a slower user experience. Unlike metadata, viewport cannot be streamed behind \\`<Suspense>\\` because it affects the initial page load.\\n\\nWays to fix this:\\n - [static] Use a static viewport export instead of \\`generateViewport()\\`\\n https://nextjs.org/docs/messages/blocking-prerender-viewport-runtime#use-static-viewport\\n - [cache] For uncached data (\\`fetch\\`, database calls): cache the viewport with \\`\"use cache\"\\` in \\`generateViewport()\\` (does not apply to \\`connection()\\`)\\n https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic#cache-the-viewport-data\\n - [block] Set \\`export const instant = false\\` to silence this warning and allow a blocking route\\n https://nextjs.org/docs/messages/blocking-prerender-viewport-dynamic#allow-blocking-route",
"1386": "Next.js encountered dynamic data during prefetching for \"%s\".\\n\\nThis will lead to slower, more expensive prefetches.\\n\\nWays to fix this:\\n - [upgrade] Opt into Partial Prefetching by exporting \\`const prefetch = 'partial'\\` from the page or layout, or by setting \\`partialPrefetching: true\\` in next.config to opt the whole app in\\n https://nextjs.org/docs/messages/instant-link-prefetch-partial#opt-into-partial-prefetching\\n - [disable] Remove \\`prefetch={true}\\` from the <Link> to use the default prefetch\\n https://nextjs.org/docs/messages/instant-link-prefetch-partial#use-the-default-prefetch\\n - [ignore] Set \\`export const instant = false\\` to silence this warning and opt the route out of instant-navigation validation\\n https://nextjs.org/docs/messages/instant-link-prefetch-partial#disable-validation-on-this-route"
}
......@@ -46,6 +46,7 @@ import { ScrollBehavior } from '../router-reducer/router-reducer-types'
import { computeChangedPath } from '../router-reducer/compute-changed-path'
import { isJavaScriptURLString } from '../../lib/javascript-url'
import { UnknownDynamicStaleTime, computeDynamicStaleAt } from './bfcache'
import { createLinkPrefetchPartialError } from '../../../shared/lib/instant-messages'
/**
* Navigate to a new URL, using the Segment Cache to construct a response.
......@@ -263,13 +264,7 @@ export function navigateToKnownRoute(
PrefetchHint.SubtreeHasPartialPrefetching) ===
0
) {
const error = new Error(
`A <Link prefetch={true}> navigated to "${url.pathname}", but Partial ` +
`Prefetching is not enabled for that route, so its dynamic data was ` +
`included in the prefetch. Enable Partial Prefetching app-wide by ` +
`setting \`partialPrefetching: true\` in next.config, or per-route by ` +
`exporting \`const prefetch = 'partial'\` from the page or layout.`
)
const error = createLinkPrefetchPartialError(url.pathname)
const ownerStack = 'ownerStack' in link ? link.ownerStack : undefined
if (ownerStack === undefined) {
console.error(
......
......@@ -8,6 +8,7 @@ import {
createRuntimeViewportError,
createDynamicViewportError,
} from '../../../../server/app-render/blocking-route-messages'
import { createLinkPrefetchPartialError } from '../../../../shared/lib/instant-messages'
import {
FIX_CARD_GROUPS,
SYNC_IO_DOCS,
......@@ -79,6 +80,12 @@ describe('instant-guidance-data card ordering', () => {
'viewport',
'dynamic',
],
[
'link-prefetch-partial',
createLinkPrefetchPartialError('/x').message,
'link-prefetch-partial',
'runtime',
],
] as const)(
'console tags and overlay card groups agree for %s',
(_name, message, kind, variant) => {
......@@ -129,6 +136,12 @@ describe('instant-guidance-data card links', () => {
'viewport',
'dynamic',
],
[
'link-prefetch-partial',
createLinkPrefetchPartialError('/x').message,
'link-prefetch-partial',
'runtime',
],
] as const)(
'console URLs and overlay card links agree for %s',
(_name, message, kind, variant) => {
......@@ -147,6 +160,7 @@ describe('instant-guidance-data card links', () => {
['viewport', 'runtime'],
['viewport', 'dynamic'],
['unrendered-segment', 'runtime'],
['link-prefetch-partial', 'runtime'],
]
for (const [kind, variant] of variants) {
for (const card of getCards(kind, variant)) {
......@@ -172,6 +186,7 @@ describe('instant-guidance-data card invariants', () => {
['viewport', 'dynamic'],
['viewport', 'dynamic', 'connection'],
['unrendered-segment', 'runtime'],
['link-prefetch-partial', 'runtime'],
]
for (const [kind, variant, cause] of variants) {
cards.push(...getCards(kind, variant, cause))
......@@ -236,6 +251,7 @@ describe('instant-guidance-data dispatcher', () => {
['viewport', 'runtime'],
['viewport', 'dynamic'],
['unrendered-segment', 'runtime'],
['link-prefetch-partial', 'runtime'],
]
for (const [kind, variant] of variants) {
for (const card of getCards(kind, variant)) used.add(card.group)
......
......@@ -11,15 +11,19 @@ export type FixCardGroup =
| 'measure'
| 'ignore'
| 'render'
| 'upgrade'
| 'disable'
export type FixCardIcon =
| 'align-left'
| 'arrow-up'
| 'database'
| 'history'
| 'layout'
| 'loading'
| 'pointer-click'
| 'minus'
| 'minus-circle'
| 'pointer-click'
| 'server-stack'
| 'timer'
| 'zap'
......@@ -38,6 +42,8 @@ export const FIX_CARD_GROUPS: Record<
measure: { label: 'Measure', color: 'gray', icon: 'timer' },
ignore: { label: 'Ignore', color: 'red', icon: 'minus-circle' },
render: { label: 'Render', color: 'gray', icon: 'layout' },
upgrade: { label: 'Upgrade', color: 'amber', icon: 'arrow-up' },
disable: { label: 'Disable', color: 'gray', icon: 'minus' },
}
export type FixCard = {
......@@ -48,6 +54,7 @@ export type FixCard = {
/** Docs URL the card links to, or `null` for no link. */
link: string | null
snippets: Snippet[]
/** Whether to render the "Copy AI prompt" button on this card. */
copyable?: boolean
}
......@@ -197,6 +204,43 @@ const unrenderedSegmentCards: FixCard[] = [
},
]
const linkPrefetchPartialCards: FixCard[] = [
{
id: 'opt-into-partial-prefetching',
title: 'Opt into Partial Prefetching',
group: 'upgrade',
link: 'https://nextjs.org/docs/messages/instant-link-prefetch-partial#opt-into-partial-prefetching',
snippets: [
{ text: '// page.tsx or layout.tsx' },
{ text: "export const prefetch = 'partial'", highlight: true },
],
copyable: true,
},
{
id: 'use-the-default-prefetch',
title: 'Use the default prefetch',
group: 'disable',
link: 'https://nextjs.org/docs/messages/instant-link-prefetch-partial#use-the-default-prefetch',
snippets: [
{ text: '<Link href="/dashboard">', highlight: true },
{ text: ' Dashboard' },
{ text: '</Link>' },
],
copyable: true,
},
{
id: 'disable-validation-on-this-route',
title: 'Disable validation on this route',
group: 'ignore',
link: 'https://nextjs.org/docs/messages/instant-link-prefetch-partial#disable-validation-on-this-route',
snippets: [
{ text: '// page.tsx or layout.tsx' },
{ text: 'export const instant = false', highlight: true },
],
copyable: true,
},
]
const metadataRuntimeCards: FixCard[] = [
{
id: 'use-static-metadata',
......@@ -531,6 +575,7 @@ export type GuidanceKind =
| 'sync-io'
| 'sync-io-client'
| 'unrendered-segment'
| 'link-prefetch-partial'
export type GuidanceVariant = 'runtime' | 'dynamic'
......@@ -546,6 +591,8 @@ export const DOCS_URLS: Record<GuidanceKind, string> = {
'sync-io-client': '',
'unrendered-segment':
'https://nextjs.org/docs/messages/instant-unrendered-segment',
'link-prefetch-partial':
'https://nextjs.org/docs/messages/instant-link-prefetch-partial',
}
export const SYNC_IO_DOCS: Record<string, string> = {
......@@ -618,6 +665,8 @@ export const EXPLANATIONS: Record<GuidanceKind, string> = {
'This value would be evaluated during the prerender and fixed at build time, instead of recomputed on each visit.',
'unrendered-segment':
'This segment was dropped from rendering. Issues that would prevent instant navigation will go undetected.',
'link-prefetch-partial':
'This will lead to slower, more expensive prefetches.',
}
export const BLOCKING_ROUTE_NAVIGATION_EXPLANATION =
......@@ -691,6 +740,8 @@ export function getCards(
return (cause && syncClientCardsByCause[cause]) || []
case 'unrendered-segment':
return unrenderedSegmentCards
case 'link-prefetch-partial':
return linkPrefetchPartialCards
default:
return kind satisfies never
}
......
import {
FixCardAlignLeftIcon,
FixCardArrowUpIcon,
FixCardDatabaseIcon,
FixCardHistoryIcon,
FixCardLayoutIcon,
FixCardLoadingIcon,
FixCardMinusIcon,
FixCardPointerClickIcon,
FixCardMinusCircleIcon,
FixCardServerStackIcon,
......@@ -53,6 +55,10 @@ function getCardIcon(icon: FixCardIcon) {
return <FixCardZapIcon />
case 'layout':
return <FixCardLayoutIcon />
case 'arrow-up':
return <FixCardArrowUpIcon />
case 'minus':
return <FixCardMinusIcon />
default:
icon satisfies never
return null
......
......@@ -22,6 +22,7 @@ import { getCards } from '../components/instant/instant-guidance-data'
import {
deriveCauseFromCodeFrame,
getBlockingRouteErrorDetails,
getLinkPrefetchPartialErrorDetails,
getUnrenderedSegmentErrorDetails,
isInstantNavigationError,
isRuntimeVariant,
......@@ -387,6 +388,16 @@ describe('card sets for all error families', () => {
).toEqual(['render-the-dropped-segment', 'skip-validation-on-the-segment'])
})
it('link-prefetch-partial', () => {
expect(
getCards('link-prefetch-partial', 'runtime').map((card) => card.id)
).toEqual([
'opt-into-partial-prefetching',
'use-the-default-prefetch',
'disable-validation-on-this-route',
])
})
it('sync-io math', () => {
expect(
getCards('sync-io', 'runtime', 'Math.random()').map((card) => card.id)
......@@ -519,6 +530,42 @@ describe('getUnrenderedSegmentErrorDetails', () => {
})
})
describe('getLinkPrefetchPartialErrorDetails', () => {
function createLinkPrefetchPartialError(pathname: string): Error {
return new Error(
`Next.js encountered dynamic data during prefetching for "${pathname}".\n\n` +
`This will lead to slower, more expensive prefetches.`
)
}
it('parses the pathname', () => {
expect(
getLinkPrefetchPartialErrorDetails(
createLinkPrefetchPartialError('/dashboard')
)
).toEqual({
type: 'link-prefetch-partial',
pathname: '/dashboard',
})
})
it('returns null for an unrelated error', () => {
expect(getLinkPrefetchPartialErrorDetails(new Error('regular bug'))).toBe(
null
)
})
it('returns null when the headline matches but the prefix is wrong', () => {
expect(
getLinkPrefetchPartialErrorDetails(
new Error(
'Some preamble: Next.js encountered dynamic data during prefetching for "/x".'
)
)
).toBe(null)
})
})
describe('isInstantNavigationError', () => {
function createUnrenderedSegmentError(route: string): Error {
return new Error(
......@@ -541,6 +588,13 @@ describe('isInstantNavigationError', () => {
)
})
it('returns true for link-prefetch-partial warnings', () => {
const error = new Error(
`Next.js encountered dynamic data during prefetching for "/dashboard".`
)
expect(isInstantNavigationError(error)).toBe(true)
})
it('returns false for prerender-phase blocking-route errors', () => {
expect(isInstantNavigationError(createRuntimeBodyError(ROUTE))).toBe(false)
expect(isInstantNavigationError(createDynamicBodyError(ROUTE))).toBe(false)
......
......@@ -114,6 +114,9 @@ export function getErrorTypeLabel(
if (errorDetails.type === 'unrendered-segment') {
return `Instant`
}
if (errorDetails.type === 'link-prefetch-partial') {
return `Instant`
}
if (type === 'recoverable') {
return `Recoverable ${error.name}`
}
......@@ -133,6 +136,7 @@ type ErrorDetails =
| SyncIOErrorDetails
| SyncIOClientErrorDetails
| UnrenderedSegmentErrorDetails
| LinkPrefetchPartialErrorDetails
type NoErrorDetails = {
type: 'empty'
......@@ -182,6 +186,11 @@ type UnrenderedSegmentErrorDetails = {
files: string[]
}
type LinkPrefetchPartialErrorDetails = {
type: 'link-prefetch-partial'
pathname: string
}
const noErrorDetails: ErrorDetails = {
type: 'empty',
}
......@@ -213,6 +222,11 @@ export function useErrorDetails(
return unrenderedSegmentDetails
}
const linkPrefetchPartialDetails = getLinkPrefetchPartialErrorDetails(error)
if (linkPrefetchPartialDetails) {
return linkPrefetchPartialDetails
}
return noErrorDetails
}, [error, getSquashedHydrationErrorDetails])
}
......@@ -494,9 +508,26 @@ export function getUnrenderedSegmentErrorDetails(
}
}
export function getLinkPrefetchPartialErrorDetails(
error: Error
): LinkPrefetchPartialErrorDetails | null {
const message = error.message
if (typeof message !== 'string') return null
const match =
/^Next\.js encountered dynamic data during prefetching for "([^"]+)"\./.exec(
message
)
if (!match) return null
return {
type: 'link-prefetch-partial',
pathname: match[1],
}
}
export function isInstantNavigationError(error: Error): boolean {
// Unrendered-segment errors are always instant-only
if (getUnrenderedSegmentErrorDetails(error)) return true
if (getLinkPrefetchPartialErrorDetails(error)) return true
const details = getBlockingRouteErrorDetails(error)
return details?.type === 'blocking-route' && details.inNavigation
}
......@@ -1138,6 +1169,43 @@ export function Errors({
/>
</ErrorOverlayLayout>
)
case 'link-prefetch-partial':
return (
<ErrorOverlayLayout
errorCode={errorCode}
errorType={errorType}
errorMessage="Next.js encountered dynamic data during prefetching."
headerChildren={
<InstantHeaderExplanation kind="link-prefetch-partial" />
}
renderTabBar={renderTabBar}
canGoPrevious={canGoPrevious}
canGoNext={canGoNext}
onPrevious={handlePrevious}
onNext={handleNext}
onClose={isServerError ? undefined : onClose}
debugInfo={debugInfo}
error={error}
runtimeErrors={activeErrors}
activeIdx={activeIdx}
setActiveIndex={setActiveIndex}
dialogResizerRef={dialogResizerRef}
generateErrorInfo={generateErrorInfo}
{...props}
>
<Suspense fallback={<div data-nextjs-error-suspended />}>
<InstantRuntimeError
key={activeError.id.toString()}
error={activeError}
variant="runtime"
kind="link-prefetch-partial"
showExplanation={false}
dialogResizerRef={dialogResizerRef}
generateErrorInfo={generateErrorInfo}
/>
</Suspense>
</ErrorOverlayLayout>
)
case 'empty':
errorMessage = <GenericErrorDescription error={error} />
break
......
......@@ -85,6 +85,23 @@ export function FixCardMinusCircleIcon() {
)
}
export function FixCardArrowUpIcon() {
return (
<svg {...ICON_PROPS}>
<path d="M12 4v16" />
<path d="M5 11l7-7 7 7" />
</svg>
)
}
export function FixCardMinusIcon() {
return (
<svg {...ICON_PROPS}>
<path d="M5 12h14" />
</svg>
)
}
export function FixCardLayoutIcon() {
return (
<svg
......
......@@ -78,6 +78,7 @@ import {
allRequiredBoundariesRendered,
} from './instant-validation/boundary-tracking'
import type { InstantValidationSampleTracking } from './instant-validation/instant-samples'
import { createUnrenderedSegmentError } from '../../shared/lib/instant-messages'
const hasPostpone = typeof React.unstable_postpone === 'function'
......@@ -1538,21 +1539,7 @@ export function getNavigationDisallowedDynamicReasons(
}
}
missingFiles.sort()
let message = `Route "${workStore.route}": Could not validate that a segment in your UI has instant navigation.`
if (missingFiles.length > 0) {
const label =
missingFiles.length === 1 ? 'Dropped segment' : 'Dropped segments'
message +=
`\n\nThis segment was dropped from rendering. Issues that would prevent instant navigation will go undetected.` +
`\n\n${label}:\n${missingFiles.map((p) => ` ${p}`).join('\n')}` +
`\n\nWays to fix this:` +
`\n - [render] Render the dropped segment` +
`\n https://nextjs.org/docs/messages/instant-unrendered-segment#render-the-dropped-segment` +
`\n - [ignore] Set \`export const instant = false\` on the dropped segment to skip validation` +
`\n https://nextjs.org/docs/messages/instant-unrendered-segment#skip-validation-on-the-segment`
}
const error = new Error(message)
return error
return createUnrenderedSegmentError(workStore.route, missingFiles)
} else if (process.env.__NEXT_DEV_SERVER && devRenderDidError) {
// Errors outside the boundary likely blocked it from rendering,
// but they're already being reported to the user via the dev
......
......@@ -3155,6 +3155,7 @@ export async function cache(
case 'private-cache':
case 'prerender':
case 'prerender-runtime':
case 'prerender-ppr':
case 'prerender-legacy':
case 'unstable-cache':
case 'generate-static-params':
......
export function createUnrenderedSegmentError(
route: string,
missingFiles: readonly string[]
): Error {
let message = `Route "${route}": Could not validate that a segment in your UI has instant navigation.`
if (missingFiles.length > 0) {
const label =
missingFiles.length === 1 ? 'Dropped segment' : 'Dropped segments'
message +=
`\n\nThis segment was dropped from rendering. Issues that would prevent instant navigation will go undetected.` +
`\n\n${label}:\n${missingFiles.map((p) => ` ${p}`).join('\n')}` +
`\n\nWays to fix this:` +
`\n - [render] Render the dropped segment` +
`\n https://nextjs.org/docs/messages/instant-unrendered-segment#render-the-dropped-segment` +
`\n - [ignore] Set \`export const instant = false\` to silence this warning and opt the dropped segment out of instant-navigation validation` +
`\n https://nextjs.org/docs/messages/instant-unrendered-segment#skip-validation-on-the-segment`
}
return new Error(message)
}
export function createLinkPrefetchPartialError(pathname: string): Error {
return new Error(
`Next.js encountered dynamic data during prefetching for "${pathname}".\n\n` +
`This will lead to slower, more expensive prefetches.\n\n` +
`Ways to fix this:\n` +
` - [upgrade] Opt into Partial Prefetching by exporting \`const prefetch = 'partial'\` from the page or layout, or by setting \`partialPrefetching: true\` in next.config to opt the whole app in\n` +
` https://nextjs.org/docs/messages/instant-link-prefetch-partial#opt-into-partial-prefetching\n` +
` - [disable] Remove \`prefetch={true}\` from the <Link> to use the default prefetch\n` +
` https://nextjs.org/docs/messages/instant-link-prefetch-partial#use-the-default-prefetch\n` +
` - [ignore] Set \`export const instant = false\` to silence this warning and opt the route out of instant-navigation validation\n` +
` https://nextjs.org/docs/messages/instant-link-prefetch-partial#disable-validation-on-this-route`
)
}
......@@ -6,7 +6,7 @@ describe('prefetch-true-partial-warning', () => {
})
// A stable substring of the dev warning emitted from navigation.ts.
const WARNING = 'Partial Prefetching is not enabled'
const WARNING = 'Next.js encountered dynamic data during prefetching'
async function navigateViaAccordion(
browser: Awaited<ReturnType<typeof next.browser>>,
......@@ -34,10 +34,10 @@ describe('prefetch-true-partial-warning', () => {
await expect(browser).toDisplayCollapsedRedbox(`
{
"code": "E1362",
"description": "A <Link prefetch={true}> navigated to "/default-route", but Partial Prefetching is not enabled for that route, so its dynamic data was included in the prefetch. Enable Partial Prefetching app-wide by setting \`partialPrefetching: true\` in next.config, or per-route by exporting \`const prefetch = 'partial'\` from the page or layout.",
"code": "E1386",
"description": "Next.js encountered dynamic data during prefetching.",
"environmentLabel": null,
"label": "Console Error",
"label": "Instant",
"source": "components/link-accordion.tsx (25:9) @ LinkAccordion
> 25 | <Link href={href} prefetch={prefetch}>
| ^",
......
......@@ -3344,7 +3344,7 @@ describe('instant validation', () => {
Ways to fix this:
- [render] Render the dropped segment
https://nextjs.org/docs/messages/instant-unrendered-segment#render-the-dropped-segment
- [ignore] Set \`export const instant = false\` on the dropped segment to skip validation
- [ignore] Set \`export const instant = false\` to silence this warning and opt the dropped segment out of instant-navigation validation
https://nextjs.org/docs/messages/instant-unrendered-segment#skip-validation-on-the-segment
at ignore-listed frames
Build-time instant validation failed for route "/suspense-in-root/static/multi-depth-deferred-fallback/inner".
......@@ -3402,7 +3402,7 @@ describe('instant validation', () => {
Ways to fix this:
- [render] Render the dropped segment
https://nextjs.org/docs/messages/instant-unrendered-segment#render-the-dropped-segment
- [ignore] Set \`export const instant = false\` on the dropped segment to skip validation
- [ignore] Set \`export const instant = false\` to silence this warning and opt the dropped segment out of instant-navigation validation
https://nextjs.org/docs/messages/instant-unrendered-segment#skip-validation-on-the-segment
at ignore-listed frames
Build-time instant validation failed for route "/suspense-in-root/static/test-firstmod/inter/inner".
......@@ -3460,7 +3460,7 @@ describe('instant validation', () => {
Ways to fix this:
- [render] Render the dropped segment
https://nextjs.org/docs/messages/instant-unrendered-segment#render-the-dropped-segment
- [ignore] Set \`export const instant = false\` on the dropped segment to skip validation
- [ignore] Set \`export const instant = false\` to silence this warning and opt the dropped segment out of instant-navigation validation
https://nextjs.org/docs/messages/instant-unrendered-segment#skip-validation-on-the-segment
at ignore-listed frames
Build-time instant validation failed for route "/suspense-in-root/static/test-multi-unrendered".
......
......@@ -705,6 +705,7 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/server-inserted-html.js",
"/node_modules/next/dist/server/runtime-reacts.external.js",
"/node_modules/next/dist/shared/lib/deep-freeze.js",
"/node_modules/next/dist/shared/lib/instant-messages.js",
"/node_modules/next/dist/shared/lib/invariant-error.js",
"/node_modules/next/dist/shared/lib/is-plain-object.js",
"/node_modules/next/dist/shared/lib/is-thenable.js",
......
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