Unverified Commit 23985382 authored by Jiwon Choi's avatar Jiwon Choi Committed by GitHub

Replace CSRBailout error with `ReactDOM.browser` behind a flag (#96826)

CSRBailout error is the use case for `ReactDOM.browser()`. Replace
behind an experimental flag.
This PR replaces the bailout error used in next/dynamic ssr: false.
parent fad31750
......@@ -253,6 +253,9 @@ export function getDefineEnv({
'process.env.__NEXT_DYNAMIC_ON_HOVER': Boolean(
config.experimental.dynamicOnHover
),
'process.env.__NEXT_EXPERIMENTAL_REACT_BROWSER_BAILOUT': Boolean(
config.experimental.reactBrowserBailout
),
'process.env.__NEXT_USE_OFFLINE': Boolean(config.experimental.useOffline),
'process.env.__NEXT_PREFETCH_INLINING': Boolean(
config.experimental.prefetchInlining
......
......@@ -941,6 +941,9 @@ export function createAppPageEntrypoint({
prefetchInlining:
nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
reactBrowserBailout: Boolean(
nextConfig.experimental.reactBrowserBailout
),
serverComponentsHmrCancellation: Boolean(
nextConfig.experimental.serverComponentsHmrCancellation
),
......
......@@ -173,6 +173,9 @@ async function requestHandler(
inlineCss: Boolean(nextConfig.experimental.inlineCss),
prefetchInlining: nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: Boolean(nextConfig.experimental.authInterrupts),
reactBrowserBailout: Boolean(
nextConfig.experimental.reactBrowserBailout
),
// Edge has no Node response-close signal, so HMR cancellation is a
// no-op.
serverComponentsHmrCancellation: false,
......
......@@ -523,6 +523,7 @@ async function exportAppImpl(
inlineCss: nextConfig.experimental.inlineCss ?? false,
prefetchInlining: nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: !!nextConfig.experimental.authInterrupts,
reactBrowserBailout: nextConfig.experimental.reactBrowserBailout ?? false,
useCacheTimeout: nextConfig.experimental.useCacheTimeout,
cachedNavigations: nextConfig.experimental.cachedNavigations ?? false,
maxPostponedStateSizeBytes: parseMaxPostponedStateSize(
......
......@@ -137,6 +137,7 @@ import {
} from './create-transport-tree-from-loader-tree'
import { handleAction } from './action-handler'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { getReactBrowserBailoutReason } from '../../shared/lib/lazy-dynamic/react-browser-bailout'
import { warn, error } from '../../build/output/log'
import {
appendMutableCookies,
......@@ -2919,7 +2920,7 @@ async function prerenderAppPage({
// Pick first userland SSR error, which is also not a RSC error.
if (response.ssrErrors.length) {
const buildFailingError = response.ssrErrors.find((err) =>
isUserLandError(err)
isUserLandError(err, ctx.renderOpts.experimental.reactBrowserBailout)
)
if (buildFailingError) throw buildFailingError
}
......@@ -3698,6 +3699,7 @@ async function renderToStream(
const htmlRendererErrorHandler = createHTMLErrorHandler(
process.env.NODE_ENV === 'development',
isBuildTimePrerendering,
ctx.renderOpts.experimental.reactBrowserBailout,
reactServerErrorsByDigest,
allCapturedErrors,
onHTMLRenderSSRError,
......@@ -6519,6 +6521,7 @@ export type ValidationRenderContext = Pick<
| 'workStore'
> & {
renderOpts: Pick<RenderOpts, 'images' | 'allowEmptyStaticShell'>
reactBrowserBailout: boolean
isDebugChannelEnabled: boolean
}
......@@ -6542,6 +6545,7 @@ export function toValidationRenderContext(
images: ctx.renderOpts.images,
allowEmptyStaticShell: ctx.renderOpts.allowEmptyStaticShell,
},
reactBrowserBailout: ctx.renderOpts.experimental.reactBrowserBailout,
isDebugChannelEnabled: !!ctx.renderOpts.setReactDebugChannel,
}
}
......@@ -6666,6 +6670,7 @@ export async function runValidationInDevFromSnapshot(
images: message.renderOpts.images,
allowEmptyStaticShell: message.renderOpts.allowEmptyStaticShell,
},
reactBrowserBailout: message.reactBrowserBailout,
isDebugChannelEnabled: message.isDebugChannelEnabled,
}
......@@ -7584,6 +7589,20 @@ async function validateInstantConfigs(
/>,
{
signal: reactSignal,
onBrowserBailout: (err: unknown, errorInfo: ErrorInfo) => {
if (!reactSignal.aborted) {
const componentStack = errorInfo.componentStack
if (typeof componentStack === 'string') {
trackThrownErrorInNavigation(
workStore,
instantValidationState,
err,
componentStack,
ctx.reactBrowserBailout
)
}
}
},
onError: (err: unknown, errorInfo: ErrorInfo) => {
if (isPrerenderInterruptedError(err) || reactSignal.aborted) {
const componentStack = errorInfo.componentStack
......@@ -7625,7 +7644,8 @@ async function validateInstantConfigs(
workStore,
instantValidationState,
errorForDisplay,
componentStack
componentStack,
ctx.reactBrowserBailout
)
}
}
......@@ -8671,6 +8691,7 @@ async function prerenderToStream(
const htmlRendererErrorHandler = createHTMLErrorHandler(
process.env.NODE_ENV === 'development',
isBuildTimePrerendering,
ctx.renderOpts.experimental.reactBrowserBailout,
reactServerErrorsByDigest,
allCapturedErrors,
onHTMLRenderSSRError
......@@ -9737,6 +9758,19 @@ async function prerenderToStream(
throw err
}
if (ctx.renderOpts.experimental.reactBrowserBailout) {
// React preserves the reason passed to browser() as the fatal error's cause.
const browserBailoutReason = getReactBrowserBailoutReason(err)
if (browserBailoutReason !== undefined) {
const stack = getStackWithoutErrorMessage(err as Error)
error(
`${browserBailoutReason} should be wrapped in a suspense boundary at page "${pagePath}". Read more: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout\n${stack}`
)
throw new StaticGenBailoutError()
}
}
// If we errored when we did not have an RSC stream to read from. This is
// not just a render error, we need to throw early.
if (reactServerPrerenderResult === null) {
......
......@@ -12,6 +12,7 @@ import { isPrerenderInterruptedError } from './dynamic-rendering'
import { getProperError } from '../../lib/is-error'
import { isReactLargeShellError } from './react-large-shell-error'
import { isInstantValidationError } from './instant-validation/instant-validation-error'
import { isNextBrowserBailoutError } from '../../shared/lib/lazy-dynamic/react-browser-bailout'
declare global {
var __next_log_error__: undefined | ((err: unknown) => void)
......@@ -149,6 +150,7 @@ export function createReactServerErrorHandler(
export function createHTMLErrorHandler(
shouldFormatError: boolean,
isBuildTimePrerendering: boolean,
reactBrowserBailout: boolean,
reactServerErrors: Map<string, DigestedError>,
allCapturedErrors: Array<unknown>,
onHTMLRenderSSRError: (err: DigestedError, errorInfo?: ErrorInfo) => void,
......@@ -168,6 +170,13 @@ export function createHTMLErrorHandler(
// If the response was closed, we don't need to log the error.
if (isAbortError(thrownValue)) return
// React turns a browser bailout outside Suspense into a fatal error. This
// is a framework signal handled by the prerender caller, so don't report it
// as a userland render error here.
if (reactBrowserBailout && isNextBrowserBailoutError(thrownValue)) {
return
}
const digest = getDigestForWellKnownError(thrownValue)
if (digest) {
......@@ -229,8 +238,14 @@ export function createHTMLErrorHandler(
}
}
export function isUserLandError(err: any): boolean {
export function isUserLandError(
err: any,
reactBrowserBailout: boolean
): boolean {
return (
!isAbortError(err) && !isBailoutToCSRError(err) && !isNextRouterError(err)
!isAbortError(err) &&
!isBailoutToCSRError(err) &&
!(reactBrowserBailout && isNextBrowserBailoutError(err)) &&
!isNextRouterError(err)
)
}
......@@ -98,6 +98,7 @@ export interface DevValidationSnapshot {
* rare renders that React's I/O tracking carries a reference into.
*/
additionalClientReferenceManifestPages: string[]
reactBrowserBailout: boolean
isDebugChannelEnabled: boolean
renderOpts: {
images: ImageConfigComplete
......
......@@ -88,6 +88,7 @@ export async function buildDevValidationSnapshot(
.additionalClientReferenceManifestPages
? [...ctx.workStore.additionalClientReferenceManifestPages]
: [],
reactBrowserBailout: ctx.renderOpts.experimental.reactBrowserBailout,
isDebugChannelEnabled: !!ctx.renderOpts.setReactDebugChannel,
renderOpts: {
images: ctx.renderOpts.images,
......
......@@ -79,6 +79,7 @@ import {
} from './instant-validation/boundary-tracking'
import type { InstantValidationSampleTracking } from './instant-validation/instant-samples'
import { createUnrenderedSegmentError } from '../../shared/lib/instant-messages'
import { getReactBrowserBailoutReason } from '../../shared/lib/lazy-dynamic/react-browser-bailout'
export type DynamicAccess = {
/**
......@@ -920,7 +921,8 @@ export function trackThrownErrorInNavigation(
workStore: WorkStore,
dynamicValidation: InstantValidationState,
thrownValue: unknown,
componentStack: string
componentStack: string,
reactBrowserBailout: boolean
) {
const boundaryLocation =
hasInstantValidationBoundaryRegex.exec(componentStack)
......@@ -932,6 +934,16 @@ export function trackThrownErrorInNavigation(
// This helps for errors from node_modules which would otherwise
// have no useful stack information due to ignore-listing,
// e.g. next/dynamic with `ssr: false`.
if (reactBrowserBailout) {
// React preserves Next's branded bailout reason as the error cause.
// Replace the internal wrapper before storing the user-facing diagnostic.
const browserBailoutReason = getReactBrowserBailoutReason(thrownValue)
if (browserBailoutReason !== undefined) {
const browserBailoutError = thrownValue as Error
browserBailoutError.cause = browserBailoutReason
}
}
const error = addErrorContext(
new Error(
'An error occurred while attempting to validate instant UI. This error may be preventing the validation from completing.',
......@@ -958,6 +970,16 @@ export function trackThrownErrorInNavigation(
// invalid - fallthrough
}
}
if (reactBrowserBailout) {
// React preserves Next's branded bailout reason as the error cause.
// Replace the internal wrapper before storing the user-facing diagnostic.
const browserBailoutReason = getReactBrowserBailoutReason(thrownValue)
if (browserBailoutReason !== undefined) {
const browserBailoutError = thrownValue as Error
browserBailoutError.cause = browserBailoutReason
}
}
const message = `Route "${workStore.route}": Could not validate \`instant\` because an error prevented the target segment from rendering.`
const error = addErrorContext(
new Error(message, { cause: thrownValue }),
......
......@@ -166,6 +166,7 @@ export interface RenderOptsPartial {
inlineCss: boolean
prefetchInlining: PrefetchInliningConfig
authInterrupts: boolean
reactBrowserBailout: boolean
serverComponentsHmrCancellation?: boolean
useCacheTimeout: number
cachedNavigations: boolean
......
......@@ -609,6 +609,8 @@ export default abstract class Server<
prefetchInlining:
this.nextConfig.experimental.prefetchInlining ?? false,
authInterrupts: !!this.nextConfig.experimental.authInterrupts,
reactBrowserBailout:
this.nextConfig.experimental.reactBrowserBailout ?? false,
serverComponentsHmrCancellation:
this.nextConfig.experimental.serverComponentsHmrCancellation,
useCacheTimeout: this.nextConfig.experimental.useCacheTimeout,
......
......@@ -226,6 +226,7 @@ export const experimentalSchema = {
clientParamParsingOrigins: z.array(z.string()).optional(),
cachedNavigations: z.boolean().optional(),
dynamicOnHover: z.boolean().optional(),
reactBrowserBailout: z.boolean().optional(),
useOffline: z.boolean().optional(),
optimisticRouting: z.boolean().optional(),
concurrentRouterQueue: z.boolean().optional(),
......
......@@ -533,6 +533,11 @@ export interface ExperimentalConfig {
*/
cachedNavigations?: boolean
dynamicOnHover?: boolean
/**
* Uses ReactDOM's browser rendering primitive for supported client-rendering
* bailouts instead of Next.js' internal bailout error.
*/
reactBrowserBailout?: boolean
useOffline?: boolean
optimisticRouting?: boolean
/**
......@@ -2262,6 +2267,7 @@ export const defaultConfig = Object.freeze({
clientParamParsingOrigins: undefined,
cachedNavigations: false,
dynamicOnHover: false,
reactBrowserBailout: false,
useOffline: false,
varyParams: true,
optimisticRouting: true,
......@@ -2422,6 +2428,7 @@ export interface NextConfigRuntime {
| 'inlineCss'
| 'prefetchInlining'
| 'authInterrupts'
| 'reactBrowserBailout'
| 'useCacheTimeout'
| 'clientTraceMetadata'
| 'clientParamParsingOrigins'
......@@ -2489,6 +2496,7 @@ export function getNextConfigRuntime(
inlineCss: ex.inlineCss,
prefetchInlining: ex.prefetchInlining,
authInterrupts: ex.authInterrupts,
reactBrowserBailout: ex.reactBrowserBailout,
useCacheTimeout: ex.useCacheTimeout,
clientTraceMetadata: ex.clientTraceMetadata,
clientParamParsingOrigins: ex.clientParamParsingOrigins,
......
'use client'
import type { ReactElement } from 'react'
import { use, type ReactElement } from 'react'
import { browser } from 'react-dom'
import { BailoutToCSRError } from './bailout-to-csr'
import { createReactBrowserBailoutReason } from './react-browser-bailout'
interface BailoutToCSRProps {
reason: string
interface BailoutToCSRForNextDynamicProps {
children: ReactElement
}
const NEXT_DYNAMIC_BAILOUT_REASON = 'next/dynamic'
const getNextDynamicBailoutReason = createReactBrowserBailoutReason.bind(
null,
NEXT_DYNAMIC_BAILOUT_REASON
)
/**
* If rendered on the server, this component throws an error
* to signal Next.js that it should bail out to client-side rendering instead.
* Signals during server rendering that this subtree should be client-rendered.
*/
export function BailoutToCSR({ reason, children }: BailoutToCSRProps) {
export function BailoutToCSRForNextDynamic({
children,
}: BailoutToCSRForNextDynamicProps) {
if (process.env.__NEXT_EXPERIMENTAL_REACT_BROWSER_BAILOUT) {
// @ts-expect-error TODO: Update @types/react-dom to include the reason argument.
use(browser(getNextDynamicBailoutReason))
return children
}
if (typeof window === 'undefined') {
throw new BailoutToCSRError(reason)
throw new BailoutToCSRError(NEXT_DYNAMIC_BAILOUT_REASON)
}
return children
......
import { Suspense, Fragment, lazy } from 'react'
import { BailoutToCSR } from './dynamic-bailout-to-csr'
import { BailoutToCSRForNextDynamic } from './dynamic-bailout-to-csr'
import type { ComponentModule } from './types'
import { PreloadChunks } from './preload-chunks'
......@@ -61,9 +61,9 @@ function Loadable(options: LoadableOptions) {
<Lazy {...props} />
</>
) : (
<BailoutToCSR reason="next/dynamic">
<BailoutToCSRForNextDynamic>
<Lazy {...props} />
</BailoutToCSR>
</BailoutToCSRForNextDynamic>
)
return <Wrap {...wrapProps}>{children}</Wrap>
......
// This module is bundled separately into user code and the precompiled App
// Router runtime. Use the global symbol registry so both copies recognize the
// same browser bailout reason.
const REACT_BROWSER_BAILOUT_REASON = Symbol.for('next.browser-bailout-reason')
type ReactBrowserBailoutReason = {
$$typeof: symbol
reason: string
}
export function createReactBrowserBailoutReason(
reason: string
): ReactBrowserBailoutReason {
return {
$$typeof: REACT_BROWSER_BAILOUT_REASON,
reason,
}
}
export function getReactBrowserBailoutReason(
error: unknown
): string | undefined {
const cause = (error as Error)?.cause as ReactBrowserBailoutReason | undefined
return cause?.$$typeof === REACT_BROWSER_BAILOUT_REASON
? cause.reason
: undefined
}
export function isNextBrowserBailoutError(error: unknown): boolean {
return getReactBrowserBailoutReason(error) !== undefined
}
......@@ -416,7 +416,7 @@ export function registerClientTests(ctx: InstantValidationCaseContext) {
"cause": [
{
"label": "Caused by: Error",
"message": "Bail out to client-side rendering: next/dynamic",
"message": "Browser-only rendering was requested by \`browser()\`.",
"source": null,
"stack": [],
},
......@@ -448,10 +448,9 @@ export function registerClientTests(ctx: InstantValidationCaseContext) {
at body (<anonymous>)
at html (<anonymous>)
at c (<anonymous>) {
[cause]: Error: Bail out to client-side rendering: next/dynamic
[cause]: Error: Browser-only rendering was requested by \`browser()\`.
at ignore-listed frames {
reason: 'next/dynamic',
digest: 'BAILOUT_TO_CLIENT_SIDE_RENDERING'
[cause]: 'next/dynamic'
}
}
Build-time instant validation failed for route "/suspense-in-root/static/invalid-csr-bailout-blocks-children".
......
......@@ -3,6 +3,7 @@ import type { NextConfig } from 'next'
const nextConfig: NextConfig = {
cacheComponents: true,
experimental: {
reactBrowserBailout: true,
instantInsights: {
validationLevel: 'manual-warning',
},
......
process.env.TEST_REACT_BROWSER_BAILOUT = '1'
require('./missing-suspense-with-csr-bailout.test')
/** @type {import("next").NextConfig} */
const config = {}
const config = {
experimental: {
reactBrowserBailout: process.env.TEST_REACT_BROWSER_BAILOUT === '1',
},
}
module.exports = config
......@@ -713,6 +713,7 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/shared/lib/is-plain-object.js",
"/node_modules/next/dist/shared/lib/is-thenable.js",
"/node_modules/next/dist/shared/lib/lazy-dynamic/bailout-to-csr.js",
"/node_modules/next/dist/shared/lib/lazy-dynamic/react-browser-bailout.js",
"/node_modules/next/dist/shared/lib/no-fallback-error.external.js",
"/node_modules/next/dist/shared/lib/promise-with-resolvers.js",
"/node_modules/next/dist/shared/lib/server-reference-info.js",
......
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