dotenv reads your .env
file and dumps those variables into process.env
. That's it. 54 million weekly downloads proves that developers prefer "just works" over fancy shit.
You know that feeling when you've hardcoded API_KEY="sk-test-whatever"
for the 47th time and think "I should really fix this properly"? That's when you reach for dotenv.
The Real Story: Why Everyone Uses This
Here's what actually happens: You start a new project, realize you need some API keys, create a `.env` file, install dotenv, add require('dotenv').config()
to the top of your app, and boom - you're done. No configuration hell, no reading 50 pages of docs.
npm install dotenv
require('dotenv').config()
// Now process.env.YOUR_SECRET_KEY just works
The latest version is 17.2.2, and honestly, unless you're doing something weird, any recent version will work fine.
The .env File That'll Probably Break
Here's your .env
file that'll cause you 2 hours of debugging:
DATABASE_URL=postgresql://user:password@localhost:5432/mydb
API_KEY=your-secret-key-here
## This comment breaks everything if you have spaces wrong
REDIS_URL = redis://localhost:6379 # NOPE - spaces around = will fuck you
PORT=3000
Gotcha #1: Spaces around the `=` sign break everything. KEY = value
doesn't work. Use KEY=value
.
Gotcha #2: Your `.env` file goes in your project root, not in some random subdirectory. I've seen developers spend an hour wondering why their config isn't loading because they put it in /config/.env
.
Gotcha #3: Comments with `#` in the middle of values need quotes or you're screwed: PASSWORD="my#password"
not PASSWORD=my#password
.
Node.js 20+ Has Built-In Support Now
Yeah, Node.js 20.6.0+ has native .env support with node --env-file=.env app.js
. Cool story. But good luck remembering that flag when you're debugging at midnight.
dotenv still makes sense because:
- You don't have to remember weird CLI flags
- It works with older Node versions (production servers are always behind)
- You can control exactly when variables load in your code
- Multiline values actually work properly
The Production Reality Check
Real talk: `.env` files are fine for development, but don't use them in production unless you enjoy being woken up at 3am.
Here's what'll happen: Someone commits the `.env` file to git (even though it's in `.gitignore`), your API keys end up on GitHub, and suddenly your AWS bill is $50,000 because crypto miners found your secrets.
Use AWS Secrets Manager, HashiCorp Vault, or Azure Key Vault for production. Or try dotenvx if you want encrypted .env
files that don't suck.
But for local development? dotenv is perfect. Install it, use it, move on with your life.