Unverified Commit e9b96b41 authored by Hendrik Liebau's avatar Hendrik Liebau Committed by GitHub

Build with dev runtimes when `--debug-prerender` is set (#89834)

When running `next build --debug-prerender`, React owner stacks are now
captured and displayed in prerender error output. This makes it much
easier to diagnose which component triggered uncached I/O or accessed
request data without Suspense. Previously, `--debug-prerender` only
enabled source maps and disabled minification. Now it also auto-enables
`allowDevelopmentBuild` and sets `NODE_ENV=development`, which loads
React development builds where `captureOwnerStack()` is available.

The main challenge is that with `NODE_ENV=development`, both server and
client bundles include dev-only code paths (HMR, WebSocket connections,
dev overlay, debug channel, etc.) that expect a running dev server. We
don't want these when using `next start`. To solve this, we introduce
`process.env.__NEXT_DEV_SERVER`, an internal env var that is truthy only
during `next dev`. In client bundles, it's inlined at build time (`'1'`
for `next dev`, `''` for `next build`). In production server runtime
bundles, it's inlined as `''` for dead-code elimination. In development
server runtime bundles, it's left as a runtime check because those
bundles are shared between `next dev` (where it's set) and `next build
--debug-prerender` (where it's not). Meanwhile, `NODE_ENV` continues to
control React's dev/prod mode and error formatting, which is exactly
what we want for `--debug-prerender`.

This also replaces the previous `renderOpts.dev` / `workStore.dev`
pattern, which was unreliable because `RouteModule.isDev` was derived
from `NODE_ENV` at compile time. When `allowDevelopmentBuild` set
`NODE_ENV=development`, `isDev` would be compiled as `true` and
incorrectly activate all dev guards during `next start`.

Key changes:

- `config.ts` auto-enables `allowDevelopmentBuild` and sets
`NODE_ENV=development` when `--debug-prerender` is active
- `define-env.ts` inlines `__NEXT_DEV_SERVER` into all bundles (truthy
for dev, falsy for build) so dev-server features are dead-code
eliminated in production and `--debug-prerender` builds
- `next-dev.ts` and `next.ts` set `__NEXT_DEV_SERVER` in the process
environment for externalized server-side code
- `renderOpts.dev` and `workStore.dev` are removed — all consumers now
use `__NEXT_DEV_SERVER` (for dev-server features) or `NODE_ENV` (for
error formatting that should work in both dev and `--debug-prerender`
builds)
- `patch-error-inspect.ts` devirtualizes React server URLs in source map
URLs so they display as readable file paths
parent b737b046
......@@ -246,6 +246,13 @@ See [Codebase structure](#codebase-structure) above for detailed explanations.
- Use `DEBUG=next:*` for debug logging
- Use `NEXT_TELEMETRY_DISABLED=1` when testing locally
### `NODE_ENV` vs `__NEXT_DEV_SERVER`
Both `next dev` and `next build --debug-prerender` produce bundles with `NODE_ENV=development`. Use `process.env.__NEXT_DEV_SERVER` to distinguish between them:
- `process.env.NODE_ENV !== 'production'` — code that should exist in dev bundles but be eliminated from prod bundles. This is a build-time check.
- `process.env.__NEXT_DEV_SERVER` — code that should only run with the dev server (`next dev`), not during `next build --debug-prerender` or `next start`.
## Commit and PR Style
- Do NOT add "Generated with Claude Code" or co-author footers to commits or PRs
......
......@@ -100,6 +100,13 @@ $ pnpm unpack-next path/to/project
The dev overlay is a feature of Next.js that allows you to see the internal state of the app including the errors. To learn more about contributing to the dev overlay, see the [Dev Overlay README.md](../../packages/next/src/client/components/react-dev-overlay/README.md).
## `NODE_ENV` vs `__NEXT_DEV_SERVER`
Both `next dev` and `next build --debug-prerender` produce bundles with `NODE_ENV=development`. Use `process.env.__NEXT_DEV_SERVER` to distinguish between them:
- `process.env.NODE_ENV !== 'production'` — code that should exist in dev bundles but be eliminated from prod bundles. This is a build-time check.
- `process.env.__NEXT_DEV_SERVER` — code that should only run with the dev server (`next dev`), not during `next build --debug-prerender` or `next start`.
## Recover disk space
Rust builds quickly add up to a lot of disk space, you can clean up old artifacts with this command:
......
......@@ -209,8 +209,11 @@ module.exports = ({ dev, turbo, bundleType, experimental, ...rest }) => {
'process.env.NEXT_MINIMAL': JSON.stringify('true'),
'this.serverOptions.experimentalTestProxy': JSON.stringify(false),
'this.minimalMode': JSON.stringify(true),
'this.renderOpts.dev': JSON.stringify(dev),
'renderOpts.dev': JSON.stringify(dev),
// Only inline __NEXT_DEV_SERVER in prod bundles (for dead-code
// elimination). Dev bundles must keep it as a runtime check because
// they're shared between `next dev` (where it's set) and `next build
// --debug-prerender` (where it's not).
...(dev ? {} : { 'process.env.__NEXT_DEV_SERVER': JSON.stringify('') }),
'process.env.NODE_ENV': JSON.stringify(
dev ? 'development' : 'production'
),
......
......@@ -194,6 +194,10 @@ program
'Enable CPU profiling. Profile is saved to .next/cpu-profiles/ on completion.'
)
.action((directory: string, options: NextBuildOptions) => {
if (options.debugPrerender) {
// @ts-expect-error not readonly
process.env.NODE_ENV = 'development'
}
if (options.experimentalNextConfigStripTypes) {
process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'true'
}
......
......@@ -157,6 +157,7 @@ export function getDefineEnv({
dev || config.experimental.allowDevelopmentBuild
? 'development'
: 'production',
'process.env.__NEXT_DEV_SERVER': dev ? '1' : '',
'process.env.NEXT_RUNTIME': isEdgeServer
? 'edge'
: isNodeServer
......
......@@ -836,7 +836,7 @@ export async function buildAppStaticPaths({
)
const supportsRoutePreGeneration =
hadAllParamsGenerated || process.env.NODE_ENV === 'production'
hadAllParamsGenerated || !process.env.__NEXT_DEV_SERVER
const fallbackMode = dynamicParams
? supportsRoutePreGeneration
......
......@@ -762,7 +762,6 @@ export async function handler(
routerServerContext
),
err: getRequestMeta(req, 'invokeError'),
dev: routeModule.isDev,
},
}
......
......@@ -197,7 +197,6 @@ async function requestHandler(
silenceLog,
routerServerContext
),
dev: pageRouteModule.isDev,
},
}
let finalStatus = 200
......
......@@ -85,8 +85,8 @@ const nextBuild = async (options: NextBuildOptions, directory?: string) => {
if (debugPrerender) {
warn(
`Prerendering is running in debug mode. ${italic(
'Note: This may affect performance and should not be used for production.'
`Prerendering is running in debug mode with NODE_ENV='development'. ${italic(
'This will affect performance and should not be used for production.'
)}`
)
}
......
......@@ -328,6 +328,7 @@ const nextDev = async (
env: {
...defaultEnv,
...(isTurbopack ? { TURBOPACK: process.env.TURBOPACK } : undefined),
__NEXT_DEV_SERVER: '1',
NEXT_PRIVATE_START_TIME: process.env.NEXT_PRIVATE_START_TIME,
NEXT_PRIVATE_WORKER: '1',
NEXT_PRIVATE_TRACE_ID: traceId,
......
......@@ -2,7 +2,8 @@ const basePath = process.env.__NEXT_ROUTER_BASEPATH || ''
const pathname = `${basePath}/__nextjs_source-map`
export const findSourceMapURL =
process.env.NODE_ENV === 'development'
// Source maps are only served by the dev server.
process.env.__NEXT_DEV_SERVER
? function findSourceMapURL(filename: string): string | null {
if (filename === '') {
return null
......
// imports polyfill from `@next/polyfill-module` after build.
import '../build/polyfills/polyfill-module'
// Only setup devtools in development
if (process.env.NODE_ENV !== 'production') {
// Only set up devtools for the dev server.
if (process.env.__NEXT_DEV_SERVER) {
require('../next-devtools/userspace/app/app-dev-overlay-setup') as typeof import('../next-devtools/userspace/app/app-dev-overlay-setup')
}
......
......@@ -190,7 +190,7 @@ let debugChannel:
| undefined
if (
process.env.NODE_ENV !== 'production' &&
process.env.__NEXT_DEV_SERVER &&
process.env.__NEXT_REACT_DEBUG_CHANNEL &&
typeof window !== 'undefined'
) {
......@@ -310,7 +310,7 @@ export async function hydrate(
let staticIndicatorState: StaticIndicatorState | undefined
let webSocket: WebSocket | undefined
if (process.env.NODE_ENV !== 'production') {
if (process.env.__NEXT_DEV_SERVER) {
const { createWebSocket } =
require('./dev/hot-reloader/app/web-socket') as typeof import('./dev/hot-reloader/app/web-socket')
......@@ -380,7 +380,7 @@ export async function hydrate(
}
// TODO-APP: Remove this logic when Float has GC built-in in development.
if (process.env.NODE_ENV !== 'production') {
if (process.env.__NEXT_DEV_SERVER) {
const { linkGc } =
require('./app-link-gc') as typeof import('./app-link-gc')
linkGc()
......
......@@ -13,7 +13,7 @@ appBootstrap((assetPrefix) => {
try {
hydrate(instrumentationHooks, assetPrefix)
} finally {
if (process.env.NODE_ENV !== 'production') {
if (process.env.__NEXT_DEV_SERVER) {
const enableCacheIndicator = process.env.__NEXT_CACHE_COMPONENTS
const { getOwnerStack } =
require('../next-devtools/userspace/app/errors/stitched-error') as typeof import('../next-devtools/userspace/app/errors/stitched-error')
......
......@@ -479,7 +479,7 @@ function Router({
</RedirectBoundary>
)
if (process.env.NODE_ENV !== 'production') {
if (process.env.__NEXT_DEV_SERVER) {
// In development, we apply few error boundaries and hot-reloader:
// - DevRootHTTPAccessFallbackBoundary: avoid using navigation API like notFound() in root layout
// - HotReloader:
......
......@@ -50,10 +50,7 @@ let createDebugChannel:
| typeof import('../../dev/debug-channel').createDebugChannel
| undefined
if (
process.env.NODE_ENV !== 'production' &&
process.env.__NEXT_REACT_DEBUG_CHANNEL
) {
if (process.env.__NEXT_DEV_SERVER && process.env.__NEXT_REACT_DEBUG_CHANNEL) {
createDebugChannel = (
require('../../dev/debug-channel') as typeof import('../../dev/debug-channel')
).createDebugChannel
......@@ -322,7 +319,7 @@ export async function createFetch<T>(
headers['x-deployment-id'] = deploymentId
}
if (process.env.NODE_ENV !== 'production') {
if (process.env.__NEXT_DEV_SERVER) {
if (self.__next_r) {
headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r
}
......
......@@ -73,10 +73,7 @@ let createDebugChannel:
| typeof import('../../../dev/debug-channel').createDebugChannel
| undefined
if (
process.env.NODE_ENV !== 'production' &&
process.env.__NEXT_REACT_DEBUG_CHANNEL
) {
if (process.env.__NEXT_DEV_SERVER && process.env.__NEXT_REACT_DEBUG_CHANNEL) {
createDebugChannel = (
require('../../../dev/debug-channel') as typeof import('../../../dev/debug-channel')
).createDebugChannel
......@@ -123,7 +120,7 @@ async function fetchServerAction(
headers[NEXT_URL] = nextUrl
}
if (process.env.NODE_ENV !== 'production') {
if (process.env.__NEXT_DEV_SERVER) {
if (self.__next_r) {
headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r
}
......
......@@ -477,7 +477,6 @@ async function exportAppImpl(
isBuildTimePrerendering: true,
assetPrefix: nextConfig.assetPrefix.replace(/\/$/, ''),
distDir,
dev: false,
basePath: nextConfig.basePath,
cacheComponents: nextConfig.cacheComponents ?? false,
trailingSlash: nextConfig.trailingSlash,
......@@ -516,14 +515,6 @@ async function exportAppImpl(
),
},
reactMaxHeadersLength: nextConfig.reactMaxHeadersLength,
hasReadableErrorStacks:
nextConfig.experimental.serverSourceMaps === true &&
// TODO(NDX-531): Checking (and setting) the minify flags should be
// unnecessary once name mapping is fixed.
(process.env.TURBOPACK
? nextConfig.experimental.turbopackMinify === false
: nextConfig.experimental.serverMinification === false) &&
nextConfig.enablePrerenderSourceMaps === true,
}
// We need this for server rendering the Link component.
......
......@@ -380,8 +380,8 @@ function parseRequestHeaders(
let requestId: string | undefined
let htmlRequestId: string | undefined
if (process.env.NODE_ENV !== 'production') {
// The request IDs are only used in development mode to send debug
if (process.env.__NEXT_DEV_SERVER) {
// The request IDs are only used for the dev server to send debug
// information to the matching client (identified by the HTML request ID
// that was sent to the client with the HTML document) for the current
// request (identified by the request ID, as defined by the client).
......@@ -538,7 +538,7 @@ async function generateDynamicRSCPayload(
// If we're performing instant validation, we need to render the whole tree,
// without skipping shared layouts.
const needsFullTree =
process.env.NODE_ENV === 'development' &&
process.env.__NEXT_DEV_SERVER &&
ctx.renderOpts.cacheComponents &&
!options?.actionResult && // Only for navigations
(await anySegmentNeedsInstantValidation(loaderTree))
......@@ -678,7 +678,6 @@ async function generateDynamicFlightRenderResult(
} = ctx
const {
dev = false,
onInstrumentationRequestError,
setReactDebugChannel,
isBuildTimePrerendering = false,
......@@ -694,7 +693,7 @@ async function generateDynamicFlightRenderResult(
}
const onError = createReactServerErrorHandler(
dev,
process.env.NODE_ENV === 'development',
isBuildTimePrerendering,
workStore.reactServerErrorsByDigest,
onFlightDataRenderError
......@@ -839,7 +838,6 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
} = ctx
const {
dev = false,
onInstrumentationRequestError,
setReactDebugChannel,
setCacheStatus,
......@@ -856,7 +854,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
}
const onError = createReactServerErrorHandler(
dev,
process.env.NODE_ENV === 'development',
isBuildTimePrerendering,
workStore.reactServerErrorsByDigest,
onFlightDataRenderError
......@@ -866,7 +864,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
// instant configs exist, since we render all the layouts necessary to perform
// the validation in those cases.
const shouldValidate =
!isBypassingCachesInDev(renderOpts, initialRequestStore) &&
!isBypassingCachesInDev(initialRequestStore) &&
(initialRequestStore.isHmrRefresh === true ||
(await anySegmentNeedsInstantValidation(loaderTree)))
......@@ -880,7 +878,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
undefined
)
if (isBypassingCachesInDev(renderOpts, requestStore)) {
if (isBypassingCachesInDev(requestStore)) {
// Mark the RSC payload to indicate that caches were bypassed in dev.
// This lets the client know not to cache anything based on this render.
payload._bypassCachesInDev = createElement(WarnForBypassCachesInDev, {
......@@ -904,7 +902,7 @@ async function generateDynamicFlightRenderResultWithStagesInDev(
createRequestStore &&
// We only do this flow if we're not bypassing caches in dev using
// "disable cache" in devtools or a hard refresh (cache-control: "no-store")
!isBypassingCachesInDev(renderOpts, initialRequestStore)
!isBypassingCachesInDev(initialRequestStore)
) {
// Before we kick off the render, we set the cache status back to it's initial state
// in case a previous render bypassed the cache.
......@@ -1510,7 +1508,7 @@ async function getRSCPayload(
let missingSlots: Set<string> | undefined
// We only track missing parallel slots in development
if (process.env.NODE_ENV === 'development') {
if (process.env.__NEXT_DEV_SERVER) {
missingSlots = new Set<string>()
}
......@@ -1679,7 +1677,7 @@ async function getErrorRSCPayload(
isPossibleServerAction: ctx.isPossibleServerAction,
}),
createElement(Viewport, null),
process.env.NODE_ENV === 'development' &&
process.env.__NEXT_DEV_SERVER &&
createElement('meta', {
name: 'next-error',
content: 'not-found',
......@@ -1710,7 +1708,7 @@ async function getErrorRSCPayload(
createElement(
'body',
null,
process.env.NODE_ENV !== 'production' && err
process.env.__NEXT_DEV_SERVER && err
? createElement('template', {
'data-next-error-message': err.message,
'data-next-error-digest': 'digest' in err ? err.digest : '',
......@@ -1916,6 +1914,7 @@ async function renderToHTMLOrFlightImpl(
assetPrefix = '',
enableTainting,
cacheComponents,
setIsrStatus,
} = renderOpts
// We need to expose the bundled `require` API globally for
......@@ -1932,7 +1931,7 @@ async function renderToHTMLOrFlightImpl(
if (!cacheComponents) {
return false
}
if (renderOpts.dev) {
if (process.env.__NEXT_DEV_SERVER) {
return true
}
const workUnitStore = workUnitAsyncStorage.getStore()
......@@ -1980,14 +1979,10 @@ async function renderToHTMLOrFlightImpl(
globalThis.__next_chunk_load__ = __next_chunk_load__
}
if (
process.env.NODE_ENV === 'development' &&
renderOpts.setIsrStatus &&
!cacheComponents
) {
if (process.env.__NEXT_DEV_SERVER && setIsrStatus && !cacheComponents) {
// Reset the ISR status at start of request.
const { pathname } = new URL(req.url || '/', 'http://n')
renderOpts.setIsrStatus(
setIsrStatus(
pathname,
// Only pages using the Node runtime can use ISR, Edge is always dynamic.
process.env.NEXT_RUNTIME === 'edge' ? false : undefined
......@@ -2252,8 +2247,8 @@ async function renderToHTMLOrFlightImpl(
const requestStore = createRequestStore()
if (
process.env.NODE_ENV === 'development' &&
renderOpts.setIsrStatus &&
process.env.__NEXT_DEV_SERVER &&
setIsrStatus &&
!cacheComponents &&
// Only pages using the Node runtime can use ISR, so we only need to
// update the status for those.
......@@ -2262,7 +2257,6 @@ async function renderToHTMLOrFlightImpl(
process.env.NEXT_RUNTIME !== 'edge' &&
isNodeNextRequest(req)
) {
const setIsrStatus = renderOpts.setIsrStatus
req.originalRequest.on('end', () => {
const { pathname } = new URL(req.url || '/', 'http://n')
const isStatic = !requestStore.usedDynamic && !workStore.forceDynamic
......@@ -2275,7 +2269,7 @@ async function renderToHTMLOrFlightImpl(
return generateRuntimePrefetchResult(req, ctx, requestStore)
} else {
if (
process.env.NODE_ENV === 'development' &&
process.env.__NEXT_DEV_SERVER &&
process.env.NEXT_RUNTIME !== 'edge' &&
cacheComponents
) {
......@@ -2371,7 +2365,7 @@ async function renderToHTMLOrFlightImpl(
// Invalid dynamic usages should only error the request in development.
// In production, it's better to produce a result.
// (the dynamic error will still be thrown inside the component tree, but it's catchable by error boundaries)
if (workStore.invalidDynamicUsageError && workStore.dev) {
if (workStore.invalidDynamicUsageError && process.env.__NEXT_DEV_SERVER) {
throw workStore.invalidDynamicUsageError
}
......@@ -2593,7 +2587,6 @@ async function renderToStream(
renderToReadableStream: serverRenderToReadableStream,
},
crossOrigin,
dev = false,
experimental,
isBuildTimePrerendering = false,
onInstrumentationRequestError,
......@@ -2646,10 +2639,9 @@ async function renderToStream(
// In development mode, set the request ID as a global variable, before the
// bootstrap script is executed, which depends on it during hydration.
const bootstrapScriptContent =
process.env.NODE_ENV !== 'production'
? `self.__next_r=${JSON.stringify(requestId)}`
: undefined
const bootstrapScriptContent = process.env.__NEXT_DEV_SERVER
? `self.__next_r=${JSON.stringify(requestId)}`
: undefined
// Create the "render route (app)" span manually so we can keep it open during streaming.
// This is necessary because errors inside Suspense boundaries are reported asynchronously
......@@ -2693,7 +2685,7 @@ async function renderToStream(
)
}
const serverComponentsErrorHandler = createReactServerErrorHandler(
dev,
process.env.NODE_ENV === 'development',
isBuildTimePrerendering,
reactServerErrorsByDigest,
onHTMLRenderRSCError,
......@@ -2714,7 +2706,7 @@ async function renderToStream(
const allCapturedErrors: Array<unknown> = []
const htmlRendererErrorHandler = createHTMLErrorHandler(
dev,
process.env.NODE_ENV === 'development',
isBuildTimePrerendering,
reactServerErrorsByDigest,
allCapturedErrors,
......@@ -2731,10 +2723,7 @@ async function renderToStream(
try {
if (
// We only want this behavior when we have React's dev builds available
process.env.NODE_ENV === 'development' &&
// We only want this behavior when running `next dev`
dev &&
process.env.__NEXT_DEV_SERVER &&
// Edge routes never prerender so we don't have a Prerender environment for anything in edge runtime
process.env.NEXT_RUNTIME !== 'edge' &&
// We only have a Prerender environment for projects opted into cacheComponents
......@@ -2755,7 +2744,7 @@ async function renderToStream(
res.statusCode === 404
)
if (isBypassingCachesInDev(renderOpts, requestStore)) {
if (isBypassingCachesInDev(requestStore)) {
// Mark the RSC payload to indicate that caches were bypassed in dev.
// This lets the client know not to cache anything based on this render.
if (renderOpts.setCacheStatus) {
......@@ -2779,7 +2768,7 @@ async function renderToStream(
createRequestStore &&
// We only do this flow if we're not bypassing caches in dev using
// "disable cache" in devtools or a hard refresh (cache-control: "no-store")
!isBypassingCachesInDev(renderOpts, requestStore)
!isBypassingCachesInDev(requestStore)
) {
const {
stream: serverStream,
......@@ -3050,7 +3039,7 @@ async function renderToStream(
deploymentId: ctx.sharedContext.deploymentId,
getServerInsertedHTML,
getServerInsertedMetadata,
validateRootLayout: dev,
validateRootLayout: !!process.env.__NEXT_DEV_SERVER,
})
} catch (err) {
if (
......@@ -3223,11 +3212,11 @@ async function renderToStream(
tracingMetadata: tracingMetadata,
}),
getServerInsertedMetadata,
validateRootLayout: dev,
validateRootLayout: !!process.env.__NEXT_DEV_SERVER,
})
} catch (finalErr: any) {
if (
process.env.NODE_ENV === 'development' &&
process.env.__NEXT_DEV_SERVER &&
isHTTPAccessFallbackError(finalErr)
) {
const { bailOnRootNotFound } =
......@@ -3435,7 +3424,7 @@ async function renderWithRestartOnCacheMissInDev(
}
}
if (process.env.NODE_ENV === 'development' && setCacheStatus) {
if (process.env.__NEXT_DEV_SERVER && setCacheStatus) {
setCacheStatus('filling', htmlRequestId)
}
......@@ -3529,7 +3518,7 @@ async function renderWithRestartOnCacheMissInDev(
)
)
if (process.env.NODE_ENV === 'development' && setCacheStatus) {
if (process.env.__NEXT_DEV_SERVER && setCacheStatus) {
setCacheStatus('filled', htmlRequestId)
}
......@@ -3742,7 +3731,7 @@ async function spawnStaticShellValidationInDev(
const rootParams = getRootParams(loaderTree, getDynamicParamFromSegment)
const hmrRefreshHash = getHmrRefreshHash(workStore, requestStore)
const hmrRefreshHash = getHmrRefreshHash(requestStore)
// We don't need to continue the prerender process if we already
// detected invalid dynamic usage in the initial prerender phase.
......@@ -4518,7 +4507,6 @@ async function prerenderToStream(
buildManifest,
ComponentMod,
crossOrigin,
dev = false,
experimental,
isDebugDynamicAccesses,
isBuildTimePrerendering = false,
......@@ -4587,7 +4575,7 @@ async function prerenderToStream(
}
}
const serverComponentsErrorHandler = createReactServerErrorHandler(
dev,
process.env.NODE_ENV === 'development',
isBuildTimePrerendering,
reactServerErrorsByDigest,
onHTMLRenderRSCError
......@@ -4608,7 +4596,7 @@ async function prerenderToStream(
}
const allCapturedErrors: Array<unknown> = []
const htmlRendererErrorHandler = createHTMLErrorHandler(
dev,
process.env.NODE_ENV === 'development',
isBuildTimePrerendering,
reactServerErrorsByDigest,
allCapturedErrors,
......@@ -5920,7 +5908,7 @@ async function prerenderToStream(
tracingMetadata: tracingMetadata,
}),
getServerInsertedMetadata,
validateRootLayout: dev,
validateRootLayout: !!process.env.__NEXT_DEV_SERVER,
deploymentId: ctx.sharedContext.deploymentId,
}),
dynamicAccess: null,
......@@ -5935,7 +5923,7 @@ async function prerenderToStream(
}
} catch (finalErr: any) {
if (
process.env.NODE_ENV === 'development' &&
process.env.__NEXT_DEV_SERVER &&
isHTTPAccessFallbackError(finalErr)
) {
const { bailOnRootNotFound } =
......@@ -5977,7 +5965,7 @@ const getGlobalErrorStyles = async (
let globalErrorStyles: ReactNode = styles
if (ctx.renderOpts.dev) {
if (process.env.__NEXT_DEV_SERVER) {
const dir =
(process.env.NEXT_RUNTIME === 'edge'
? process.env.__NEXT_EDGE_PROJECT_DIR
......@@ -6063,13 +6051,9 @@ async function collectSegmentData(
)
}
function isBypassingCachesInDev(
renderOpts: RenderOpts,
requestStore: RequestStore
): boolean {
function isBypassingCachesInDev(requestStore: RequestStore): boolean {
return (
process.env.NODE_ENV === 'development' &&
!!renderOpts.dev &&
!!process.env.__NEXT_DEV_SERVER &&
requestStore.headers.get('cache-control') === 'no-cache'
)
}
......
......@@ -424,7 +424,7 @@ async function createComponentTreeInternal(
}
// Resolve the segment param
const isSegmentViewEnabled = !!ctx.renderOpts.dev
const isSegmentViewEnabled = !!process.env.__NEXT_DEV_SERVER
const dir =
(process.env.NEXT_RUNTIME === 'edge'
? process.env.__NEXT_EDGE_PROJECT_DIR
......@@ -1193,7 +1193,7 @@ async function createBoundaryConventionElement({
const {
componentMod: { createElement, Fragment },
} = ctx
const isSegmentViewEnabled = !!ctx.renderOpts.dev
const isSegmentViewEnabled = !!process.env.__NEXT_DEV_SERVER
const dir =
(process.env.NEXT_RUNTIME === 'edge'
? process.env.__NEXT_EDGE_PROJECT_DIR
......
......@@ -980,16 +980,10 @@ export function logDisallowedDynamicError(
): void {
console.error(error)
if (!workStore.dev) {
if (workStore.hasReadableErrorStacks) {
console.error(
`To get a more detailed stack trace and pinpoint the issue, start the app in development mode by running \`next dev\`, then open "${workStore.route}" in your browser to investigate the error.`
)
} else {
console.error(`To get a more detailed stack trace and pinpoint the issue, try one of the following:
if (process.env.NODE_ENV !== 'development') {
console.error(`To get a more detailed stack trace and pinpoint the issue, try one of the following:
- Start the app in development mode by running \`next dev\`, then open "${workStore.route}" in your browser to investigate the error.
- Rerun the production build with \`next build --debug-prerender\` to generate better stack traces.`)
}
}
}
......
......@@ -91,7 +91,6 @@ export interface RenderOptsPartial {
dir?: string
previewProps: __ApiPreviewProps | undefined
err?: Error | null
dev?: boolean
basePath: string
cacheComponents: boolean
trailingSlash: boolean
......@@ -192,13 +191,6 @@ export interface RenderOptsPartial {
isDebugDynamicAccesses?: boolean
/**
* This is true when:
* - source maps are generated
* - source maps are applied
* - minification is disabled
*/
hasReadableErrorStacks?: boolean
/**
* The maximum length of the headers that are emitted by React and added to
* the response.
......
......@@ -32,14 +32,6 @@ export interface WorkStore {
readonly isOnDemandRevalidate?: boolean
readonly isBuildTimePrerendering?: boolean
/**
* This is true when:
* - source maps are generated
* - source maps are applied
* - minification is disabled
*/
readonly hasReadableErrorStacks?: boolean
forceDynamic?: boolean
fetchCache?: AppSegmentConfig['fetchCache']
......@@ -106,7 +98,6 @@ export interface WorkStore {
readonly nonce?: string
cacheComponentsEnabled: boolean
dev: boolean
/**
* Run the given function inside a clean AsyncLocalStorage snapshot. This is
......
......@@ -415,10 +415,9 @@ export function getRenderResumeDataCache(
}
export function getHmrRefreshHash(
workStore: WorkStore,
workUnitStore: WorkUnitStore
): string | undefined {
if (workStore.dev) {
if (process.env.__NEXT_DEV_SERVER) {
switch (workUnitStore.type) {
case 'cache':
case 'private-cache':
......@@ -440,11 +439,8 @@ export function getHmrRefreshHash(
return undefined
}
export function isHmrRefresh(
workStore: WorkStore,
workUnitStore: WorkUnitStore
): boolean {
if (workStore.dev) {
export function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {
if (process.env.__NEXT_DEV_SERVER) {
switch (workUnitStore.type) {
case 'cache':
case 'private-cache':
......@@ -466,10 +462,9 @@ export function isHmrRefresh(
}
export function getServerComponentsHmrCache(
workStore: WorkStore,
workUnitStore: WorkUnitStore
): ServerComponentsHmrCache | undefined {
if (workStore.dev) {
if (process.env.__NEXT_DEV_SERVER) {
switch (workUnitStore.type) {
case 'cache':
case 'private-cache':
......
......@@ -58,8 +58,6 @@ export type WorkStoreContext = {
| 'isBuildTimePrerendering'
| 'isDraftMode'
| 'isDebugDynamicAccesses'
| 'dev'
| 'hasReadableErrorStacks'
> &
RequestLifecycleOpts &
Partial<Pick<RenderOpts, 'reactLoadableManifest'>>
......@@ -105,10 +103,8 @@ export function createWorkStore({
!renderOpts.isDraftMode &&
!renderOpts.isPossibleServerAction
const isDevelopment = renderOpts.dev ?? false
const shouldTrackFetchMetrics =
isDevelopment ||
!!process.env.__NEXT_DEV_SERVER ||
// The only times we want to track fetch metrics outside of development is
// when we are performing a static generation and we either are in debug
// mode, or tracking fetch metrics was specifically opted into.
......@@ -126,7 +122,6 @@ export function createWorkStore({
renderOpts.incrementalCache || (globalThis as any).__incrementalCache,
cacheLifeProfiles: renderOpts.cacheLifeProfiles,
isBuildTimePrerendering: renderOpts.isBuildTimePrerendering,
hasReadableErrorStacks: renderOpts.hasReadableErrorStacks,
fetchCache: renderOpts.fetchCache,
isOnDemandRevalidate: renderOpts.isOnDemandRevalidate,
......@@ -140,7 +135,6 @@ export function createWorkStore({
afterContext: createAfterContext(renderOpts),
cacheComponentsEnabled: renderOpts.cacheComponents,
dev: isDevelopment,
previouslyRevalidatedTags,
refreshTagsByCacheKind: createRefreshTagsByCacheKind(),
runInCleanSnapshot: createSnapshot(),
......
......@@ -326,6 +326,7 @@ export default abstract class Server<
protected readonly appPathsManifest?: PagesManifest
protected readonly buildId: string
protected readonly deploymentId: string
protected readonly dev: boolean
protected readonly minimalMode: boolean
protected readonly renderOpts: BaseRenderOpts
protected readonly serverOptions: Readonly<ServerOptions>
......@@ -444,6 +445,7 @@ export default abstract class Server<
experimentalTestProxy,
} = options
this.dev = dev
this.experimentalTestProxy = experimentalTestProxy
this.serverOptions = options
......@@ -1593,11 +1595,7 @@ export default abstract class Server<
return this.renderError(null, req, res, '/_error', {})
}
if (
this.minimalMode ||
this.renderOpts.dev ||
(isBubbledError(err) && err.bubble)
) {
if (this.minimalMode || this.dev || (isBubbledError(err) && err.bubble)) {
throw err
}
this.logError(getProperError(err))
......@@ -1788,10 +1786,10 @@ export default abstract class Server<
const { body } = payload
let { cacheControl } = payload
if (!res.sent) {
const { generateEtags, poweredByHeader, dev } = this.renderOpts
const { generateEtags, poweredByHeader } = this.renderOpts
// In dev, we should not cache pages for any reason.
if (dev) {
if (this.dev) {
res.setHeader(
'Cache-Control',
this.nextConfig.experimental.devCacheControlNoCache
......@@ -2122,7 +2120,7 @@ export default abstract class Server<
req.headers['x-now-route-matches']
) {
isSSG = true
} else if (!this.renderOpts.dev) {
} else if (!this.dev) {
isSSG ||= !!prerenderManifest.routes[toRoute(pathname)]
}
......@@ -2199,7 +2197,7 @@ export default abstract class Server<
// Whether the testing API is exposed (dev mode or explicit flag)
const exposeTestingApi =
this.renderOpts.dev === true ||
this.dev === true ||
this.nextConfig.experimental.exposeTestingApiInProductionBuild === true
// Check for the instant test cookie for MPA navigations (page reload, full
......@@ -2292,7 +2290,7 @@ export default abstract class Server<
}
// In development, we always want to generate dynamic HTML.
if (!isNextDataRequest && isAppPath && opts.dev) {
if (!isNextDataRequest && isAppPath && this.dev) {
opts.supportsDynamicResponse = true
}
......@@ -2329,7 +2327,7 @@ export default abstract class Server<
(components.getStaticPaths || isAppPath)
) {
let getStaticPathsStart: bigint | undefined
if (opts.dev) {
if (this.dev) {
getStaticPathsStart = process.hrtime.bigint()
}
......@@ -2341,7 +2339,7 @@ export default abstract class Server<
isAppPath,
})
if (opts.dev && getStaticPathsStart && pathsResults.staticPaths?.length) {
if (this.dev && getStaticPathsStart && pathsResults.staticPaths?.length) {
addRequestMeta(
req,
'devGenerateStaticParamsDuration',
......@@ -2676,7 +2674,7 @@ export default abstract class Server<
const isWrappedError = err instanceof WrappedBuildError
if (!isWrappedError) {
if (this.minimalMode || this.renderOpts.dev) {
if (this.minimalMode || this.dev) {
if (isError(err)) err.page = page
throw err
}
......@@ -2798,7 +2796,7 @@ export default abstract class Server<
): Promise<ResponsePayload | null> {
// Short-circuit favicon.ico in development to avoid compiling 404 page when the app has no favicon.ico.
// Since favicon.ico is automatically requested by the browser.
if (this.renderOpts.dev && ctx.pathname === '/favicon.ico') {
if (this.dev && ctx.pathname === '/favicon.ico') {
return {
body: RenderResult.EMPTY,
}
......@@ -2850,7 +2848,7 @@ export default abstract class Server<
) {
// skip ensuring /500 in dev mode as it isn't used and the
// dev overlay is used instead
if (statusPage !== '/500' || !this.renderOpts.dev) {
if (statusPage !== '/500' || !this.dev) {
if (!result && hasAppDir) {
// Otherwise if app router present, load app router built-in 500 page
result = await this.findPageComponents({
......@@ -2907,7 +2905,7 @@ export default abstract class Server<
if (!result) {
// this can occur when a project directory has been moved/deleted
// which is handled in the parent process in development
if (this.renderOpts.dev) {
if (this.dev) {
return {
// wait for dev-server to restart before refreshing
body: RenderResult.fromStatic(
......
......@@ -1894,6 +1894,13 @@ function enforceExperimentalFeatures(
false,
configuredExperimentalFeatures
)
setExperimentalFeatureForDebugPrerender(
config.experimental,
'allowDevelopmentBuild',
true,
configuredExperimentalFeatures
)
}
// TODO: Remove this once we've made Cache Components the default.
......
......@@ -186,7 +186,6 @@ export default class DevServer extends Server {
this.bundlerService = options.bundlerService
this.startServerSpan =
options.startServerSpan ?? trace('start-next-dev-server')
this.renderOpts.dev = true
this.renderOpts.ErrorDebug = ReactDevOverlay
this.staticPathsCache = new LRUCache(
// 5MB
......
......@@ -409,7 +409,7 @@ export default class NextNodeServer extends BaseServer<
}: {
requestHeaders: IncrementalCache['requestHeaders']
}) {
const dev = !!this.renderOpts.dev
const dev = !!this.dev
let CacheHandler: any
const { cacheHandler } = this.nextConfig
......@@ -717,7 +717,7 @@ export default class NextNodeServer extends BaseServer<
)
return imageOptimizer(imageUpstream, paramsResult, this.nextConfig, {
isDev: this.renderOpts.dev,
isDev: this.dev,
previousCacheEntry,
})
}
......@@ -922,7 +922,7 @@ export default class NextNodeServer extends BaseServer<
)
)
this.imageCacheHandler = new CacheHandler({
dev: !!this.renderOpts.dev,
dev: !!this.dev,
flushToDisk: this.nextConfig.experimental.isrFlushToDisk,
serverDistDir: this.serverDistDir,
maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize,
......@@ -955,7 +955,7 @@ export default class NextNodeServer extends BaseServer<
req.originalRequest,
parsedUrl.query,
this.nextConfig,
!!this.renderOpts.dev
!!this.dev
)
if ('errorMessage' in paramsResult) {
......@@ -1015,7 +1015,7 @@ export default class NextNodeServer extends BaseServer<
cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT',
imagesConfig,
cacheEntry.cacheControl?.revalidate || 0,
Boolean(this.renderOpts.dev)
Boolean(this.dev)
)
return true
} catch (err) {
......@@ -1146,7 +1146,7 @@ export default class NextNodeServer extends BaseServer<
}
try {
if (this.renderOpts.dev) {
if (this.dev) {
const { formatServerError } =
require('../lib/format-server-error') as typeof import('../lib/format-server-error')
formatServerError(err)
......@@ -1324,7 +1324,7 @@ export default class NextNodeServer extends BaseServer<
const is404 = res.statusCode === 404
if (is404 && this.enabledDirectories.app) {
if (this.renderOpts.dev) {
if (this.dev) {
await this.ensurePage({
page: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
clientOnly: false,
......@@ -1512,7 +1512,7 @@ export default class NextNodeServer extends BaseServer<
private async loadNodeMiddleware() {
if (!process.env.NEXT_MINIMAL) {
try {
const functionsConfig = this.renderOpts.dev
const functionsConfig = this.dev
? {}
: require(
join(
......@@ -1522,10 +1522,7 @@ export default class NextNodeServer extends BaseServer<
)
)
if (
this.renderOpts.dev ||
functionsConfig?.functions?.['/_middleware']
) {
if (this.dev || functionsConfig?.functions?.['/_middleware']) {
// if used with top level await, this will be a promise
return require(
join(
......@@ -1720,7 +1717,7 @@ export default class NextNodeServer extends BaseServer<
})
}
if (!this.renderOpts.dev) {
if (!this.dev) {
result.waitUntil.catch((error) => {
console.error(`Uncaught: middleware waitUntil errored`, error)
})
......@@ -2075,7 +2072,7 @@ export default class NextNodeServer extends BaseServer<
await super.instrumentationOnRequestError(...args)
// For Node.js runtime production logs, in dev it will be overridden by next-dev-server
if (!this.renderOpts.dev) {
if (!this.dev) {
const [err, , , silenceLog] = args
if (!silenceLog) {
this.logError(err)
......
......@@ -402,6 +402,10 @@ class NextCustomServer implements NextWrapperServer {
}
async prepare() {
if (this.options.dev) {
process.env.__NEXT_DEV_SERVER = '1'
}
const { getRequestHandlers } =
require('./lib/start-server') as typeof import('./lib/start-server')
......
......@@ -5,6 +5,7 @@ import type * as util from 'util'
import { SourceMapConsumer as SyncSourceMapConsumer } from 'next/dist/compiled/source-map'
import {
type ModernSourceMapPayload,
devirtualizeReactServerURL,
findApplicableSourceMapPayload,
ignoreListAnonymousStackFramesIfSandwiched as ignoreListAnonymousStackFramesIfSandwichedGeneric,
sourceMapIgnoreListsEverything,
......@@ -201,11 +202,15 @@ function getSourcemappedFrameIfPossible(
sourceMapPayload = maybeSourceMapPayload
try {
// Pass the source map URL as the second parameter so that the consumer
// can resolve relative paths in the source map's `sources` array.
// This is a guess! Turbopack places .map files as siblings to the chunks so this is sufficient to compute
// relative paths but is actually wrong (the chunk and sourcemap have different content hashes).
// We are using the node API to read the sourcemap and it doesn't give us access to the URI.
const sourceMapURL = sourceURL + '.map'
// can resolve relative paths in the source map's `sources` array. This is
// a guess! Turbopack places .map files as siblings to the chunks so this
// is sufficient to compute relative paths but is actually wrong (the
// chunk and sourcemap have different content hashes). We are using the
// node API to read the sourcemap and it doesn't give us access to the
// URI. Devirtualize `about://React/Server/file:///path/to/chunk.js?4` to
// `file:///path/to/chunk.js` so that relative `sources` in the source map
// resolve against the real chunk URL, not the virtual one.
const sourceMapURL = devirtualizeReactServerURL(sourceURL) + '.map'
sourceMapConsumer = new SyncSourceMapConsumer(
sourceMapPayload,
// @ts-expect-error: our typings don't include this parameter but it is here.
......
......@@ -244,7 +244,6 @@ export type RenderOptsPartial = {
assetPrefix?: string
err?: Error | null
isBuildTimePrerendering?: boolean
dev?: boolean
ErrorDebug?: PagesDevOverlayBridgeType
isNextDataRequest?: boolean
params?: ParsedUrlQuery
......@@ -457,9 +456,9 @@ export async function renderToHTMLImpl(
const metadata: PagesRenderResultMetadata = {}
metadata.assetQueryString =
(renderOpts.dev && renderOpts.assetQueryString) || ''
(process.env.__NEXT_DEV_SERVER && renderOpts.assetQueryString) || ''
if (renderOpts.dev && !metadata.assetQueryString) {
if (process.env.__NEXT_DEV_SERVER && !metadata.assetQueryString) {
const userAgent = (req.headers['user-agent'] || '').toLowerCase()
if (userAgent.includes('safari') && !userAgent.includes('chrome')) {
// In dev we invalidate the cache by appending a timestamp to the resource URL.
......@@ -483,7 +482,6 @@ export async function renderToHTMLImpl(
const {
err,
dev = false,
pageConfig = {},
buildManifest,
reactLoadableManifest,
......@@ -554,7 +552,7 @@ export async function renderToHTMLImpl(
// would normally be automatically statically optimized
// ensure we set cache header so it's not rendered on-demand
// every request
if (isAutoExport && !dev && isExperimentalCompile) {
if (isAutoExport && !process.env.__NEXT_DEV_SERVER && isExperimentalCompile) {
res.setHeader(
'Cache-Control',
getCacheControlHeader({ revalidate: false, expire: expireTime })
......@@ -602,7 +600,7 @@ export async function renderToHTMLImpl(
let asPath: string = renderOpts.resolvedAsPath || (req.url as string)
if (dev) {
if (process.env.__NEXT_DEV_SERVER) {
const { isValidElementType } =
require('next/dist/compiled/react-is') as typeof import('next/dist/compiled/react-is')
if (!isValidElementType(Component)) {
......@@ -836,7 +834,7 @@ export async function renderToHTMLImpl(
const nextExport =
!isSSG &&
(renderOpts.isBuildTimePrerendering ||
(dev && (isAutoExport || isFallback)))
(process.env.__NEXT_DEV_SERVER && (isAutoExport || isFallback)))
const styledJsxInsertedHTML = () => {
const styles = jsxStyleRegistry.styles()
......@@ -964,7 +962,7 @@ export async function renderToHTMLImpl(
}
if (
(dev || isBuildTimeSSG) &&
(process.env.__NEXT_DEV_SERVER || isBuildTimeSSG) &&
!metadata.isNotFound &&
!isSerializableProps(pathname, 'getStaticProps', (data as any).props)
) {
......@@ -1183,7 +1181,7 @@ export async function renderToHTMLImpl(
}
if (
(dev || isBuildTimeSSG) &&
(process.env.__NEXT_DEV_SERVER || isBuildTimeSSG) &&
!isSerializableProps(pathname, 'getServerSideProps', (data as any).props)
) {
// this fn should throw an error instead of ever returning `false`
......@@ -1301,7 +1299,10 @@ export async function renderToHTMLImpl(
return { html, head }
}
if (dev && (props.router || props.Component)) {
if (
process.env.__NEXT_DEV_SERVER &&
(props.router || props.Component)
) {
throw new Error(
`'router' and 'Component' can not be returned in getInitialProps from _app.js https://nextjs.org/docs/messages/cant-override-next-props`
)
......@@ -1483,7 +1484,9 @@ export async function renderToHTMLImpl(
dynamicImportsIds.size === 0
? undefined
: Array.from(dynamicImportsIds),
err: renderOpts.err ? serializeError(dev, renderOpts.err) : undefined, // Error if one happened, otherwise don't sent in the resulting HTML
err: renderOpts.err
? serializeError(!!process.env.__NEXT_DEV_SERVER, renderOpts.err)
: undefined, // Error if one happened, otherwise don't sent in the resulting HTML
gsp: !!getStaticProps ? true : undefined, // whether the page is getStaticProps
gssp: !!getServerSideProps ? true : undefined, // whether the page is getServerSideProps
customServer: sharedContext.customServer,
......@@ -1494,13 +1497,16 @@ export async function renderToHTMLImpl(
defaultLocale,
domainLocales,
isPreview: isPreview === true ? true : undefined,
notFoundSrcPage: notFoundSrcPage && dev ? notFoundSrcPage : undefined,
notFoundSrcPage:
notFoundSrcPage && process.env.__NEXT_DEV_SERVER
? notFoundSrcPage
: undefined,
},
nonce,
buildManifest: filteredBuildManifest,
docComponentsRendered,
dangerousAsPath: router.asPath,
isDevelopment: !!dev,
isDevelopment: !!process.env.__NEXT_DEV_SERVER,
deploymentId: sharedContext.deploymentId,
dynamicImports: Array.from(dynamicImports),
dynamicCssManifest: new Set(renderOpts.dynamicCssManifest || []),
......
......@@ -339,7 +339,6 @@ export const getHandler = ({
ErrorDebug: getRequestMeta(req, 'PagesErrorDebug'),
err: getRequestMeta(req, 'invokeError'),
dev: routeModule.isDev,
// needed for experimental.optimizeCss feature
distDir: path.join(
......
......@@ -137,7 +137,7 @@ export abstract class RouteModule<
}: RouteModuleOptions<D, U>) {
this.userland = userland
this.definition = definition
this.isDev = process.env.NODE_ENV === 'development'
this.isDev = !!process.env.__NEXT_DEV_SERVER
this.distDir = distDir
this.relativeProjectDir = relativeProjectDir
}
......
......@@ -217,12 +217,9 @@ function createUseCacheStore(
explicitExpire: undefined,
explicitStale: undefined,
tags: null,
hmrRefreshHash: getHmrRefreshHash(workStore, outerWorkUnitStore),
isHmrRefresh: isHmrRefresh(workStore, outerWorkUnitStore),
serverComponentsHmrCache: getServerComponentsHmrCache(
workStore,
outerWorkUnitStore
),
hmrRefreshHash: getHmrRefreshHash(outerWorkUnitStore),
isHmrRefresh: isHmrRefresh(outerWorkUnitStore),
serverComponentsHmrCache: getServerComponentsHmrCache(outerWorkUnitStore),
forceRevalidate: shouldForceRevalidate(workStore, outerWorkUnitStore),
runtimeStagePromise: getRuntimeStagePromise(outerWorkUnitStore),
draftMode: getDraftModeProviderForCacheScope(
......@@ -267,7 +264,7 @@ function createUseCacheStore(
explicitStale: undefined,
tags: null,
hmrRefreshHash:
outerWorkUnitStore && getHmrRefreshHash(workStore, outerWorkUnitStore),
outerWorkUnitStore && getHmrRefreshHash(outerWorkUnitStore),
isHmrRefresh: useCacheOrRequestStore?.isHmrRefresh ?? false,
serverComponentsHmrCache:
useCacheOrRequestStore?.serverComponentsHmrCache,
......@@ -637,7 +634,7 @@ async function generateCacheEntryImpl(
// necessary here; the errors are encoded in the stream, and will be reported
// in the "Server" environment.
const handleError = createReactServerErrorHandler(
workStore.dev,
process.env.NODE_ENV === 'development',
workStore.isBuildTimePrerendering ?? false,
workStore.reactServerErrorsByDigest,
(error) => {
......@@ -1046,8 +1043,7 @@ export async function cache(
// components have been edited. This is a very coarse approach. But it's
// also only a temporary solution until Action IDs are unique per
// implementation. Remove this once Action IDs hash the implementation.
const hmrRefreshHash =
workUnitStore && getHmrRefreshHash(workStore, workUnitStore)
const hmrRefreshHash = workUnitStore && getHmrRefreshHash(workUnitStore)
const hangingInputAbortSignal = workUnitStore
? createHangingInputAbortSignal(workUnitStore)
......@@ -1906,7 +1902,7 @@ function shouldForceRevalidate(
return true
}
if (workStore.dev && workUnitStore) {
if (process.env.__NEXT_DEV_SERVER && workUnitStore) {
switch (workUnitStore.type) {
case 'request':
return workUnitStore.headers.get('cache-control') === 'no-cache'
......
This source diff could not be displayed because it is too large. You can view the blob instead.
......@@ -18,7 +18,15 @@ describe('build-output-prerender', () => {
if (cacheComponentsEnabled) {
if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (Turbopack, Cache Components)
"▲ Next.js x.y.z (Turbopack)
- Cache Components enabled
- Experiments (use with caution):
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)"
`)
} else if (isRspack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (Rspack)
- Cache Components enabled
- Experiments (use with caution):
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)"
......@@ -42,7 +50,10 @@ describe('build-output-prerender', () => {
`)
} else if (isRspack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (Rspack, Cache Components)"
"▲ Next.js x.y.z (Rspack)
- Cache Components enabled
- Experiments (use with caution):
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)"
`)
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
......@@ -100,21 +111,36 @@ describe('build-output-prerender', () => {
if (cacheComponentsEnabled) {
if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z (Turbopack, Cache Components)
"⚠ Prerendering is running in debug mode with NODE_ENV='development'. This will affect performance and should not be used for production.
▲ Next.js x.y.z (Turbopack)
- Cache Components enabled
- Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)
⨯ turbopackMinify (disabled by \`--debug-prerender\`)"
`)
} else if (isRspack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode with NODE_ENV='development'. This will affect performance and should not be used for production.
▲ Next.js x.y.z (Rspack)
- Cache Components enabled
- Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)
⨯ serverMinification (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)"
`)
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
"⚠ Prerendering is running in debug mode with NODE_ENV='development'. This will affect performance and should not be used for production.
▲ Next.js x.y.z (webpack)
- Cache Components enabled
- Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)
......@@ -125,10 +151,11 @@ describe('build-output-prerender', () => {
} else {
if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
"⚠ Prerendering is running in debug mode with NODE_ENV='development'. This will affect performance and should not be used for production.
▲ Next.js x.y.z (Turbopack)
- Cache Components enabled
- Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)
......@@ -136,19 +163,23 @@ describe('build-output-prerender', () => {
`)
} else if (isRspack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z (Rspack, Cache Components)
"⚠ Prerendering is running in debug mode with NODE_ENV='development'. This will affect performance and should not be used for production.
▲ Next.js x.y.z (Rspack)
- Cache Components enabled
- Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
⨯ serverMinification (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)"
✓ serverSourceMaps (enabled by \`--debug-prerender\`)
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)"
`)
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
"⚠ Prerendering is running in debug mode with NODE_ENV='development'. This will affect performance and should not be used for production.
▲ Next.js x.y.z (webpack)
- Cache Components enabled
- Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
⨯ serverMinification (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)
......@@ -169,17 +200,16 @@ describe('build-output-prerender', () => {
| ^
5 | }
6 |
To get a more detailed stack trace and pinpoint the issue, start the app in development mode by running \`next dev\`, then open "/client" in your browser to investigate the error.
Error occurred prerendering page "/client". Read more: https://nextjs.org/docs/messages/prerender-error
Error: Route "/server" used \`Math.random()\` before accessing either uncached data (e.g. \`fetch()\`) or Request data (e.g. \`cookies()\`, \`headers()\`, \`connection()\`, and \`searchParams\`). Accessing random values synchronously in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-random
at Page (app/server/page.tsx:13:27)
at Page (<anonymous>)
11 | await cachedDelay()
12 |
> 13 | return <p>Random: {Math.random()}</p>
| ^
14 | }
15 |
To get a more detailed stack trace and pinpoint the issue, start the app in development mode by running \`next dev\`, then open "/server" in your browser to investigate the error.
Error occurred prerendering page "/server". Read more: https://nextjs.org/docs/messages/prerender-error
> Export encountered errors on following paths:
......@@ -191,23 +221,23 @@ describe('build-output-prerender', () => {
expect(getPrerenderOutput(next.cliOutput)).toMatchInlineSnapshot(`
"Error: Route "/client" used \`new Date()\` inside a Client Component without a Suspense boundary above it. See more info here: https://nextjs.org/docs/messages/next-prerender-current-time-client
at Page (webpack:///app/client/page.tsx:4:28)
at ClientPageRoot (webpack:///src/client/components/client-page.tsx:74:12)
2 |
3 | export default function Page() {
> 4 | return <p>Current time: {new Date().toISOString()}</p>
| ^
5 | }
6 |
To get a more detailed stack trace and pinpoint the issue, start the app in development mode by running \`next dev\`, then open "/client" in your browser to investigate the error.
Error occurred prerendering page "/client". Read more: https://nextjs.org/docs/messages/prerender-error
Error: Route "/server" used \`Math.random()\` before accessing either uncached data (e.g. \`fetch()\`) or Request data (e.g. \`cookies()\`, \`headers()\`, \`connection()\`, and \`searchParams\`). Accessing random values synchronously in a Server Component requires reading one of these data sources first. Alternatively, consider moving this expression into a Client Component or Cache Component. See more info here: https://nextjs.org/docs/messages/next-prerender-random
at Page (webpack:///app/server/page.tsx:13:27)
at Page (<anonymous>)
11 | await cachedDelay()
12 |
> 13 | return <p>Random: {Math.random()}</p>
| ^
14 | }
15 |
To get a more detailed stack trace and pinpoint the issue, start the app in development mode by running \`next dev\`, then open "/server" in your browser to investigate the error.
Error occurred prerendering page "/server". Read more: https://nextjs.org/docs/messages/prerender-error
> Export encountered errors on following paths:
......@@ -232,7 +262,15 @@ describe('build-output-prerender', () => {
if (cacheComponentsEnabled) {
if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (Turbopack, Cache Components)
"▲ Next.js x.y.z (Turbopack)
- Cache Components enabled
- Experiments (use with caution):
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)"
`)
} else if (isRspack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (Rspack)
- Cache Components enabled
- Experiments (use with caution):
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)"
......@@ -254,9 +292,11 @@ describe('build-output-prerender', () => {
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)"
`)
} else if (isRspack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(
`"▲ Next.js x.y.z (Rspack)"`
)
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (Rspack)
- Experiments (use with caution):
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)"
`)
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"▲ Next.js x.y.z (webpack)
......@@ -281,21 +321,36 @@ describe('build-output-prerender', () => {
if (cacheComponentsEnabled) {
if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z (Turbopack, Cache Components)
"⚠ Prerendering is running in debug mode with NODE_ENV='development'. This will affect performance and should not be used for production.
▲ Next.js x.y.z (Turbopack)
- Cache Components enabled
- Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)
⨯ turbopackMinify (disabled by \`--debug-prerender\`)"
`)
} else if (isRspack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode with NODE_ENV='development'. This will affect performance and should not be used for production.
▲ Next.js x.y.z (Rspack)
- Cache Components enabled
- Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)
⨯ serverMinification (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)"
`)
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
"⚠ Prerendering is running in debug mode with NODE_ENV='development'. This will affect performance and should not be used for production.
▲ Next.js x.y.z (webpack)
- Cache Components enabled
- Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
✓ appNewScrollHandler (enabled by \`__NEXT_EXPERIMENTAL_APP_NEW_SCROLL_HANDLER\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ reactDebugChannel (enabled by \`__NEXT_EXPERIMENTAL_DEBUG_CHANNEL\`)
......@@ -306,9 +361,10 @@ describe('build-output-prerender', () => {
} else {
if (isTurbopack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
"⚠ Prerendering is running in debug mode with NODE_ENV='development'. This will affect performance and should not be used for production.
▲ Next.js x.y.z (Turbopack)
- Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)
......@@ -316,18 +372,21 @@ describe('build-output-prerender', () => {
`)
} else if (isRspack) {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
▲ Next.js x.y.z (Rspack)
- Experiments (use with caution):
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
⨯ serverMinification (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)"
"⚠ Prerendering is running in debug mode with NODE_ENV='development'. This will affect performance and should not be used for production.
▲ Next.js x.y.z (Rspack)
- Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
⨯ serverMinification (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)
✓ strictRouteTypes (enabled by \`__NEXT_EXPERIMENTAL_STRICT_ROUTE_TYPES\`)"
`)
} else {
expect(getPreambleOutput(next.cliOutput)).toMatchInlineSnapshot(`
"⚠ Prerendering is running in debug mode. Note: This may affect performance and should not be used for production.
"⚠ Prerendering is running in debug mode with NODE_ENV='development'. This will affect performance and should not be used for production.
▲ Next.js x.y.z (webpack)
- Experiments (use with caution):
✓ allowDevelopmentBuild (enabled by \`--debug-prerender\`)
⨯ prerenderEarlyExit (disabled by \`--debug-prerender\`)
⨯ serverMinification (disabled by \`--debug-prerender\`)
✓ serverSourceMaps (enabled by \`--debug-prerender\`)
......
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