Unverified Commit ff59f108 authored by Andrew Clark's avatar Andrew Clark Committed by GitHub

Surface an error for blocking routes under the Navigation Inspector (#95139)

When the Navigation Inspector (Instant Navigation Testing API) is
active, the server renders only a route's static shell. A blocking route
— one that reads a dynamic value such as `await cookies()` at the root
with no Suspense boundary above it, opting into blocking via `export
const instant = false` — produces an empty shell. We served that empty
shell directly, so the browser showed a blank document with no DevTools.
With no DevTools, there's no way to release the inspector lock from the
UI, so every reload stayed blank and the user was stuck.

Detect the empty static shell at serve time and throw to surface a
normal error page instead, and clear the instant-navigation cookie so
the next reload renders the route normally.

In the future we plan to render this error message inline in the
Navigation Inspector panel rather than as a full-page error.
parent 7f271d14
......@@ -1384,5 +1384,6 @@
"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",
"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"
"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",
"1387": "The Navigation Inspector was active, but you attempted to load a blocking route. Reload the page to reset the inspector.\\n\\nTo identify why this route is blocking, refer to the Instant Navigation docs: https://preview.nextjs.org/docs/app/guides/instant-navigation"
}
......@@ -1859,6 +1859,25 @@ export async function handler(
// In dev mode, also inject self.__next_r so the HMR WebSocket and
// debug channel can initialize.
if (isInstantNavigationTest && isDebugStaticShell) {
// If the static shell came back empty, the page reads a dynamic value
// (e.g. `await cookies()`) at the root with no Suspense boundary above
// it, so there is nothing to render before the first dynamic hole.
// Serving it would be a blank document with no DevTools, leaving the
// user unable to release the instant navigation lock. Throw so we
// surface an error page instead; the catch below clears the instant
// navigation cookie so the next reload renders normally. The empty
// prelude marker is carried in the postponed state, so this works for
// both fresh dev renders and prebuilt production shells.
if (
typeof cachedData.postponed === 'string' &&
entryBase.isEmptyHTMLPrelude(cachedData.postponed)
) {
throw new Error(
`The Navigation Inspector was active, but you attempted to load a blocking route. Reload the page to reset the inspector.\n\n` +
`To identify why this route is blocking, refer to the Instant Navigation docs: https://preview.nextjs.org/docs/app/guides/instant-navigation`
)
}
const instantTestRequestId =
routeModule.isDev === true ? crypto.randomUUID() : null
body.pipeThrough(
......@@ -2031,6 +2050,19 @@ export async function handler(
)
}
} catch (err) {
// If an Instant Navigation Testing document render fails (e.g. the page
// blocks at the root with no Suspense boundary above it, producing an empty
// or bailed-out static shell), clear the instant navigation cookie before
// serving the error page. Otherwise the cookie would persist and every
// reload would re-render the same broken shell, leaving the user stuck
// without a way to release the lock.
if (isInstantNavigationTest && !res.headersSent) {
res.setHeader(
'Set-Cookie',
`${NEXT_INSTANT_TEST_COOKIE}=; Path=/; Max-Age=0`
)
}
if (!(err instanceof NoFallbackError)) {
const silenceLog = false
await routeModule.onRequestError(
......
......@@ -62,6 +62,7 @@ export { createMetadataComponents } from '../../lib/metadata/metadata'
export { RootLayoutBoundary } from '../../lib/framework/boundary-components'
export { preloadStyle, preloadFont, preconnect } from './rsc/preloads'
export { isEmptyHTMLPrelude } from './postponed-state'
export { Postpone } from './rsc/postpone'
export { taintObjectReference } from './rsc/taint'
export {
......
......@@ -219,3 +219,53 @@ export function getPostponedFromState(state: DynamicHTMLPostponedState) {
const [preludeState, postponed] = state.data
return { preludeState, postponed }
}
/**
* Cheaply determines whether a serialized postponed state represents an empty
* HTML prelude — i.e. the static shell rendered no bytes before the first
* dynamic hole (a blocking dynamic API at the root with no Suspense boundary
* above it). Returns false for dynamic-data states or unparseable input.
*
* Unlike `parsePostponedState`, this does not interpolate fallback route params
* or build a resume data cache: it only reads the prelude marker, which is
* independent of param values. The Instant Navigation Testing API uses this to
* detect the blank-document case in both dev (fresh render) and production
* (prebuilt shell), where the marker is persisted in the postponed state.
*/
export function isEmptyHTMLPrelude(state: string): boolean {
try {
const lengthMatch = state.match(/^([0-9]*):/)?.[1]
if (!lengthMatch) {
return false
}
const length = parseInt(lengthMatch)
let postponedString = state.slice(
lengthMatch.length + 1,
lengthMatch.length + 1 + length
)
// `null` is the dynamic-data case (a full shell was produced).
if (postponedString === 'null') {
return false
}
// An optional `<n><replacements>` prefix carries fallback route param
// replacements; skip it to reach the `[preludeState, postponed]` data.
if (/^[0-9]/.test(postponedString)) {
const replacementsLengthMatch = postponedString.match(/^([0-9]*)/)?.[1]
if (!replacementsLengthMatch) {
return false
}
const replacementsLength = parseInt(replacementsLengthMatch)
postponedString = postponedString.slice(
replacementsLengthMatch.length + replacementsLength
)
}
const data = JSON.parse(postponedString)
return Array.isArray(data) && data[0] === DynamicHTMLPreludeState.Empty
} catch {
return false
}
}
......@@ -63,6 +63,12 @@ export default function HomePage() {
<a href="/client-fetch-page" id="plain-link-to-client-fetch">
Go to client fetch page (MPA)
</a>
<Link href="/root-blocking-page" id="link-to-root-blocking">
Go to blocking route (no static shell)
</Link>
<a href="/root-blocking-page" id="plain-link-to-root-blocking">
Go to blocking route (no static shell) (MPA)
</a>
</div>
)
}
import { cookies } from 'next/headers'
// Opt out of instant validation so the empty static shell is allowed (rather
// than throwing a static-shell bailout). This reproduces the blank-document
// scenario the fix targets.
export const instant = false
// A page that reads a dynamic value at the root with no Suspense boundary above
// it. During Instant Navigation Testing this produces an empty static shell,
// which previously rendered as a blank document with no DevTools. The server
// now clears the instant-nav cookie and surfaces an error page instead.
export default async function RootBlockingPage() {
const cookieStore = await cookies()
const testCookie = cookieStore.get('testCookie')
return (
<div data-testid="root-blocking-content">
testCookie: {testCookie?.value ?? 'not set'}
</div>
)
}
......@@ -808,6 +808,33 @@ describe('instant-navigation-testing-api', () => {
)
expect(instantCookie).toBeUndefined()
})
// A page that reads a dynamic value (e.g. `await cookies()`) at the root with
// no Suspense boundary above it produces an empty static shell. During
// Instant Navigation Testing that shell is served directly, so an empty shell
// would be a blank document with no DevTools — leaving the user unable to
// release the instant navigation lock. Instead the server clears the instant
// cookie (so the next reload renders normally) and surfaces an error page.
it('clears the instant cookie and serves an error when the static shell is empty', async () => {
const res = await next.fetch('/root-blocking-page', {
headers: { cookie: 'next-instant-navigation-testing=[0]' },
})
// An error response is served instead of a blank document. (The exact body
// differs by mode — a dev error overlay vs. a minimal production error —
// but the 500 status is what distinguishes it from the empty 200 shell.)
expect(res.status).toBe(500)
// The instant cookie is cleared so the next reload renders normally.
const setCookie = res.headers.get('set-cookie') ?? ''
expect(setCookie).toContain('next-instant-navigation-testing=')
expect(setCookie).toMatch(/Max-Age=0|expires=/i)
// The response is a real, non-empty error response — not a blank shell.
const body = await res.text()
expect(body.length).toBeGreaterThan(0)
expect(body).toMatch(/error/i)
})
})
describe('instant-navigation-testing-api - root params', () => {
......
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