Commit d75ddba2 authored by Josh Story's avatar Josh Story

Centralize node environment setup and config-dependent global behaviors

Currently node-environment is imported inconsistently — some entry points load it, others rely on downstream modules to eventually import it. This is fragile because it means the environment extensions (AsyncLocalStorage polyfill, error formatting, console patching, etc.) aren't guaranteed to be set up before other code runs. Similarly, installGlobalBehaviors is called separately from config loading even though it always needs to happen whenever config is produced.

This PR makes two changes:

1. Add node-environment to all process entry points

The three CLI commands (next-build.ts, next-dev.ts, next-start.ts) and start-server.ts (the forked child process entry point for next dev) now import node-environment at the top, before any other imports. This guarantees environment extensions are available before config loading, server initialization, or any other code runs.

The import is removed from next-server.ts because NextNodeServer is never a process entry point — it's always constructed after a CLI entry point or start-server.ts has already loaded the environment. Other process entry points (export/worker.ts, static-paths-worker.ts, router-server.ts) keep their existing imports since they're separate processes.

2. Move installGlobalBehaviors into config loading

installGlobalBehaviors (which configures console dimming for aborted requests) was called from two places — NextNodeServer constructor and export/worker.ts — separately from where config was loaded. This separated cause (config is available) from effect (global behaviors are installed) and meant every new config consumer had to remember to call it.

loadConfig is renamed to loadConfigFromFile and now calls installGlobalBehaviors internally after resolving config. A new loadConfigForBuildWorker function handles the export worker case where config arrives pre-serialized via IPC rather than being loaded from disk — it also calls installGlobalBehaviors internally.

Both use lazy require() for installGlobalBehaviors rather than a static import because console-dim.external.tsx depends on AsyncLocalStorage being on globalThis, which requires node-environment-baseline.ts to have run first. Static importing it from config.ts would trigger the dependency chain at module load time, before the environment is set up in contexts like the Jest test process that import config.ts transitively.

