In Node.js 24, what does node --env-file=.env do, and which value wins when the shell environment and several env files set the same variable?
answer
- read before the entry point runs
- the real environment beats any file
- a later file beats an earlier one
- missing file versus the -if-exists form
- startup variables only work at startup
basics
~20 snode --env-file=.env reads the file before your code runs and adds its variables to process.env. A variable already set in the real environment wins over the file, and a later --env-file wins over an earlier one.
solid answer
~40 s`--env-file=path` makes Node parse a dotenv-style file, relative to the current working directory, before the entry point runs, and add its pairs to `process.env` as strings. Precedence is fixed: a variable already present in the process environment wins over any file, and when several `--env-file` flags are passed, later files override earlier ones. A missing file is a startup error; `--env-file-if-exists` behaves the same without that error, which suits an optional local override file. Because the file is read during startup, a `NODE_OPTIONS` line in it is applied to the runtime. `process.loadEnvFile(path)`, whose path defaults to `./.env`, loads a file from code instead, but it runs after startup, so `NODE_OPTIONS` in that file has no effect. In Node 24 all three stopped being experimental in v24.10.0.
code
bash · 7 lines# .env -> PORT=3000
# LOG_LEVEL=debug
# .env.ci -> LOG_LEVEL=info
node --env-file=.env --env-file=.env.ci app.js # LOG_LEVEL is 'info'
LOG_LEVEL=warn node --env-file=.env --env-file=.env.ci app.js # LOG_LEVEL is 'warn'
node --env-file=.env --env-file-if-exists=.env.local app.js # no error if .env.local is absentgo deeper
Recall that --env-file loads a dotenv file into process.env before your code runs, and that every loaded value is a string.
Explain the three precedence rules, the missing-file error and its -if-exists variant, and why NODE_OPTIONS in the file works with the flag but not with process.loadEnvFile.
Use the precedence to design deployments: commit defaults in a file, let the platform's real variables win, and know the edges such as node --run and the Permission Model.
Decide whether a team standardises on Node's built-in loader or keeps a userland one, weighing one less dependency against format differences and a parser the team does not control.
## What --env-file does A **dotenv file** is a text file of `KEY=value` lines, a format popularised by a userland package and now read by Node itself. Passing `--env-file=.env` on the `node` command line tells Node to read that file **during startup, before your entry point runs**, and to add each pair to `process.env`. The path is resolved **relative to the current working directory**, not to the script, so `cd`-ing elsewhere and running the same command reads a different file or none. If the file does not exist, Node throws an error and the program does not run. `--env-file-if-exists=file` is the same flag without that error, for a file that may legitimately be absent, such as a developer's personal overrides. ## The file format Node accepts Node defines its own dotenv rules, because the format has no formal specification: - One `KEY=value` pair per line; whitespace around keys and unquoted values is ignored. - A valid name matches `^[a-zA-Z_]+[a-zA-Z0-9_]*$`, so `MY-VAR` is not a valid name. - `#` starts a comment, except inside quotes. - Values may be wrapped in single quotes, double quotes or backticks, which are stripped; quoted values may span several lines (multi-line support arrived in v21.7.0 and v20.12.0). - A leading `export` keyword is ignored, so the same file can be `source`d by a shell. - **Every value is a string**: `0`, `true` and `{ "a": 1 }` arrive as text. - When a key appears twice in one file, the later line wins, as `util.parseEnv('HELLO=world\nHELLO=oh my\n')` returning `{ HELLO: 'oh my' }` shows. ## Which value wins Node's rules for `--env-file` are short and fixed: 1. A variable that is **already in the process environment** wins over every file. The file only fills gaps. 2. Among several `--env-file` flags, **later files override earlier ones**. 3. Within one file, the later line for a key wins. Applied to one service that runs in three places: | Where it runs | How it starts | `LOG_LEVEL` the code sees | |---|---|---| | Laptop | `node --env-file=.env app.js`, where `.env` says `debug` | `'debug'` | | CI | `node --env-file=.env --env-file=.env.ci app.js`, where `.env.ci` says `info` | `'info'` | | Production | same command, platform sets `LOG_LEVEL=warn` in the environment | `'warn'` | The production row is the important property: a committed `.env` of development defaults can ship in the image, and the platform's real variables still win without anyone deleting the file. ## Loading from code: process.loadEnvFile and util.parseEnv - `process.loadEnvFile(path)` loads a dotenv file into `process.env` from inside the program; `path` defaults to `'./.env'`. It runs after the runtime has started, so the documentation states that `NODE_OPTIONS` in that file has no effect on Node, although the value is still readable through `process.env`. - `util.parseEnv(content)` parses the text of a dotenv file and returns a plain object without touching `process.env`, which is useful when you want to validate or merge values yourself. ## Choosing between the flag and the function | Need | Use | |---|---| | Load defaults before any module runs, and allow `NODE_OPTIONS` in the file | `--env-file` | | Load a file that may be absent without failing | `--env-file-if-exists` | | Pick the file at run time, for example from a command-line argument | `process.loadEnvFile(path)` | | Inspect or validate values without changing `process.env` | `util.parseEnv(content)` | The flag has one practical advantage beyond timing: modules that read `process.env` at import time, before your first line runs, already see the values. With `process.loadEnvFile`, any module evaluated before the call sees the environment without the file, a common source of "the variable is undefined in one module only" reports. In a CommonJS entry point, call it before the `require()` of the modules that depend on it. In an ES module entry point, static imports are evaluated before the module's own first line, so put the call in a small module imported first, or load the dependants afterwards with dynamic `import()`. ## Edges worth knowing - **`NODE_OPTIONS` inside the file is applied** when the file is loaded with `--env-file`, because the read happens during startup. A real `NODE_OPTIONS` in the environment still ranks above it. - **`--env-file` cannot itself go in `NODE_OPTIONS`**: it is not on the documented list of flags allowed there. - **The Permission Model does not govern it**: `--env-file` reads its file before the environment is initialised, so the read is not subject to `--permission` rules. - **`node --run` does not pass them on**: variables loaded with `--env-file` are not applied to the command that `node --run` executes from `package.json`. - Node does not need a third-party dotenv package for any of this on Node 24.
- Why does a NODE_OPTIONS line work in a file passed to --env-file but not in one loaded with process.loadEnvFile?`--env-file` is read while Node is still starting, so the runtime variables it finds, `NODE_OPTIONS` among them, are parsed and applied before the entry point runs. `process.loadEnvFile` runs inside your program after startup has finished, so it can still put `NODE_OPTIONS` into `process.env`, but the flags have already been fixed and nothing re-reads them.
- A teammate wants a committed .env to override the platform's DATABASE_URL in production. What does Node do with that plan?It defeats it by design. With `--env-file`, a variable already present in the process environment takes precedence over the file, so the platform's value stays in force. That is usually what you want: defaults live in the file and each environment overrides them. Forcing a file value would need code that assigns to `process.env` after parsing it with `util.parseEnv`, which hides where the value came from.
- Values in a .env file override variables already set in the environment.
- The first --env-file passed wins over later ones.
- --env-file resolves its path relative to the script file.
- A missing --env-file is silently ignored.
- NODE_OPTIONS in a file loaded with process.loadEnvFile changes runtime flags.
- Node 24 still needs a third-party dotenv package to read .env files.
Assumes Node 24: --env-file (added v20.6.0), --env-file-if-exists (added v22.9.0) and process.loadEnvFile (added v20.12.0) are all no longer experimental as of v24.10.0.