Is there a way to read environment variables in Node.js code?
Yes! In Node.js, you can access environment variables through the built-in process.env
object. These variables are typically set outside of your Node.js code—often in your operating system’s environment, in a Docker container, or from a CI/CD pipeline. Below are the most common ways to read environment variables:
1. Using process.env
Directly
// server.js const port = process.env.PORT || 3000; console.log('Server will run on port:', port);
- Here,
process.env.PORT
will pull the value of thePORT
environment variable. - If it’s undefined, we use a default fallback:
3000
.
Setting Environment Variables
- macOS/Linux:
PORT=5000 node server.js
- Windows (cmd.exe):
set PORT=5000 && node server.js
- PowerShell:
$env:PORT=5000; node server.js
2. Using a .env
File with dotenv
A popular approach for local development is to create a .env
file that stores your environment variables. Then use the dotenv library to load them into process.env
:
-
Install dotenv:
npm install dotenv
-
Create a
.env
file in your project root:PORT=3000 DB_HOST=localhost DB_USER=myuser DB_PASS=mypassword
-
Load variables in code:
// server.js require('dotenv').config(); // load .env into process.env const port = process.env.PORT || 3000; console.log('Server will run on port:', port); console.log('DB Host:', process.env.DB_HOST); console.log('DB User:', process.env.DB_USER); console.log('DB Password:', process.env.DB_PASS);
Important Notes
- Do not commit your
.env
file to public repositories if it contains sensitive data (like passwords or API keys). - You can list
.env
in your.gitignore
to ensure it stays out of version control.
3. Best Practices for Managing Environment Variables
-
Avoid Committing Secrets
- Use local
.env
files or environment configuration on your hosting platform, but don’t store sensitive data in code repositories.
- Use local
-
Use a Library
- dotenv is widely adopted for local dev. In production (e.g., Docker, Kubernetes, or cloud hosting), environment variables are often set at the infrastructure level.
-
Validate Variables
- For critical environment variables, consider using a validation library or custom checks to ensure they are defined before your app proceeds.
-
Keep Production Config Out of Dev
- Maintain separate
.env
files or environment management for each stage (development, staging, production) to avoid mixing credentials or configurations.
- Maintain separate
Recommended Resource
Summary
- Native Approach: Use
process.env.VARIABLE_NAME
directly in your code. - Local Development: Rely on dotenv and a
.env
file to easily manage environment variables. - Production: Typically set variables via the hosting environment or deployment scripts.
This approach ensures your application logic stays flexible and secure, separating environment-specific details (like ports, database credentials, or API keys) from your codebase.