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

Preserve error boundaries during on-demand prerendering (#99037)

In production, an error while generating an App Router page on demand
can return a generic 500 response or a Pages Router 500 page instead of
the route's `error.tsx` or `global-error.tsx`. This affects dynamic
routes using `generateStaticParams`, even though their error boundaries
work in development.

A completed prerender failure now carries its error and recovery output
through the renderer and response cache as an explicit result. The
response cache retains completed failures within each platform
invocation, without changing existing in-flight batching. Failed output
is not persisted as a successful ISR entry. The server sends recovered
documents with status 500 and non-cacheable headers. Failed RSC
responses have empty bodies; navigation falls back to loading the
document. Build failures and incomplete recovery continue to throw.
Asynchronous error reporting runs in the background and uses the
platform's `waitUntil` when available.

Recovery that requires resuming a partially prerendered page is out of
scope for this PR and continues to throw. A follow-up PR will preserve
and resume that partial recovery output.

The fix applies to self-hosted production servers and adapter-based
Vercel deployments. The legacy Vercel deployment path retains its
existing behavior of replacing the response with a generic error page.

The tests cover both Cache Components settings, batched invocation
failures, pending I/O inside Suspense, same-URL recovery,
successful-page retention, and original-error reporting.

Fixes #62046
parent f8ae35c2
......@@ -65,7 +65,9 @@ import {
FallbackMode,
parseFallbackField,
} from '../../lib/fallback' with { 'turbopack-transition': 'next-server-utility' }
import RenderResult from '../../server/render-result' with { 'turbopack-transition': 'next-server-utility' }
import RenderResult, {
type PrerenderFailure,
} from '../../server/render-result' with { 'turbopack-transition': 'next-server-utility' }
import {
CACHE_ONE_YEAR_SECONDS,
HTML_CONTENT_TYPE_HEADER,
......@@ -852,7 +854,7 @@ export function createAppPageEntrypoint({
fallbackRouteParams: OpaqueFallbackRouteParams | null
renderOperation: AppPageRenderOperation
}): Promise<ResponseCacheEntry> => {
}): Promise<ResponseCacheEntry | PrerenderFailure> => {
const context: AppPageRouteHandlerContext = {
query,
params,
......@@ -1020,6 +1022,12 @@ export function createAppPageEntrypoint({
const result = await invokeRouteModule(span, context, renderOperation)
// Keep recovery output separate from successful response cache entries.
if ('error' in result) {
;(req as any).fetchMetrics = result.result.metadata.fetchMetrics
return result
}
const { metadata } = result
const {
......@@ -1106,6 +1114,23 @@ export function createAppPageEntrypoint({
const isProduction = routeModule.isDev === false
const didRespond = hasResolved || res.writableEnded
const reportRevalidationError = (error: unknown) =>
routeModule.onRequestError(
req,
error,
{
routerKind: 'App Router',
routePath: srcPage,
routeType: 'render',
revalidateReason: getRevalidateReason({
isStaticGeneration: isSSG,
isOnDemandRevalidate,
}),
},
false,
routerServerContext
)
try {
// skip on-demand revalidate if cache is not present and
// revalidate-if-generated is set
......@@ -1270,8 +1295,9 @@ export function createAppPageEntrypoint({
isMinimalMode,
})
// If the fallback response was set to null, then we should return null.
if (fallbackResponse === null) return null
if (fallbackResponse === null || 'error' in fallbackResponse) {
return fallbackResponse
}
// Otherwise, if we did get a fallback response, we should return it.
if (fallbackResponse) {
......@@ -1306,7 +1332,7 @@ export function createAppPageEntrypoint({
// params stay deferred so the revalidated result is a more
// specific shell (e.g. `/prefix/c/[two]`), not a fully
// concrete route (`/prefix/c/foo`).
await responseCache.revalidate(
const result = await responseCache.revalidate(
ssgCacheKey,
incrementalCache,
isRoutePPREnabled,
......@@ -1329,6 +1355,9 @@ export function createAppPageEntrypoint({
hasResolved,
ctx.waitUntil
)
if (result !== null && 'error' in result) {
throw result.error
}
} catch (err) {
console.error(
'Error revalidating the page in the background',
......@@ -1414,7 +1443,7 @@ export function createAppPageEntrypoint({
const responseCache = routeModule.getResponseCache(req)
try {
await responseCache.revalidate(
const result = await responseCache.revalidate(
incrementalCacheKey,
incrementalCache,
isRoutePPREnabled,
......@@ -1434,6 +1463,9 @@ export function createAppPageEntrypoint({
hasResolved,
ctx.waitUntil
)
if (result !== null && 'error' in result) {
throw result.error
}
} catch (err) {
console.error(
'Error revalidating the page in the background',
......@@ -1592,33 +1624,25 @@ export function createAppPageEntrypoint({
(supportsDynamicResponse || isPossibleServerAction)
// Perform the render.
return doRender({
const result = await doRender({
span,
postponed,
fallbackRouteParams,
renderOperation: isRequestSpecificRender ? 'render' : 'prerender',
allowEmptyStaticShell: isInstantNavigationTest || undefined,
})
// The response cache already served the stale entry, so response
// delivery cannot report this background failure.
if ('error' in result && hasResolved) {
await reportRevalidationError(result.error)
}
return result
} catch (err) {
// if this is a background revalidate we need to report
// the request error here as it won't be bubbled
if (previousIncrementalCacheEntry?.isStale) {
const silenceLog = false
await routeModule.onRequestError(
req,
err,
{
routerKind: 'App Router',
routePath: srcPage,
routeType: 'render',
revalidateReason: getRevalidateReason({
isStaticGeneration: isSSG,
isOnDemandRevalidate,
}),
},
silenceLog,
routerServerContext
)
// The foreground handler reports errors while it awaits a response.
// Report here only after the cache has resolved that response.
if (hasResolved) {
await reportRevalidationError(err)
}
throw err
}
......@@ -1663,6 +1687,79 @@ export function createAppPageEntrypoint({
isMinimalMode,
})
if (cacheEntry !== null && 'error' in cacheEntry) {
if (res.headersSent || res.writableEnded) {
// The outer catch reports the error when we cannot send recovery.
throw cacheEntry.error
}
// Returned failures bypass the outer catch's error reporting. Do not
// await async reporting before delivering recovery.
const errorReporting = routeModule
.onRequestError(
req,
cacheEntry.error,
{
routerKind: 'App Router',
routePath: srcPage,
routeType: 'render',
revalidateReason: getRevalidateReason({
isStaticGeneration: isSSG,
isOnDemandRevalidate,
}),
},
false,
routerServerContext
)
.catch((err) => {
console.error(err)
})
ctx.waitUntil?.(errorReporting)
const { result } = cacheEntry
for (const [name, value] of Object.entries(
result.metadata.headers ?? {}
)) {
if (value !== undefined) {
res.appendHeader(
name,
typeof value === 'number' ? value.toString() : value
)
}
}
// Each request needs the failure status, including callers that
// reused another request's render through the response cache.
res.statusCode = 500
span?.setAttributes({
'http.status_code': 500,
'next.rsc': isRSCRequest,
'error.type': '500',
})
span?.setStatus({ code: SpanStatusCode.ERROR })
res.removeHeader('x-nextjs-cache')
res.setHeader(
'Cache-Control',
'private, no-cache, no-store, max-age=0, must-revalidate'
)
let response = result
if (isRSCRequest) {
// The router discards failed prefetches and falls back to a
// document load when navigation receives a failed Flight response.
response = RenderResult.fromStatic('', RSC_CONTENT_TYPE_HEADER)
}
return sendRenderResult({
req,
res,
result: response,
generateEtags: false,
poweredByHeader: nextConfig.poweredByHeader,
cacheControl: undefined,
})
}
if (isDraftMode) {
res.setHeader(
'Cache-Control',
......@@ -2155,6 +2252,10 @@ export function createAppPageEntrypoint({
throw new Error('Invariant: expected a result to be returned')
}
if ('error' in result) {
throw result.error
}
if (result.value?.kind !== CachedRouteKind.APP_PAGE) {
throw new Error(
`Invariant: expected a page response, got ${result.value?.kind}`
......
......@@ -416,6 +416,10 @@ export async function handler(
isMinimalMode,
})
if (cacheEntry !== null && 'error' in cacheEntry) {
throw cacheEntry.error
}
// we don't create a cacheEntry for ISR
if (!isIsr) {
return
......
......@@ -89,6 +89,10 @@ export async function exportAppPage(
sharedContext
)
if ('error' in result) {
throw result.error
}
const html = result.toUnchunkedString()
// TODO(after): if we abort a prerender because of an error in an after-callback
......
......@@ -666,7 +666,7 @@ export default class NextNodeServer extends BaseServer<
? lazyPrerenderAppPage
: lazyRenderAppPage
return renderAppPage(
const result = await renderAppPage(
req,
res,
pathname,
......@@ -684,6 +684,10 @@ export default class NextNodeServer extends BaseServer<
: this.deploymentId,
}
)
if ('error' in result) {
throw result.error
}
return result
} else {
// TODO: re-enable this once we've refactored to use implicit matches
// throw new Error('Invariant: render should have used routeModule')
......@@ -1067,6 +1071,10 @@ export default class NextNodeServer extends BaseServer<
}
)
if (cacheEntry !== null && 'error' in cacheEntry) {
throw cacheEntry.error
}
if (cacheEntry?.value?.kind !== CachedRouteKind.IMAGE) {
throw new Error(
'invariant did not get entry from image response cache'
......
......@@ -76,6 +76,17 @@ export type AppPageRenderResultMetadata = {
renderResumeDataCache?: RenderResumeDataCache
}
export type PrerenderFailure = {
readonly error: Error
readonly result: RenderResult<
Pick<AppPageRenderResultMetadata, 'headers' | 'flightData' | 'fetchMetrics'>
>
}
export type PrerenderResult =
| RenderResult<AppPageRenderResultMetadata>
| PrerenderFailure
export type PagesRenderResultMetadata = {
pageData?: any
cacheControl?: CacheControl
......
import ResponseCache from './index'
import { CachedRouteKind, type ResponseCacheEntry } from './types'
import { RouteKind } from '../route-kind'
import RenderResult from '../render-result'
import RenderResult, { type PrerenderFailure } from '../render-result'
import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants'
function mockIncrementalCache() {
......@@ -78,6 +78,71 @@ describe('ResponseCache', () => {
expect(followUpB).not.toBeNull()
})
it('shares an in-flight failure across invocations but retries for a later invocation', async () => {
const cache = new ResponseCache(true)
const incrementalCache = mockIncrementalCache()
const context = { routeKind: RouteKind.APP_PAGE, incrementalCache }
let startRender: () => void
const renderStarted = new Promise<void>((resolve) => {
startRender = resolve
})
let finishRender!: () => void
const renderPending = new Promise<void>((resolve) => {
finishRender = resolve
})
const failure: PrerenderFailure = {
error: new Error('Invocation A failed'),
result: RenderResult.fromStatic(
'<p>Error boundary</p>',
HTML_CONTENT_TYPE_HEADER
),
}
const successfulEntry = makeCacheEntry('<p>Invocation C succeeded</p>')
const failedGenerator = jest.fn(async () => {
startRender()
await renderPending
return failure
})
const successfulGenerator = jest.fn(async () => successfulEntry)
const invocationA = cache.get('/test', failedGenerator, {
...context,
invocationID: 'invocation-a',
})
await renderStarted
const invocationB = cache.get('/test', successfulGenerator, {
...context,
invocationID: 'invocation-b',
})
finishRender()
const [resultA, resultB] = await Promise.all([invocationA, invocationB])
expect(resultA).toBe(failure)
expect(resultB).toBe(failure)
expect(successfulGenerator).not.toHaveBeenCalled()
for (const invocationID of ['invocation-a', 'invocation-b']) {
const followUp = await cache.get('/test', successfulGenerator, {
...context,
invocationID,
})
expect(followUp).toBe(failure)
}
expect(successfulGenerator).not.toHaveBeenCalled()
const resultC = await cache.get('/test', successfulGenerator, {
...context,
invocationID: 'invocation-c',
})
expect(resultC).toMatchObject(successfulEntry)
expect(failedGenerator).toHaveBeenCalledTimes(1)
expect(successfulGenerator).toHaveBeenCalledTimes(1)
expect(incrementalCache.set).not.toHaveBeenCalled()
})
it('should use TTL-based LRU when invocationID is absent', async () => {
const cache = new ResponseCache(true)
const incrementalCache = mockIncrementalCache()
......
......@@ -2,6 +2,7 @@ import type { OutgoingHttpHeaders } from 'http'
import type RenderResult from '../render-result'
import type { CacheControl, Revalidate } from '../lib/cache-control'
import type { RouteKind } from '../route-kind'
import type { PrerenderFailure } from '../render-result'
export interface ResponseCacheBase {
get(
......@@ -28,7 +29,7 @@ export interface ResponseCacheBase {
*/
isRoutePPREnabled?: boolean
}
): Promise<ResponseCacheEntry | null>
): Promise<ResponseCacheResult>
}
// The server components HMR cache might store other data as well in the future,
......@@ -182,6 +183,8 @@ export type ResponseCacheEntry = {
isFallback?: boolean
}
export type ResponseCacheResult = ResponseCacheEntry | PrerenderFailure | null
/**
* @param hasResolved whether the responseGenerator has resolved it's promise
* @param previousCacheEntry the previous cache entry if it exists or the current
......@@ -200,7 +203,7 @@ export type ResponseGenerator = (state: {
* dynamic RSC request.
*/
forceStaticRender?: boolean
}) => Promise<ResponseCacheEntry | null>
}) => Promise<ResponseCacheResult>
export const enum IncrementalCacheKind {
APP_PAGE = 'APP_PAGE',
......
......@@ -85,6 +85,10 @@ export default class WebResponseCache {
;(async () => {
try {
const cacheEntry = await responseGenerator({ hasResolved })
if (cacheEntry !== null && 'error' in cacheEntry) {
throw cacheEntry.error
}
const resolveValue =
cacheEntry === null
? null
......
import type { AppPageRender } from '../../app-render/app-render'
import type {
AppPagePrerender,
AppPageRender,
} from '../../app-render/app-render'
function getAppPageModule(): typeof import('./module.compiled') {
if (process.env.NEXT_MINIMAL) {
......@@ -13,7 +16,7 @@ export const lazyRenderAppPage: AppPageRender = (...args) => {
return render(...args)
}
export const lazyPrerenderAppPage: AppPageRender = (...args) => {
const prerender: AppPageRender = getAppPageModule().prerenderToHTMLOrFlight
export const lazyPrerenderAppPage: AppPagePrerender = (...args) => {
const prerender: AppPagePrerender = getAppPageModule().prerenderToHTMLOrFlight
return prerender(...args)
}
import type { AppPageRouteDefinition } from '../../route-definitions/app-page-route-definition'
import type RenderResult from '../../render-result'
import type { PrerenderResult } from '../../render-result'
import type { RenderOpts } from '../../app-render/types'
import { addRequestMeta, type NextParsedUrlQuery } from '../../request-meta'
import type { LoaderTree } from '../../lib/app-dir-module'
......@@ -176,7 +177,7 @@ export class AppPageRouteModule extends RouteModule<
req: BaseNextRequest,
res: BaseNextResponse,
context: AppPageRouteHandlerContext
): Promise<RenderResult> {
): Promise<PrerenderResult> {
return prerenderToHTMLOrFlight(
req,
res,
......
......@@ -484,6 +484,10 @@ export const getHandler = ({
waitUntil: ctx.waitUntil,
}
)
if (fallbackResponse !== null && 'error' in fallbackResponse) {
throw fallbackResponse.error
}
if (fallbackResponse) {
// Remove the cache control from the response to prevent it from being
// used in the surrounding cache.
......@@ -545,6 +549,10 @@ export const getHandler = ({
isMinimalMode,
})
if (result !== null && 'error' in result) {
throw result.error
}
// if we got a cache hit this wasn't an ISR fallback
// but it wasn't generated during build so isn't in the
// prerender-manifest
......
'use client'
export default function ErrorBoundary() {
return <h1>Custom error boundary</h1>
}
import { Suspense } from 'react'
import { headers } from 'next/headers'
import { cacheLife, unstable_noStore } from 'next/cache'
import { SsrError } from '../../ssr-error'
import { getOrigin } from '../../origin'
export function generateStaticParams() {
return [{ slug: 'prerendered' }]
}
async function HeadersContent() {
const requestHeaders = await headers()
return <p id="content">{requestHeaders.get('accept-language')}</p>
}
async function IOContent() {
const response = await fetch(`${getOrigin()}/global/prerendered`, {
cache: 'no-store',
})
if (!response.ok) {
throw new Error(`Failed to fetch content: ${response.status}`)
}
await response.text()
return <p id="io-content">Fetched content</p>
}
function NoStoreContent() {
unstable_noStore()
return <p id="content">No-store content</p>
}
async function getData(key: string) {
'use cache'
// The HTTP boundary keeps the data tag out of the page's ISR entry.
const response = await fetch(
`${getOrigin()}/test-data?key=${encodeURIComponent(key)}`,
{ cache: 'no-store' }
)
if (!response.ok) {
throw new Error(`Failed to read test data: ${response.status}`)
}
return response.text()
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
if (slug.startsWith('recovery-')) {
const value = await getData(slug)
if (value === 'error') {
throw new Error('On-demand application data is unavailable')
}
return <p id="content">{value}</p>
}
if (slug.startsWith('reported-revalidate-')) {
const value = await getRevalidatingData(slug)
if (value === 'error') {
throw new Error(`Reported revalidation error: ${slug}`)
}
return <p id="content">{value}</p>
}
if (slug.startsWith('reported-')) {
throw new Error(`Reported prerender error: ${slug}`)
}
if (slug === 'error' || slug.startsWith('error-')) {
throw new Error('On-demand page render failed')
}
switch (slug) {
case 'io-suspense':
case 'io-suspense-error':
return (
<>
<Suspense fallback={<p>Loading IO</p>}>
<IOContent />
</Suspense>
{slug === 'io-suspense-error' ? <HeadersContent /> : null}
</>
)
case 'ssr-zero':
return <SsrError value={0} />
case 'ssr-false':
return <SsrError value={false} />
case 'ssr-empty-string':
return <SsrError value="" />
case 'ssr-null':
return <SsrError value={null} />
case 'ssr-undefined':
return <SsrError value={undefined} />
case 'headers':
return <HeadersContent />
case 'headers-suspense':
return (
<Suspense fallback={<p>Loading</p>}>
<HeadersContent />
</Suspense>
)
case 'no-store':
return <NoStoreContent />
case 'no-store-suspense':
return (
<Suspense fallback={<p>Loading</p>}>
<NoStoreContent />
</Suspense>
)
default:
return <h1>{slug}</h1>
}
}
async function getRevalidatingData(key: string) {
'use cache'
cacheLife({ revalidate: 1, expire: 3600 })
return getData(key)
}
'use client'
export default function GlobalError() {
return (
<html>
<body>
<h1>Custom global error boundary</h1>
</body>
</html>
)
}
import { LinkAccordion } from '../../../link-accordion'
export function generateStaticParams() {
return [{ slug: 'prerendered' }]
}
export default async function Page({
params,
}: {
params: Promise<{ slug: string }>
}) {
const { slug } = await params
if (slug === 'error') {
throw new Error('On-demand page render failed')
}
if (slug.startsWith('error-')) {
return (
<>
<h1>{slug}</h1>
<LinkAccordion href={`/${slug}`}>Open failing page</LinkAccordion>
</>
)
}
return <h1>{slug}</h1>
}
import type { ReactNode } from 'react'
export default function Root({ children }: { children: ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
import { cacheLife, cacheTag, revalidateTag } from 'next/cache'
import { connection } from 'next/server'
async function getData(key: string) {
'use cache: remote'
cacheTag(key)
const value = process.env[`NEXT_TEST_DATA_${key}`]
if (value === undefined) {
// A polling read must not cache a miss before the writer fills this key.
cacheLife({ stale: 0, revalidate: 0, expire: 0 })
return null
}
return value
}
export async function GET(request: Request) {
await connection()
const key = new URL(request.url).searchParams.get('key')
if (!key) {
return new Response('Missing key', { status: 400 })
}
const value = await getData(key)
return value === null
? new Response('No test data', { status: 404 })
: new Response(value)
}
export async function POST(request: Request) {
const key = new URL(request.url).searchParams.get('key')
if (!key) {
return new Response('Missing key', { status: 400 })
}
const environmentKey = `NEXT_TEST_DATA_${key}`
const previousValue = process.env[environmentKey]
process.env[environmentKey] = await request.text()
try {
return new Response(await getData(key))
} finally {
if (previousValue === undefined) {
delete process.env[environmentKey]
} else {
process.env[environmentKey] = previousValue
}
}
}
export async function DELETE(request: Request) {
const key = new URL(request.url).searchParams.get('key')
if (!key) {
return new Response('Missing key', { status: 400 })
}
revalidateTag(key, { expire: 0 })
return new Response(null, { status: 204 })
}
const {
createDefaultCacheHandler,
} = require('next/dist/server/lib/cache-handlers/default')
// Do not retain the page's 'use cache' result between prerenders. Each
// prerender must read updated test data without invalidating the full-route
// cache, so the tests can also verify retention of successful pages.
module.exports = createDefaultCacheHandler(0)
import type { Instrumentation } from 'next'
import { getOrigin } from './origin'
export const onRequestError: Instrumentation.onRequestError = async (
error,
request,
context
) => {
if (!request.path.startsWith('/reported-')) {
return
}
if (request.path.startsWith('/reported-blocked-')) {
const started = await fetch(
`${getOrigin()}/test-data?key=${encodeURIComponent(`started-${request.path}`)}`,
{ method: 'POST', body: 'started' }
)
if (!started.ok) {
throw new Error(`Failed to record hook start: ${started.status}`)
}
// The test releases this hook only after receiving the recovery response.
// Poll shared data so separate deployment invocations can coordinate.
const timeoutSignal = AbortSignal.timeout(60_000)
while (true) {
// Each fetch gets its own signal so its abort listeners do not
// accumulate.
const release = await fetch(
`${getOrigin()}/test-data?key=${encodeURIComponent(`release-${request.path}`)}`,
{ cache: 'no-store', signal: AbortSignal.any([timeoutSignal]) }
)
const value = await release.text()
if (release.ok && value === 'released') {
break
}
}
}
const response = await fetch(
`${getOrigin()}/test-data?key=${encodeURIComponent(`report-${request.path}`)}`,
{
method: 'POST',
body: JSON.stringify({
message: error instanceof Error ? error.message : String(error),
request: { path: request.path, method: request.method },
context,
}),
}
)
if (!response.ok) {
throw new Error(`Failed to record the request error: ${response.status}`)
}
}
'use client'
import Link from 'next/link'
import { useState } from 'react'
export function LinkAccordion({
href,
children,
}: {
href: string
children: React.ReactNode
}) {
const [isVisible, setIsVisible] = useState(false)
return (
<>
<input
type="checkbox"
checked={isVisible}
onChange={() => setIsVisible(!isVisible)}
data-link-accordion={href}
/>
{isVisible ? (
<Link href={href}>{children}</Link>
) : (
`${children} (link is hidden)`
)}
</>
)
}
/**
* @type {import('next').NextConfig}
*/
module.exports = {
experimental: {
useCache: true,
},
cacheHandlers: {
default: require.resolve('./default-cache-handler.js'),
},
}
export function getOrigin() {
if (process.env.VERCEL_URL) {
return `https://${process.env.VERCEL_URL}`
}
if (process.env.PORT) {
return `http://localhost:${process.env.PORT}`
}
throw new Error('The fixture requires VERCEL_URL or PORT')
}
'use client'
export function SsrError({
value,
}: {
value: 0 | false | '' | null | undefined
}) {
if (typeof window === 'undefined') {
throw value
}
return <p id="content">Recovered in browser</p>
}
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