Node.js Reference ยท CLI Flags
Node.js --env-file flag
Reference for the node --env-file and --env-file-if-exists flags: loading .env files without packages, file syntax, precedence and security notes.
--env-file makes Node.js read a .env style file at startup and copy its KEY=value lines into process.env before your code runs. You no longer need a package such as dotenv just to keep local configuration out of your source.
The flag takes a path, written as --env-file=.env (or --env-file .env). It can be repeated to load several files. If the file does not exist, Node exits with an error; use --env-file-if-exists when the file is optional.
// shell: node --env-file=.env app.js
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
// shell
node --env-file=<path> [--env-file=<path> ...] <script>
node --env-file-if-exists=<path> <script>
| Name | Description |
|---|---|
--env-file=<path> |
Loads the file. A missing file stops startup with an error. |
--env-file-if-exists=<path> |
Loads the file only when it exists; otherwise startup continues and Node prints a short notice on stderr. |
Returns: nothing; values appear in process.env as strings.
Edge cases: the file is parsed with the same rules as util.parseEnv() and process.loadEnvFile(). Comments start with #, values may be wrapped in single, double or backtick quotes, export prefixes are ignored, and double-quoted values can span several lines.
Usage notes
- Precedence: a variable that is already set in the real environment is not overwritten by the file. Between files, the one named later wins.
- Variables are loaded before the script, so top-level code and every imported module see them. Compare with
process.loadEnvFile(), which you call yourself once the program is running. - Values are always strings.
PORT=3000gives'3000'; convert withNumber()and validate. - Never commit real secrets. Add
.envto.gitignore, commit a.env.examplewith fake values, and give production its secrets through the host's own mechanism. - Test runner and watch mode: the flag works together with
node --testandnode --watch. NODE_OPTIONSrule:--env-fileis not allowed insideNODE_OPTIONS; put it on the command line.- Version notes:
--env-filewas added in Node.js 20.6;--env-file-if-existsin 22.9 and 20.18. - Common mistake: expecting
${OTHER}expansion. Node does not interpolate variables inside values.