Unverified Commit 4666e854 authored by Zack Tanner's avatar Zack Tanner Committed by GitHub

revert ppr logging changes (#57486)

need to investigate this better

---------
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent a9fc27a8
---
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,8 +18,5 @@ export function maybePostpone( ...@@ -18,8 +18,5 @@ 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,7 +27,6 @@ export interface StaticGenerationStore { ...@@ -27,7 +27,6 @@ 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,4 +7,6 @@ export const isDynamicUsageError = (err: any) => ...@@ -7,4 +7,6 @@ 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')
...@@ -13,6 +13,7 @@ import { ...@@ -13,6 +13,7 @@ import {
NEXT_URL, NEXT_URL,
NEXT_ROUTER_PREFETCH, NEXT_ROUTER_PREFETCH,
} from '../../client/components/app-router-headers' } from '../../client/components/app-router-headers'
import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error'
import { NEXT_CACHE_TAGS_HEADER } from '../../lib/constants' import { NEXT_CACHE_TAGS_HEADER } 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'
...@@ -79,6 +80,7 @@ export async function exportAppPage( ...@@ -79,6 +80,7 @@ export async function exportAppPage(
pathname = '/404' pathname = '/404'
} }
try {
if (isAppPrefetch) { if (isAppPrefetch) {
await generatePrefetchRsc( await generatePrefetchRsc(
req, req,
...@@ -93,7 +95,13 @@ export async function exportAppPage( ...@@ -93,7 +95,13 @@ export async function exportAppPage(
return { revalidate: 0 } return { revalidate: 0 }
} }
const result = await lazyRenderAppPage(req, res, pathname, query, renderOpts) const result = await lazyRenderAppPage(
req,
res,
pathname,
query,
renderOpts
)
const html = result.toUnchunkedString() const html = result.toUnchunkedString()
const { metadata } = result const { metadata } = result
const flightData = metadata.pageData const flightData = metadata.pageData
...@@ -144,7 +152,12 @@ export async function exportAppPage( ...@@ -144,7 +152,12 @@ export async function exportAppPage(
} }
// Writing static HTML to a file. // Writing static HTML to a file.
await fileWriter(ExportedAppPageFiles.HTML, htmlFilepath, html ?? '', 'utf8') await fileWriter(
ExportedAppPageFiles.HTML,
htmlFilepath,
html ?? '',
'utf8'
)
// Writing the request metadata to a file. // Writing the request metadata to a file.
const meta: RouteMetadata = { const meta: RouteMetadata = {
...@@ -173,4 +186,11 @@ export async function exportAppPage( ...@@ -173,4 +186,11 @@ export async function exportAppPage(
hasPostponed: Boolean(postponed), hasPostponed: Boolean(postponed),
revalidate, revalidate,
} }
} catch (err: any) {
if (!isDynamicUsageError(err)) {
throw err
}
return { revalidate: 0 }
}
} }
...@@ -16,7 +16,7 @@ import type { ...@@ -16,7 +16,7 @@ import type {
MockedRequest, MockedRequest,
MockedResponse, MockedResponse,
} from '../../server/lib/mock-request' } from '../../server/lib/mock-request'
import { isDynamicUsageError } from '../../server/app-render/is-dynamic-usage-error' import { isDynamicUsageError } from '../helpers/is-dynamic-usage-error'
import { SERVER_DIRECTORY } from '../../shared/lib/constants' import { SERVER_DIRECTORY } from '../../shared/lib/constants'
import { hasNextSupport } from '../../telemetry/ci-info' import { hasNextSupport } from '../../telemetry/ci-info'
......
...@@ -72,8 +72,6 @@ import { createComponentTree } from './create-component-tree' ...@@ -72,8 +72,6 @@ import { createComponentTree } from './create-component-tree'
import { getAssetQueryString } from './get-asset-query-string' import { getAssetQueryString } from './get-asset-query-string'
import { setReferenceManifestsSingleton } from './action-encryption-utils' import { setReferenceManifestsSingleton } from './action-encryption-utils'
import { createStaticRenderer } from './static/static-renderer' import { createStaticRenderer } from './static/static-renderer'
import { isPostpone } from '../lib/router-utils/is-postpone'
import { isDynamicUsageError } from './is-dynamic-usage-error'
export type GetDynamicParamFromSegment = ( export type GetDynamicParamFromSegment = (
// [slug] / [[slug]] / [...slug] // [slug] / [[slug]] / [...slug]
...@@ -465,16 +463,13 @@ async function renderToHTMLOrFlightImpl( ...@@ -465,16 +463,13 @@ 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',
...@@ -482,7 +477,6 @@ async function renderToHTMLOrFlightImpl( ...@@ -482,7 +477,6 @@ async function renderToHTMLOrFlightImpl(
isNextExport, isNextExport,
errorLogger: appDirDevErrorLogger, errorLogger: appDirDevErrorLogger,
capturedErrors, capturedErrors,
skipLogging: renderOpts.ppr,
}) })
const htmlRendererErrorHandler = createErrorHandler({ const htmlRendererErrorHandler = createErrorHandler({
_source: 'htmlRenderer', _source: 'htmlRenderer',
...@@ -491,7 +485,6 @@ async function renderToHTMLOrFlightImpl( ...@@ -491,7 +485,6 @@ async function renderToHTMLOrFlightImpl(
errorLogger: appDirDevErrorLogger, errorLogger: appDirDevErrorLogger,
capturedErrors, capturedErrors,
allCapturedErrors, allCapturedErrors,
skipLogging: renderOpts.ppr,
}) })
patchFetch(ComponentMod) patchFetch(ComponentMod)
...@@ -785,6 +778,15 @@ async function renderToHTMLOrFlightImpl( ...@@ -785,6 +778,15 @@ 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`,
...@@ -1001,24 +1003,10 @@ async function renderToHTMLOrFlightImpl( ...@@ -1001,24 +1003,10 @@ async function renderToHTMLOrFlightImpl(
if (staticGenerationStore.isStaticGeneration) { if (staticGenerationStore.isStaticGeneration) {
const htmlResult = await renderResult.toUnchunkedString(true) const htmlResult = await renderResult.toUnchunkedString(true)
if ( // if we encountered any unexpected errors during build
renderOpts.ppr && // we fail the prerendering phase and the build
staticGenerationStore.postponeWasTriggered && if (capturedErrors.length > 0) {
!extraRenderResultMeta.postponed throw capturedErrors[0]
) {
throw new Error(
`Postpone signal was caught while rendering ${urlPathname}. These errors should not be caught during static generation. Learn more: https://nextjs.org/docs/messages/ppr-postpone-errors`
)
}
for (const err of capturedErrors) {
if (!isDynamicUsageError(err) && !isPostpone(err)) {
throw err
}
if (isDynamicUsageError(err)) {
staticGenerationStore.revalidate = 0
}
} }
if (staticGenerationStore.forceStatic === false) { if (staticGenerationStore.forceStatic === false) {
......
...@@ -24,8 +24,6 @@ export function createErrorHandler({ ...@@ -24,8 +24,6 @@ export function createErrorHandler({
errorLogger, errorLogger,
capturedErrors, capturedErrors,
allCapturedErrors, allCapturedErrors,
postponeErrors,
skipLogging,
}: { }: {
_source: string _source: string
dev?: boolean dev?: boolean
...@@ -33,8 +31,6 @@ export function createErrorHandler({ ...@@ -33,8 +31,6 @@ 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)
...@@ -77,11 +73,6 @@ export function createErrorHandler({ ...@@ -77,11 +73,6 @@ export function createErrorHandler({
}) })
} }
if (postponeErrors) {
postponeErrors.push(err)
}
if (!skipLogging) {
if (errorLogger) { if (errorLogger) {
errorLogger(err).catch(() => {}) errorLogger(err).catch(() => {})
} else { } else {
...@@ -98,7 +89,6 @@ export function createErrorHandler({ ...@@ -98,7 +89,6 @@ export function createErrorHandler({
} }
} }
} }
}
capturedErrors.push(err) capturedErrors.push(err)
// TODO-APP: look at using webcrypto instead. Requires a promise to be awaited. // TODO-APP: look at using webcrypto instead. Requires a promise to be awaited.
......
import React from 'react'
export default function Root({ children }) {
return (
<html>
<body>{children}</body>
</html>
)
}
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.
</p>
<div id="container">
<Suspense fallback={<div>Loading...</div>}>
<Foobar />
</Suspense>
</div>
</>
)
}
async function Foobar() {
try {
cookies()
} catch (err) {}
return null
}
/**
* @type {import('next').NextConfig}
*/
const nextConfig = {
experimental: {
ppr: true,
},
}
module.exports = nextConfig
import { nextBuild } from 'next-test-utils'
describe('ppr build errors', () => {
it('should fail the build', async () => {
const out = await nextBuild(__dirname, [], { stderr: true })
expect(out.stderr).toContain(
'Postpone signal was caught while rendering /. These errors should not be caught during static generation.'
)
})
})
...@@ -2,22 +2,14 @@ import React, { use } from 'react' ...@@ -2,22 +2,14 @@ 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, catchErrors }) { export function Dynamic({ fallback }) {
const dynamic = fallback !== true const dynamic = fallback !== true
let signedIn let signedIn
let active let active
if (dynamic) { if (dynamic) {
if (catchErrors) {
try {
signedIn = cookies().has('session') ? true : false signedIn = cookies().has('session') ? true : false
active = cookies().has('delay') ? 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,7 @@ createNextDescribe( ...@@ -6,7 +6,7 @@ createNextDescribe(
files: __dirname, files: __dirname,
skipDeployment: true, skipDeployment: true,
}, },
({ next, isNextDev, isNextStart }) => { ({ next, isNextDev }) => {
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