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

`@Next/Env`: `LoadEnvConfig` With `ForceReload` Wipes `Process.Env` Before Reading, Breaking FIFO-Mounted `.Env` Files

In Next.js development, when `loadEnvConfig` is called with `forceReload: true` (e.g., on `.env` file watcher events), it resets `process.env` to an initial snapshot before re-reading `.env` files. If a FIFO-mounted `.env` from a secret manager is used, the second read returns empty (the pipe is drained), causing the previously loaded environment variables to be permanently lost. This affects Next.js 15+ where FIFO support was added.

highConfidence 85%Next.jsAffected V15.xAffected V16.x

Origin Analysis

The function `loadEnvConfig` in `packages/next-env/index.ts` calls `replaceProcessEnv(initialEnv)` before attempting to read the `.env` files. `initialEnv` is a snapshot taken before the first load and does not contain any `.env` values. If the subsequent read fails or yields no data (as with a drained FIFO), the environment remains reset, and errors/empty reads are silently ignored.
1. Clone https://github.com/jhb-dev/next-env-fifo-repro 2. Run `npm install` 3. Run `npm run repro` The script creates a FIFO named `.env` that serves its contents once then empty. It calls `loadEnvConfig` twice: normally, then with `forceReload: true`. The output shows the value loads initially but is undefined after the forced reload.

Fixing Code Block

Edge Case Audit

The change alters the order of environment reset. In scenarios where a user intentionally replaces a `.env` file with an empty one and expects to clear variables during a forced reload, this fix would keep the old variables. This may be surprising. Additionally, the guard relies on `previousEnv.parsedEnv` being non-empty; if the previous load was also empty, the reset still occurs. Rollback: To revert, restore the original code by moving `replaceProcessEnv(initialEnv)` back to its original position before the reading loop. Test thoroughly with multiple environment files and different file-system types to ensure no regression.

Ecosystem Topology