Node.js Guide
Environment Variables with dotenv
Never hardcode API keys or database passwords again. Here's how to use .env files in Node.js the right way.
Quick answer: Install dotenv (npm install dotenv), create a .env file with KEY=value lines, add require('dotenv').config() at the top of your entry file, then read values via process.env.KEY. Add .env to .gitignore.
Install dotenv
npm install dotenv
Add it to your project dependencies. It's a small package with zero sub-dependencies.
Create a .env File
In your project root, create .env:
PORT=3000
DATABASE_URL=postgres://user:pass@localhost:5432/mydb
OPENAI_API_KEY=sk-abc123
NODE_ENV=development
Rules for .env files:
- One
KEY=valueper line - No spaces around the
= - No quotes needed (they become part of the value)
- Comments start with
#
Add .env to .gitignore
Critical: NEVER commit .env to Git. It contains secrets. Add it to .gitignore immediately.
# .gitignore
node_modules/
.env
.env.local
.env.*.local
Instead, commit a .env.example with fake values that documents what variables are needed:
# .env.example
PORT=3000
DATABASE_URL=postgres://user:pass@localhost:5432/mydb
OPENAI_API_KEY=sk-your-key-here
NODE_ENV=development
Load .env at Startup
CommonJS:
require('dotenv').config();
console.log(process.env.PORT); // "3000"
ES Modules:
import 'dotenv/config';
console.log(process.env.PORT);
The import 'dotenv/config' form runs dotenv as a side effect — you don't need to call .config() manually.
💡 Must be the FIRST import in your entry file. Otherwise other code might read process.env before it's populated.
Use Environment Variables
const port = process.env.PORT || 3000;
const dbUrl = process.env.DATABASE_URL;
const apiKey = process.env.OPENAI_API_KEY;
// Validate required variables at startup
const required = ['DATABASE_URL', 'OPENAI_API_KEY'];
for (const key of required) {
if (!process.env[key]) {
console.error(`Missing required env var: ${key}`);
process.exit(1);
}
}
Always check required variables at startup. Better to fail fast than to crash later.
Native Alternative (Node 20.6+)
Recent Node versions have dotenv-like support built in:
node --env-file=.env app.js
No package needed. Works exactly the same as dotenv. Use this for new projects on Node 20+.
You can also specify per-environment files:
node --env-file=.env.production app.js
🛡️ Security Best Practices
- Never commit .env. Add to .gitignore before creating it.
- Rotate leaked keys immediately. If you accidentally push a key, revoke it and generate a new one.
- Use different values per environment. Dev keys should not match production keys.
- Validate on startup. Fail fast if required variables are missing.
- Don't log them. Never
console.log(process.env)— it exposes all secrets to logs. - Set production env vars on the host. Most hosts (Vercel, Railway, Render) provide a UI for env vars rather than using files.
❓ Frequently Asked Questions
What is dotenv?
An npm package that loads environment variables from a .env file into process.env.
Should I commit .env?
Never. Add it to .gitignore. Commit .env.example instead.
Do I need dotenv in Node 20+?
No. Use node --env-file=.env app.js instead — it's built in.
Different .env files per environment?
Create .env.development, .env.production. Load with --env-file or dotenv's path option.