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. ...@@ -246,6 +246,13 @@ See [Codebase structure](#codebase-structure) above for detailed explanations.
- Use `DEBUG=next:*` for debug logging - Use `DEBUG=next:*` for debug logging
- Use `NEXT_TELEMETRY_DISABLED=1` when testing locally - 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 ## Commit and PR Style
- Do NOT add "Generated with Claude Code" or co-author footers to commits or PRs - 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 ...@@ -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). 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 ## Recover disk space
Rust builds quickly add up to a lot of disk space, you can clean up old artifacts with this command: 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 }) => { ...@@ -209,8 +209,11 @@ module.exports = ({ dev, turbo, bundleType, experimental, ...rest }) => {
'process.env.NEXT_MINIMAL': JSON.stringify('true'), 'process.env.NEXT_MINIMAL': JSON.stringify('true'),
'this.serverOptions.experimentalTestProxy': JSON.stringify(false), 'this.serverOptions.experimentalTestProxy': JSON.stringify(false),
'this.minimalMode': JSON.stringify(true), 'this.minimalMode': JSON.stringify(true),
'this.renderOpts.dev': JSON.stringify(dev), // Only inline __NEXT_DEV_SERVER in prod bundles (for dead-code
'renderOpts.dev': JSON.stringify(dev), // 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( 'process.env.NODE_ENV': JSON.stringify(
dev ? 'development' : 'production' dev ? 'development' : 'production'
), ),
......
...@@ -194,6 +194,10 @@ program ...@@ -194,6 +194,10 @@ program
'Enable CPU profiling. Profile is saved to .next/cpu-profiles/ on completion.' 'Enable CPU profiling. Profile is saved to .next/cpu-profiles/ on completion.'
) )
.action((directory: string, options: NextBuildOptions) => { .action((directory: string, options: NextBuildOptions) => {
if (options.debugPrerender) {
// @ts-expect-error not readonly
process.env.NODE_ENV = 'development'
}
if (options.experimentalNextConfigStripTypes) { if (options.experimentalNextConfigStripTypes) {
process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'true' process.env.__NEXT_NODE_NATIVE_TS_LOADER_ENABLED = 'true'
} }
......
...@@ -157,6 +157,7 @@ export function getDefineEnv({ ...@@ -157,6 +157,7 @@ export function getDefineEnv({
dev || config.experimental.allowDevelopmentBuild dev || config.experimental.allowDevelopmentBuild
? 'development' ? 'development'
: 'production', : 'production',
'process.env.__NEXT_DEV_SERVER': dev ? '1' : '',
'process.env.NEXT_RUNTIME': isEdgeServer 'process.env.NEXT_RUNTIME': isEdgeServer
? 'edge' ? 'edge'
: isNodeServer : isNodeServer
......
...@@ -836,7 +836,7 @@ export async function buildAppStaticPaths({ ...@@ -836,7 +836,7 @@ export async function buildAppStaticPaths({
) )
const supportsRoutePreGeneration = const supportsRoutePreGeneration =
hadAllParamsGenerated || process.env.NODE_ENV === 'production' hadAllParamsGenerated || !process.env.__NEXT_DEV_SERVER
const fallbackMode = dynamicParams const fallbackMode = dynamicParams
? supportsRoutePreGeneration ? supportsRoutePreGeneration
......
...@@ -762,7 +762,6 @@ export async function handler( ...@@ -762,7 +762,6 @@ export async function handler(
routerServerContext routerServerContext
), ),
err: getRequestMeta(req, 'invokeError'), err: getRequestMeta(req, 'invokeError'),
dev: routeModule.isDev,
}, },
} }
......
...@@ -197,7 +197,6 @@ async function requestHandler( ...@@ -197,7 +197,6 @@ async function requestHandler(
silenceLog, silenceLog,
routerServerContext routerServerContext
), ),
dev: pageRouteModule.isDev,
}, },
} }
let finalStatus = 200 let finalStatus = 200
......
...@@ -85,8 +85,8 @@ const nextBuild = async (options: NextBuildOptions, directory?: string) => { ...@@ -85,8 +85,8 @@ const nextBuild = async (options: NextBuildOptions, directory?: string) => {
if (debugPrerender) { if (debugPrerender) {
warn( warn(
`Prerendering is running in debug mode. ${italic( `Prerendering is running in debug mode with NODE_ENV='development'. ${italic(
'Note: This may affect performance and should not be used for production.' 'This will affect performance and should not be used for production.'
)}` )}`
) )
} }
......
...@@ -328,6 +328,7 @@ const nextDev = async ( ...@@ -328,6 +328,7 @@ const nextDev = async (
env: { env: {
...defaultEnv, ...defaultEnv,
...(isTurbopack ? { TURBOPACK: process.env.TURBOPACK } : undefined), ...(isTurbopack ? { TURBOPACK: process.env.TURBOPACK } : undefined),
__NEXT_DEV_SERVER: '1',
NEXT_PRIVATE_START_TIME: process.env.NEXT_PRIVATE_START_TIME, NEXT_PRIVATE_START_TIME: process.env.NEXT_PRIVATE_START_TIME,
NEXT_PRIVATE_WORKER: '1', NEXT_PRIVATE_WORKER: '1',
NEXT_PRIVATE_TRACE_ID: traceId, NEXT_PRIVATE_TRACE_ID: traceId,
......
...@@ -2,7 +2,8 @@ const basePath = process.env.__NEXT_ROUTER_BASEPATH || '' ...@@ -2,7 +2,8 @@ const basePath = process.env.__NEXT_ROUTER_BASEPATH || ''
const pathname = `${basePath}/__nextjs_source-map` const pathname = `${basePath}/__nextjs_source-map`
export const findSourceMapURL = 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 { ? function findSourceMapURL(filename: string): string | null {
if (filename === '') { if (filename === '') {
return null return null
......
// imports polyfill from `@next/polyfill-module` after build. // imports polyfill from `@next/polyfill-module` after build.
import '../build/polyfills/polyfill-module' import '../build/polyfills/polyfill-module'
// Only setup devtools in development // Only set up devtools for the dev server.
if (process.env.NODE_ENV !== 'production') { 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') 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: ...@@ -190,7 +190,7 @@ let debugChannel:
| undefined | undefined
if ( if (
process.env.NODE_ENV !== 'production' && process.env.__NEXT_DEV_SERVER &&
process.env.__NEXT_REACT_DEBUG_CHANNEL && process.env.__NEXT_REACT_DEBUG_CHANNEL &&
typeof window !== 'undefined' typeof window !== 'undefined'
) { ) {
...@@ -310,7 +310,7 @@ export async function hydrate( ...@@ -310,7 +310,7 @@ export async function hydrate(
let staticIndicatorState: StaticIndicatorState | undefined let staticIndicatorState: StaticIndicatorState | undefined
let webSocket: WebSocket | undefined let webSocket: WebSocket | undefined
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_DEV_SERVER) {
const { createWebSocket } = const { createWebSocket } =
require('./dev/hot-reloader/app/web-socket') as typeof import('./dev/hot-reloader/app/web-socket') require('./dev/hot-reloader/app/web-socket') as typeof import('./dev/hot-reloader/app/web-socket')
...@@ -380,7 +380,7 @@ export async function hydrate( ...@@ -380,7 +380,7 @@ export async function hydrate(
} }
// TODO-APP: Remove this logic when Float has GC built-in in development. // 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 } = const { linkGc } =
require('./app-link-gc') as typeof import('./app-link-gc') require('./app-link-gc') as typeof import('./app-link-gc')
linkGc() linkGc()
......
...@@ -13,7 +13,7 @@ appBootstrap((assetPrefix) => { ...@@ -13,7 +13,7 @@ appBootstrap((assetPrefix) => {
try { try {
hydrate(instrumentationHooks, assetPrefix) hydrate(instrumentationHooks, assetPrefix)
} finally { } finally {
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_DEV_SERVER) {
const enableCacheIndicator = process.env.__NEXT_CACHE_COMPONENTS const enableCacheIndicator = process.env.__NEXT_CACHE_COMPONENTS
const { getOwnerStack } = const { getOwnerStack } =
require('../next-devtools/userspace/app/errors/stitched-error') as typeof import('../next-devtools/userspace/app/errors/stitched-error') require('../next-devtools/userspace/app/errors/stitched-error') as typeof import('../next-devtools/userspace/app/errors/stitched-error')
......
...@@ -479,7 +479,7 @@ function Router({ ...@@ -479,7 +479,7 @@ function Router({
</RedirectBoundary> </RedirectBoundary>
) )
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_DEV_SERVER) {
// In development, we apply few error boundaries and hot-reloader: // In development, we apply few error boundaries and hot-reloader:
// - DevRootHTTPAccessFallbackBoundary: avoid using navigation API like notFound() in root layout // - DevRootHTTPAccessFallbackBoundary: avoid using navigation API like notFound() in root layout
// - HotReloader: // - HotReloader:
......
...@@ -50,10 +50,7 @@ let createDebugChannel: ...@@ -50,10 +50,7 @@ let createDebugChannel:
| typeof import('../../dev/debug-channel').createDebugChannel | typeof import('../../dev/debug-channel').createDebugChannel
| undefined | undefined
if ( if (process.env.__NEXT_DEV_SERVER && process.env.__NEXT_REACT_DEBUG_CHANNEL) {
process.env.NODE_ENV !== 'production' &&
process.env.__NEXT_REACT_DEBUG_CHANNEL
) {
createDebugChannel = ( createDebugChannel = (
require('../../dev/debug-channel') as typeof import('../../dev/debug-channel') require('../../dev/debug-channel') as typeof import('../../dev/debug-channel')
).createDebugChannel ).createDebugChannel
...@@ -322,7 +319,7 @@ export async function createFetch<T>( ...@@ -322,7 +319,7 @@ export async function createFetch<T>(
headers['x-deployment-id'] = deploymentId headers['x-deployment-id'] = deploymentId
} }
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_DEV_SERVER) {
if (self.__next_r) { if (self.__next_r) {
headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r
} }
......
...@@ -73,10 +73,7 @@ let createDebugChannel: ...@@ -73,10 +73,7 @@ let createDebugChannel:
| typeof import('../../../dev/debug-channel').createDebugChannel | typeof import('../../../dev/debug-channel').createDebugChannel
| undefined | undefined
if ( if (process.env.__NEXT_DEV_SERVER && process.env.__NEXT_REACT_DEBUG_CHANNEL) {
process.env.NODE_ENV !== 'production' &&
process.env.__NEXT_REACT_DEBUG_CHANNEL
) {
createDebugChannel = ( createDebugChannel = (
require('../../../dev/debug-channel') as typeof import('../../../dev/debug-channel') require('../../../dev/debug-channel') as typeof import('../../../dev/debug-channel')
).createDebugChannel ).createDebugChannel
...@@ -123,7 +120,7 @@ async function fetchServerAction( ...@@ -123,7 +120,7 @@ async function fetchServerAction(
headers[NEXT_URL] = nextUrl headers[NEXT_URL] = nextUrl
} }
if (process.env.NODE_ENV !== 'production') { if (process.env.__NEXT_DEV_SERVER) {
if (self.__next_r) { if (self.__next_r) {
headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r headers[NEXT_HTML_REQUEST_ID_HEADER] = self.__next_r
} }
......
...@@ -477,7 +477,6 @@ async function exportAppImpl( ...@@ -477,7 +477,6 @@ async function exportAppImpl(
isBuildTimePrerendering: true, isBuildTimePrerendering: true,
assetPrefix: nextConfig.assetPrefix.replace(/\/$/, ''), assetPrefix: nextConfig.assetPrefix.replace(/\/$/, ''),
distDir, distDir,
dev: false,
basePath: nextConfig.basePath, basePath: nextConfig.basePath,
cacheComponents: nextConfig.cacheComponents ?? false, cacheComponents: nextConfig.cacheComponents ?? false,
trailingSlash: nextConfig.trailingSlash, trailingSlash: nextConfig.trailingSlash,
...@@ -516,14 +515,6 @@ async function exportAppImpl( ...@@ -516,14 +515,6 @@ async function exportAppImpl(
), ),
}, },
reactMaxHeadersLength: nextConfig.reactMaxHeadersLength, 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. // We need this for server rendering the Link component.
......
...@@ -424,7 +424,7 @@ async function createComponentTreeInternal( ...@@ -424,7 +424,7 @@ async function createComponentTreeInternal(
} }
// Resolve the segment param // Resolve the segment param
const isSegmentViewEnabled = !!ctx.renderOpts.dev const isSegmentViewEnabled = !!process.env.__NEXT_DEV_SERVER
const dir = const dir =
(process.env.NEXT_RUNTIME === 'edge' (process.env.NEXT_RUNTIME === 'edge'
? process.env.__NEXT_EDGE_PROJECT_DIR ? process.env.__NEXT_EDGE_PROJECT_DIR
...@@ -1193,7 +1193,7 @@ async function createBoundaryConventionElement({ ...@@ -1193,7 +1193,7 @@ async function createBoundaryConventionElement({
const { const {
componentMod: { createElement, Fragment }, componentMod: { createElement, Fragment },
} = ctx } = ctx
const isSegmentViewEnabled = !!ctx.renderOpts.dev const isSegmentViewEnabled = !!process.env.__NEXT_DEV_SERVER
const dir = const dir =
(process.env.NEXT_RUNTIME === 'edge' (process.env.NEXT_RUNTIME === 'edge'
? process.env.__NEXT_EDGE_PROJECT_DIR ? process.env.__NEXT_EDGE_PROJECT_DIR
......
...@@ -980,16 +980,10 @@ export function logDisallowedDynamicError( ...@@ -980,16 +980,10 @@ export function logDisallowedDynamicError(
): void { ): void {
console.error(error) console.error(error)
if (!workStore.dev) { if (process.env.NODE_ENV !== 'development') {
if (workStore.hasReadableErrorStacks) { console.error(`To get a more detailed stack trace and pinpoint the issue, try one of the following:
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:
- Start the app in development mode by running \`next dev\`, then open "${workStore.route}" in your browser to investigate the error. - 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.`) - Rerun the production build with \`next build --debug-prerender\` to generate better stack traces.`)
}
} }
} }
......
...@@ -91,7 +91,6 @@ export interface RenderOptsPartial { ...@@ -91,7 +91,6 @@ export interface RenderOptsPartial {
dir?: string dir?: string
previewProps: __ApiPreviewProps | undefined previewProps: __ApiPreviewProps | undefined
err?: Error | null err?: Error | null
dev?: boolean
basePath: string basePath: string
cacheComponents: boolean cacheComponents: boolean
trailingSlash: boolean trailingSlash: boolean
...@@ -192,13 +191,6 @@ export interface RenderOptsPartial { ...@@ -192,13 +191,6 @@ export interface RenderOptsPartial {
isDebugDynamicAccesses?: boolean 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 maximum length of the headers that are emitted by React and added to
* the response. * the response.
......
...@@ -32,14 +32,6 @@ export interface WorkStore { ...@@ -32,14 +32,6 @@ export interface WorkStore {
readonly isOnDemandRevalidate?: boolean readonly isOnDemandRevalidate?: boolean
readonly isBuildTimePrerendering?: boolean readonly isBuildTimePrerendering?: boolean
/**
* This is true when:
* - source maps are generated
* - source maps are applied
* - minification is disabled
*/
readonly hasReadableErrorStacks?: boolean
forceDynamic?: boolean forceDynamic?: boolean
fetchCache?: AppSegmentConfig['fetchCache'] fetchCache?: AppSegmentConfig['fetchCache']
...@@ -106,7 +98,6 @@ export interface WorkStore { ...@@ -106,7 +98,6 @@ export interface WorkStore {
readonly nonce?: string readonly nonce?: string
cacheComponentsEnabled: boolean cacheComponentsEnabled: boolean
dev: boolean
/** /**
* Run the given function inside a clean AsyncLocalStorage snapshot. This is * Run the given function inside a clean AsyncLocalStorage snapshot. This is
......
...@@ -415,10 +415,9 @@ export function getRenderResumeDataCache( ...@@ -415,10 +415,9 @@ export function getRenderResumeDataCache(
} }
export function getHmrRefreshHash( export function getHmrRefreshHash(
workStore: WorkStore,
workUnitStore: WorkUnitStore workUnitStore: WorkUnitStore
): string | undefined { ): string | undefined {
if (workStore.dev) { if (process.env.__NEXT_DEV_SERVER) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -440,11 +439,8 @@ export function getHmrRefreshHash( ...@@ -440,11 +439,8 @@ export function getHmrRefreshHash(
return undefined return undefined
} }
export function isHmrRefresh( export function isHmrRefresh(workUnitStore: WorkUnitStore): boolean {
workStore: WorkStore, if (process.env.__NEXT_DEV_SERVER) {
workUnitStore: WorkUnitStore
): boolean {
if (workStore.dev) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
...@@ -466,10 +462,9 @@ export function isHmrRefresh( ...@@ -466,10 +462,9 @@ export function isHmrRefresh(
} }
export function getServerComponentsHmrCache( export function getServerComponentsHmrCache(
workStore: WorkStore,
workUnitStore: WorkUnitStore workUnitStore: WorkUnitStore
): ServerComponentsHmrCache | undefined { ): ServerComponentsHmrCache | undefined {
if (workStore.dev) { if (process.env.__NEXT_DEV_SERVER) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'cache': case 'cache':
case 'private-cache': case 'private-cache':
......
...@@ -58,8 +58,6 @@ export type WorkStoreContext = { ...@@ -58,8 +58,6 @@ export type WorkStoreContext = {
| 'isBuildTimePrerendering' | 'isBuildTimePrerendering'
| 'isDraftMode' | 'isDraftMode'
| 'isDebugDynamicAccesses' | 'isDebugDynamicAccesses'
| 'dev'
| 'hasReadableErrorStacks'
> & > &
RequestLifecycleOpts & RequestLifecycleOpts &
Partial<Pick<RenderOpts, 'reactLoadableManifest'>> Partial<Pick<RenderOpts, 'reactLoadableManifest'>>
...@@ -105,10 +103,8 @@ export function createWorkStore({ ...@@ -105,10 +103,8 @@ export function createWorkStore({
!renderOpts.isDraftMode && !renderOpts.isDraftMode &&
!renderOpts.isPossibleServerAction !renderOpts.isPossibleServerAction
const isDevelopment = renderOpts.dev ?? false
const shouldTrackFetchMetrics = const shouldTrackFetchMetrics =
isDevelopment || !!process.env.__NEXT_DEV_SERVER ||
// The only times we want to track fetch metrics outside of development is // 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 // when we are performing a static generation and we either are in debug
// mode, or tracking fetch metrics was specifically opted into. // mode, or tracking fetch metrics was specifically opted into.
...@@ -126,7 +122,6 @@ export function createWorkStore({ ...@@ -126,7 +122,6 @@ export function createWorkStore({
renderOpts.incrementalCache || (globalThis as any).__incrementalCache, renderOpts.incrementalCache || (globalThis as any).__incrementalCache,
cacheLifeProfiles: renderOpts.cacheLifeProfiles, cacheLifeProfiles: renderOpts.cacheLifeProfiles,
isBuildTimePrerendering: renderOpts.isBuildTimePrerendering, isBuildTimePrerendering: renderOpts.isBuildTimePrerendering,
hasReadableErrorStacks: renderOpts.hasReadableErrorStacks,
fetchCache: renderOpts.fetchCache, fetchCache: renderOpts.fetchCache,
isOnDemandRevalidate: renderOpts.isOnDemandRevalidate, isOnDemandRevalidate: renderOpts.isOnDemandRevalidate,
...@@ -140,7 +135,6 @@ export function createWorkStore({ ...@@ -140,7 +135,6 @@ export function createWorkStore({
afterContext: createAfterContext(renderOpts), afterContext: createAfterContext(renderOpts),
cacheComponentsEnabled: renderOpts.cacheComponents, cacheComponentsEnabled: renderOpts.cacheComponents,
dev: isDevelopment,
previouslyRevalidatedTags, previouslyRevalidatedTags,
refreshTagsByCacheKind: createRefreshTagsByCacheKind(), refreshTagsByCacheKind: createRefreshTagsByCacheKind(),
runInCleanSnapshot: createSnapshot(), runInCleanSnapshot: createSnapshot(),
......
...@@ -326,6 +326,7 @@ export default abstract class Server< ...@@ -326,6 +326,7 @@ export default abstract class Server<
protected readonly appPathsManifest?: PagesManifest protected readonly appPathsManifest?: PagesManifest
protected readonly buildId: string protected readonly buildId: string
protected readonly deploymentId: string protected readonly deploymentId: string
protected readonly dev: boolean
protected readonly minimalMode: boolean protected readonly minimalMode: boolean
protected readonly renderOpts: BaseRenderOpts protected readonly renderOpts: BaseRenderOpts
protected readonly serverOptions: Readonly<ServerOptions> protected readonly serverOptions: Readonly<ServerOptions>
...@@ -444,6 +445,7 @@ export default abstract class Server< ...@@ -444,6 +445,7 @@ export default abstract class Server<
experimentalTestProxy, experimentalTestProxy,
} = options } = options
this.dev = dev
this.experimentalTestProxy = experimentalTestProxy this.experimentalTestProxy = experimentalTestProxy
this.serverOptions = options this.serverOptions = options
...@@ -1593,11 +1595,7 @@ export default abstract class Server< ...@@ -1593,11 +1595,7 @@ export default abstract class Server<
return this.renderError(null, req, res, '/_error', {}) return this.renderError(null, req, res, '/_error', {})
} }
if ( if (this.minimalMode || this.dev || (isBubbledError(err) && err.bubble)) {
this.minimalMode ||
this.renderOpts.dev ||
(isBubbledError(err) && err.bubble)
) {
throw err throw err
} }
this.logError(getProperError(err)) this.logError(getProperError(err))
...@@ -1788,10 +1786,10 @@ export default abstract class Server< ...@@ -1788,10 +1786,10 @@ export default abstract class Server<
const { body } = payload const { body } = payload
let { cacheControl } = payload let { cacheControl } = payload
if (!res.sent) { if (!res.sent) {
const { generateEtags, poweredByHeader, dev } = this.renderOpts const { generateEtags, poweredByHeader } = this.renderOpts
// In dev, we should not cache pages for any reason. // In dev, we should not cache pages for any reason.
if (dev) { if (this.dev) {
res.setHeader( res.setHeader(
'Cache-Control', 'Cache-Control',
this.nextConfig.experimental.devCacheControlNoCache this.nextConfig.experimental.devCacheControlNoCache
...@@ -2122,7 +2120,7 @@ export default abstract class Server< ...@@ -2122,7 +2120,7 @@ export default abstract class Server<
req.headers['x-now-route-matches'] req.headers['x-now-route-matches']
) { ) {
isSSG = true isSSG = true
} else if (!this.renderOpts.dev) { } else if (!this.dev) {
isSSG ||= !!prerenderManifest.routes[toRoute(pathname)] isSSG ||= !!prerenderManifest.routes[toRoute(pathname)]
} }
...@@ -2199,7 +2197,7 @@ export default abstract class Server< ...@@ -2199,7 +2197,7 @@ export default abstract class Server<
// Whether the testing API is exposed (dev mode or explicit flag) // Whether the testing API is exposed (dev mode or explicit flag)
const exposeTestingApi = const exposeTestingApi =
this.renderOpts.dev === true || this.dev === true ||
this.nextConfig.experimental.exposeTestingApiInProductionBuild === true this.nextConfig.experimental.exposeTestingApiInProductionBuild === true
// Check for the instant test cookie for MPA navigations (page reload, full // Check for the instant test cookie for MPA navigations (page reload, full
...@@ -2292,7 +2290,7 @@ export default abstract class Server< ...@@ -2292,7 +2290,7 @@ export default abstract class Server<
} }
// In development, we always want to generate dynamic HTML. // In development, we always want to generate dynamic HTML.
if (!isNextDataRequest && isAppPath && opts.dev) { if (!isNextDataRequest && isAppPath && this.dev) {
opts.supportsDynamicResponse = true opts.supportsDynamicResponse = true
} }
...@@ -2329,7 +2327,7 @@ export default abstract class Server< ...@@ -2329,7 +2327,7 @@ export default abstract class Server<
(components.getStaticPaths || isAppPath) (components.getStaticPaths || isAppPath)
) { ) {
let getStaticPathsStart: bigint | undefined let getStaticPathsStart: bigint | undefined
if (opts.dev) { if (this.dev) {
getStaticPathsStart = process.hrtime.bigint() getStaticPathsStart = process.hrtime.bigint()
} }
...@@ -2341,7 +2339,7 @@ export default abstract class Server< ...@@ -2341,7 +2339,7 @@ export default abstract class Server<
isAppPath, isAppPath,
}) })
if (opts.dev && getStaticPathsStart && pathsResults.staticPaths?.length) { if (this.dev && getStaticPathsStart && pathsResults.staticPaths?.length) {
addRequestMeta( addRequestMeta(
req, req,
'devGenerateStaticParamsDuration', 'devGenerateStaticParamsDuration',
...@@ -2676,7 +2674,7 @@ export default abstract class Server< ...@@ -2676,7 +2674,7 @@ export default abstract class Server<
const isWrappedError = err instanceof WrappedBuildError const isWrappedError = err instanceof WrappedBuildError
if (!isWrappedError) { if (!isWrappedError) {
if (this.minimalMode || this.renderOpts.dev) { if (this.minimalMode || this.dev) {
if (isError(err)) err.page = page if (isError(err)) err.page = page
throw err throw err
} }
...@@ -2798,7 +2796,7 @@ export default abstract class Server< ...@@ -2798,7 +2796,7 @@ export default abstract class Server<
): Promise<ResponsePayload | null> { ): Promise<ResponsePayload | null> {
// Short-circuit favicon.ico in development to avoid compiling 404 page when the app has no favicon.ico. // 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. // 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 { return {
body: RenderResult.EMPTY, body: RenderResult.EMPTY,
} }
...@@ -2850,7 +2848,7 @@ export default abstract class Server< ...@@ -2850,7 +2848,7 @@ export default abstract class Server<
) { ) {
// skip ensuring /500 in dev mode as it isn't used and the // skip ensuring /500 in dev mode as it isn't used and the
// dev overlay is used instead // dev overlay is used instead
if (statusPage !== '/500' || !this.renderOpts.dev) { if (statusPage !== '/500' || !this.dev) {
if (!result && hasAppDir) { if (!result && hasAppDir) {
// Otherwise if app router present, load app router built-in 500 page // Otherwise if app router present, load app router built-in 500 page
result = await this.findPageComponents({ result = await this.findPageComponents({
...@@ -2907,7 +2905,7 @@ export default abstract class Server< ...@@ -2907,7 +2905,7 @@ export default abstract class Server<
if (!result) { if (!result) {
// this can occur when a project directory has been moved/deleted // this can occur when a project directory has been moved/deleted
// which is handled in the parent process in development // which is handled in the parent process in development
if (this.renderOpts.dev) { if (this.dev) {
return { return {
// wait for dev-server to restart before refreshing // wait for dev-server to restart before refreshing
body: RenderResult.fromStatic( body: RenderResult.fromStatic(
......
...@@ -1894,6 +1894,13 @@ function enforceExperimentalFeatures( ...@@ -1894,6 +1894,13 @@ function enforceExperimentalFeatures(
false, false,
configuredExperimentalFeatures configuredExperimentalFeatures
) )
setExperimentalFeatureForDebugPrerender(
config.experimental,
'allowDevelopmentBuild',
true,
configuredExperimentalFeatures
)
} }
// TODO: Remove this once we've made Cache Components the default. // TODO: Remove this once we've made Cache Components the default.
......
...@@ -186,7 +186,6 @@ export default class DevServer extends Server { ...@@ -186,7 +186,6 @@ export default class DevServer extends Server {
this.bundlerService = options.bundlerService this.bundlerService = options.bundlerService
this.startServerSpan = this.startServerSpan =
options.startServerSpan ?? trace('start-next-dev-server') options.startServerSpan ?? trace('start-next-dev-server')
this.renderOpts.dev = true
this.renderOpts.ErrorDebug = ReactDevOverlay this.renderOpts.ErrorDebug = ReactDevOverlay
this.staticPathsCache = new LRUCache( this.staticPathsCache = new LRUCache(
// 5MB // 5MB
......
...@@ -409,7 +409,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -409,7 +409,7 @@ export default class NextNodeServer extends BaseServer<
}: { }: {
requestHeaders: IncrementalCache['requestHeaders'] requestHeaders: IncrementalCache['requestHeaders']
}) { }) {
const dev = !!this.renderOpts.dev const dev = !!this.dev
let CacheHandler: any let CacheHandler: any
const { cacheHandler } = this.nextConfig const { cacheHandler } = this.nextConfig
...@@ -717,7 +717,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -717,7 +717,7 @@ export default class NextNodeServer extends BaseServer<
) )
return imageOptimizer(imageUpstream, paramsResult, this.nextConfig, { return imageOptimizer(imageUpstream, paramsResult, this.nextConfig, {
isDev: this.renderOpts.dev, isDev: this.dev,
previousCacheEntry, previousCacheEntry,
}) })
} }
...@@ -922,7 +922,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -922,7 +922,7 @@ export default class NextNodeServer extends BaseServer<
) )
) )
this.imageCacheHandler = new CacheHandler({ this.imageCacheHandler = new CacheHandler({
dev: !!this.renderOpts.dev, dev: !!this.dev,
flushToDisk: this.nextConfig.experimental.isrFlushToDisk, flushToDisk: this.nextConfig.experimental.isrFlushToDisk,
serverDistDir: this.serverDistDir, serverDistDir: this.serverDistDir,
maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize, maxMemoryCacheSize: this.nextConfig.cacheMaxMemorySize,
...@@ -955,7 +955,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -955,7 +955,7 @@ export default class NextNodeServer extends BaseServer<
req.originalRequest, req.originalRequest,
parsedUrl.query, parsedUrl.query,
this.nextConfig, this.nextConfig,
!!this.renderOpts.dev !!this.dev
) )
if ('errorMessage' in paramsResult) { if ('errorMessage' in paramsResult) {
...@@ -1015,7 +1015,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -1015,7 +1015,7 @@ export default class NextNodeServer extends BaseServer<
cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT', cacheEntry.isMiss ? 'MISS' : cacheEntry.isStale ? 'STALE' : 'HIT',
imagesConfig, imagesConfig,
cacheEntry.cacheControl?.revalidate || 0, cacheEntry.cacheControl?.revalidate || 0,
Boolean(this.renderOpts.dev) Boolean(this.dev)
) )
return true return true
} catch (err) { } catch (err) {
...@@ -1146,7 +1146,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -1146,7 +1146,7 @@ export default class NextNodeServer extends BaseServer<
} }
try { try {
if (this.renderOpts.dev) { if (this.dev) {
const { formatServerError } = const { formatServerError } =
require('../lib/format-server-error') as typeof import('../lib/format-server-error') require('../lib/format-server-error') as typeof import('../lib/format-server-error')
formatServerError(err) formatServerError(err)
...@@ -1324,7 +1324,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -1324,7 +1324,7 @@ export default class NextNodeServer extends BaseServer<
const is404 = res.statusCode === 404 const is404 = res.statusCode === 404
if (is404 && this.enabledDirectories.app) { if (is404 && this.enabledDirectories.app) {
if (this.renderOpts.dev) { if (this.dev) {
await this.ensurePage({ await this.ensurePage({
page: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY, page: UNDERSCORE_NOT_FOUND_ROUTE_ENTRY,
clientOnly: false, clientOnly: false,
...@@ -1512,7 +1512,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -1512,7 +1512,7 @@ export default class NextNodeServer extends BaseServer<
private async loadNodeMiddleware() { private async loadNodeMiddleware() {
if (!process.env.NEXT_MINIMAL) { if (!process.env.NEXT_MINIMAL) {
try { try {
const functionsConfig = this.renderOpts.dev const functionsConfig = this.dev
? {} ? {}
: require( : require(
join( join(
...@@ -1522,10 +1522,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -1522,10 +1522,7 @@ export default class NextNodeServer extends BaseServer<
) )
) )
if ( if (this.dev || functionsConfig?.functions?.['/_middleware']) {
this.renderOpts.dev ||
functionsConfig?.functions?.['/_middleware']
) {
// if used with top level await, this will be a promise // if used with top level await, this will be a promise
return require( return require(
join( join(
...@@ -1720,7 +1717,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -1720,7 +1717,7 @@ export default class NextNodeServer extends BaseServer<
}) })
} }
if (!this.renderOpts.dev) { if (!this.dev) {
result.waitUntil.catch((error) => { result.waitUntil.catch((error) => {
console.error(`Uncaught: middleware waitUntil errored`, error) console.error(`Uncaught: middleware waitUntil errored`, error)
}) })
...@@ -2075,7 +2072,7 @@ export default class NextNodeServer extends BaseServer< ...@@ -2075,7 +2072,7 @@ export default class NextNodeServer extends BaseServer<
await super.instrumentationOnRequestError(...args) await super.instrumentationOnRequestError(...args)
// For Node.js runtime production logs, in dev it will be overridden by next-dev-server // 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 const [err, , , silenceLog] = args
if (!silenceLog) { if (!silenceLog) {
this.logError(err) this.logError(err)
......
...@@ -402,6 +402,10 @@ class NextCustomServer implements NextWrapperServer { ...@@ -402,6 +402,10 @@ class NextCustomServer implements NextWrapperServer {
} }
async prepare() { async prepare() {
if (this.options.dev) {
process.env.__NEXT_DEV_SERVER = '1'
}
const { getRequestHandlers } = const { getRequestHandlers } =
require('./lib/start-server') as typeof import('./lib/start-server') require('./lib/start-server') as typeof import('./lib/start-server')
......
...@@ -5,6 +5,7 @@ import type * as util from 'util' ...@@ -5,6 +5,7 @@ import type * as util from 'util'
import { SourceMapConsumer as SyncSourceMapConsumer } from 'next/dist/compiled/source-map' import { SourceMapConsumer as SyncSourceMapConsumer } from 'next/dist/compiled/source-map'
import { import {
type ModernSourceMapPayload, type ModernSourceMapPayload,
devirtualizeReactServerURL,
findApplicableSourceMapPayload, findApplicableSourceMapPayload,
ignoreListAnonymousStackFramesIfSandwiched as ignoreListAnonymousStackFramesIfSandwichedGeneric, ignoreListAnonymousStackFramesIfSandwiched as ignoreListAnonymousStackFramesIfSandwichedGeneric,
sourceMapIgnoreListsEverything, sourceMapIgnoreListsEverything,
...@@ -201,11 +202,15 @@ function getSourcemappedFrameIfPossible( ...@@ -201,11 +202,15 @@ function getSourcemappedFrameIfPossible(
sourceMapPayload = maybeSourceMapPayload sourceMapPayload = maybeSourceMapPayload
try { try {
// Pass the source map URL as the second parameter so that the consumer // Pass the source map URL as the second parameter so that the consumer
// can resolve relative paths in the source map's `sources` array. // can resolve relative paths in the source map's `sources` array. This is
// This is a guess! Turbopack places .map files as siblings to the chunks so this is sufficient to compute // a guess! Turbopack places .map files as siblings to the chunks so this
// relative paths but is actually wrong (the chunk and sourcemap have different content hashes). // is sufficient to compute relative paths but is actually wrong (the
// We are using the node API to read the sourcemap and it doesn't give us access to the URI. // chunk and sourcemap have different content hashes). We are using the
const sourceMapURL = sourceURL + '.map' // 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( sourceMapConsumer = new SyncSourceMapConsumer(
sourceMapPayload, sourceMapPayload,
// @ts-expect-error: our typings don't include this parameter but it is here. // @ts-expect-error: our typings don't include this parameter but it is here.
......
...@@ -244,7 +244,6 @@ export type RenderOptsPartial = { ...@@ -244,7 +244,6 @@ export type RenderOptsPartial = {
assetPrefix?: string assetPrefix?: string
err?: Error | null err?: Error | null
isBuildTimePrerendering?: boolean isBuildTimePrerendering?: boolean
dev?: boolean
ErrorDebug?: PagesDevOverlayBridgeType ErrorDebug?: PagesDevOverlayBridgeType
isNextDataRequest?: boolean isNextDataRequest?: boolean
params?: ParsedUrlQuery params?: ParsedUrlQuery
...@@ -457,9 +456,9 @@ export async function renderToHTMLImpl( ...@@ -457,9 +456,9 @@ export async function renderToHTMLImpl(
const metadata: PagesRenderResultMetadata = {} const metadata: PagesRenderResultMetadata = {}
metadata.assetQueryString = 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() const userAgent = (req.headers['user-agent'] || '').toLowerCase()
if (userAgent.includes('safari') && !userAgent.includes('chrome')) { if (userAgent.includes('safari') && !userAgent.includes('chrome')) {
// In dev we invalidate the cache by appending a timestamp to the resource URL. // In dev we invalidate the cache by appending a timestamp to the resource URL.
...@@ -483,7 +482,6 @@ export async function renderToHTMLImpl( ...@@ -483,7 +482,6 @@ export async function renderToHTMLImpl(
const { const {
err, err,
dev = false,
pageConfig = {}, pageConfig = {},
buildManifest, buildManifest,
reactLoadableManifest, reactLoadableManifest,
...@@ -554,7 +552,7 @@ export async function renderToHTMLImpl( ...@@ -554,7 +552,7 @@ export async function renderToHTMLImpl(
// would normally be automatically statically optimized // would normally be automatically statically optimized
// ensure we set cache header so it's not rendered on-demand // ensure we set cache header so it's not rendered on-demand
// every request // every request
if (isAutoExport && !dev && isExperimentalCompile) { if (isAutoExport && !process.env.__NEXT_DEV_SERVER && isExperimentalCompile) {
res.setHeader( res.setHeader(
'Cache-Control', 'Cache-Control',
getCacheControlHeader({ revalidate: false, expire: expireTime }) getCacheControlHeader({ revalidate: false, expire: expireTime })
...@@ -602,7 +600,7 @@ export async function renderToHTMLImpl( ...@@ -602,7 +600,7 @@ export async function renderToHTMLImpl(
let asPath: string = renderOpts.resolvedAsPath || (req.url as string) let asPath: string = renderOpts.resolvedAsPath || (req.url as string)
if (dev) { if (process.env.__NEXT_DEV_SERVER) {
const { isValidElementType } = const { isValidElementType } =
require('next/dist/compiled/react-is') as typeof import('next/dist/compiled/react-is') require('next/dist/compiled/react-is') as typeof import('next/dist/compiled/react-is')
if (!isValidElementType(Component)) { if (!isValidElementType(Component)) {
...@@ -836,7 +834,7 @@ export async function renderToHTMLImpl( ...@@ -836,7 +834,7 @@ export async function renderToHTMLImpl(
const nextExport = const nextExport =
!isSSG && !isSSG &&
(renderOpts.isBuildTimePrerendering || (renderOpts.isBuildTimePrerendering ||
(dev && (isAutoExport || isFallback))) (process.env.__NEXT_DEV_SERVER && (isAutoExport || isFallback)))
const styledJsxInsertedHTML = () => { const styledJsxInsertedHTML = () => {
const styles = jsxStyleRegistry.styles() const styles = jsxStyleRegistry.styles()
...@@ -964,7 +962,7 @@ export async function renderToHTMLImpl( ...@@ -964,7 +962,7 @@ export async function renderToHTMLImpl(
} }
if ( if (
(dev || isBuildTimeSSG) && (process.env.__NEXT_DEV_SERVER || isBuildTimeSSG) &&
!metadata.isNotFound && !metadata.isNotFound &&
!isSerializableProps(pathname, 'getStaticProps', (data as any).props) !isSerializableProps(pathname, 'getStaticProps', (data as any).props)
) { ) {
...@@ -1183,7 +1181,7 @@ export async function renderToHTMLImpl( ...@@ -1183,7 +1181,7 @@ export async function renderToHTMLImpl(
} }
if ( if (
(dev || isBuildTimeSSG) && (process.env.__NEXT_DEV_SERVER || isBuildTimeSSG) &&
!isSerializableProps(pathname, 'getServerSideProps', (data as any).props) !isSerializableProps(pathname, 'getServerSideProps', (data as any).props)
) { ) {
// this fn should throw an error instead of ever returning `false` // this fn should throw an error instead of ever returning `false`
...@@ -1301,7 +1299,10 @@ export async function renderToHTMLImpl( ...@@ -1301,7 +1299,10 @@ export async function renderToHTMLImpl(
return { html, head } return { html, head }
} }
if (dev && (props.router || props.Component)) { if (
process.env.__NEXT_DEV_SERVER &&
(props.router || props.Component)
) {
throw new Error( throw new Error(
`'router' and 'Component' can not be returned in getInitialProps from _app.js https://nextjs.org/docs/messages/cant-override-next-props` `'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( ...@@ -1483,7 +1484,9 @@ export async function renderToHTMLImpl(
dynamicImportsIds.size === 0 dynamicImportsIds.size === 0
? undefined ? undefined
: Array.from(dynamicImportsIds), : 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 gsp: !!getStaticProps ? true : undefined, // whether the page is getStaticProps
gssp: !!getServerSideProps ? true : undefined, // whether the page is getServerSideProps gssp: !!getServerSideProps ? true : undefined, // whether the page is getServerSideProps
customServer: sharedContext.customServer, customServer: sharedContext.customServer,
...@@ -1494,13 +1497,16 @@ export async function renderToHTMLImpl( ...@@ -1494,13 +1497,16 @@ export async function renderToHTMLImpl(
defaultLocale, defaultLocale,
domainLocales, domainLocales,
isPreview: isPreview === true ? true : undefined, isPreview: isPreview === true ? true : undefined,
notFoundSrcPage: notFoundSrcPage && dev ? notFoundSrcPage : undefined, notFoundSrcPage:
notFoundSrcPage && process.env.__NEXT_DEV_SERVER
? notFoundSrcPage
: undefined,
}, },
nonce, nonce,
buildManifest: filteredBuildManifest, buildManifest: filteredBuildManifest,
docComponentsRendered, docComponentsRendered,
dangerousAsPath: router.asPath, dangerousAsPath: router.asPath,
isDevelopment: !!dev, isDevelopment: !!process.env.__NEXT_DEV_SERVER,
deploymentId: sharedContext.deploymentId, deploymentId: sharedContext.deploymentId,
dynamicImports: Array.from(dynamicImports), dynamicImports: Array.from(dynamicImports),
dynamicCssManifest: new Set(renderOpts.dynamicCssManifest || []), dynamicCssManifest: new Set(renderOpts.dynamicCssManifest || []),
......
...@@ -339,7 +339,6 @@ export const getHandler = ({ ...@@ -339,7 +339,6 @@ export const getHandler = ({
ErrorDebug: getRequestMeta(req, 'PagesErrorDebug'), ErrorDebug: getRequestMeta(req, 'PagesErrorDebug'),
err: getRequestMeta(req, 'invokeError'), err: getRequestMeta(req, 'invokeError'),
dev: routeModule.isDev,
// needed for experimental.optimizeCss feature // needed for experimental.optimizeCss feature
distDir: path.join( distDir: path.join(
......
...@@ -137,7 +137,7 @@ export abstract class RouteModule< ...@@ -137,7 +137,7 @@ export abstract class RouteModule<
}: RouteModuleOptions<D, U>) { }: RouteModuleOptions<D, U>) {
this.userland = userland this.userland = userland
this.definition = definition this.definition = definition
this.isDev = process.env.NODE_ENV === 'development' this.isDev = !!process.env.__NEXT_DEV_SERVER
this.distDir = distDir this.distDir = distDir
this.relativeProjectDir = relativeProjectDir this.relativeProjectDir = relativeProjectDir
} }
......
...@@ -217,12 +217,9 @@ function createUseCacheStore( ...@@ -217,12 +217,9 @@ function createUseCacheStore(
explicitExpire: undefined, explicitExpire: undefined,
explicitStale: undefined, explicitStale: undefined,
tags: null, tags: null,
hmrRefreshHash: getHmrRefreshHash(workStore, outerWorkUnitStore), hmrRefreshHash: getHmrRefreshHash(outerWorkUnitStore),
isHmrRefresh: isHmrRefresh(workStore, outerWorkUnitStore), isHmrRefresh: isHmrRefresh(outerWorkUnitStore),
serverComponentsHmrCache: getServerComponentsHmrCache( serverComponentsHmrCache: getServerComponentsHmrCache(outerWorkUnitStore),
workStore,
outerWorkUnitStore
),
forceRevalidate: shouldForceRevalidate(workStore, outerWorkUnitStore), forceRevalidate: shouldForceRevalidate(workStore, outerWorkUnitStore),
runtimeStagePromise: getRuntimeStagePromise(outerWorkUnitStore), runtimeStagePromise: getRuntimeStagePromise(outerWorkUnitStore),
draftMode: getDraftModeProviderForCacheScope( draftMode: getDraftModeProviderForCacheScope(
...@@ -267,7 +264,7 @@ function createUseCacheStore( ...@@ -267,7 +264,7 @@ function createUseCacheStore(
explicitStale: undefined, explicitStale: undefined,
tags: null, tags: null,
hmrRefreshHash: hmrRefreshHash:
outerWorkUnitStore && getHmrRefreshHash(workStore, outerWorkUnitStore), outerWorkUnitStore && getHmrRefreshHash(outerWorkUnitStore),
isHmrRefresh: useCacheOrRequestStore?.isHmrRefresh ?? false, isHmrRefresh: useCacheOrRequestStore?.isHmrRefresh ?? false,
serverComponentsHmrCache: serverComponentsHmrCache:
useCacheOrRequestStore?.serverComponentsHmrCache, useCacheOrRequestStore?.serverComponentsHmrCache,
...@@ -637,7 +634,7 @@ async function generateCacheEntryImpl( ...@@ -637,7 +634,7 @@ async function generateCacheEntryImpl(
// necessary here; the errors are encoded in the stream, and will be reported // necessary here; the errors are encoded in the stream, and will be reported
// in the "Server" environment. // in the "Server" environment.
const handleError = createReactServerErrorHandler( const handleError = createReactServerErrorHandler(
workStore.dev, process.env.NODE_ENV === 'development',
workStore.isBuildTimePrerendering ?? false, workStore.isBuildTimePrerendering ?? false,
workStore.reactServerErrorsByDigest, workStore.reactServerErrorsByDigest,
(error) => { (error) => {
...@@ -1046,8 +1043,7 @@ export async function cache( ...@@ -1046,8 +1043,7 @@ export async function cache(
// components have been edited. This is a very coarse approach. But it's // components have been edited. This is a very coarse approach. But it's
// also only a temporary solution until Action IDs are unique per // also only a temporary solution until Action IDs are unique per
// implementation. Remove this once Action IDs hash the implementation. // implementation. Remove this once Action IDs hash the implementation.
const hmrRefreshHash = const hmrRefreshHash = workUnitStore && getHmrRefreshHash(workUnitStore)
workUnitStore && getHmrRefreshHash(workStore, workUnitStore)
const hangingInputAbortSignal = workUnitStore const hangingInputAbortSignal = workUnitStore
? createHangingInputAbortSignal(workUnitStore) ? createHangingInputAbortSignal(workUnitStore)
...@@ -1906,7 +1902,7 @@ function shouldForceRevalidate( ...@@ -1906,7 +1902,7 @@ function shouldForceRevalidate(
return true return true
} }
if (workStore.dev && workUnitStore) { if (process.env.__NEXT_DEV_SERVER && workUnitStore) {
switch (workUnitStore.type) { switch (workUnitStore.type) {
case 'request': case 'request':
return workUnitStore.headers.get('cache-control') === 'no-cache' 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.
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