How to Use Environment Variables in Express for Configuration
In Express, use
process.env.VARIABLE_NAME to access environment variables. Load them from a .env file using the dotenv package for easy configuration management.Syntax
Environment variables in Express are accessed via process.env. You can read any variable by its name, for example, process.env.PORT to get the port number.
To load variables from a file, use the dotenv package and call require('dotenv').config() at the start of your app.
javascript
require('dotenv').config(); const port = process.env.PORT || 3000; console.log(`Server will run on port: ${port}`);
Output
Server will run on port: 3000
Example
This example shows how to create a simple Express server that uses environment variables for the port and a secret key. It loads variables from a .env file using dotenv.
javascript
import express from 'express'; import dotenv from 'dotenv'; dotenv.config(); const app = express(); const port = process.env.PORT || 3000; const secretKey = process.env.SECRET_KEY || 'defaultsecret'; app.get('/', (req, res) => { res.send(`Secret key is: ${secretKey}`); }); app.listen(port, () => { console.log(`Server running on port ${port}`); });
Output
Server running on port 4000
Common Pitfalls
- Forgetting to call
dotenv.config()before accessingprocess.envcauses variables to be undefined. - Not creating a
.envfile or not placing it in the project root leads to missing variables. - Using strings like
process.env.PORTdirectly without fallback can crash your app if the variable is missing. - Committing
.envfiles with secrets to public repos risks security leaks.
javascript
/* Wrong way: Missing dotenv config */ console.log(process.env.API_KEY); // undefined /* Right way: */ require('dotenv').config(); console.log(process.env.API_KEY); // prints the key if set
Quick Reference
- Install dotenv:
npm install dotenv - Create a
.envfile in your project root - Put variables like
PORT=4000andSECRET_KEY=mysecretin.env - Load variables early with
require('dotenv').config() - Access variables with
process.env.VARIABLE_NAME
Key Takeaways
Always load environment variables early using dotenv.config() in Express apps.
Access variables safely with process.env.VARIABLE_NAME and provide defaults.
Never commit .env files with secrets to public repositories.
Use environment variables to keep configuration flexible and secure.
Create a .env file in your project root to store variables for local development.