packagesconfigurationReferenceBeginner
dotenv: Environment Variable Management
Complete developer reference for dotenv, loading .env files into process.env, custom paths, multi-environment overrides, and modern alternatives.
Verified: 2026-09-30
Tested on:dotenv 16.4.x, node 22.x
Platforms:
nodejs
#dotenv#nodejs#env#configuration
What It Is
dotenv is a zero-dependency module that loads environment variables from a .env file into Node.js process.env. It follows the Twelve-Factor App methodology for separating code from configuration.
Why Use It
- Local Secret Isolation: Keep database passwords, API credentials, and secret tokens out of version-controlled source code.
- Environment Parity: Easily toggle between development, staging, and test environments by switching configuration files.
- De-facto Standard: Universal support across virtually all Node.js libraries, frameworks, and deployment scripts.
Installation
Quick Start
1. Create .env file in project root:
# .env
PORT=4000
DATABASE_URL=postgresql://postgres:secret@localhost:5432/devdb
API_SECRET_KEY=supersecretkey1232. Require / Import as early as possible in your entry point:
// CommonJS
require('dotenv').config();
console.log(process.env.PORT); // "4000"
console.log(process.env.DATABASE_URL);In ES Modules ("type": "module"):
import 'dotenv/config';
console.log(process.env.PORT);Common APIs & Options
| Usage | Description | Example |
|---|---|---|
dotenv.config() | Loads .env from current working directory | dotenv.config() |
path option | Custom path to .env file | dotenv.config({ path: '.env.local' }) |
encoding option | Encoding of file | dotenv.config({ encoding: 'latin1' }) |
override option | Overwrite existing process.env keys | dotenv.config({ override: true }) |
CLI preload (-r) | Preload dotenv before app boots (No code import needed) | node -r dotenv/config index.js |
Examples
Loading Custom Path Based on NODE_ENV
const path = require('path');
const dotenv = require('dotenv');
const envFile = process.env.NODE_ENV === 'test' ? '.env.test' : '.env';
dotenv.config({
path: path.resolve(process.cwd(), envFile),
});Preloading via npm Scripts
{
"scripts": {
"start": "node -r dotenv/config dist/index.js",
"dev": "nodemon -r dotenv/config src/index.js"
}
}Best Practices
- Add
.env*to.gitignore: Never commit actual secrets or.envfiles to git. - Commit
.env.example: Commit a template file with placeholder values showing required variables:# .env.example PORT=3000 DATABASE_URL= API_SECRET_KEY= - Validate with Zod: Combine
dotenvwithzodto fail fast during server startup if required variables are missing.
Common Mistakes
- Importing after application modules: If another module reads
process.env.DATABASE_URLat top-level evaluation time beforedotenv.config()is called, the value will beundefined. - Assuming values are typed: All variables in
process.envarestringorundefined. NumericPORT=3000is read as"3000".
Alternatives & Modern Native Feature
- Node.js 20.6+ Native
--env-fileFlag: Node.js now has native.envloading without any third-party dependencies:node --env-file=.env index.js - dotenv-expand: Extends dotenv to support variable expansion (e.g.
URL=${PROTOCOL}://${HOST}).
When Not to Use It
- In Next.js, Vite, or Remix applications where
.envfile loading is already built directly into the framework core. - In Node.js 20.6+ where
node --env-file=.envsatisfies your requirements without installing extra packages.