Loading a Node.js env file no longer needs the dotenv package. Node.js 20 added an --env-file flag that reads a .env file into process.env before your code runs.
The flag takes the path to the file and goes before the script name:
node --env-file .env main.jsNode reads the variables from that file into the process environment. No import, no dependency, no call at the top of your entry file.
The flag belongs to the node binary itself. If you start the app through a wrapper such as ts-node or nodemon, pass it to Node rather than to the wrapper.
If the .env file does not exist, node --env-file throws and the process exits. Use --env-file-if-exists instead when the file is optional:
node --env-file-if-exists=.env main.jsWith --env-file-if-exists, a missing file is skipped and the process keeps running. That fits CI jobs and containers where the variables already come from the environment.
You can pass --env-file more than once, and later files override earlier ones:
node --env-file=.env --env-file=.dev.env main.jsThis loads variables from both .env and .dev.env, so you can keep shared defaults in one file and per-environment overrides in another.
Node.js 20 introduces the --env-file flag to load environment variables directly from a file, eliminating the need for external packages like dotenv. Use --env-file-if-exists to avoid errors if the file is missing, and you can load multiple files by specifying multiple --env-file flags.
Occasional notes on software, tools, and things I learn. No spam.
Unsubscribe anytime.