Node.js Environment Variables
Here is a complete and easy-to-understand guide on Node.js Environment Variables — covering .env usage, process.env, configuration patterns, security, and best practices.
🌱 Node.js Environment Variables
Environment variables allow you to store sensitive data and configuration outside your source code.
Examples of what they store:
-
Database credentials
-
API keys
-
JWT secrets
-
Port numbers
-
Mode (development / production)
Node.js reads them using:
⭐ 1. Using Environment Variables Without Any Library
Set variables temporarily:
On Linux / macOS:
On Windows CMD:
In your Node.js file:
⭐ 2. Using .env File (Recommended)
Most Node.js apps use dotenv package.
Install:
Create .env file:
Load .env in app:
Access variables:
⭐ 3. Basic Example with Express
📁 app.js
⭐ 4. Environment Modes (dev / prod / test)
Set environment mode:
Access:
Common values:
-
development -
production -
test
⭐ 5. Multiple .env Files
Many apps use:
Load based on environment:
⭐ 6. Never Commit .env to Git
Add to .gitignore:
⭐ 7. Default Values
Use fallback:
⭐ 8. Type Conversion
Environment variables are strings. Convert as needed:
Boolean conversion example:
⭐ 9. Using Environment Variables in Scripts
In package.json:
For Windows users (cross-platform):
⭐ 10. Security Best Practices
✔ Never commit .env
✔ Use .env.example as a template
✔ Use environment variables in production (Heroku, AWS, Vercel)
✔ Encrypt secrets using Vault or Docker secrets
✔ Load secrets only at startup
⭐ 11. Environment Variable Validation
Use Joi or Zod for required variables.
Example with Joi:
⭐ 12. Safe Config Pattern (Recommended)
Instead of using process.env everywhere, create a config file.
📁 config.js
Use it:
⭐ 13. Using Environment Variables in Docker
Dockerfile:
docker-compose.yml:
🎉 Summary
Environment variables provide:
✔ Security
✔ Clean configuration
✔ Production-ready app setup
✔ Easy portability
Use:
-
.env+ dotenv for development -
process.envdirectly in production
