Why Not Hardcode Config?
A database URL or API key hardcoded directly in your source code means every environment (local, staging, production) needs a different copy of the code — and worse, secrets end up committed to version control. Environment variables solve both problems.
Reading Environment Variables
Console Output
Click “Run” to see the console output here.
Using dotenv for Local Development
npm install dotenvLoading a .env File
Console Output
Click “Run” to see the console output here.
Where Variables Come From, by Environment
| Environment | Typical Source |
|---|---|
| Local development | A .env file, loaded by dotenv |
| CI/CD pipeline | Secrets configured in the CI provider's settings |
| Production (containers) | Injected by the orchestrator (Docker, Kubernetes) at runtime |
Never Commit .env to Version Control
A .env file containing real secrets should always be listed in .gitignore. Commit a .env.example instead, listing the variable names (with placeholder or no values) so teammates know what to configure.
Best Practice
Validate required environment variables at startup (throw early if something critical is missing) rather than discovering a missing DATABASE_URL only when the first database query fails at runtime.