Environment variables let you manage configuration settings like database credentials, API keys, and application settings outside your code. This enhances security, flexibility, and adaptability across different development, testing, and production environments. In this tutorial, you will learn how to use environment variables effectively in an Express.js application.
What Are Environment Variables?
Environment variables are pairs of keys and values stored outside the application code. They allow dynamic configuration without modifying the source code. They are commonly used for:
- Database Credentials: Define hostnames, usernames, and passwords securely.
- API Keys: Store secrets for third-party services.
- Application Settings: Configure port numbers and environment modes dynamically.
In Node.js, you can access environment variables using process.env.
Setting Up Environment Variables in Express.js
Express doesn't automatically load environment variables from files. You need the dotenv package to manage them easily.
Install dotenv Package
Run this command in your project directory:
npm install dotenv
Create a .env File
Create a .env file in your project's root directory and define environment variables:
# Application Settings
PORT=3000
HOST=127.0.0.1
PAGESIZE_DEFAULT=15
# Environment Mode
ENVIRONMENT=development
# MySQL Database Configuration
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=password
DB_NAME=example_db
MYSQL_PORT=3306
Load Environment Variables
Modify server.js or app.js to load environment variables using dotenv:
require('dotenv').config(); // Load .env file
const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000; // Use environment variable or default to 3000
app.get('/', (req, res) => {
res.send('Environment Variables in Express.js');
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Now, when you start the server, it will read the PORT and other values from the .env file.
Access Environment Variables
You can access environment variables anywhere in your Express application using process.env:
console.log('Database Host:', process.env.DB_HOST);
console.log('Environment Mode:', process.env.ENVIRONMENT);
Using Variables with Conditional Logic
Use the ENVIRONMENT variable to adjust application behavior:
const ENVIRONMENT = process.env.ENVIRONMENT || 'development';
if (ENVIRONMENT === 'development') {
console.log('Debug mode enabled');
} else {
console.log('Production mode active');
}
Organizing Configuration in a Separate File
To keep your code organized, store configuration settings in config.js:
// config.js
require('dotenv').config();
module.exports = {
port: process.env.PORT || 3000,
environment: process.env.ENVIRONMENT || 'development',
db: {
host: process.env.DB_HOST || 'localhost',
user: process.env.DB_USER || 'root',
password: process.env.DB_PASSWORD || ''
}
};
Import this configuration in your application:
const config = require('./config');
console.log('Port:', config.port);
console.log('DB Host:', config.db.host);
Best Practices for Using Environment Variables
- Do Not Commit
.envto Git- Add
.envto.gitignoreto prevent exposing sensitive data. - Example
.gitignoreentry:.env
- Add
- Manually Create the
.envFile on the Server (If Using a.envFile).- Do not upload
.envvia Git. - After deployment, SSH into your server and create it manually:
nano /path/to/your/project/.env - Set secure file permissions:
chmod 600 .env
- Do not upload
- Use Default Values for Missing Variables
- Ensure your app does not break if an environment variable is missing.
const PORT = process.env.PORT || 3000;
- Ensure your app does not break if an environment variable is missing.
- Use a
.env.exampleFile for Reference- Create a
.env.examplefile with placeholders to help developers understand the required environment variables.PORT=5000 DB_HOST=your_database_host DB_USER=your_database_user DB_PASS=your_database_password
- Create a
Conclusion
You have learned how to use environment variables in Express.js to manage configurations securely. You now know how to set up the dotenv package, create a .env file, access variables using process.env, and organize configurations efficiently. Additionally, you understand best practices to keep sensitive data secure and ensure application reliability.