Browse topics

Loading environment files with --env-file

Version
24
Since
20.6.0
Review
Draft

Summary#

Pass --env-file before the script name to load variables into process.env at startup. Paths are relative to the working directory. When you pass more than one file, later files override earlier ones. Variables inherited from the environment take precedence over all the files.

Syntax#

sh
node --env-file=base.env --env-file=local.env app.cjs
node --env-file-if-exists=optional.env app.cjs

Use NAME=value assignments in the file. Node.js reads values as strings, including values such as true and 3000.

Example#

Load two temporary files and supply DLR_REPORT_COLOR in the environment for the Node.js process.

sh
(
  set -eu
  temp_root=$(CDPATH= cd -- "${TMPDIR:-/tmp}" && pwd -P)
  work_dir=$(mktemp -d "$temp_root/dlr-nodejs-env-XXXXXXXX")
  trap 'rm -rf -- "$work_dir"' 0
  trap 'exit 1' HUP INT TERM
  cd "$work_dir"
  unset NODE_OPTIONS NODE_COMPILE_CACHE NODE_V8_COVERAGE DLR_REPORT_FORMAT

  printf '%s\n' 'DLR_REPORT_FORMAT=text' 'DLR_REPORT_COLOR=amber' > base.env
  printf '%s\n' 'DLR_REPORT_FORMAT=json' 'DLR_REPORT_COLOR=blue' > local.env
  cat > report.cjs <<'JS'
console.log("format=" + process.env.DLR_REPORT_FORMAT);
console.log("color=" + process.env.DLR_REPORT_COLOR);
JS

  DLR_REPORT_COLOR=green node --env-file=base.env --env-file=local.env report.cjs
)

Expected output#

Text
format=json
color=green

Common mistakes#

Running the same command from another directory can change which files it loads. Use absolute paths if the working directory can change. A missing --env-file causes startup to fail. Use --env-file-if-exists for a file that may be absent, such as a developer’s local override.

Version applicability#

Node.js 20.6.0 introduced --env-file and is the minimum for the single-line assignments in the example. Multiline values arrived in 20.12.0 and 21.7.0. Node.js 22.9.0 added --env-file-if-exists. Both flags became stable in 24.10.0.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0