Unverified Commit b829c618 authored by Jamiboy Mohammad's avatar Jamiboy Mohammad Committed by GitHub

fix: preserve HTTP status codes during prerendering (#99078)

## Summary

Set the correct HTTP status and redirect location when a prerendered
page throws `notFound()`, `unauthorized()`, `forbidden()`, `redirect()`,
or `permanentRedirect()` inside Suspense. Preserve the prerendered
layout and Suspense fallback so the client can recover at the
appropriate error boundary.

Redirects take precedence over HTTP access fallbacks. Among access
fallbacks, or among redirects, the first observed error wins. The HTML
error callback and prerender recovery catch share this rule, so a later
fatal not-found error cannot overwrite an already captured redirect. The
catch still classifies its own error independently of the selected
response.

Request-time streaming behavior is unchanged. A dynamic not-found after
`connection()` can still return 200. The custom error UI itself is not
prerendered and remains a follow-up.

Related:
[NAR-435](https://linear.app/vercel/issue/NAR-435/set-status-code-on-prerendered-output-whenever-notfound-or-redirect).

## Verification

- All 57 production Turbopack tests pass with Cache Components enabled
and disabled, with `__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true`. This
includes 44 ordered-error cases covering sibling Suspense boundaries and
the outer recovery catch, status/location consistency, and preserved
layout/fallback HTML.
- Removing the precedence fix causes 22 regression cases to fail.
- All 36 existing on-demand prerender recovery tests pass with Cache
Components enabled: `NEXT_SKIP_ISOLATE=1 NEXT_TELEMETRY_DISABLED=1
__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES=true __NEXT_CACHE_COMPONENTS=true
pnpm test-start-turbo
test/e2e/app-dir/on-demand-prerender-error-boundary/on-demand-prerender-error-boundary.test.ts`.
- Dev gate verified: all 57 tests are skipped.
- Local tests used the installed SWC canary.38 binary with Next.js
canary.42 and emitted a version mismatch warning. Deploy mode was not
run locally.

<!-- NEXT_JS_LLM -->

---------
Co-authored-by: 's avatarJamiboy Mohammad <2085704+jamiboym@users.noreply.github.com>
parent b114f7cf
...@@ -9062,7 +9062,7 @@ async function prerenderToStream( ...@@ -9062,7 +9062,7 @@ async function prerenderToStream(
} }
} }
const allCapturedErrors: Array<unknown> = [] const allCapturedErrors: Array<unknown> = []
const htmlRendererErrorHandler = createHTMLErrorHandler( const captureHTMLError = createHTMLErrorHandler(
process.env.NODE_ENV === 'development', process.env.NODE_ENV === 'development',
isBuildTimePrerendering, isBuildTimePrerendering,
ctx.renderOpts.experimental.reactBrowserBailout, ctx.renderOpts.experimental.reactBrowserBailout,
...@@ -9101,6 +9101,47 @@ async function prerenderToStream( ...@@ -9101,6 +9101,47 @@ async function prerenderToStream(
let prerenderStore: PrerenderStore | null = null let prerenderStore: PrerenderStore | null = null
let capturedHTTPErrorType: 'access-fallback' | 'redirect' | undefined
// Redirects take precedence over access fallbacks. Within each category, the
// first error wins. Always return the current error's type, even if it does
// not change the response, so the recovery catch can recognize HTTP errors.
function setHTTPAccessFallbackOrRedirectStatus(
err: unknown
): MetadataErrorType | 'redirect' | undefined {
if (isHTTPAccessFallbackError(err)) {
const statusCode = getAccessFallbackHTTPStatus(err)
if (capturedHTTPErrorType === undefined) {
capturedHTTPErrorType = 'access-fallback'
res.statusCode = statusCode
metadata.statusCode = statusCode
}
return getAccessFallbackErrorTypeByStatus(statusCode)
} else if (isRedirectError(err)) {
if (capturedHTTPErrorType !== 'redirect') {
capturedHTTPErrorType = 'redirect'
res.statusCode = getRedirectStatusCodeFromError(err)
metadata.statusCode = res.statusCode
setHeader(
'location',
addPathPrefix(getURLFromRedirectError(err), basePath)
)
}
return 'redirect'
}
}
// React can complete a prerender after an HTTP access fallback or redirect
// error is thrown inside a Suspense boundary. Update the response while
// preserving the prerendered content outside the boundary.
const htmlRendererErrorHandler: typeof captureHTMLError = (
err,
errorInfo
) => {
setHTTPAccessFallbackOrRedirectStatus(err)
return captureHTMLError(err, errorInfo)
}
try { try {
if (cacheComponents) { if (cacheComponents) {
const partialPrefetching = const partialPrefetching =
...@@ -10323,34 +10364,19 @@ async function prerenderToStream( ...@@ -10323,34 +10364,19 @@ async function prerenderToStream(
) )
} }
let errorType: MetadataErrorType | 'redirect' | undefined const errorType = setHTTPAccessFallbackOrRedirectStatus(err)
const isHTTPAccessFallback = isHTTPAccessFallbackError(err)
const isRedirect = isRedirectError(err)
if (isHTTPAccessFallback) { if (errorType === undefined) {
res.statusCode = getAccessFallbackHTTPStatus(err)
metadata.statusCode = res.statusCode
errorType = getAccessFallbackErrorTypeByStatus(res.statusCode)
} else if (isRedirect) {
errorType = 'redirect'
res.statusCode = getRedirectStatusCodeFromError(err)
metadata.statusCode = res.statusCode
const redirectUrl = addPathPrefix(getURLFromRedirectError(err), basePath)
setHeader('location', redirectUrl)
} else {
res.statusCode = 500 res.statusCode = 500
metadata.statusCode = res.statusCode metadata.statusCode = res.statusCode
}
if ( if (
cacheComponents && cacheComponents &&
!isHTTPAccessFallback && (isBuildTimePrerendering ||
!isRedirect && reactServerPrerenderResultIsDynamic === null)
(isBuildTimePrerendering || reactServerPrerenderResultIsDynamic === null) ) {
) { throw reactServerErrorsByDigest.get((err as any)?.digest) ?? err
throw reactServerErrorsByDigest.get((err as any)?.digest) ?? err }
} }
const [errorPreinitScripts, errorBootstrapScript] = getRequiredScripts( const [errorPreinitScripts, errorBootstrapScript] = getRequiredScripts(
...@@ -10636,10 +10662,7 @@ async function prerenderToStream( ...@@ -10636,10 +10662,7 @@ async function prerenderToStream(
originalFlightPrerenderResult.consume() originalFlightPrerenderResult.consume()
errorServerResult.consume() errorServerResult.consume()
return { return {
error: error: errorType !== undefined ? undefined : { thrownValue: err },
isHTTPAccessFallback || isRedirect
? undefined
: { thrownValue: err },
digestErrorsMap: reactServerErrorsByDigest, digestErrorsMap: reactServerErrorsByDigest,
ssrErrors: allCapturedErrors, ssrErrors: allCapturedErrors,
stream: await continueDynamicPrerender(errorHtmlStream, { stream: await continueDynamicPrerender(errorHtmlStream, {
...@@ -10712,10 +10735,7 @@ async function prerenderToStream( ...@@ -10712,10 +10735,7 @@ async function prerenderToStream(
errorServerResult.consume() errorServerResult.consume()
return { return {
error: error: errorType !== undefined ? undefined : { thrownValue: err },
isHTTPAccessFallback || isRedirect
? undefined
: { thrownValue: err },
digestErrorsMap: reactServerErrorsByDigest, digestErrorsMap: reactServerErrorsByDigest,
ssrErrors: allCapturedErrors, ssrErrors: allCapturedErrors,
stream, stream,
......
...@@ -249,7 +249,7 @@ describe('on-demand-prerender-error-boundary', () => { ...@@ -249,7 +249,7 @@ describe('on-demand-prerender-error-boundary', () => {
['healthy', 200, 'Healthy page'], ['healthy', 200, 'Healthy page'],
['suspense-error', 500, 'Partial prerender error boundary'], ['suspense-error', 500, 'Partial prerender error boundary'],
['error', 500, 'Partial prerender error boundary'], ['error', 500, 'Partial prerender error boundary'],
['suspense-missing', 200, 'Partial prerender not-found boundary'], ['suspense-missing', 404, 'Partial prerender not-found boundary'],
['missing', 404, 'Partial prerender not-found boundary'], ['missing', 404, 'Partial prerender not-found boundary'],
] as const) { ] as const) {
it(`resumes ${slug} with the current request outside the page boundary`, async () => { it(`resumes ${slug} with the current request outside the page boundary`, async () => {
......
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>{children}</body>
</html>
)
}
export default function NotFound() {
return <h1 id="not-found">This page could not be found.</h1>
}
import { HTTPErrorPair } from '../../../http-error'
export function generateStaticParams() {
const errors = [
'not-found',
'unauthorized',
'forbidden',
'redirect',
'permanent-redirect',
]
return errors.flatMap((first) =>
errors.flatMap((second) =>
['suspense', 'root'].map((boundary) => ({ first, second, boundary }))
)
)
}
export default async function Page({
params,
}: {
params: Promise<{
first: string
second: string
boundary: string
}>
}) {
const { first, second, boundary } = await params
return <HTTPErrorPair first={first} second={second} boundary={boundary} />
}
'use client'
import { Suspense, use } from 'react'
import {
forbidden,
notFound,
permanentRedirect,
redirect,
unauthorized,
} from 'next/navigation'
function throwHTTPError(type: string, destination: string) {
switch (type) {
case 'not-found':
return notFound()
case 'unauthorized':
return unauthorized()
case 'forbidden':
return forbidden()
case 'redirect':
return redirect(destination)
case 'permanent-redirect':
return permanentRedirect(destination)
default:
throw new Error(`Unknown HTTP error type: ${type}`)
}
}
function FirstError({ type, onError }: { type: string; onError: () => void }) {
try {
return throwHTTPError(type, '/first')
} finally {
onError()
}
}
function SecondError({ type, after }: { type: string; after: Promise<void> }) {
use(after)
return throwHTTPError(type, '/second')
}
export function HTTPErrorPair({
first,
second,
boundary,
}: {
first: string
second: string
boundary: string
}) {
let resolveFirstError: () => void
const firstError = new Promise<void>((resolve) => {
resolveFirstError = resolve
})
// Prerendering can defer Suspense children until after the shell. Wait for
// the first error before rendering the second, even when it is in the shell.
// The promise belongs to this render, so routes and prerender passes do not
// share state. Its continuation runs after React handles the first error.
const secondError = <SecondError type={second} after={firstError} />
return (
<>
<h1 id="precedence-layout">HTTP error precedence</h1>
<Suspense fallback={<p id="first-fallback">First fallback</p>}>
<FirstError type={first} onError={() => resolveFirstError()} />
</Suspense>
{boundary === 'suspense' ? (
<Suspense fallback={<p id="second-fallback">Second fallback</p>}>
{secondError}
</Suspense>
) : (
// Exercise the recovery catch as well as the HTML error callback.
secondError
)}
</>
)
}
import { notFound } from 'next/navigation'
import { connection } from 'next/server'
export default async function Page() {
await connection()
return notFound()
}
import { forbidden } from 'next/navigation'
export default async function Page() {
return forbidden()
}
import { Suspense } from 'react'
export default function Layout({ children }: { children: React.ReactNode }) {
return (
<>
<h1 id="layout">Shared layout</h1>
<Suspense fallback={<p id="suspense-fallback">Loading...</p>}>
{children}
</Suspense>
</>
)
}
import { notFound } from 'next/navigation'
export default async function Page() {
return notFound()
}
import { permanentRedirect } from 'next/navigation'
export default async function Page() {
return permanentRedirect('/')
}
import { redirect } from 'next/navigation'
export default async function Page() {
return redirect('/')
}
import { unauthorized } from 'next/navigation'
export default async function Page() {
return unauthorized()
}
import { forbidden } from 'next/navigation'
export default async function Page() {
return forbidden()
}
import { notFound } from 'next/navigation'
export default async function Page() {
return notFound()
}
import { permanentRedirect } from 'next/navigation'
export default async function Page() {
return permanentRedirect('/')
}
import { redirect } from 'next/navigation'
export default async function Page() {
return redirect('/')
}
import { unauthorized } from 'next/navigation'
export default async function Page() {
return unauthorized()
}
import { nextTestSetup } from 'e2e-utils'
import { load } from 'cheerio'
// These status assertions require production prerendering. In dev, pages are
// rendered on request and Suspense may stream a 200 before an HTTP error occurs.
// @force-gate !dev
describe('prerendered-http-status-codes', () => {
const { next } = nextTestSetup({
files: __dirname,
})
it('returns 200 when notFound() runs after connection() inside Suspense, then shows the not-found UI', async () => {
const { browser, response } = await next.browserWithResponse(
'/with-suspense/dynamic-not-found'
)
try {
expect(response.status()).toBe(200)
expect(await browser.elementByCss('#not-found').text()).toBe(
'This page could not be found.'
)
} finally {
await browser.close()
}
})
describe.each(['suspense', 'root'])(
'HTTP error precedence with the second error caught at %s',
(boundary) => {
async function expectResponse(
first: string,
second: string,
status: number,
location: string | null = null
) {
const response = await next.fetch(
`/precedence/${first}/${second}/${boundary}`,
{
headers: { Accept: 'text/html' },
redirect: 'manual',
}
)
expect(response.status).toBe(status)
expect(response.headers.get('location')).toBe(location)
expect(response.headers.get('content-type')).toContain('text/html')
if (boundary === 'suspense') {
const $ = load(await response.text())
expect($('#precedence-layout').text()).toBe('HTTP error precedence')
expect($('#first-fallback').text()).toBe('First fallback')
expect($('#second-fallback').text()).toBe('Second fallback')
}
}
it.each([
['not-found', 'unauthorized', 404],
['not-found', 'forbidden', 404],
['unauthorized', 'not-found', 401],
['unauthorized', 'forbidden', 401],
['forbidden', 'not-found', 403],
['forbidden', 'unauthorized', 403],
])('keeps the first access fallback: %s before %s', expectResponse)
describe.each([
{ redirect: 'redirect', status: 307 },
{ redirect: 'permanent-redirect', status: 308 },
])('$redirect', ({ redirect, status }) => {
it.each(['not-found', 'unauthorized', 'forbidden'])(
'overrides an earlier %s',
async (fallback) => {
await expectResponse(fallback, redirect, status, '/second')
}
)
it.each(['not-found', 'unauthorized', 'forbidden'])(
'takes precedence over a later %s',
async (fallback) => {
await expectResponse(redirect, fallback, status, '/first')
}
)
it.each(['redirect', 'permanent-redirect'])(
'keeps its status and location when followed by %s',
async (second) => {
await expectResponse(redirect, second, status, '/first')
}
)
})
}
)
describe.each(['with-suspense', 'without-suspense'])('%s', (variant) => {
it.each([
{ route: 'unauthorized', status: 401 },
{ route: 'forbidden', status: 403 },
{ route: 'not-found', status: 404 },
])(
'returns $status for the $route HTML response',
async ({ route, status }) => {
const response = await next.fetch(`/${variant}/${route}`, {
headers: { Accept: 'text/html' },
})
expect(response.headers.get('content-type')).toContain('text/html')
expect(response.status).toBe(status)
if (variant === 'with-suspense') {
const $ = load(await response.text())
expect($('#layout').text()).toBe('Shared layout')
expect($('#suspense-fallback').text()).toBe('Loading...')
}
}
)
it('shows the custom not-found UI in the browser', async () => {
const browser = await next.browser(`/${variant}/not-found`)
try {
expect(await browser.elementByCss('#not-found').text()).toBe(
'This page could not be found.'
)
if (variant === 'with-suspense') {
expect(await browser.elementByCss('#layout').text()).toBe(
'Shared layout'
)
expect(
await browser.hasElementByCssSelector('#suspense-fallback')
).toBe(false)
}
} finally {
await browser.close()
}
})
it.each([
{ route: 'redirect', status: 307 },
{ route: 'permanent-redirect', status: 308 },
])('returns $status and location for $route', async ({ route, status }) => {
const response = await next.fetch(`/${variant}/${route}`, {
headers: { Accept: 'text/html' },
redirect: 'manual',
})
expect(response.status).toBe(status)
expect(response.headers.get('location')).toBe('/')
if (variant === 'with-suspense') {
const $ = load(await response.text())
expect($('#layout').text()).toBe('Shared layout')
expect($('#suspense-fallback').text()).toBe('Loading...')
}
})
})
})
/** @type {import('next').NextConfig} */
module.exports = {
experimental: {
authInterrupts: true,
},
}
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