dotenv

Layered Configuration with dotenv

dotenv 17.4.2 20,543 (github.com/motdotla/dotenv (https://github.com/motdotla/dotenv 20,543 ), npm 2,036 i dotenv, BSD-2-Clause) still draws around 130 million downloads a week, and it does two things the built-in flag does not: it takes an ordered list of files in one call, and it can write the result somewhere other than process.env. Its ordering rule is the opposite of Node's — the first file to define a key wins, unless you pass override: true.

Three layers: machine-local, per-environment, committed defaultsJavaScript
import dotenv from 'dotenv';
const env = process.env.APP_ENV ?? 'development';
const result = dotenv.config({
  path: ['.env.local', `.env.${env}`, '.env'],   // first file to set a key wins
  quiet: true,                                   // no "injected env" banner
});
console.log('keys loaded:', Object.keys(result.parsed).sort().join(','));
console.log('PORT =', process.env.PORT, '| LOG_LEVEL =', process.env.LOG_LEVEL);
const sandbox = {};
dotenv.config({ path: '.env', processEnv: sandbox, quiet: true });
console.log('sandbox:', sandbox.PORT, '| process.env untouched:', process.env.PORT);
Output
keys loaded: GREETING,LOG_LEVEL,PORT,SERVICE_NAME
PORT = 4000 | LOG_LEVEL = trace
sandbox: 3000 | process.env untouched: 4000

.env.local set LOG_LEVEL=trace and won it; .env.development set PORT=4000 and won that; .env supplied the rest. processEnv is the underrated option: aimed at a fresh object, it lets a test load a fixture without poisoning the global environment for the rest of the suite. Since version 17 the package prints a banner on load, so pass quiet: true where stdout is parsed. Interpolation, command substitution and encrypted files have moved out to dotenvx 2.28.0 5,814 (github.com/dotenvx/dotenvx (https://github.com/dotenvx/dotenvx 5,814 )), a binary that wraps any command as dotenvx run -- node server.js.

Ways to get configuration into a Node process, verified 17 September 2026
Tool Version Interpolation Validation
--env-file built in no no
dotenv 17.4.2 no no
dotenvx 2.28.0 yes no
envalid 8.2.0 no yes