How to Configure Dotenv Config in Node.js to Load .env Files

Node.js 20.12.0+ includes a built-in dotenv implementation that loads environment variables from .env files using either the node --env-file=.env CLI flag or the process.loadEnvFile() runtime API, eliminating the need for third-party packages.

Configuring dotenv config in Node.js is now a native capability. Since version 20.12.0, the official nodejs/node repository ships with a high-performance C++ implementation that parses .env files and populates process.env either before script execution or at runtime, mirroring the behavior of the popular dotenv npm package.

Native Dotenv Support in Node.js (v20.12.0+)

Node.js provides stable, built-in support for loading environment variables without external dependencies. The implementation resides in the src/node_dotenv.h and src/node_dotenv.cc source files, where a Dotenv class handles parsing and environment population in C++ for optimal performance and safety.

This native approach supports standard .env file features including:

  • Comment lines starting with #
  • Quoted values and multiline values
  • Optional export prefix
  • Whitespace trimming

Two Methods to Configure .env File Loading

You can configure dotenv config using two distinct approaches depending on when you need the variables available.

CLI Flag Method: --env-file for Early Loading

Use the --env-file flag to parse the file before any JavaScript executes. This method is ideal for Docker entrypoints, CI scripts, and production deployments where environment variables must be present immediately.

node --env-file=.env server.js

Under the hood, the Node.js launcher creates a Dotenv object and calls Dotenv::ParseContent followed by Dotenv::SetEnvironment to populate the per-process environment map before the event loop starts.

Programmatic Method: process.loadEnvFile() for Runtime Loading

For conditional loading or when you need to execute logic before reading configuration files, use the API exposed in src/node_process_methods.cc:

// Load .env after checking conditions
if (process.env.NODE_ENV !== 'production') {
  const ok = process.loadEnvFile('.env');
  if (!ok) console.warn('Failed to load .env file');
}

This method returns a boolean indicating success and allows you to specify absolute paths or alternative filenames such as process.loadEnvFile('config/local.env').

Technical Implementation Details

The native dotenv implementation guarantees consistent parsing across all platforms. According to the doc/api/environment_variables.md specification and the C++ source code:

  • Dotenv::ParseContent in src/node_dotenv.cc handles the parsing algorithm
  • Dotenv::SetEnvironment writes key-value pairs to process.env
  • Existing variables are never overwritten, matching standard dotenv behavior
  • Parsing occurs entirely in C++, avoiding the overhead of JavaScript-based solutions

The parser correctly handles edge cases including inline comments, double-quoted multiline strings, and single-quoted literal values.

Practical Code Examples

Loading Environment Variables via CLI

Create a .env file:

DB_HOST=localhost
DB_PORT=5432
API_KEY="my-secret-key"

Run your application:

node --env-file=.env app.js

Access variables in app.js:

console.log('Database host:', process.env.DB_HOST);
console.log('API key:', process.env.API_KEY);

Conditionally Loading .env Files

Use the programmatic API when you need to load different files based on the environment:

// bootstrap.js
const envFile = process.env.NODE_ENV === 'test' 
  ? '.env.test' 
  : '.env.development';

process.loadEnvFile(envFile);
console.log('Loaded config from', envFile);

Layered Configuration with Multiple Files

Combine CLI and API approaches for layered configuration. Variables loaded via CLI persist, and process.loadEnvFile() merges additional variables without overwriting existing ones:

node --env-file=.env server.js
// server.js
// Load local overrides only for variables not already set
process.loadEnvFile('.env.local');

Summary

  • Native implementation: Node.js 20.12.0+ includes dotenv support in src/node_dotenv.cc, eliminating npm package dependencies.
  • CLI configuration: Use node --env-file=.env for pre-execution loading.
  • Runtime configuration: Use process.loadEnvFile() for conditional or dynamic loading.
  • Non-destructive: Both methods skip variables that already exist in process.env.
  • Spec-compliant: The C++ parser supports comments, quotes, multiline values, and export prefixes per the official documentation.

Frequently Asked Questions

When was dotenv support added to Node.js?

Native dotenv support was added in Node.js version 20.12.0 as a stable feature. Prior versions required the third-party dotenv npm package.

Does process.loadEnvFile overwrite existing environment variables?

No. According to the implementation in src/node_dotenv.cc, the Dotenv::SetEnvironment method skips any variables that already exist in the process environment, preserving existing values and preventing accidental overwrites.

Can I use multiple --env-file flags?

Yes. You can specify multiple --env-file arguments when launching Node.js. The files are processed in order, and later files cannot override variables set by earlier ones due to the non-destructive nature of the implementation.

Is the native implementation compatible with the dotenv npm package?

Yes. The native implementation in nodejs/node follows the same parsing specification documented in doc/api/environment_variables.md and is designed to be compatible with the widely-used dotenv package, supporting the same syntax for comments, quoted strings, and multiline values.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →