How to use environment variables in Node.js applications
· Category: Node.js
Short answer
Read environment variables with process.env.VAR_NAME. Use the dotenv package to load variables from a .env file in development. Validate required variables at startup and fail fast if any are missing.
Details
The Twelve-Factor App methodology recommends storing config in environment variables. Never commit .env files to version control; instead, provide a .env.example template. For type safety and validation, use libraries like zod or joi to parse process.env into a typed config object. This catches misconfiguration before the server accepts traffic.
In production, inject variables through your container orchestrator or secrets manager rather than files. If you are containerizing your app, see How to write a Dockerfile for patterns that pass env vars at runtime. For managing Linux server configuration, how to write bash scripts can automate environment setup.
Tips
- Separate secrets (API keys, database URLs) from non-secret config (port numbers, feature flags).
- Use
NODE_ENVsparingly; prefer explicit feature flags instead of branching logic on environment names. - For cloud deployments, see how to choose a cloud provider when deciding where to manage secrets.