Introduction
dotenv is a small zero-dependency module that reads key-value pairs from a .env file and injects them into process.env. It is the standard approach for managing environment-specific configuration in Node.js without hardcoding secrets in source code.
What dotenv Does
- Parses
.envfiles following aKEY=VALUEformat - Populates
process.envwith the parsed variables - Does not override existing environment variables by default
- Supports multiline values, quoted strings, and inline comments
- Works with
dotenv-expandfor variable interpolation within.envfiles
Architecture Overview
dotenv reads the specified file (default .env in the project root), parses each line using a regex-based parser that handles quoting and escaping, and assigns the result to process.env. It runs synchronously at startup so variables are available before any other module reads them. The parser handles single-quoted, double-quoted, and backtick-quoted values, each with different escape semantics.
Self-Hosting & Configuration
- Install via
npm install dotenvand callrequire('dotenv').config()at the top of your entry file - Use
--require dotenv/configas a Node.js CLI flag to preload without changing code - Pass
{ path: '.env.local' }to load from a custom file path - Set
{ override: true }to let.envvalues overwrite existing environment variables - Add
.envto.gitignoreand commit a.env.exampletemplate instead
Key Features
- Zero dependencies for a minimal footprint
- Does not overwrite pre-existing environment variables (safe for production)
- Supports multiline values enclosed in double or single quotes
- Companion
dotenv-expandpackage adds variable expansion (${VAR}syntax) - Preload mode via
node --require dotenv/config app.jsfor zero-code integration
Comparison with Similar Tools
- dotenvx — encrypted
.envfiles with multi-environment support; dotenv is simpler and unencrypted - direnv — shell-level env loading triggered on
cd; dotenv loads inside the Node.js process - cross-env — sets env vars inline in npm scripts; dotenv reads from files for larger config sets
- env-cmd — executes commands with env from a file; dotenv integrates directly into Node.js code
- Vault / SOPS — secret managers for production; dotenv is meant for development and simple deployments
FAQ
Q: Should I commit my .env file to Git?
A: No. Add .env to .gitignore. Commit a .env.example with placeholder values so other developers know which variables to set.
Q: Does dotenv work with TypeScript?
A: Yes. Install dotenv and call config() at the top of your entry file. Type declarations are included.
Q: How do I use different .env files per environment?
A: Call dotenv.config({ path: '.env.production' }) or use a wrapper like dotenv-flow that loads .env, .env.local, .env.{NODE_ENV} in order.
Q: Does dotenv work in the browser? A: Not directly. Bundlers like Vite and webpack have their own env variable handling. dotenv is for Node.js server-side code.