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

LoadEnvConfig Ignores Directory Argument Due To Module-Level Cache Without Dir Key

In Next.js 16.2.1, @next/env's loadEnvConfig caches the first result globally and returns it for subsequent calls without checking if the requested directory matches the cached directory. This silently returns empty env files and undefined variables when users call loadEnvConfig with a different directory (e.g., monorepo root), even if the .env file exists. The only workaround is passing forceReload: true, which is undocumented and unintuitive.

highConfidence 85%Next.jsPages RouterReact Server ComponentsServer ActionsAffected V16.2.1

Origin Analysis

The loadEnvConfig function stores combinedEnv, parsedEnv, and cachedLoadedEnvFiles in module-level variables. The cache hit condition only checks combinedEnv && !forceReload, ignoring the dir argument. After Next.js internally calls loadEnvConfig with the project's app directory, user code calling loadEnvConfig with the monorepo root hits the cache and receives the previous (empty) result without any warning.
1. Create a monorepo with a root .env file containing DATABASE_URL=postgres://... and a Next.js app in apps/web. 2. In apps/web/envConfig.ts, call loadEnvConfig(path.resolve(process.cwd(), '../../')) and log loadedEnvFiles and combinedEnv.DATABASE_URL. 3. Import './envConfig.ts' as the first import in next.config.ts. 4. Run next dev. The logs show [] and undefined for DATABASE_URL even though the .env file exists at the provided directory.

Fixing Code Block

Edge Case Audit

If the patch is applied without resetting cachedDir on forceReload, calling loadEnvConfig with forceReload: true for the same directory will reload but cachedDir will be reassigned correctly (the assignment happens after loading). However, if concurrent calls occur from different directories, the module-level cache is not thread-safe and may race. This was already an issue for combinedEnv; adding cachedDir does not introduce new concurrency risks but should be considered if Next.js adopts worker threads. Rollback: revert the patch and use the forceReload workaround in user code until an official fix is released.

Ecosystem Topology

Agent Frameworks

LangChain, LlamaIndex, and Pydantic

  1. highProperty graph relation keys collide when entity IDs or labels contain underscores
  2. highCodeActAgent drops assistant tool-call metadata during handoff, leaving an orphan tool response
  3. high[Bug]: HierarchicalNodeParser async methods return the documents unsplit
  4. highLLM.predict_and_call fails with ValidationError for non-function-calling models when react_chat_formatter is omitted
  5. highAnthropic streaming server-tool input_json_delta overwrites completed client tool_use arguments due to stale cur_tool_call state