Environment variables (.env)
A .env file keeps settings and secrets out of your code and out of git.
In this page:
Syntax
# .env
KEY=value
// app.js
require('dotenv').config();
const value = process.env.KEY;
Environment variables (.env)
The dotenv package loads KEY=value lines from .env into process.env at start-up. Node 20.6 and later can load it with node --env-file=.env. Add .env to .gitignore and commit a .env.example listing names only.
Note:
Never commit .env with real secrets.
Example: Environment variables (.env)
function parseEnv(text) {
const out = {};
for (const line of text.split("\n")) {
const m = line.match(/^\s*([A-Z_]+)\s*=\s*(.*)\s*$/);
if (m) out[m[1]] = m[2];
}
return out;
}
const env = parseEnv("PORT=3000\nDB_HOST=localhost\n");
console.log(env, typeof env.PORT, Number(env.PORT) + 1);
// Output:
// { PORT: '3000', DB_HOST: 'localhost' } string 3001
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Committing secrets
- Forgetting to load dotenv before reading variables
- Assuming values are numbers
Chapter Summary
- .env holds configuration
- dotenv or --env-file loads it
- Values are strings
- Keep it out of git
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: