Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readNode

Load .env files with --env-file

Load local configuration with Node’s --env-file flag and see how multiple files and shell variables set the final value.

Your Node script loads dotenv just to read a local port. You can give the file to Node at startup and keep reading the value through process.env. This puts the local configuration in the launch command and leaves the script's interface alone.

Load a file at startup

In an empty directory, paste this into a shell. The two short files give the example a value to read and a script that prints it.

printf 'APP_PORT=8080\n' > .env
printf 'console.log(process.env.APP_PORT)\n' > server.mjs
node --env-file=.env server.mjs

Node prints 8080. Put the flag before server.mjs so Node handles it. If you put it after the script name, Node passes it to the script as an argument instead.

Node resolves .env from the working directory at launch. If you run the same script from a different directory, point the flag at a file relative to that directory or give it an absolute path. A missing file makes this command fail at startup. That can be useful when the script requires local configuration.

Layer files under the shell environment

You can pass the flag more than once. Add an override file, then try the command with and without an exported value. Run these two examples in the same shell directory as before.

printf 'APP_PORT=8081\n' > .env.local
node --env-file=.env --env-file=.env.local server.mjs
APP_PORT=9090 node --env-file=.env --env-file=.env.local server.mjs

The commands print 8081 and 9090, respectively. Node reads defaults from .env, lets .env.local replace duplicate keys, then gives the inherited environment precedence. If the first command prints a value you did not expect, check whether your shell already exports APP_PORT.

process.env.APP_PORT is still a string. If you pass it to a function that expects a number, convert it and check the result at your configuration boundary. This is the same work you had when the script loaded the file itself.

Switch the entry point

The Node CLI reference describes the file order and precedence. The flag first shipped in Node 20.6.0. Node 20.7.0 added support for passing it more than once. Check the Node version behind your launch command before removing the old loader.

I start by changing the development command and deleting the early dotenv import. Then I run the script once with the file and once with an environment variable set by the shell. If production already supplies the variables, its launch command can continue to use the inherited environment.