Unverified Commit ce77607e authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Update error handling during app static generation (#40823)

This updates to ensure we properly error during static generation when a
non-dynamic SSR error is thrown so that unexpected errors are not
tolerated. This also fixes the static generation async storage not being
shared correctly due to different instances being created during
bundling.
parent 1bbd2642
...@@ -192,6 +192,8 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{ ...@@ -192,6 +192,8 @@ const nextAppLoader: webpack.LoaderDefinitionFunction<{
: 'null' : 'null'
} }
export const staticGenerationAsyncStorage = require('next/dist/client/components/static-generation-async-storage.js').staticGenerationAsyncStorage
export const serverHooks = require('next/dist/client/components/hooks-server-context.js') export const serverHooks = require('next/dist/client/components/hooks-server-context.js')
export const renderToReadableStream = require('next/dist/compiled/react-server-dom-webpack/writer.browser.server').renderToReadableStream export const renderToReadableStream = require('next/dist/compiled/react-server-dom-webpack/writer.browser.server').renderToReadableStream
......
...@@ -17,8 +17,8 @@ export function redirect(url: string) { ...@@ -17,8 +17,8 @@ export function redirect(url: string) {
use(createInfinitePromise()) use(createInfinitePromise())
} }
// eslint-disable-next-line no-throw-literal // eslint-disable-next-line no-throw-literal
throw { const error = new Error(REDIRECT_ERROR_CODE)
url, ;(error as any).url = url
code: REDIRECT_ERROR_CODE, ;(error as any).code = REDIRECT_ERROR_CODE
} throw error
} }
...@@ -75,7 +75,8 @@ function createErrorHandler( ...@@ -75,7 +75,8 @@ function createErrorHandler(
/** /**
* Used for debugging * Used for debugging
*/ */
_source: string _source: string,
capturedErrors: Error[]
) { ) {
return (err: any) => { return (err: any) => {
if ( if (
...@@ -83,23 +84,18 @@ function createErrorHandler( ...@@ -83,23 +84,18 @@ function createErrorHandler(
err.message && err.message &&
!err.message.includes('Dynamic server usage') && !err.message.includes('Dynamic server usage') &&
// TODO-APP: Handle redirect throw // TODO-APP: Handle redirect throw
err.code !== REDIRECT_ERROR_CODE err.code !== REDIRECT_ERROR_CODE &&
err.message !== REDIRECT_ERROR_CODE
) { ) {
// Used for debugging error source // Used for debugging error source
// console.error(_source, err) // console.error(_source, err)
console.error(err) console.error(err)
capturedErrors.push(err)
} }
return null return null
} }
} }
const serverComponentsErrorHandler = createErrorHandler(
'serverComponentsRenderer'
)
const flightDataRendererErrorHandler = createErrorHandler('flightDataRenderer')
const htmlRendererErrorHandler = createErrorHandler('htmlRenderer')
let isFetchPatched = false let isFetchPatched = false
// we patch fetch to collect cache information used for // we patch fetch to collect cache information used for
...@@ -111,8 +107,7 @@ function patchFetch(ComponentMod: any) { ...@@ -111,8 +107,7 @@ function patchFetch(ComponentMod: any) {
const { DynamicServerError } = const { DynamicServerError } =
ComponentMod.serverHooks as typeof import('../client/components/hooks-server-context') ComponentMod.serverHooks as typeof import('../client/components/hooks-server-context')
const { staticGenerationAsyncStorage } = const staticGenerationAsyncStorage = ComponentMod.staticGenerationAsyncStorage
require('../client/components/static-generation-async-storage') as typeof import('../client/components/static-generation-async-storage')
const origFetch = (global as any).fetch const origFetch = (global as any).fetch
...@@ -244,6 +239,7 @@ function createServerComponentRenderer( ...@@ -244,6 +239,7 @@ function createServerComponentRenderer(
> >
rscChunks: Uint8Array[] rscChunks: Uint8Array[]
}, },
serverComponentsErrorHandler: ReturnType<typeof createErrorHandler>,
nonce?: string nonce?: string
): () => JSX.Element { ): () => JSX.Element {
// We need to expose the `__webpack_require__` API globally for // We need to expose the `__webpack_require__` API globally for
...@@ -518,6 +514,21 @@ export async function renderToHTMLOrFlight( ...@@ -518,6 +514,21 @@ export async function renderToHTMLOrFlight(
isPagesDir: boolean, isPagesDir: boolean,
isStaticGeneration: boolean = false isStaticGeneration: boolean = false
): Promise<RenderResult | null> { ): Promise<RenderResult | null> {
const capturedErrors: Error[] = []
const serverComponentsErrorHandler = createErrorHandler(
'serverComponentsRenderer',
capturedErrors
)
const flightDataRendererErrorHandler = createErrorHandler(
'flightDataRenderer',
capturedErrors
)
const htmlRendererErrorHandler = createErrorHandler(
'htmlRenderer',
capturedErrors
)
const { const {
buildManifest, buildManifest,
subresourceIntegrityManifest, subresourceIntegrityManifest,
...@@ -529,8 +540,7 @@ export async function renderToHTMLOrFlight( ...@@ -529,8 +540,7 @@ export async function renderToHTMLOrFlight(
patchFetch(ComponentMod) patchFetch(ComponentMod)
const { staticGenerationAsyncStorage } = const staticGenerationAsyncStorage = ComponentMod.staticGenerationAsyncStorage
require('../client/components/static-generation-async-storage') as typeof import('../client/components/static-generation-async-storage')
if ( if (
!('getStore' in staticGenerationAsyncStorage) && !('getStore' in staticGenerationAsyncStorage) &&
...@@ -771,6 +781,13 @@ export async function renderToHTMLOrFlight( ...@@ -771,6 +781,13 @@ export async function renderToHTMLOrFlight(
if (layoutOrPageMod?.config) { if (layoutOrPageMod?.config) {
defaultRevalidate = layoutOrPageMod.config.revalidate defaultRevalidate = layoutOrPageMod.config.revalidate
if (isStaticGeneration && defaultRevalidate === 0) {
const { DynamicServerError } =
ComponentMod.serverHooks as typeof import('../client/components/hooks-server-context')
throw new DynamicServerError(`revalidate: 0 configured ${segment}`)
}
} }
/** /**
* Checks if the current segment is a root layout. * Checks if the current segment is a root layout.
...@@ -1145,6 +1162,7 @@ export async function renderToHTMLOrFlight( ...@@ -1145,6 +1162,7 @@ export async function renderToHTMLOrFlight(
}, },
ComponentMod, ComponentMod,
serverComponentsRenderOpts, serverComponentsRenderOpts,
serverComponentsErrorHandler,
nonce nonce
) )
...@@ -1248,6 +1266,12 @@ export async function renderToHTMLOrFlight( ...@@ -1248,6 +1266,12 @@ export async function renderToHTMLOrFlight(
(await readable.getReader().read()).value || '' (await readable.getReader().read()).value || ''
).toString() ).toString()
// if we encountered any unexpected errors during build
// we fail the prerendering phase and the build
if (capturedErrors.length > 0) {
throw capturedErrors[0]
}
;(renderOpts as any).pageData = Buffer.concat( ;(renderOpts as any).pageData = Buffer.concat(
serverComponentsRenderOpts.rscChunks serverComponentsRenderOpts.rscChunks
).toString() ).toString()
...@@ -1286,7 +1310,7 @@ export async function renderToHTMLOrFlight( ...@@ -1286,7 +1310,7 @@ export async function renderToHTMLOrFlight(
return new Promise<UnwrapPromise<ReturnType<typeof renderToHTMLOrFlight>>>( return new Promise<UnwrapPromise<ReturnType<typeof renderToHTMLOrFlight>>>(
(resolve, reject) => { (resolve, reject) => {
staticGenerationAsyncStorage.run(initialStaticGenerationStore, () => { staticGenerationAsyncStorage.run(initialStaticGenerationStore, () => {
wrappedRender().then(resolve).catch(reject) return wrappedRender().then(resolve).catch(reject)
}) })
} }
) )
......
import { useCookies } from 'next/dist/client/components/hooks-server'
import Router from './router' import Router from './router'
export default function Page() { export default function Page() {
useCookies()
return ( return (
<div id="old-router"> <div id="old-router">
<Router /> <Router />
......
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