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

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

When Next.js is invoked from a directory other than the project root, relative imports in next.config.ts are resolved against the current working directory instead of the configuration file's own directory, leading to module resolution failures or loading incorrect files.

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

Origin Analysis

In the SWC-based TypeScript configuration transpilation path, `requireFromString` creates a new Node.js Module instance without setting its `filename` property. As a result, Node's `Module._resolveLookupPaths` treats the module as if it were from the REPL and resolves relative imports against `process.cwd()` rather than the config file's directory.
1. Create a Next.js project with a next.config.ts that imports a local file (e.g., './src/headers'). 2. Install dependencies inside the project directory. 3. From the project directory, run `npx next build` (works). 4. From the parent directory, run `node app/node_modules/next/dist/bin/next build app` (fails with 'Cannot find module'). 5. Optionally create a file at the same relative path under the parent directory; the build succeeds but loads the wrong file from the working directory.

Fixing Code Block

Edge Case Audit

The fix is straightforward but should be verified with absolute paths to avoid issues if the filename is relative. Ensure that the filename passed to `requireFromString` is normalized to an absolute path. Regression testing should cover Windows path handling and scenarios where the config file is symlinked. Rollback is straightforward: remove the `m.filename = filename` line if the change causes unexpected module resolution side effects. No concurrency or multi-threading risks are expected since Node.js module loading is synchronous and single-threaded.

Ecosystem Topology