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