The direct installGlobalBehaviors calls are removed from NextNodeServer and export/worker.ts — it's now an internal detail of config loading that consumers don't need to think about.
parent ccee817b
#!/usr/bin/env node
import '../server/node-environment'
import { saveCpuProfile } from '../server/lib/cpu-profile'
import { existsSync } from 'fs'
import { italic } from '../lib/picocolors'
......
#!/usr/bin/env node
import '../server/node-environment'
import '../server/lib/cpu-profile'
import { saveCpuProfile } from '../server/lib/cpu-profile'
import type { StartServerOptions } from '../server/lib/start-server'
......
......@@ -7,6 +7,7 @@ if (!process.env.NEXT_PRIVATE_START_TIME) {
process.env.NEXT_PRIVATE_START_TIME = Date.now().toString()
}
import '../server/node-environment'
import '../server/lib/cpu-profile'
import { saveCpuProfile } from '../server/lib/cpu-profile'
import { startServer } from '../server/lib/start-server'
......
......@@ -53,7 +53,7 @@ import type { PagesRenderContext, PagesSharedContext } from '../server/render'
import type { AppSharedContext } from '../server/app-render/app-render'
import { MultiFileWriter } from '../lib/multi-file-writer'
import { createRenderResumeDataCache } from '../server/resume-data-cache/resume-data-cache'
import { installGlobalBehaviors } from '../server/node-environment-extensions/global-behaviors'
import { loadConfigForBuildWorker } from '../server/config'
;(globalThis as any).__NEXT_DATA__ = {
nextExport: true,
}
......@@ -345,7 +345,7 @@ export async function exportPages(
renderResumeDataCachesByPage = {},
} = input
installGlobalBehaviors(nextConfig)
loadConfigForBuildWorker(nextConfig)
if (nextConfig.enablePrerenderSourceMaps) {
try {
......
......@@ -1480,23 +1480,49 @@ type LoadConfigOptions = {
debugPrerender?: boolean
}
export default async function loadConfig(
export default async function loadConfigFromFile(
phase: typeof PHASE_DEVELOPMENT_SERVER,
dir: string,
opts?: LoadConfigOptions
): Promise<NextConfigComplete>
export default async function loadConfig(
export default async function loadConfigFromFile(
phase: typeof PHASE_PRODUCTION_SERVER | typeof PHASE_DEVELOPMENT_SERVER,
dir: string,
opts?: LoadConfigOptions
): Promise<NextConfigRuntime | NextConfigComplete>
export default async function loadConfig(
export default async function loadConfigFromFile(
phase: PHASE_TYPE,
dir: string,
opts?: LoadConfigOptions
): Promise<NextConfigComplete>
export default async function loadConfig(
export default async function loadConfigFromFile(
phase: PHASE_TYPE,
dir: string,
opts: LoadConfigOptions = {}
): Promise<NextConfigComplete> {
const config = await loadConfigImpl(phase, dir, opts)
const { installGlobalBehaviors } =
require('./node-environment-extensions/global-behaviors') as typeof import('./node-environment-extensions/global-behaviors')
installGlobalBehaviors(config)
return config
}
/**
* Initialize global behaviors from a pre-resolved config received via IPC
* in a build worker process. The parent process already loaded and serialized
* the config — this sets up the worker's globals.
*/
export function loadConfigForBuildWorker(
config: NextConfigComplete
): NextConfigComplete {
const { installGlobalBehaviors } =
require('./node-environment-extensions/global-behaviors') as typeof import('./node-environment-extensions/global-behaviors')
installGlobalBehaviors(config)
return config
}
async function loadConfigImpl(
phase: PHASE_TYPE,
dir: string,
{
......
import '../node-environment'
// Start CPU profile if it wasn't already started.
import './cpu-profile'
import { getNetworkHost } from '../../lib/get-network-host'
......
import './node-environment'
import './require-hook'
import './node-polyfill-crypto'
......@@ -128,7 +127,6 @@ import {
RouterServerContextSymbol,
routerServerGlobal,
} from './lib/router-utils/router-server-context'
import { installGlobalBehaviors } from './node-environment-extensions/global-behaviors'
import { installProcessErrorHandlers } from './node-environment-extensions/process-error-handlers'
export * from './base-server'
......@@ -199,8 +197,6 @@ export default class NextNodeServer extends BaseServer<
// Initialize super class
super(options)
installGlobalBehaviors(this.nextConfig)
const isDev = options.dev ?? false
this.isDev = isDev
this.sriEnabled = Boolean(options.conf.experimental?.sri?.algorithm)
......
......@@ -444,12 +444,7 @@ async function readNormalizedNFT(next, name) {
"/node_modules/client-only/index.js",
"/node_modules/next/dist/client/components/app-router-headers.js",
"/node_modules/next/dist/compiled/@opentelemetry/api/index.js",
"/node_modules/next/dist/compiled/babel-code-frame/index.js",
"/node_modules/next/dist/compiled/babel/code-frame.js",
"/node_modules/next/dist/compiled/next-server/server.runtime.prod.js",
"/node_modules/next/dist/compiled/source-map/source-map.js",
"/node_modules/next/dist/compiled/stacktrace-parser/stack-trace-parser.cjs.js",
"/node_modules/next/dist/compiled/ws/index.js",
"/node_modules/next/dist/experimental/testmode/context.js",
"/node_modules/next/dist/experimental/testmode/fetch.js",
"/node_modules/next/dist/experimental/testmode/server-edge.js",
......@@ -457,12 +452,9 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/lib/constants.js",
"/node_modules/next/dist/lib/interop-default.js",
"/node_modules/next/dist/lib/is-error.js",
"/node_modules/next/dist/lib/picocolors.js",
"/node_modules/next/dist/server/app-render/after-task-async-storage-instance.js",
"/node_modules/next/dist/server/app-render/after-task-async-storage.external.js",
"/node_modules/next/dist/server/app-render/async-local-storage.js",
"/node_modules/next/dist/server/app-render/console-async-storage-instance.js",
"/node_modules/next/dist/server/app-render/console-async-storage.external.js",
"/node_modules/next/dist/server/app-render/staged-rendering.js",
"/node_modules/next/dist/server/app-render/work-async-storage-instance.js",
"/node_modules/next/dist/server/app-render/work-async-storage.external.js",
......@@ -477,9 +469,6 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/server/lib/trace/constants.js",
"/node_modules/next/dist/server/lib/trace/tracer.js",
"/node_modules/next/dist/server/load-manifest.external.js",
"/node_modules/next/dist/server/node-environment-extensions/console-dim.external.js",
"/node_modules/next/dist/server/node-environment-extensions/fast-set-immediate.external.js",
"/node_modules/next/dist/server/node-environment-extensions/unhandled-rejection.external.js",
"/node_modules/next/dist/server/response-cache/types.js",
"/node_modules/next/dist/server/route-modules/app-page/module.compiled.js",
"/node_modules/next/dist/server/route-modules/app-page/vendored/contexts/app-router-context.js",
......@@ -500,7 +489,6 @@ async function readNormalizedNFT(next, name) {
"/node_modules/next/dist/server/route-modules/pages/vendored/contexts/loadable.js",
"/node_modules/next/dist/server/route-modules/pages/vendored/contexts/router-context.js",
"/node_modules/next/dist/server/route-modules/pages/vendored/contexts/server-inserted-html.js",
"/node_modules/next/dist/server/runtime-reacts.external.js",
"/node_modules/next/dist/shared/lib/deep-freeze.js",
"/node_modules/next/dist/shared/lib/invariant-error.js",
"/node_modules/next/dist/shared/lib/is-plain-object.js",
......
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