Environment Variables in Node.js
⏱ Estimated reading time: 2 min
Environment variables are external values used to configure applications without changing source code.
They are commonly used to store sensitive information and environment-specific settings.
1. Why Environment Variables Are Important
-
Keep secrets out of source code
-
Support different environments (development, testing, production)
-
Improve security
-
Simplify configuration management
Examples:
-
Database URLs
-
API keys
-
Port numbers
2. Accessing Environment Variables in Node.js
Node.js provides the process.env object.
3. Setting Environment Variables
3.1 On Windows
3.2 On macOS / Linux
4. Using Environment Variables in Code
5. Using .env Files (dotenv Package)
Managing many environment variables manually is difficult.
The dotenv package loads variables from a .env file.
Install dotenv
Create .env File
Load Environment Variables
6. Using Environment Variables with Express.js
7. Environment-Based Configuration
8. Security Best Practices
-
Never commit
.envfiles to Git -
Add
.envto.gitignore -
Use strong secret values
-
Rotate secrets regularly
9. Common Environment Variables
| Variable | Purpose |
|---|---|
PORT | Server port |
NODE_ENV | App environment |
DB_URL | Database connection |
API_KEY | External service key |
10. Common Mistakes
❌ Hardcoding secrets
❌ Forgetting to load dotenv
❌ Using wrong variable names
11. Summary
-
Environment variables store configuration data
-
Accessed via
process.env -
dotenvsimplifies management -
Essential for secure Node.js applications
Register Now
Share this Post
← Back to Tutorials