Unverified Commit dda18705 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Reapply "feat(app-router): introduce…

Reapply "feat(app-router): introduce `experimental.missingSuspenseWithCSRBailout` flag" (#60508) (#60751)

This reapplies the `experimental.missingSuspenseWithCSRBailout` option
to bail out during build if there was a missing suspense boundary when
using something that bails out to client side rendering (like
`useSearchParams()`). See #57642

Closes [NEXT-1770](https://linear.app/vercel/issue/NEXT-1770)
parent 7f3d9099
---
title: Missing Suspense with CSR Bailout
---
#### Why This Error Occurred
Certain methods like `useSearchParams()` opt Next.js into client-side rendering. Without a suspense boundary, this will opt the entire page into client-side rendering, which is likely not intended.
#### Possible Ways to Fix It
Make sure that the method is wrapped in a suspense boundary. This way Next.js will only opt the component into client-side rendering up to the suspense boundary.
### Useful Links
- [`useSearchParams`](https://nextjs.org/docs/app/api-reference/functions/use-search-params)
import { throwWithNoSSR } from '../../shared/lib/lazy-dynamic/no-ssr-error' import { BailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { staticGenerationAsyncStorage } from './static-generation-async-storage.external' import { staticGenerationAsyncStorage } from './static-generation-async-storage.external'
export function bailoutToClientRendering(): void | never { export function bailoutToClientRendering(reason: string): void | never {
const staticGenerationStore = staticGenerationAsyncStorage.getStore() const staticGenerationStore = staticGenerationAsyncStorage.getStore()
if (staticGenerationStore?.forceStatic) { if (staticGenerationStore?.forceStatic) return
return
}
if (staticGenerationStore?.isStaticGeneration) { if (staticGenerationStore?.isStaticGeneration)
throwWithNoSSR() throw new BailoutToCSRError(reason)
}
} }
export const DYNAMIC_ERROR_CODE = 'DYNAMIC_SERVER_USAGE' const DYNAMIC_ERROR_CODE = 'DYNAMIC_SERVER_USAGE'
export class DynamicServerError extends Error { export class DynamicServerError extends Error {
digest: typeof DYNAMIC_ERROR_CODE = DYNAMIC_ERROR_CODE digest: typeof DYNAMIC_ERROR_CODE = DYNAMIC_ERROR_CODE
constructor(type: string) { constructor(public readonly description: string) {
super(`Dynamic server usage: ${type}`) super(`Dynamic server usage: ${description}`)
} }
} }
export function isDynamicServerError(err: unknown): err is DynamicServerError {
if (
typeof err !== 'object' ||
err === null ||
!('digest' in err) ||
typeof err.digest !== 'string'
) {
return false
}
return err.digest === DYNAMIC_ERROR_CODE
}
...@@ -92,7 +92,7 @@ export function useSearchParams(): ReadonlyURLSearchParams { ...@@ -92,7 +92,7 @@ export function useSearchParams(): ReadonlyURLSearchParams {
const { bailoutToClientRendering } = const { bailoutToClientRendering } =
require('./bailout-to-client-rendering') as typeof import('./bailout-to-client-rendering') require('./bailout-to-client-rendering') as typeof import('./bailout-to-client-rendering')
// TODO-APP: handle dynamic = 'force-static' here and on the client // TODO-APP: handle dynamic = 'force-static' here and on the client
bailoutToClientRendering() bailoutToClientRendering('useSearchParams()')
} }
return readonlySearchParams return readonlySearchParams
......
...@@ -20,6 +20,10 @@ export function notFound(): never { ...@@ -20,6 +20,10 @@ export function notFound(): never {
* @param error the error that may reference a not found error * @param error the error that may reference a not found error
* @returns true if the error is a not found error * @returns true if the error is a not found error
*/ */
export function isNotFoundError(error: any): error is NotFoundError { export function isNotFoundError(error: unknown): error is NotFoundError {
return error?.digest === NOT_FOUND_ERROR_CODE if (typeof error !== 'object' || error === null || !('digest' in error)) {
return false
}
return error.digest === NOT_FOUND_ERROR_CODE
} }
...@@ -85,14 +85,18 @@ export function permanentRedirect( ...@@ -85,14 +85,18 @@ export function permanentRedirect(
* @returns true if the error is a redirect error * @returns true if the error is a redirect error
*/ */
export function isRedirectError<U extends string>( export function isRedirectError<U extends string>(
error: any error: unknown
): error is RedirectError<U> { ): error is RedirectError<U> {
if (typeof error?.digest !== 'string') return false if (
typeof error !== 'object' ||
error === null ||
!('digest' in error) ||
typeof error.digest !== 'string'
) {
return false
}
const [errorCode, type, destination, status] = (error.digest as string).split( const [errorCode, type, destination, status] = error.digest.split(';', 4)
';',
4
)
const statusCode = Number(status) const statusCode = Number(status)
......
...@@ -3,8 +3,20 @@ import type { AppConfigDynamic } from '../../build/utils' ...@@ -3,8 +3,20 @@ import type { AppConfigDynamic } from '../../build/utils'
import { DynamicServerError } from './hooks-server-context' import { DynamicServerError } from './hooks-server-context'
import { staticGenerationAsyncStorage } from './static-generation-async-storage.external' import { staticGenerationAsyncStorage } from './static-generation-async-storage.external'
const NEXT_STATIC_GEN_BAILOUT = 'NEXT_STATIC_GEN_BAILOUT'
class StaticGenBailoutError extends Error { class StaticGenBailoutError extends Error {
code = 'NEXT_STATIC_GEN_BAILOUT' public readonly code = NEXT_STATIC_GEN_BAILOUT
}
export function isStaticGenBailoutError(
error: unknown
): error is StaticGenBailoutError {
if (typeof error !== 'object' || error === null || !('code' in error)) {
return false
}
return error.code === NEXT_STATIC_GEN_BAILOUT
} }
type BailoutOpts = { dynamic?: AppConfigDynamic; link?: string } type BailoutOpts = { dynamic?: AppConfigDynamic; link?: string }
......
import { isBailoutCSRError } from '../shared/lib/lazy-dynamic/no-ssr-error' import { isBailoutToCSRError } from '../shared/lib/lazy-dynamic/bailout-to-csr'
export default function onRecoverableError(err: any) { export default function onRecoverableError(err: unknown) {
// Using default react onRecoverableError // Using default react onRecoverableError
// x-ref: https://github.com/facebook/react/blob/d4bc16a7d69eb2ea38a88c8ac0b461d5f72cdcab/packages/react-dom/src/client/ReactDOMRoot.js#L83 // x-ref: https://github.com/facebook/react/blob/d4bc16a7d69eb2ea38a88c8ac0b461d5f72cdcab/packages/react-dom/src/client/ReactDOMRoot.js#L83
const defaultOnRecoverableError = const defaultOnRecoverableError =
...@@ -13,7 +13,7 @@ export default function onRecoverableError(err: any) { ...@@ -13,7 +13,7 @@ export default function onRecoverableError(err: any) {
} }
// Skip certain custom errors which are not expected to be reported on client // Skip certain custom errors which are not expected to be reported on client
if (isBailoutCSRError(err)) return if (isBailoutToCSRError(err)) return
defaultOnRecoverableError(err) defaultOnRecoverableError(err)
} }
import { DYNAMIC_ERROR_CODE } from '../../client/components/hooks-server-context' import { isDynamicServerError } from '../../client/components/hooks-server-context'
import { isNotFoundError } from '../../client/components/not-found' import { isNotFoundError } from '../../client/components/not-found'
import { isRedirectError } from '../../client/components/redirect' import { isRedirectError } from '../../client/components/redirect'
import { isBailoutCSRError } from '../../shared/lib/lazy-dynamic/no-ssr-error' import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
export const isDynamicUsageError = (err: any) => export const isDynamicUsageError = (err: unknown) =>
err.digest === DYNAMIC_ERROR_CODE || isDynamicServerError(err) ||
isBailoutToCSRError(err) ||
isNotFoundError(err) || isNotFoundError(err) ||
isBailoutCSRError(err) ||
isRedirectError(err) isRedirectError(err)
...@@ -506,7 +506,11 @@ export async function exportAppImpl( ...@@ -506,7 +506,11 @@ export async function exportAppImpl(
: {}), : {}),
strictNextHead: !!nextConfig.experimental.strictNextHead, strictNextHead: !!nextConfig.experimental.strictNextHead,
deploymentId: nextConfig.experimental.deploymentId, deploymentId: nextConfig.experimental.deploymentId,
experimental: { ppr: nextConfig.experimental.ppr === true }, experimental: {
ppr: nextConfig.experimental.ppr === true,
missingSuspenseWithCSRBailout:
nextConfig.experimental.missingSuspenseWithCSRBailout === true,
},
} }
const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig const { serverRuntimeConfig, publicRuntimeConfig } = nextConfig
......
...@@ -16,6 +16,7 @@ import { ...@@ -16,6 +16,7 @@ import {
} from '../../lib/constants' } from '../../lib/constants'
import { hasNextSupport } from '../../telemetry/ci-info' import { hasNextSupport } from '../../telemetry/ci-info'
import { lazyRenderAppPage } from '../../server/future/route-modules/app-page/module.render' import { lazyRenderAppPage } from '../../server/future/route-modules/app-page/module.render'
import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
export const enum ExportedAppPageFiles { export const enum ExportedAppPageFiles {
HTML = 'HTML', HTML = 'HTML',
...@@ -139,11 +140,20 @@ export async function exportAppPage( ...@@ -139,11 +140,20 @@ export async function exportAppPage(
hasPostponed: Boolean(postponed), hasPostponed: Boolean(postponed),
revalidate, revalidate,
} }
} catch (err: any) { } catch (err) {
if (!isDynamicUsageError(err)) { if (!isDynamicUsageError(err)) {
throw err throw err
} }
// If enabled, we should fail rendering if a client side rendering bailout
// occurred at the page level.
if (
renderOpts.experimental.missingSuspenseWithCSRBailout &&
isBailoutToCSRError(err)
) {
throw err
}
if (debugOutput) { if (debugOutput) {
const { dynamicUsageDescription, dynamicUsageStack } = (renderOpts as any) const { dynamicUsageDescription, dynamicUsageStack } = (renderOpts as any)
.store .store
......
...@@ -15,7 +15,7 @@ import { ...@@ -15,7 +15,7 @@ import {
NEXT_DATA_SUFFIX, NEXT_DATA_SUFFIX,
SERVER_PROPS_EXPORT_ERROR, SERVER_PROPS_EXPORT_ERROR,
} from '../../lib/constants' } from '../../lib/constants'
import { isBailoutCSRError } from '../../shared/lib/lazy-dynamic/no-ssr-error' import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import AmpHtmlValidator from 'next/dist/compiled/amphtml-validator' import AmpHtmlValidator from 'next/dist/compiled/amphtml-validator'
import { FileType, fileExists } from '../../lib/file-exists' import { FileType, fileExists } from '../../lib/file-exists'
import { lazyRenderPagesPage } from '../../server/future/route-modules/pages/module.render' import { lazyRenderPagesPage } from '../../server/future/route-modules/pages/module.render'
...@@ -105,10 +105,8 @@ export async function exportPages( ...@@ -105,10 +105,8 @@ export async function exportPages(
query, query,
renderOpts renderOpts
) )
} catch (err: any) { } catch (err) {
if (!isBailoutCSRError(err)) { if (!isBailoutToCSRError(err)) throw err
throw err
}
} }
} }
...@@ -163,10 +161,8 @@ export async function exportPages( ...@@ -163,10 +161,8 @@ export async function exportPages(
{ ...query, amp: '1' }, { ...query, amp: '1' },
renderOpts renderOpts
) )
} catch (err: any) { } catch (err) {
if (!isBailoutCSRError(err)) { if (!isBailoutToCSRError(err)) throw err
throw err
}
} }
const ampHtml = const ampHtml =
......
...@@ -35,6 +35,7 @@ import { createIncrementalCache } from './helpers/create-incremental-cache' ...@@ -35,6 +35,7 @@ import { createIncrementalCache } from './helpers/create-incremental-cache'
import { isPostpone } from '../server/lib/router-utils/is-postpone' import { isPostpone } from '../server/lib/router-utils/is-postpone'
import { isMissingPostponeDataError } from '../server/app-render/is-missing-postpone-error' import { isMissingPostponeDataError } from '../server/app-render/is-missing-postpone-error'
import { isDynamicUsageError } from './helpers/is-dynamic-usage-error' import { isDynamicUsageError } from './helpers/is-dynamic-usage-error'
import { isBailoutToCSRError } from '../shared/lib/lazy-dynamic/bailout-to-csr'
const envConfig = require('../shared/lib/runtime-config.external') const envConfig = require('../shared/lib/runtime-config.external')
...@@ -318,9 +319,11 @@ async function exportPageImpl( ...@@ -318,9 +319,11 @@ async function exportPageImpl(
// if this is a postpone error, it's logged elsewhere, so no need to log it again here // if this is a postpone error, it's logged elsewhere, so no need to log it again here
if (!isMissingPostponeDataError(err)) { if (!isMissingPostponeDataError(err)) {
console.error( console.error(
`\nError occurred prerendering page "${path}". Read more: https://nextjs.org/docs/messages/prerender-error\n` + `\nError occurred prerendering page "${path}". Read more: https://nextjs.org/docs/messages/prerender-error\n`
(isError(err) && err.stack ? err.stack : err)
) )
if (!isBailoutToCSRError(err)) {
console.error(isError(err) && err.stack ? err.stack : err)
}
} }
return { error: true } return { error: true }
......
...@@ -63,7 +63,7 @@ import { parseAndValidateFlightRouterState } from './parse-and-validate-flight-r ...@@ -63,7 +63,7 @@ import { parseAndValidateFlightRouterState } from './parse-and-validate-flight-r
import { validateURL } from './validate-url' import { validateURL } from './validate-url'
import { createFlightRouterStateFromLoaderTree } from './create-flight-router-state-from-loader-tree' import { createFlightRouterStateFromLoaderTree } from './create-flight-router-state-from-loader-tree'
import { handleAction } from './action-handler' import { handleAction } from './action-handler'
import { isBailoutCSRError } from '../../shared/lib/lazy-dynamic/no-ssr-error' import { isBailoutToCSRError } from '../../shared/lib/lazy-dynamic/bailout-to-csr'
import { warn, error } from '../../build/output/log' import { warn, error } from '../../build/output/log'
import { appendMutableCookies } from '../web/spec-extension/adapters/request-cookies' import { appendMutableCookies } from '../web/spec-extension/adapters/request-cookies'
import { createServerInsertedHTML } from './server-inserted-html' import { createServerInsertedHTML } from './server-inserted-html'
...@@ -77,8 +77,9 @@ import { setReferenceManifestsSingleton } from './action-encryption-utils' ...@@ -77,8 +77,9 @@ import { setReferenceManifestsSingleton } from './action-encryption-utils'
import { createStaticRenderer } from './static/static-renderer' import { createStaticRenderer } from './static/static-renderer'
import { MissingPostponeDataError } from './is-missing-postpone-error' import { MissingPostponeDataError } from './is-missing-postpone-error'
import { DetachedPromise } from '../../lib/detached-promise' import { DetachedPromise } from '../../lib/detached-promise'
import { DYNAMIC_ERROR_CODE } from '../../client/components/hooks-server-context' import { isDynamicServerError } from '../../client/components/hooks-server-context'
import { useFlightResponse } from './use-flight-response' import { useFlightResponse } from './use-flight-response'
import { isStaticGenBailoutError } from '../../client/components/static-generation-bailout'
export type GetDynamicParamFromSegment = ( export type GetDynamicParamFromSegment = (
// [slug] / [[slug]] / [...slug] // [slug] / [[slug]] / [...slug]
...@@ -306,6 +307,23 @@ async function generateFlight( ...@@ -306,6 +307,23 @@ async function generateFlight(
return new FlightRenderResult(flightReadableStream) return new FlightRenderResult(flightReadableStream)
} }
type RenderToStreamResult = {
stream: RenderResultResponse
err?: unknown
}
type RenderToStreamOptions = {
/**
* This option is used to indicate that the page should be rendered as
* if it was not found. When it's enabled, instead of rendering the
* page component, it renders the not-found segment.
*
*/
asNotFound: boolean
tree: LoaderTree
formState: any
}
/** /**
* Creates a resolver that eagerly generates a flight payload that is then * Creates a resolver that eagerly generates a flight payload that is then
* resolved when the resolver is called. * resolved when the resolver is called.
...@@ -804,23 +822,6 @@ async function renderToHTMLOrFlightImpl( ...@@ -804,23 +822,6 @@ async function renderToHTMLOrFlightImpl(
// response directly. // response directly.
const onHeadersFinished = new DetachedPromise<void>() const onHeadersFinished = new DetachedPromise<void>()
type RenderToStreamResult = {
stream: RenderResultResponse
err?: Error
}
type RenderToStreamOptions = {
/**
* This option is used to indicate that the page should be rendered as
* if it was not found. When it's enabled, instead of rendering the
* page component, it renders the not-found segment.
*
*/
asNotFound: boolean
tree: LoaderTree
formState: any
}
const renderToStream = getTracer().wrap( const renderToStream = getTracer().wrap(
AppRenderSpan.getBodyResult, AppRenderSpan.getBodyResult,
{ {
...@@ -979,29 +980,43 @@ async function renderToHTMLOrFlightImpl( ...@@ -979,29 +980,43 @@ async function renderToHTMLOrFlightImpl(
} }
return { stream } return { stream }
} catch (err: any) { } catch (err) {
if ( if (
err.code === 'NEXT_STATIC_GEN_BAILOUT' || isStaticGenBailoutError(err) ||
err.message?.includes( (typeof err === 'object' &&
'https://nextjs.org/docs/advanced-features/static-html-export' err !== null &&
) 'message' in err &&
typeof err.message === 'string' &&
err.message.includes(
'https://nextjs.org/docs/advanced-features/static-html-export'
))
) { ) {
// Ensure that "next dev" prints the red error overlay // Ensure that "next dev" prints the red error overlay
throw err throw err
} }
if (isStaticGeneration && err.digest === DYNAMIC_ERROR_CODE) { // If this is a static generation error, we need to throw it so that it
// ensure that DynamicUsageErrors bubble up during static generation // can be handled by the caller if we're in static generation mode.
// as this will indicate that the page needs to be dynamically rendered if (isStaticGeneration && isDynamicServerError(err)) {
throw err throw err
} }
// True if this error was a bailout to client side rendering error. // If a bailout made it to this point, it means it wasn't wrapped inside
const shouldBailoutToCSR = isBailoutCSRError(err) // a suspense boundary.
const shouldBailoutToCSR = isBailoutToCSRError(err)
if (shouldBailoutToCSR) { if (shouldBailoutToCSR) {
console.log()
if (renderOpts.experimental.missingSuspenseWithCSRBailout) {
error(
`${err.reason} should be wrapped in a suspense boundary at page "${pagePath}". Read more: https://nextjs.org/docs/messages/missing-suspense-with-csr-bailout`
)
throw err
}
warn( warn(
`Entire page ${pagePath} deopted into client-side rendering. https://nextjs.org/docs/messages/deopted-into-client-rendering`, `Entire page "${pagePath}" deopted into client-side rendering due to "${err.reason}". Read more: https://nextjs.org/docs/messages/deopted-into-client-rendering`
pagePath
) )
} }
...@@ -1212,7 +1227,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -1212,7 +1227,7 @@ async function renderToHTMLOrFlightImpl(
renderOpts.experimental.ppr && renderOpts.experimental.ppr &&
staticGenerationStore.postponeWasTriggered && staticGenerationStore.postponeWasTriggered &&
!metadata.postponed && !metadata.postponed &&
(!response.err || !isBailoutCSRError(response.err)) (!response.err || !isBailoutToCSRError(response.err))
) { ) {
// a call to postpone was made but was caught and not detected by Next.js. We should fail the build immediately // a call to postpone was made but was caught and not detected by Next.js. We should fail the build immediately
// as we won't be able to generate the static part // as we won't be able to generate the static part
......
...@@ -36,9 +36,7 @@ export function createErrorHandler({ ...@@ -36,9 +36,7 @@ export function createErrorHandler({
// These errors are expected. We return the digest // These errors are expected. We return the digest
// so that they can be properly handled. // so that they can be properly handled.
if (isDynamicUsageError(err)) { if (isDynamicUsageError(err)) return err.digest
return err.digest
}
// 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(err)) return if (isAbortError(err)) return
......
...@@ -142,7 +142,7 @@ export interface RenderOptsPartial { ...@@ -142,7 +142,7 @@ export interface RenderOptsPartial {
} }
params?: ParsedUrlQuery params?: ParsedUrlQuery
isPrefetch?: boolean isPrefetch?: boolean
experimental: { ppr: boolean } experimental: { ppr: boolean; missingSuspenseWithCSRBailout: boolean }
postponed?: string postponed?: string
} }
......
...@@ -18,7 +18,7 @@ export type StaticGenerationContext = { ...@@ -18,7 +18,7 @@ export type StaticGenerationContext = {
isDraftMode?: boolean isDraftMode?: boolean
isServerAction?: boolean isServerAction?: boolean
waitUntil?: Promise<any> waitUntil?: Promise<any>
experimental: { ppr: boolean } experimental: { ppr: boolean; missingSuspenseWithCSRBailout?: boolean }
/** /**
* A hack around accessing the store value outside the context of the * A hack around accessing the store value outside the context of the
......
...@@ -258,7 +258,7 @@ type BaseRenderOpts = { ...@@ -258,7 +258,7 @@ type BaseRenderOpts = {
appDirDevErrorLogger?: (err: any) => Promise<void> appDirDevErrorLogger?: (err: any) => Promise<void>
strictNextHead: boolean strictNextHead: boolean
isExperimentalCompile?: boolean isExperimentalCompile?: boolean
experimental: { ppr: boolean } experimental: { ppr: boolean; missingSuspenseWithCSRBailout: boolean }
} }
export interface BaseRequestHandler { export interface BaseRequestHandler {
...@@ -548,6 +548,8 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -548,6 +548,8 @@ export default abstract class Server<ServerOptions extends Options = Options> {
ppr: ppr:
this.enabledDirectories.app && this.enabledDirectories.app &&
this.nextConfig.experimental.ppr === true, this.nextConfig.experimental.ppr === true,
missingSuspenseWithCSRBailout:
this.nextConfig.experimental.missingSuspenseWithCSRBailout === true,
}, },
} }
......
...@@ -370,6 +370,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() => ...@@ -370,6 +370,7 @@ export const configSchema: zod.ZodType<NextConfig> = z.lazy(() =>
staticWorkerRequestDeduping: z.boolean().optional(), staticWorkerRequestDeduping: z.boolean().optional(),
useWasmBinary: z.boolean().optional(), useWasmBinary: z.boolean().optional(),
useLightningcss: z.boolean().optional(), useLightningcss: z.boolean().optional(),
missingSuspenseWithCSRBailout: z.boolean().optional(),
}) })
.optional(), .optional(),
exportPathMap: z exportPathMap: z
......
...@@ -379,6 +379,16 @@ export interface ExperimentalConfig { ...@@ -379,6 +379,16 @@ export interface ExperimentalConfig {
* Use lightningcss instead of swc_css * Use lightningcss instead of swc_css
*/ */
useLightningcss?: boolean useLightningcss?: boolean
/**
* Certain methods calls like `useSearchParams()` can bail out of server-side rendering of **entire** pages to client-side rendering,
* if they are not wrapped in a suspense boundary.
*
* When this flag is set to `true`, Next.js will break the build instead of warning, to force the developer to add a suspense boundary above the method call.
*
* @default false
*/
missingSuspenseWithCSRBailout?: boolean
} }
export type ExportPathMap = { export type ExportPathMap = {
...@@ -840,6 +850,7 @@ export const defaultConfig: NextConfig = { ...@@ -840,6 +850,7 @@ export const defaultConfig: NextConfig = {
? true ? true
: false, : false,
webpackBuildWorker: undefined, webpackBuildWorker: undefined,
missingSuspenseWithCSRBailout: false,
}, },
} }
......
// This has to be a shared module which is shared between client component error boundary and dynamic component
const BAILOUT_TO_CSR = 'BAILOUT_TO_CLIENT_SIDE_RENDERING'
/** An error that should be thrown when we want to bail out to client-side rendering. */
export class BailoutToCSRError extends Error {
public readonly digest = BAILOUT_TO_CSR
constructor(public readonly reason: string) {
super(`Bail out to client-side rendering: ${reason}`)
}
}
/** Checks if a passed argument is an error that is thrown if we want to bail out to client-side rendering. */
export function isBailoutToCSRError(err: unknown): err is BailoutToCSRError {
if (typeof err !== 'object' || err === null || !('digest' in err)) {
return false
}
return err.digest === BAILOUT_TO_CSR
}
'use client'
import type { ReactElement } from 'react'
import { BailoutToCSRError } from './bailout-to-csr'
interface BailoutToCSRProps {
reason: string
children: ReactElement
}
/**
* If rendered on the server, this component throws an error
* to signal Next.js that it should bail out to client-side rendering instead.
*/
export function BailoutToCSR({ reason, children }: BailoutToCSRProps) {
if (typeof window === 'undefined') {
throw new BailoutToCSRError(reason)
}
return children
}
'use client'
import type React from 'react'
import { throwWithNoSSR } from './no-ssr-error'
type Child = React.ReactElement<any, any>
export function NoSSR({ children }: { children: Child }): Child {
if (typeof window === 'undefined') {
throwWithNoSSR()
}
return children
}
import { Suspense, lazy, Fragment } from 'react' import { Suspense, lazy } from 'react'
import { NoSSR } from './dynamic-no-ssr' import { BailoutToCSR } from './dynamic-bailout-to-csr'
import type { ComponentModule } from './types' import type { ComponentModule } from './types'
// Normalize loader to return the module as form { default: Component } for `React.lazy`. // Normalize loader to return the module as form { default: Component } for `React.lazy`.
// Also for backward compatible since next/dynamic allows to resolve a component directly with loader // Also for backward compatible since next/dynamic allows to resolve a component directly with loader
// Client component reference proxy need to be converted to a module. // Client component reference proxy need to be converted to a module.
function convertModule<P>(mod: React.ComponentType<P> | ComponentModule<P>) { function convertModule<P>(mod: React.ComponentType<P> | ComponentModule<P>) {
return { default: (mod as ComponentModule<P>)?.default || mod } return { default: (mod as ComponentModule<P>)?.default ?? mod }
} }
function Loadable(options: any) { const defaultOptions = {
const opts = { loader: () => Promise.resolve(convertModule(() => null)),
loader: null, loading: null,
loading: null, ssr: true,
ssr: true, }
...options,
}
const loader = () => interface LoadableOptions {
opts.loader != null loader?: () => Promise<React.ComponentType<any> | ComponentModule<any>>
? opts.loader().then(convertModule) loading?: React.ComponentType<any> | null
: Promise.resolve(convertModule(() => null)) ssr?: boolean
}
const Lazy = lazy(loader) function Loadable(options: LoadableOptions) {
const opts = { ...defaultOptions, ...options }
const Lazy = lazy(() => opts.loader().then(convertModule))
const Loading = opts.loading const Loading = opts.loading
const Wrap = opts.ssr ? Fragment : NoSSR
function LoadableComponent(props: any) { function LoadableComponent(props: any) {
const fallbackElement = Loading ? ( const fallbackElement = Loading ? (
<Loading isLoading={true} pastDelay={true} error={null} /> <Loading isLoading={true} pastDelay={true} error={null} />
) : null ) : null
return ( const children = opts.ssr ? (
<Suspense fallback={fallbackElement}> <Lazy {...props} />
<Wrap> ) : (
<Lazy {...props} /> <BailoutToCSR reason="next/dynamic">
</Wrap> <Lazy {...props} />
</Suspense> </BailoutToCSR>
) )
return <Suspense fallback={fallbackElement}>{children}</Suspense>
} }
LoadableComponent.displayName = 'LoadableComponent' LoadableComponent.displayName = 'LoadableComponent'
......
// This has to be a shared module which is shared between client component error boundary and dynamic component
export const NEXT_DYNAMIC_NO_SSR_CODE = 'NEXT_DYNAMIC_NO_SSR_CODE'
export function throwWithNoSSR() {
const error = new Error(NEXT_DYNAMIC_NO_SSR_CODE)
;(error as any).digest = NEXT_DYNAMIC_NO_SSR_CODE
throw error
}
export function isBailoutCSRError(err: any) {
return err?.digest === NEXT_DYNAMIC_NO_SSR_CODE
}
import UseSearchParams from '../search-params'
export default function Page() {
return (
<>
<p id="hooks-use-search-params" />
<UseSearchParams />
</>
)
}
...@@ -13,7 +13,7 @@ module.exports = { ...@@ -13,7 +13,7 @@ module.exports = {
afterFiles: [ afterFiles: [
{ {
source: '/rewritten-use-search-params', source: '/rewritten-use-search-params',
destination: '/hooks/use-search-params/static-bailout', destination: '/hooks/use-search-params/with-suspense',
}, },
{ {
source: '/rewritten-use-pathname', source: '/rewritten-use-pathname',
......
'use client' 'use client'
import { useSearchParams } from 'next/navigation' import { useSearchParams } from 'next/navigation'
import { Suspense } from 'react'
export default function Page() { export default function Page() {
return (
<Suspense fallback={<div>Loading...</div>}>
<Component />
</Suspense>
)
}
function Component() {
const params = useSearchParams() const params = useSearchParams()
return ( return (
......
export default () => {
return <div id="dynamic">Hello, world!</div>
}
import dynamic from 'next/dynamic'
const Dynamic = dynamic(() => import('./dynamic'), {
ssr: false,
})
export default () => {
return <Dynamic />
}
export default function Layout({ children }) {
return (
<html>
<head />
<body>{children}</body>
</html>
)
}
import { Suspense } from 'react'
export default function Layout({ children }) {
return (
<html>
<head />
<body>
<Suspense fallback={<div>Loading...</div>}>{children}</Suspense>
</body>
</html>
)
}
'use client'
import { useSearchParams } from 'next/navigation'
export default function Page() {
useSearchParams()
return <div>Page</div>
}
import { createNextDescribe } from 'e2e-utils'
createNextDescribe(
'missing-suspense-with-csr-bailout',
{
files: __dirname,
skipStart: true,
},
({ next, isNextDev }) => {
if (isNextDev) {
it.skip('skip test for dev mode', () => {})
return
}
beforeEach(async () => {
await next.clean()
})
describe('useSearchParams', () => {
const message = `useSearchParams() should be wrapped in a suspense boundary at page "/".`
it('should pass build if useSearchParams is wrapped in a suspense boundary', async () => {
await expect(next.build()).resolves.toEqual({
exitCode: 0,
cliOutput: expect.not.stringContaining(message),
})
})
it('should fail build if useSearchParams is not wrapped in a suspense boundary', async () => {
await next.renameFile('app/layout.js', 'app/layout-suspense.js')
await next.renameFile('app/layout-no-suspense.js', 'app/layout.js')
await expect(next.build()).resolves.toEqual({
exitCode: 1,
cliOutput: expect.stringContaining(message),
})
await next.renameFile('app/layout.js', 'app/layout-no-suspense.js')
await next.renameFile('app/layout-suspense.js', 'app/layout.js')
})
})
describe('next/dynamic', () => {
beforeEach(async () => {
await next.start()
})
it('does not emit errors related to bailing out of client side rendering', async () => {
const browser = await next.browser('/dynamic', {
pushErrorAsConsoleLog: true,
})
try {
await browser.waitForElementByCss('#dynamic')
// await new Promise((resolve) => setTimeout(resolve, 1000))
expect(await browser.log()).not.toContainEqual(
expect.objectContaining({
source: 'error',
})
)
} finally {
await browser.close()
}
})
})
}
)
/** @type {import("next").NextConfig} */
const config = {
experimental: {
missingSuspenseWithCSRBailout: true,
},
}
module.exports = config
...@@ -13,7 +13,9 @@ export default function Root({ children }) { ...@@ -13,7 +13,9 @@ export default function Root({ children }) {
return ( return (
<html className="root-layout-html"> <html className="root-layout-html">
<body> <body>
<NotFoundTrigger /> <React.Suspense fallback={<div>Loading...</div>}>
<NotFoundTrigger />
</React.Suspense>
<button id="trigger-not-found" onClick={() => setClicked(true)}> <button id="trigger-not-found" onClick={() => setClicked(true)}>
Click to not found Click to not found
</button> </button>
......
...@@ -129,10 +129,12 @@ export abstract class BrowserInterface implements PromiseLike<any> { ...@@ -129,10 +129,12 @@ export abstract class BrowserInterface implements PromiseLike<any> {
disableCache, disableCache,
cpuThrottleRate, cpuThrottleRate,
beforePageLoad, beforePageLoad,
pushErrorAsConsoleLog,
}: { }: {
disableCache?: boolean disableCache?: boolean
cpuThrottleRate?: number cpuThrottleRate?: number
beforePageLoad?: Function beforePageLoad?: Function
pushErrorAsConsoleLog?: boolean
} }
): Promise<void> {} ): Promise<void> {}
async get(url: string): Promise<void> {} async get(url: string): Promise<void> {}
......
...@@ -197,6 +197,7 @@ export class Playwright extends BrowserInterface { ...@@ -197,6 +197,7 @@ export class Playwright extends BrowserInterface {
opts?: { opts?: {
disableCache: boolean disableCache: boolean
cpuThrottleRate: number cpuThrottleRate: number
pushErrorAsConsoleLog?: boolean
beforePageLoad?: (...args: any[]) => void beforePageLoad?: (...args: any[]) => void
} }
) { ) {
...@@ -225,6 +226,10 @@ export class Playwright extends BrowserInterface { ...@@ -225,6 +226,10 @@ export class Playwright extends BrowserInterface {
}) })
page.on('pageerror', (error) => { page.on('pageerror', (error) => {
console.error('page error', error) console.error('page error', error)
if (opts?.pushErrorAsConsoleLog) {
pageLogs.push({ source: 'error', message: error.message })
}
}) })
page.on('request', (req) => { page.on('request', (req) => {
this.eventCallbacks.request.forEach((cb) => cb(req)) this.eventCallbacks.request.forEach((cb) => cb(req))
......
import os from 'os' import os from 'os'
import path from 'path' import path from 'path'
import fs from 'fs-extra' import { existsSync, promises as fs } from 'fs'
import treeKill from 'tree-kill' import treeKill from 'tree-kill'
import type { NextConfig } from 'next' import type { NextConfig } from 'next'
import { FileRef } from '../e2e-utils' import { FileRef } from '../e2e-utils'
...@@ -101,17 +101,18 @@ export class NextInstance { ...@@ -101,17 +101,18 @@ export class NextInstance {
`FileRef passed to "files" in "createNext" is not a directory ${files.fsPath}` `FileRef passed to "files" in "createNext" is not a directory ${files.fsPath}`
) )
} }
await fs.copy(files.fsPath, this.testDir)
await fs.cp(files.fsPath, this.testDir, { recursive: true })
} else { } else {
for (const filename of Object.keys(files)) { for (const filename of Object.keys(files)) {
const item = files[filename] const item = files[filename]
const outputFilename = path.join(this.testDir, filename) const outputFilename = path.join(this.testDir, filename)
if (typeof item === 'string') { if (typeof item === 'string') {
await fs.ensureDir(path.dirname(outputFilename)) await fs.mkdir(path.dirname(outputFilename), { recursive: true })
await fs.writeFile(outputFilename, item) await fs.writeFile(outputFilename, item)
} else { } else {
await fs.copy(item.fsPath, outputFilename) await fs.cp(item.fsPath, outputFilename, { recursive: true })
} }
} }
} }
...@@ -159,7 +160,7 @@ export class NextInstance { ...@@ -159,7 +160,7 @@ export class NextInstance {
if (skipInstall || skipIsolatedNext) { if (skipInstall || skipIsolatedNext) {
const pkgScripts = (this.packageJson['scripts'] as {}) || {} const pkgScripts = (this.packageJson['scripts'] as {}) || {}
await fs.ensureDir(this.testDir) await fs.mkdir(this.testDir, { recursive: true })
await fs.writeFile( await fs.writeFile(
path.join(this.testDir, 'package.json'), path.join(this.testDir, 'package.json'),
JSON.stringify( JSON.stringify(
...@@ -194,7 +195,9 @@ export class NextInstance { ...@@ -194,7 +195,9 @@ export class NextInstance {
!this.packageJson && !this.packageJson &&
!(global as any).isNextDeploy !(global as any).isNextDeploy
) { ) {
await fs.copy(process.env.NEXT_TEST_STARTER, this.testDir) await fs.cp(process.env.NEXT_TEST_STARTER, this.testDir, {
recursive: true,
})
} else { } else {
const { installDir } = await createNextInstall({ const { installDir } = await createNextInstall({
parentSpan: rootSpan, parentSpan: rootSpan,
...@@ -219,7 +222,7 @@ export class NextInstance { ...@@ -219,7 +222,7 @@ export class NextInstance {
file.startsWith('next.config.') file.startsWith('next.config.')
) )
if (await fs.pathExists(path.join(this.testDir, 'next.config.js'))) { if (existsSync(path.join(this.testDir, 'next.config.js'))) {
nextConfigFile = 'next.config.js' nextConfigFile = 'next.config.js'
} }
...@@ -317,7 +320,10 @@ export class NextInstance { ...@@ -317,7 +320,10 @@ export class NextInstance {
] ]
for (const file of await fs.readdir(this.testDir)) { for (const file of await fs.readdir(this.testDir)) {
if (!keptFiles.includes(file)) { if (!keptFiles.includes(file)) {
await fs.remove(path.join(this.testDir, file)) await fs.rm(path.join(this.testDir, file), {
recursive: true,
force: true,
})
} }
} }
await this.writeInitialFiles() await this.writeInitialFiles()
...@@ -359,7 +365,7 @@ export class NextInstance { ...@@ -359,7 +365,7 @@ export class NextInstance {
if (process.env.TRACE_PLAYWRIGHT) { if (process.env.TRACE_PLAYWRIGHT) {
await fs await fs
.copy( .cp(
path.join(this.testDir, '.next/trace'), path.join(this.testDir, '.next/trace'),
path.join( path.join(
__dirname, __dirname,
...@@ -371,7 +377,8 @@ export class NextInstance { ...@@ -371,7 +377,8 @@ export class NextInstance {
) )
.replace(/\//g, '-')}`, .replace(/\//g, '-')}`,
`next-trace` `next-trace`
) ),
{ recursive: true }
) )
.catch((e) => { .catch((e) => {
require('console').error(e) require('console').error(e)
...@@ -379,7 +386,7 @@ export class NextInstance { ...@@ -379,7 +386,7 @@ export class NextInstance {
} }
if (!process.env.NEXT_TEST_SKIP_CLEANUP) { if (!process.env.NEXT_TEST_SKIP_CLEANUP) {
await fs.remove(this.testDir) await fs.rm(this.testDir, { recursive: true, force: true })
} }
require('console').log(`destroyed next instance`) require('console').log(`destroyed next instance`)
} catch (err) { } catch (err) {
...@@ -405,13 +412,15 @@ export class NextInstance { ...@@ -405,13 +412,15 @@ export class NextInstance {
// TODO: block these in deploy mode // TODO: block these in deploy mode
public async hasFile(filename: string) { public async hasFile(filename: string) {
return fs.pathExists(path.join(this.testDir, filename)) return existsSync(path.join(this.testDir, filename))
} }
public async readFile(filename: string) { public async readFile(filename: string) {
return fs.readFile(path.join(this.testDir, filename), 'utf8') return fs.readFile(path.join(this.testDir, filename), 'utf8')
} }
public async readJSON(filename: string) { public async readJSON(filename: string) {
return fs.readJSON(path.join(this.testDir, filename)) return JSON.parse(
await fs.readFile(path.join(this.testDir, filename), 'utf-8')
)
} }
private async handleDevWatchDelayBeforeChange(filename: string) { private async handleDevWatchDelayBeforeChange(filename: string) {
// This is a temporary workaround for turbopack starting watching too late. // This is a temporary workaround for turbopack starting watching too late.
...@@ -443,8 +452,8 @@ export class NextInstance { ...@@ -443,8 +452,8 @@ export class NextInstance {
await this.handleDevWatchDelayBeforeChange(filename) await this.handleDevWatchDelayBeforeChange(filename)
const outputPath = path.join(this.testDir, filename) const outputPath = path.join(this.testDir, filename)
const newFile = !(await fs.pathExists(outputPath)) const newFile = !existsSync(outputPath)
await fs.ensureDir(path.dirname(outputPath)) await fs.mkdir(path.dirname(outputPath), { recursive: true })
await fs.writeFile( await fs.writeFile(
outputPath, outputPath,
typeof content === 'function' typeof content === 'function'
...@@ -467,12 +476,13 @@ export class NextInstance { ...@@ -467,12 +476,13 @@ export class NextInstance {
path.join(this.testDir, filename), path.join(this.testDir, filename),
path.join(this.testDir, newFilename) path.join(this.testDir, newFilename)
) )
await this.handleDevWatchDelayAfterChange(filename) await this.handleDevWatchDelayAfterChange(filename)
} }
public async renameFolder(foldername: string, newFoldername: string) { public async renameFolder(foldername: string, newFoldername: string) {
await this.handleDevWatchDelayBeforeChange(foldername) await this.handleDevWatchDelayBeforeChange(foldername)
await fs.move( await fs.rename(
path.join(this.testDir, foldername), path.join(this.testDir, foldername),
path.join(this.testDir, newFoldername) path.join(this.testDir, newFoldername)
) )
...@@ -481,7 +491,11 @@ export class NextInstance { ...@@ -481,7 +491,11 @@ export class NextInstance {
public async deleteFile(filename: string) { public async deleteFile(filename: string) {
await this.handleDevWatchDelayBeforeChange(filename) await this.handleDevWatchDelayBeforeChange(filename)
await fs.remove(path.join(this.testDir, filename)) await fs.rm(path.join(this.testDir, filename), {
recursive: true,
force: true,
})
await this.handleDevWatchDelayAfterChange(filename) await this.handleDevWatchDelayAfterChange(filename)
} }
......
...@@ -69,6 +69,7 @@ export default async function webdriver( ...@@ -69,6 +69,7 @@ export default async function webdriver(
headless?: boolean headless?: boolean
ignoreHTTPSErrors?: boolean ignoreHTTPSErrors?: boolean
cpuThrottleRate?: number cpuThrottleRate?: number
pushErrorAsConsoleLog?: boolean
} }
): Promise<BrowserInterface> { ): Promise<BrowserInterface> {
let CurrentInterface: new () => BrowserInterface let CurrentInterface: new () => BrowserInterface
...@@ -89,6 +90,7 @@ export default async function webdriver( ...@@ -89,6 +90,7 @@ export default async function webdriver(
ignoreHTTPSErrors, ignoreHTTPSErrors,
headless, headless,
cpuThrottleRate, cpuThrottleRate,
pushErrorAsConsoleLog,
} = options } = options
// we import only the needed interface // we import only the needed interface
...@@ -133,6 +135,7 @@ export default async function webdriver( ...@@ -133,6 +135,7 @@ export default async function webdriver(
disableCache, disableCache,
cpuThrottleRate, cpuThrottleRate,
beforePageLoad, beforePageLoad,
pushErrorAsConsoleLog,
}) })
console.log(`\n> Loaded browser with ${fullUrl}\n`) console.log(`\n> Loaded browser with ${fullUrl}\n`)
......
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