Loads environment variables from .env file
The dotenv package is a zero-dependency module that loads environment variables from a .env file into Node.js's process.env object. With over 90 million weekly downloads, it has become the de facto standard for managing configuration and secrets in JavaScript applications, following the Twelve-Factor App methodology of separating config from code.
At its core, dotenv solves a critical problem: how to handle sensitive data like API keys, database credentials, and environment-specific settings without hardcoding them into source code or committing them to version control. It provides a simple interface to parse key-value pairs from a plain text file and make them available throughout your application runtime.
The package is particularly valuable for teams working across development, staging, and production environments. Developers can maintain local .env files with their own database credentials while CI/CD pipelines inject production secrets, all using the same codebase. Version 17.3.1 introduces enhanced multi-environment support and encryption capabilities for secure deployments.
While Node.js v20.6.0+ includes native --env-file support, dotenv remains essential for projects requiring advanced features like variable expansion, multiline values, programmatic configuration, or compatibility with older Node.js versions. Its battle-tested parsing logic handles edge cases that native implementations overlook.
// Install: npm install dotenv
// Load at application entry point (server.js, index.js)
require('dotenv').config();
const express = require('express');
const { Pool } = require('pg');
// Access variables from process.env
const pool = new Pool({
host: process.env.DB_HOST,
port: parseInt(process.env.DB_PORT || '5432', 10),
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME
});
const app = express();
const PORT = process.env.PORT || 3000;
app.get('/api/health', async (req, res) => {
try {
await pool.query('SELECT 1');
res.json({ status: 'healthy', environment: process.env.NODE_ENV });
} catch (error) {
res.status(500).json({ status: 'unhealthy', error: error.message });
}
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT} in ${process.env.NODE_ENV || 'development'} mode`);
});
/* .env file:
NODE_ENV=development
PORT=3000
DB_HOST=localhost
DB_PORT=5432
DB_USER=devuser
DB_PASSWORD=secret123
DB_NAME=myapp_dev
*/
// Advanced: Multi-environment loading
const dotenv = require('dotenv');
const path = require('path');
dotenv.config({ path: path.resolve(__dirname, '.env') });
dotenv.config({ path: path.resolve(__dirname, `.env.${process.env.NODE_ENV}`), override: true });
dotenv.config({ path: path.resolve(__dirname, '.env.local'), override: true });Local Development Databases: Developers maintain individual .env files with personal PostgreSQL or MongoDB connection strings, avoiding conflicts when multiple team members work on the same codebase. Each developer's .env stays in .gitignore while .env.example documents required variables.
API Key Management: Store third-party service credentials (Stripe, SendGrid, AWS) in .env files instead of hardcoding them. Rotate keys by updating the file without touching application code, and prevent accidental commits of secrets to public repositories.
Multi-Stage Deployments: Use .env.development, .env.staging, and .env.production files to manage different configurations. The override option allows layering environments where .env.local overrides base .env settings for developer-specific tweaks.
Docker and Container Orchestration: Inject environment-specific configurations at container runtime by mounting .env files or using dotenv to parse configurations from orchestration tools. Particularly useful when combining static defaults with dynamic secrets from vaults.
Feature Flags and Configuration: Toggle features or adjust application behavior (debug modes, rate limits, third-party integrations) through environment variables without redeployment. Non-developers can modify .env files on servers to adjust settings safely.
npm install dotenvpnpm add dotenvbun add dotenv