Unverified Commit 0052c590 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

add better messaging around wrapping postpone with try/catch (#57446)

when calls to `maybePostpone` throw but there's no postpone state, we want to handle those errors differently so that we can provide clearer messaging around how to prevent them, while still retaining any errors that were re-thrown by the user.

ex:
![CleanShot 2023-10-25 at 16 05 56@2x](https://github.com/vercel/next.js/assets/1939140/d86cce9f-f9ed-477d-8d1c-0ce7c934d073)
parent f412c8a9
---
title: Understanding the postpone error triggered during static generation
---
## Why This Error Occurred
When Partial Prerendering (PPR) is enabled, using APIs that opt into Dynamic Rendering like `cookies`, `headers`, or `fetch` (such as with `cache: 'no-store'` or `revalidate: 0`) will cause Next.js to throw a special error to know which part of the page cannot be statically generated. If you catch this error, Next.js will not be able to recognize that dynamic content was used and will only be able to statically render the page, opting you out of partial prerendering and lead to potentially undefined behavior.
## Possible Ways to Fix It
To resolve this issue, ensure that you are not wrapping Next.js APIs that opt into dynamic rendering in a `try/catch` block.
...@@ -18,5 +18,8 @@ export function maybePostpone( ...@@ -18,5 +18,8 @@ export function maybePostpone(
const React = require('react') as typeof import('react') const React = require('react') as typeof import('react')
if (typeof React.unstable_postpone !== 'function') return if (typeof React.unstable_postpone !== 'function') return
// Keep track of if the postpone API has been called.
staticGenerationStore.postponeWasTriggered = true
React.unstable_postpone(reason) React.unstable_postpone(reason)
} }
...@@ -27,6 +27,7 @@ export interface StaticGenerationStore { ...@@ -27,6 +27,7 @@ export interface StaticGenerationStore {
forceStatic?: boolean forceStatic?: boolean
dynamicShouldError?: boolean dynamicShouldError?: boolean
pendingRevalidates?: Promise<any>[] pendingRevalidates?: Promise<any>[]
postponeWasTriggered?: boolean
dynamicUsageDescription?: string dynamicUsageDescription?: string
dynamicUsageStack?: string dynamicUsageStack?: string
......
...@@ -7,6 +7,4 @@ export const isDynamicUsageError = (err: any) => ...@@ -7,6 +7,4 @@ export const isDynamicUsageError = (err: any) =>
err.digest === DYNAMIC_ERROR_CODE || err.digest === DYNAMIC_ERROR_CODE ||
isNotFoundError(err) || isNotFoundError(err) ||
err.digest === NEXT_DYNAMIC_NO_SSR_CODE || err.digest === NEXT_DYNAMIC_NO_SSR_CODE ||
isRedirectError(err) || isRedirectError(err)
// TODO: (wyattjoh) remove once we bump react
err.$$typeof === Symbol.for('react.postpone')
...@@ -187,10 +187,13 @@ export async function exportAppPage( ...@@ -187,10 +187,13 @@ export async function exportAppPage(
revalidate, revalidate,
} }
} catch (err: any) { } catch (err: any) {
if (!isDynamicUsageError(err)) { // if the error isn't a special dynamic usage error (caught by Next)
// we also do not throw the error if it occurred while attempting a postpone
// since those will be captured and logged during build/ISR
if (!isDynamicUsageError(err) && !renderOpts.hasPostponeErrors) {
throw err throw err
} }
return { revalidate: 0 } return { revalidate: 0, hasEmptyPrelude: true }
} }
} }
...@@ -61,7 +61,7 @@ import { validateURL } from './validate-url' ...@@ -61,7 +61,7 @@ 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 { NEXT_DYNAMIC_NO_SSR_CODE } from '../../shared/lib/lazy-dynamic/no-ssr-error' import { NEXT_DYNAMIC_NO_SSR_CODE } from '../../shared/lib/lazy-dynamic/no-ssr-error'
import { warn } 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'
import { getRequiredScripts } from './required-scripts' import { getRequiredScripts } from './required-scripts'
...@@ -463,13 +463,16 @@ async function renderToHTMLOrFlightImpl( ...@@ -463,13 +463,16 @@ async function renderToHTMLOrFlightImpl(
const capturedErrors: Error[] = [] const capturedErrors: Error[] = []
const allCapturedErrors: Error[] = [] const allCapturedErrors: Error[] = []
const postponeErrors: Error[] = []
const isNextExport = !!renderOpts.nextExport const isNextExport = !!renderOpts.nextExport
const serverComponentsErrorHandler = createErrorHandler({ const serverComponentsErrorHandler = createErrorHandler({
_source: 'serverComponentsRenderer', _source: 'serverComponentsRenderer',
dev, dev,
isNextExport, isNextExport,
postponeErrors: renderOpts.ppr ? postponeErrors : undefined,
errorLogger: appDirDevErrorLogger, errorLogger: appDirDevErrorLogger,
capturedErrors, capturedErrors,
skipLogging: renderOpts.ppr,
}) })
const flightDataRendererErrorHandler = createErrorHandler({ const flightDataRendererErrorHandler = createErrorHandler({
_source: 'flightDataRenderer', _source: 'flightDataRenderer',
...@@ -477,6 +480,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -477,6 +480,7 @@ async function renderToHTMLOrFlightImpl(
isNextExport, isNextExport,
errorLogger: appDirDevErrorLogger, errorLogger: appDirDevErrorLogger,
capturedErrors, capturedErrors,
skipLogging: renderOpts.ppr,
}) })
const htmlRendererErrorHandler = createErrorHandler({ const htmlRendererErrorHandler = createErrorHandler({
_source: 'htmlRenderer', _source: 'htmlRenderer',
...@@ -485,6 +489,7 @@ async function renderToHTMLOrFlightImpl( ...@@ -485,6 +489,7 @@ async function renderToHTMLOrFlightImpl(
errorLogger: appDirDevErrorLogger, errorLogger: appDirDevErrorLogger,
capturedErrors, capturedErrors,
allCapturedErrors, allCapturedErrors,
skipLogging: renderOpts.ppr,
}) })
patchFetch(ComponentMod) patchFetch(ComponentMod)
...@@ -778,15 +783,6 @@ async function renderToHTMLOrFlightImpl( ...@@ -778,15 +783,6 @@ async function renderToHTMLOrFlightImpl(
throw err throw err
} }
// If there was a postponed error that escaped, it means that there was
// a postpone called without a wrapped suspense component.
if (err.$$typeof === Symbol.for('react.postpone')) {
// Ensure that we force the revalidation time to zero.
staticGenerationStore.revalidate = 0
throw err
}
if (err.digest === NEXT_DYNAMIC_NO_SSR_CODE) { if (err.digest === NEXT_DYNAMIC_NO_SSR_CODE) {
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. https://nextjs.org/docs/messages/deopted-into-client-rendering`,
...@@ -1003,6 +999,29 @@ async function renderToHTMLOrFlightImpl( ...@@ -1003,6 +999,29 @@ async function renderToHTMLOrFlightImpl(
if (staticGenerationStore.isStaticGeneration) { if (staticGenerationStore.isStaticGeneration) {
const htmlResult = await renderResult.toUnchunkedString(true) const htmlResult = await renderResult.toUnchunkedString(true)
if (renderOpts.ppr && postponeErrors.length > 0) {
renderOpts.hasPostponeErrors = true
}
if (
renderOpts.ppr &&
staticGenerationStore.postponeWasTriggered &&
!extraRenderResultMeta.postponed
) {
warn('')
warn(
`${urlPathname} opted out of partial prerendering because the postpone signal was intercepted by a try/catch in your application code.`
)
if (postponeErrors.length > 0) {
warn(
'The following errors were re-thrown, and might help find the location of the try/catch that triggered this.'
)
for (let i = 0; i < postponeErrors.length; i++) {
error(`${postponeErrors[i].stack?.split('\n').join('\n ')}`)
}
}
}
// if we encountered any unexpected errors during build // if we encountered any unexpected errors during build
// we fail the prerendering phase and the build // we fail the prerendering phase and the build
if (capturedErrors.length > 0) { if (capturedErrors.length > 0) {
......
...@@ -24,6 +24,8 @@ export function createErrorHandler({ ...@@ -24,6 +24,8 @@ export function createErrorHandler({
errorLogger, errorLogger,
capturedErrors, capturedErrors,
allCapturedErrors, allCapturedErrors,
postponeErrors,
skipLogging,
}: { }: {
_source: string _source: string
dev?: boolean dev?: boolean
...@@ -31,6 +33,8 @@ export function createErrorHandler({ ...@@ -31,6 +33,8 @@ export function createErrorHandler({
errorLogger?: (err: any) => Promise<void> errorLogger?: (err: any) => Promise<void>
capturedErrors: Error[] capturedErrors: Error[]
allCapturedErrors?: Error[] allCapturedErrors?: Error[]
postponeErrors?: Error[]
skipLogging?: boolean
}): ErrorHandler { }): ErrorHandler {
return (err) => { return (err) => {
if (allCapturedErrors) allCapturedErrors.push(err) if (allCapturedErrors) allCapturedErrors.push(err)
...@@ -73,19 +77,25 @@ export function createErrorHandler({ ...@@ -73,19 +77,25 @@ export function createErrorHandler({
}) })
} }
if (errorLogger) { if (postponeErrors) {
errorLogger(err).catch(() => {}) postponeErrors.push(err)
} else { }
// The error logger is currently not provided in the edge runtime.
// Use `log-app-dir-error` instead. if (!skipLogging) {
// It won't log the source code, but the error will be more useful. if (errorLogger) {
if (process.env.NODE_ENV !== 'production') { errorLogger(err).catch(() => {})
const { logAppDirError } = } else {
require('../dev/log-app-dir-error') as typeof import('../dev/log-app-dir-error') // The error logger is currently not provided in the edge runtime.
logAppDirError(err) // Use `log-app-dir-error` instead.
} // It won't log the source code, but the error will be more useful.
if (process.env.NODE_ENV === 'production') { if (process.env.NODE_ENV !== 'production') {
console.error(err) const { logAppDirError } =
require('../dev/log-app-dir-error') as typeof import('../dev/log-app-dir-error')
logAppDirError(err)
}
if (process.env.NODE_ENV === 'production') {
console.error(err)
}
} }
} }
} }
......
...@@ -137,6 +137,7 @@ export interface RenderOptsPartial { ...@@ -137,6 +137,7 @@ export interface RenderOptsPartial {
isPrefetch?: boolean isPrefetch?: boolean
ppr: boolean ppr: boolean
postponed?: string postponed?: string
hasPostponeErrors?: boolean
} }
export type RenderOpts = LoadComponentsReturnType<AppPageModule> & export type RenderOpts = LoadComponentsReturnType<AppPageModule> &
......
...@@ -2664,7 +2664,7 @@ export default abstract class Server<ServerOptions extends Options = Options> { ...@@ -2664,7 +2664,7 @@ export default abstract class Server<ServerOptions extends Options = Options> {
} }
if (isDataReq) { if (isDataReq) {
// If this isn't a prefetch and this isn't a resume request, we want to // If this isn't a prefetch and this isn't a resume request, we want to
// respond with the dynamic flight data. In the case that this is a // respond with the dynamic flight data. In the case that this is a
// resume request the page data will already be dynamic. // resume request the page data will already be dynamic.
if (!isAppPrefetch && !resumed) { if (!isAppPrefetch && !resumed) {
......
import React, { Suspense } from 'react'
import { cookies } from 'next/headers'
export default async function Page() {
return (
<>
<h2>Dynamic Component Catching Errors</h2>
<p>
This shows the dynamic component that reads cookies but wraps the read
in a try/catch. This test does not re-throw the caught error.
</p>
<div id="container">
<Suspense fallback={<div>Loading...</div>}>
<Foobar />
</Suspense>
</div>
</>
)
}
async function Foobar() {
try {
cookies()
} catch (err) {}
return null
}
import React, { Suspense } from 'react'
import { cookies } from 'next/headers'
import { Dynamic } from '../../../../components/dynamic'
export default async function Page() {
return (
<>
<h2>Dynamic Component Catching Errors</h2>
<p>
This shows the dynamic component that reads cookies but wraps the read
in a try/catch. This test re-throws the error that is caught.
</p>
<div id="container">
<Suspense fallback={<Dynamic fallback />}>
<Dynamic catchErrors />
</Suspense>
<Suspense fallback={<div>Loading...</div>}>
<Foobar />
</Suspense>
</div>
</>
)
}
async function Foobar() {
try {
cookies()
} catch (err) {
throw new Error('You are not signed in')
}
return null
}
import React, { Suspense } from 'react'
import { Dynamic } from '../../../../components/dynamic'
export default async function Page() {
const getData = () =>
fetch('https://example.vercel.sh', {
cache: 'no-store',
})
.then((res) => res.text())
.then((text) => new Promise((res) => setTimeout(() => res(text), 1000)))
try {
await getData()
} catch (err) {
throw new Error('Fetch failed')
}
return (
<>
<h2>Dynamic Component Catching Errors</h2>
<p>
This shows the dynamic component that reads cookies but wraps the read
in a try/catch.
</p>
<div id="container">
<Suspense fallback={<Dynamic fallback />}>
<Dynamic catchErrors />
</Suspense>
</div>
</>
)
}
...@@ -2,14 +2,22 @@ import React, { use } from 'react' ...@@ -2,14 +2,22 @@ import React, { use } from 'react'
import { cookies } from 'next/headers' import { cookies } from 'next/headers'
import { Delay, Login } from './state' import { Delay, Login } from './state'
export function Dynamic({ fallback }) { export function Dynamic({ fallback, catchErrors }) {
const dynamic = fallback !== true const dynamic = fallback !== true
let signedIn let signedIn
let active let active
if (dynamic) { if (dynamic) {
signedIn = cookies().has('session') ? true : false if (catchErrors) {
active = cookies().has('delay') ? true : false try {
signedIn = cookies().has('session') ? true : false
active = cookies().has('delay') ? true : false
} catch (err) {}
} else {
signedIn = cookies().has('session') ? true : false
active = cookies().has('delay') ? true : false
}
if (active) { if (active) {
use(new Promise((resolve) => setTimeout(resolve, 1000))) use(new Promise((resolve) => setTimeout(resolve, 1000)))
} }
......
...@@ -6,7 +6,27 @@ createNextDescribe( ...@@ -6,7 +6,27 @@ createNextDescribe(
files: __dirname, files: __dirname,
skipDeployment: true, skipDeployment: true,
}, },
({ next, isNextDev }) => { ({ next, isNextDev, isNextStart }) => {
if (isNextStart) {
it("should log a warning when `unstable_postpone` is called but there's no postpone state", async () => {
// Three different pages wrap APIs that use `unstable_postpone` in a try catch to trigger these errors
expect(next.cliOutput).toContain(
'/suspense/node/cookies-error-no-throw opted out of partial prerendering because the postpone signal was intercepted by a try/catch in your application code.'
)
expect(next.cliOutput).toContain(
'/suspense/node/fetch-error opted out of partial prerendering because the postpone signal was intercepted by a try/catch in your application code.'
)
expect(next.cliOutput).toContain(
'/suspense/node/cookies-error opted out of partial prerendering because the postpone signal was intercepted by a try/catch in your application code.'
)
// fetch-error re-throws the error after catching it, so we want to make sure that's retained in the logs
expect(next.cliOutput).toContain(
'The following errors were re-thrown, and might help find the location of the try/catch that triggered this.'
)
expect(next.cliOutput).toContain('Error: You are not signed in')
})
}
describe.each([ describe.each([
{ pathname: '/suspense/node' }, { pathname: '/suspense/node' },
{ pathname: '/suspense/node/nested/1' }, { pathname: '/suspense/node/nested/1' },
......
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