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.
......
......@@ -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.
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