Environment Lifecycle
1
Development
Your local machine. Local database, verbose logging, hot reload. Config: .env.development
2
Staging
Pre-production server. Production-like setup, staging database, sandbox API keys. Config: .env.staging
3
Production
Live server with real users. Production database, real API keys, minimal logging. Config: .env.production
Pattern 1: Per-Environment .env Files
Pattern 2: dotenv-flow (Recommended)
Loads files in cascading order, with later files overriding earlier ones:.env(shared defaults).env.local(local overrides, not committed).env.development(or staging/production/test).env.development.local
cross-env: Cross-Platform NODE_ENV
SettingNODE_ENV in npm scripts works differently on Windows vs Unix:
cross-env normalizes this:
Centralized Config Module
Never scatterprocess.env throughout your codebase. Create one file that reads, validates, and exports all variables:
Environment Variables in Docker
Dockerfile (default values)
docker run with —env-file
docker-compose.yml
GitHub Actions Secrets
Store sensitive values in GitHub: Settings > Secrets and variables > Actions > New repository secret.Secret Rotation: Zero-Downtime Process
1
Generate new secret
2
Update in secret store
Add the new secret to GitHub Actions secrets, Heroku Config Vars, or your secret manager.
3
Redeploy the application
Restart the app so it picks up the new value.
4
Verify new secret works
Run health checks. Test authenticated endpoints.
5
Revoke the old secret
Only disable the old credential AFTER confirming the new one is active.
Monitoring for Leaked Secrets
git-secrets (Pre-commit hook)
GitHub Secret Scanning
Enable in repository settings. GitHub automatically scans every commit and pull request for known secret patterns (AWS keys, GitHub tokens, etc.).Emergency: Secret Found in Git History
If you discover a secret was committed:- Rotate the secret immediately (generate new, update everywhere)
- Use
git filter-repoor BFG Repo Cleaner to remove from history - Force-push the cleaned history
- Notify all team members to re-clone the repo
Key Terms
Common Mistakes
Scattering process.env throughout the codebase
Scattering process.env throughout the codebase
When process.env.X appears in 50 files, refactoring and testing become painful. Use a config module: one place to change, mock, and validate.
Committing .env.production to git
Committing .env.production to git
Every .env.* file with real secrets must be in .gitignore. Only .env.example is safe to commit.
Using the same secrets across all environments
Using the same secrets across all environments
Development and production must have separate credentials. If a developer’s laptop is compromised, you don’t want production credentials exposed.
No validation at startup
No validation at startup
If DB_URI is undefined, your app might start successfully and crash only when the first database query runs. Validate all required vars before the server starts.