Never hardcode API keys, passwords, or database URLs. Environment variables store sensitive configuration separately from code. dotenv loads these from a .env file locally. Production deploys inject them directly. Learn to build secure applications from day one.
Why environment variables matter
| // DON'T: Hardcode secrets (security risk) const DB_URL = 'mongodb://[email protected]'; const API_KEY = 'sk_live_abc123xyz789'; // DO: Use environment variables const DB_URL = process.env.DATABASE_URL; const API_KEY = process.env.API_KEY; // Why? ✅ Secrets never in version control ✅ Different configs per environment ✅ Easy to rotate secrets ✅ Secure in production ✅ Team members don't see keys |
dotenv setup
| // 1. Install $ npm install dotenv // 2. Create .env file (NEVER commit this) DATABASE_URL=mongodb://localhost:27017/myapp API_KEY=sk_live_abc123xyz789 JWT_SECRET=super_secret_key_here PORT=3000 NODE_ENV=development // 3. Add to .gitignore .env .env.local node_modules/ // 4. Load at app start (FIRST LINE) require('dotenv').config(); const express = require('express'); const app = express(); // 5. Access via process.env const PORT = process.env.PORT || 5000; const DB_URL = process.env.DATABASE_URL; app.listen(PORT, () => { console.log(`Server on port ${PORT}`); }); |