AI & Agent Dev Bug Sandbox logo
AI & Agent Dev Bug Sandbox
Back to Radar

Relative Imports In Next.Config.Ts Resolve Against Process.Cwd() Instead Of The Config File Directory

When building a Next.js project with next.config.ts from a working directory different from the project root, relative imports inside next.config.ts are resolved relative to process.cwd() rather than the config file's location. This causes module-not-found errors or, worse, silently loads a file with the same relative path from the current working directory, potentially applying unintended configuration.

highConfidence 95%Next.jsAffected V15.0.0Affected V15.5.26Affected V16.4.0-Canary.63

Origin Analysis

In packages/next/src/build/next-config-ts/require-hook.ts, the SWC-based transpileConfig compiles next.config.ts to CommonJS and loads it via requireFromString. The code creates a new Module instance with `new Module(filename, module.parent)`, sets `m.paths`, and then calls `m._compile(code, filename)`. However, Node's Module constructor sets the `id` property, not `filename`, and `_compile` does not assign `filename`. With no `filename` set, Node's `Module._resolveLookupPaths` treats the module as if it were executed from the REPL, resolving relative require calls against `process.cwd()` instead of the config file's directory.
1. Clone https://github.com/dxdc/next-config-ts-cwd-repro and install dependencies inside app/. 2. Run `(cd app && npx next build)` - build succeeds. 3. From the parent directory run `node app/node_modules/next/dist/bin/next build app` - build fails with `Cannot find module './src/headers'`. 4. Create `src/headers.ts` in the parent directory with different content and rerun the build from the parent - build succeeds but uses the parent's file instead of `app/src/headers.ts`.

Fixing Code Block

Edge Case Audit

This change corrects an undefined resolution behavior, so builds that previously succeeded by accidentally relying on cwd-relative imports may now fail if the relative file does not exist next to the config. Users with such accidental configurations should move or alias the required files. The fix may not fully resolve paths when the config file path contains symlinks; testing with pnpm and monorepo symlink setups is recommended. To rollback, remove the `m.filename = filename` line. No threading or concurrent execution risk is expected because config loading is synchronous and per-process.

Ecosystem Topology