Environment Variables and Config
Passwords, API keys and database addresses must never be written in your code or committed to Git. Keep them in environment variables and read them with process.env.
The same code runs on your laptop, a test server and production, but with different settings and secrets. Environment variables keep those values outside the code, so secrets never end up in Git and each environment gets its own configuration.
Example
# .env (add .env to .gitignore!)
PORT=3000
DATABASE_URL=postgres://shop:change-me@localhost:5432/shop
PAYMENT_KEY=put-your-test-key-hereExample
Loading a .env file
Example
# Node 20.6+ can load it directly:
node --env-file=.env server.js
# or with the popular dotenv package:
npm install dotenv
# then at the top of server.js: import "dotenv/config";Good habits
- Commit a
.env.examplewith the names but fake values, so others know what to set - Fail at start-up if a needed setting is missing, not later in the middle of an order
- Use different values for development and production
- If a secret was ever committed, change it - deleting the file doesn't remove it from Git history
Key points
- Read settings from process.env.
- Keep secrets in .env files that are git-ignored.
- Check required settings at start-up.
📝 Test yourself
1. Where should an API key go?
2. What should .gitignore include?
3. Fill in the object that holds environment variables:
const port = .env.PORT;
