Unverified Commit f14048b6 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Recover from blocking routes under Instant Navigation lock when deployed (#95227)

The Instant Navigation feature locks navigation to a route's static
shell so you can inspect the prefetched shell before any dynamic content
streams in. It is controlled by a cookie: in development the Instant
Navigation DevTools set and clear it for you, and in any environment you
can drive it by hand by setting the cookie in the browser's DevTools. A
blocking route (one with a Suspense boundary above `<body>`, or `export
const instant = false`) has an empty static shell, so when you do a full
page load of such a route while the cookie is set, that empty shell is
served as a blank document with no way to release the lock, and every
reload renders the same blank shell and leaves you stuck.

Previously the handler threw for an empty shell. In development that
surfaces as the error overlay, which is what we want, and the catch
clears the cookie so a reload recovers. It did not recover when
deployed: the cookie could only be cleared via `Set-Cookie`, which
cannot take effect there because the empty shell is served from the ISR
cache with its response headers already committed, so the user stayed on
the blank shell across reloads. In `next start` it recovered but
rendered only a generic "Internal Server Error" page.

With this change a deployed blocking route recovers. For the empty-shell
case we serve a minimal document whose inline script clears the cookie
client-side, so the next full page load renders the route normally; we
clear it from the document rather than with `Set-Cookie` because the
headers are already committed when the shell is served from the cache.
Development still throws so the error overlay shows. As a secondary
improvement, `next start` now serves that same document with a readable
explanation instead of the generic "Internal Server Error" page.

The blocking-route test now asserts the user-facing outcome (after a
reload the route renders normally) rather than transport details such as
the status code and `Set-Cookie`, which legitimately differ across dev,
`next start`, and deploy, and it now runs on deploy as well.
parent 31774433
......@@ -1755,7 +1755,15 @@ export async function handler(
? (getRequestMeta(req, 'onCacheEntryV2') ??
getRequestMeta(req, 'onCacheEntry'))
: getRequestMeta(req, 'onCacheEntry')
if (onCacheEntry) {
// `onCacheEntry` lets the platform capture a freshly prerendered result
// so the proxy can write it to the ISR cache; on deploy it returns true
// and the function returns below. In debug-shell mode the render was
// skipped and we only serve the already-cached shell, so there is nothing
// to capture, and we need to reach the serve path below to close the
// document. `onCacheEntry` is absent in `next start`/dev, so this guard
// only affects the deploy (minimalMode) path.
if (onCacheEntry && !isDebugStaticShell) {
const rawCacheEntryUrl = getRequestMeta(req, 'initURL') ?? req.url
const cacheEntryUrl = rawCacheEntryUrl
? (parseUrl(rawCacheEntryUrl)?.pathname ?? rawCacheEntryUrl)
......@@ -1875,33 +1883,62 @@ export async function handler(
// This is a request for HTML data.
const body = cachedData.html
// Instant Navigation Testing API: serve the static shell without resuming
// the dynamic render. The cookie-guarded bootstrap that sets
// self.__next_instant_test is embedded in the prerendered shell via
// `bootstrapScriptContent`, so it is already present (in the served shell
// for a fresh render, or in the cached prelude on deploy). Since the
// render is not resumed, append the closing tags so the browser can parse
// a complete document.
// Instant Navigation Testing API: under the instant lock we serve the
// static shell as a complete document without resuming the dynamic
// render, either recovering from an empty (blocking) shell or appending
// the closing tags to a non-empty one.
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 (
const isEmptyPrelude =
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`
)
if (isEmptyPrelude) {
// A blocking route (a Suspense boundary above <body>, or `export
// const instant = false`) has an empty static shell. Serving it under
// the lock would be a blank document with no way to release the lock,
// so every reload would render the same blank shell and leave the
// user stuck. We surface the reason instead: in development we throw
// so it shows as an error overlay (the catch below clears the instant
// cookie via Set-Cookie); in production we serve a minimal document
// whose script clears the cookie client-side, since on deploy the
// edge has already served the cached shell and committed the response
// headers and this function only resumes by appending to the body, so
// a Set-Cookie could not take effect. `next start` reuses the same
// document, where throwing would render only a generic "Internal
// Server Error" page.
if (routeModule.isDev === true) {
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 recoveryHtml =
`<!DOCTYPE html><html><head><meta charSet="utf-8"/></head><body>` +
`<script>document.cookie="${NEXT_INSTANT_TEST_COOKIE}=; Path=/; Max-Age=0"</script>` +
`<p>The Navigation Inspector was active, but you attempted to load a blocking route. Reload the page to reset the inspector.</p>` +
`<p>To identify why this route is blocking, refer to the ` +
`<a href="https://preview.nextjs.org/docs/app/guides/instant-navigation">Instant Navigation docs</a>.</p>` +
`</body></html>`
return sendRenderResult({
req,
res,
generateEtags: nextConfig.generateEtags,
poweredByHeader: nextConfig.poweredByHeader,
result: RenderResult.fromStatic(
recoveryHtml,
HTML_CONTENT_TYPE_HEADER
),
cacheControl: { revalidate: 0, expire: undefined },
})
}
// Non-empty shell: the cookie-guarded bootstrap that sets
// self.__next_instant_test is embedded in the prerendered shell via
// `bootstrapScriptContent`, so it is already present (in the served
// shell for a fresh render, or in the cached prelude on deploy). Append
// the closing tags so the browser can parse a complete document.
body.push(
new ReadableStream({
start(controller) {
......
......@@ -26,7 +26,6 @@ import {
NextInstance,
nextTestSetup,
isNextDev,
isNextDeploy,
type Playwright as NextBrowser,
} from 'e2e-utils'
import { instant } from '@next/playwright'
......@@ -101,8 +100,6 @@ afterEach(async () => {
}
})
const itSkipDeploy = isNextDeploy ? it.skip : it
describe('instant-navigation-testing-api', () => {
const { next } = nextTestSetup({
files: join(__dirname, 'fixtures', 'default'),
......@@ -1121,38 +1118,55 @@ describe('instant-navigation-testing-api', () => {
})
// 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.
//
// TODO: This is skipped on deploy. There, the empty prelude is served
// straight from the platform cache before this code runs, so the Set-Cookie
// that clears the instant cookie never takes effect and the user stays on a
// blank shell. A follow-up serves a client-side cookie-clearing recovery
// document so the next reload renders the route normally on deploy too.
// prettier-ignore
itSkipDeploy('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]' },
// no Suspense boundary above it produces an empty static shell. Serving that
// shell under the instant lock would be a blank document with no way to
// release the lock, so every reload would render the same empty shell and
// leave the user stuck. The framework breaks that loop: it surfaces the error
// and clears the instant cookie so the next reload renders the route
// normally. We assert the user-facing outcome, not transport details (status
// code, Set-Cookie) which legitimately differ across dev, `next start`, and
// deploy.
it('recovers on reload for a blocking route under the instant lock', async () => {
const browser = await next.browser('/root-blocking-page', {
beforePageLoad(p: Playwright.Page) {
const { hostname } = new URL(next.url)
p.context().addCookies([
{
name: 'next-instant-navigation-testing',
value: '[0]',
domain: hostname,
path: '/',
},
])
},
})
// 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)
// In development the empty shell surfaces as an error overlay so the
// developer sees why the route is blocking.
if (isNextDev) {
await expect(browser).toDisplayRedbox(`
{
"code": "E1387",
"description": "The Navigation Inspector was active, but you attempted to load a blocking route. Reload the page to reset the inspector.
To identify why this route is blocking, refer to the Instant Navigation docs: https://preview.nextjs.org/docs/app/guides/instant-navigation",
"environmentLabel": null,
"label": "Runtime Error",
"source": null,
"stack": [],
}
`)
}
// The empty shell can render nothing useful, but the instant cookie is
// cleared, so reloading renders the route normally instead of the blank
// shell.
await browser.refresh()
const content = await browser
.elementByCss('[data-testid="root-blocking-content"]')
.text()
expect(content).toContain('testCookie:')
})
})
......
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