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 { ...@@ -65,7 +65,9 @@ import {
FallbackMode, FallbackMode,
parseFallbackField, parseFallbackField,
} from '../../lib/fallback' with { 'turbopack-transition': 'next-server-utility' } } 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 { import {
CACHE_ONE_YEAR_SECONDS, CACHE_ONE_YEAR_SECONDS,
HTML_CONTENT_TYPE_HEADER, HTML_CONTENT_TYPE_HEADER,
...@@ -852,7 +854,7 @@ export function createAppPageEntrypoint({ ...@@ -852,7 +854,7 @@ export function createAppPageEntrypoint({
fallbackRouteParams: OpaqueFallbackRouteParams | null fallbackRouteParams: OpaqueFallbackRouteParams | null
renderOperation: AppPageRenderOperation renderOperation: AppPageRenderOperation
}): Promise<ResponseCacheEntry> => { }): Promise<ResponseCacheEntry | PrerenderFailure> => {
const context: AppPageRouteHandlerContext = { const context: AppPageRouteHandlerContext = {
query, query,
params, params,
...@@ -1020,6 +1022,12 @@ export function createAppPageEntrypoint({ ...@@ -1020,6 +1022,12 @@ export function createAppPageEntrypoint({
const result = await invokeRouteModule(span, context, renderOperation) 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 { metadata } = result
const { const {
...@@ -1106,6 +1114,23 @@ export function createAppPageEntrypoint({ ...@@ -1106,6 +1114,23 @@ export function createAppPageEntrypoint({
const isProduction = routeModule.isDev === false const isProduction = routeModule.isDev === false
const didRespond = hasResolved || res.writableEnded 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 { try {
// skip on-demand revalidate if cache is not present and // skip on-demand revalidate if cache is not present and
// revalidate-if-generated is set // revalidate-if-generated is set
...@@ -1270,8 +1295,9 @@ export function createAppPageEntrypoint({ ...@@ -1270,8 +1295,9 @@ export function createAppPageEntrypoint({
isMinimalMode, isMinimalMode,
}) })
// If the fallback response was set to null, then we should return null. if (fallbackResponse === null || 'error' in fallbackResponse) {
if (fallbackResponse === null) return null return fallbackResponse
}
// Otherwise, if we did get a fallback response, we should return it. // Otherwise, if we did get a fallback response, we should return it.
if (fallbackResponse) { if (fallbackResponse) {
...@@ -1306,7 +1332,7 @@ export function createAppPageEntrypoint({ ...@@ -1306,7 +1332,7 @@ export function createAppPageEntrypoint({
// params stay deferred so the revalidated result is a more // params stay deferred so the revalidated result is a more
// specific shell (e.g. `/prefix/c/[two]`), not a fully // specific shell (e.g. `/prefix/c/[two]`), not a fully
// concrete route (`/prefix/c/foo`). // concrete route (`/prefix/c/foo`).
await responseCache.revalidate( const result = await responseCache.revalidate(
ssgCacheKey, ssgCacheKey,
incrementalCache, incrementalCache,
isRoutePPREnabled, isRoutePPREnabled,
...@@ -1329,6 +1355,9 @@ export function createAppPageEntrypoint({ ...@@ -1329,6 +1355,9 @@ export function createAppPageEntrypoint({
hasResolved, hasResolved,
ctx.waitUntil ctx.waitUntil
) )
if (result !== null && 'error' in result) {
throw result.error
}
} catch (err) { } catch (err) {
console.error( console.error(
'Error revalidating the page in the background', 'Error revalidating the page in the background',
...@@ -1414,7 +1443,7 @@ export function createAppPageEntrypoint({ ...@@ -1414,7 +1443,7 @@ export function createAppPageEntrypoint({
const responseCache = routeModule.getResponseCache(req) const responseCache = routeModule.getResponseCache(req)
try { try {
await responseCache.revalidate( const result = await responseCache.revalidate(
incrementalCacheKey, incrementalCacheKey,
incrementalCache, incrementalCache,
isRoutePPREnabled, isRoutePPREnabled,
...@@ -1434,6 +1463,9 @@ export function createAppPageEntrypoint({ ...@@ -1434,6 +1463,9 @@ export function createAppPageEntrypoint({
hasResolved, hasResolved,
ctx.waitUntil ctx.waitUntil
) )
if (result !== null && 'error' in result) {
throw result.error
}
} catch (err) { } catch (err) {
console.error( console.error(
'Error revalidating the page in the background', 'Error revalidating the page in the background',
...@@ -1592,33 +1624,25 @@ export function createAppPageEntrypoint({ ...@@ -1592,33 +1624,25 @@ export function createAppPageEntrypoint({
(supportsDynamicResponse || isPossibleServerAction) (supportsDynamicResponse || isPossibleServerAction)
// Perform the render. // Perform the render.
return doRender({ const result = await doRender({
span, span,
postponed, postponed,
fallbackRouteParams, fallbackRouteParams,
renderOperation: isRequestSpecificRender ? 'render' : 'prerender', renderOperation: isRequestSpecificRender ? 'render' : 'prerender',
allowEmptyStaticShell: isInstantNavigationTest || undefined, 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) { } catch (err) {
// if this is a background revalidate we need to report // The foreground handler reports errors while it awaits a response.
// the request error here as it won't be bubbled // Report here only after the cache has resolved that response.
if (previousIncrementalCacheEntry?.isStale) { if (hasResolved) {
const silenceLog = false await reportRevalidationError(err)
await routeModule.onRequestError(
req,
err,
{
routerKind: 'App Router',
routePath: srcPage,
routeType: 'render',
revalidateReason: getRevalidateReason({
isStaticGeneration: isSSG,
isOnDemandRevalidate,
}),
},
silenceLog,
routerServerContext
)
} }
throw err throw err
} }
...@@ -1663,6 +1687,79 @@ export function createAppPageEntrypoint({ ...@@ -1663,6 +1687,79 @@ export function createAppPageEntrypoint({
isMinimalMode, 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) { if (isDraftMode) {
res.setHeader( res.setHeader(
'Cache-Control', 'Cache-Control',
...@@ -2155,6 +2252,10 @@ export function createAppPageEntrypoint({ ...@@ -2155,6 +2252,10 @@ export function createAppPageEntrypoint({
throw new Error('Invariant: expected a result to be returned') throw new Error('Invariant: expected a result to be returned')
} }
if ('error' in result) {
throw result.error
}
if (result.value?.kind !== CachedRouteKind.APP_PAGE) { if (result.value?.kind !== CachedRouteKind.APP_PAGE) {
throw new Error( throw new Error(
`Invariant: expected a page response, got ${result.value?.kind}` `Invariant: expected a page response, got ${result.value?.kind}`
......
...@@ -416,6 +416,10 @@ export async function handler( ...@@ -416,6 +416,10 @@ export async function handler(
isMinimalMode, isMinimalMode,
}) })
if (cacheEntry !== null && 'error' in cacheEntry) {
throw cacheEntry.error
}
// we don't create a cacheEntry for ISR // we don't create a cacheEntry for ISR
if (!isIsr) { if (!isIsr) {
return return
......
...@@ -89,6 +89,10 @@ export async function exportAppPage( ...@@ -89,6 +89,10 @@ export async function exportAppPage(
sharedContext sharedContext
) )
if ('error' in result) {
throw result.error
}
const html = result.toUnchunkedString() const html = result.toUnchunkedString()
// TODO(after): if we abort a prerender because of an error in an after-callback // 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< ...@@ -666,7 +666,7 @@ export default class NextNodeServer extends BaseServer<
? lazyPrerenderAppPage ? lazyPrerenderAppPage
: lazyRenderAppPage : lazyRenderAppPage
return renderAppPage( const result = await renderAppPage(
req, req,
res, res,
pathname, pathname,
...@@ -684,6 +684,10 @@ export default class NextNodeServer extends BaseServer< ...@@ -684,6 +684,10 @@ export default class NextNodeServer extends BaseServer<
: this.deploymentId, : this.deploymentId,
} }
) )
if ('error' in result) {
throw result.error
}
return result
} else { } else {
// TODO: re-enable this once we've refactored to use implicit matches // TODO: re-enable this once we've refactored to use implicit matches
// throw new Error('Invariant: render should have used routeModule') // throw new Error('Invariant: render should have used routeModule')
...@@ -1067,6 +1071,10 @@ export default class NextNodeServer extends BaseServer< ...@@ -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) { if (cacheEntry?.value?.kind !== CachedRouteKind.IMAGE) {
throw new Error( throw new Error(
'invariant did not get entry from image response cache' 'invariant did not get entry from image response cache'
......
...@@ -76,6 +76,17 @@ export type AppPageRenderResultMetadata = { ...@@ -76,6 +76,17 @@ export type AppPageRenderResultMetadata = {
renderResumeDataCache?: RenderResumeDataCache 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 = { export type PagesRenderResultMetadata = {
pageData?: any pageData?: any
cacheControl?: CacheControl cacheControl?: CacheControl
......
import ResponseCache from './index' import ResponseCache from './index'
import { CachedRouteKind, type ResponseCacheEntry } from './types' import { CachedRouteKind, type ResponseCacheEntry } from './types'
import { RouteKind } from '../route-kind' 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' import { HTML_CONTENT_TYPE_HEADER } from '../../lib/constants'
function mockIncrementalCache() { function mockIncrementalCache() {
...@@ -78,6 +78,71 @@ describe('ResponseCache', () => { ...@@ -78,6 +78,71 @@ describe('ResponseCache', () => {
expect(followUpB).not.toBeNull() 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 () => { it('should use TTL-based LRU when invocationID is absent', async () => {
const cache = new ResponseCache(true) const cache = new ResponseCache(true)
const incrementalCache = mockIncrementalCache() const incrementalCache = mockIncrementalCache()
......
...@@ -2,6 +2,7 @@ import type { OutgoingHttpHeaders } from 'http' ...@@ -2,6 +2,7 @@ import type { OutgoingHttpHeaders } from 'http'
import type RenderResult from '../render-result' import type RenderResult from '../render-result'
import type { CacheControl, Revalidate } from '../lib/cache-control' import type { CacheControl, Revalidate } from '../lib/cache-control'
import type { RouteKind } from '../route-kind' import type { RouteKind } from '../route-kind'
import type { PrerenderFailure } from '../render-result'
export interface ResponseCacheBase { export interface ResponseCacheBase {
get( get(
...@@ -28,7 +29,7 @@ export interface ResponseCacheBase { ...@@ -28,7 +29,7 @@ export interface ResponseCacheBase {
*/ */
isRoutePPREnabled?: boolean isRoutePPREnabled?: boolean
} }
): Promise<ResponseCacheEntry | null> ): Promise<ResponseCacheResult>
} }
// The server components HMR cache might store other data as well in the future, // The server components HMR cache might store other data as well in the future,
...@@ -182,6 +183,8 @@ export type ResponseCacheEntry = { ...@@ -182,6 +183,8 @@ export type ResponseCacheEntry = {
isFallback?: boolean isFallback?: boolean
} }
export type ResponseCacheResult = ResponseCacheEntry | PrerenderFailure | null
/** /**
* @param hasResolved whether the responseGenerator has resolved it's promise * @param hasResolved whether the responseGenerator has resolved it's promise
* @param previousCacheEntry the previous cache entry if it exists or the current * @param previousCacheEntry the previous cache entry if it exists or the current
...@@ -200,7 +203,7 @@ export type ResponseGenerator = (state: { ...@@ -200,7 +203,7 @@ export type ResponseGenerator = (state: {
* dynamic RSC request. * dynamic RSC request.
*/ */
forceStaticRender?: boolean forceStaticRender?: boolean
}) => Promise<ResponseCacheEntry | null> }) => Promise<ResponseCacheResult>
export const enum IncrementalCacheKind { export const enum IncrementalCacheKind {
APP_PAGE = 'APP_PAGE', APP_PAGE = 'APP_PAGE',
......
...@@ -85,6 +85,10 @@ export default class WebResponseCache { ...@@ -85,6 +85,10 @@ export default class WebResponseCache {
;(async () => { ;(async () => {
try { try {
const cacheEntry = await responseGenerator({ hasResolved }) const cacheEntry = await responseGenerator({ hasResolved })
if (cacheEntry !== null && 'error' in cacheEntry) {
throw cacheEntry.error
}
const resolveValue = const resolveValue =
cacheEntry === null cacheEntry === null
? 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') { function getAppPageModule(): typeof import('./module.compiled') {
if (process.env.NEXT_MINIMAL) { if (process.env.NEXT_MINIMAL) {
...@@ -13,7 +16,7 @@ export const lazyRenderAppPage: AppPageRender = (...args) => { ...@@ -13,7 +16,7 @@ export const lazyRenderAppPage: AppPageRender = (...args) => {
return render(...args) return render(...args)
} }
export const lazyPrerenderAppPage: AppPageRender = (...args) => { export const lazyPrerenderAppPage: AppPagePrerender = (...args) => {
const prerender: AppPageRender = getAppPageModule().prerenderToHTMLOrFlight const prerender: AppPagePrerender = getAppPageModule().prerenderToHTMLOrFlight
return prerender(...args) return prerender(...args)
} }
import type { AppPageRouteDefinition } from '../../route-definitions/app-page-route-definition' import type { AppPageRouteDefinition } from '../../route-definitions/app-page-route-definition'
import type RenderResult from '../../render-result' import type RenderResult from '../../render-result'
import type { PrerenderResult } from '../../render-result'
import type { RenderOpts } from '../../app-render/types' import type { RenderOpts } from '../../app-render/types'
import { addRequestMeta, type NextParsedUrlQuery } from '../../request-meta' import { addRequestMeta, type NextParsedUrlQuery } from '../../request-meta'
import type { LoaderTree } from '../../lib/app-dir-module' import type { LoaderTree } from '../../lib/app-dir-module'
...@@ -176,7 +177,7 @@ export class AppPageRouteModule extends RouteModule< ...@@ -176,7 +177,7 @@ export class AppPageRouteModule extends RouteModule<
req: BaseNextRequest, req: BaseNextRequest,
res: BaseNextResponse, res: BaseNextResponse,
context: AppPageRouteHandlerContext context: AppPageRouteHandlerContext
): Promise<RenderResult> { ): Promise<PrerenderResult> {
return prerenderToHTMLOrFlight( return prerenderToHTMLOrFlight(
req, req,
res, res,
......
...@@ -484,6 +484,10 @@ export const getHandler = ({ ...@@ -484,6 +484,10 @@ export const getHandler = ({
waitUntil: ctx.waitUntil, waitUntil: ctx.waitUntil,
} }
) )
if (fallbackResponse !== null && 'error' in fallbackResponse) {
throw fallbackResponse.error
}
if (fallbackResponse) { if (fallbackResponse) {
// Remove the cache control from the response to prevent it from being // Remove the cache control from the response to prevent it from being
// used in the surrounding cache. // used in the surrounding cache.
...@@ -545,6 +549,10 @@ export const getHandler = ({ ...@@ -545,6 +549,10 @@ export const getHandler = ({
isMinimalMode, isMinimalMode,
}) })
if (result !== null && 'error' in result) {
throw result.error
}
// if we got a cache hit this wasn't an ISR fallback // if we got a cache hit this wasn't an ISR fallback
// but it wasn't generated during build so isn't in the // but it wasn't generated during build so isn't in the
// prerender-manifest // 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