Learn how to effectively use environment variables in Node.js to manage configurations, enhance security, and streamline your web development workflow.
Table of content
Managing configuration safely and reliably is crucial in web development. Node.js developers frequently use environment variables to inject configuration details like API keys, database URLs, and application secrets, keeping sensitive data out of source code. In this guide, you’ll learn best practices for using environment variables in Node.js projects.
Node.js exposes environment variables through the process.env
global object. Access variables as shown below:
console.log(process.env.NODE_ENV); // outputs 'development', 'production', etc.
If you try to access an undefined variable, it will return undefined
, so always check for its existence:
const dbUrl = process.env.DB_URL;
if (!dbUrl) {
throw new Error('DB_URL is required!');
}
export PORT=3000
node app.js
set PORT=3000
node app.js
$env:PORT=3000
node app.js
Manually managing variables can be cumbersome, especially as your project grows. The popular dotenv package loads environment variables from a .env
file into process.env
automatically.
npm install dotenv
// app.js
require('dotenv').config();
console.log(process.env.SECRET_TOKEN);
Create a .env
file in your project’s root:
SECRET_TOKEN=mysecrettoken123
DB_URL=mongodb://localhost:27017/devdb
Important: Add .env
to your .gitignore
to avoid committing secrets.
.env
files out of source control..env.example
file.MYAPP_DB_HOST
.Here’s a basic example of using environment variables for configuration:
// config.js
require('dotenv').config();
module.exports = {
port: process.env.PORT || 3000,
dbUrl: process.env.DB_URL,
secretToken: process.env.SECRET_TOKEN,
};
// app.js
const config = require('./config');
console.log(`App running on port ${config.port}`);
Environment variables are a backbone of robust Node.js applications. Mastering them helps you write cleaner, more secure, and portable web applications. Always remember to keep your secrets private and document your configuration keys for your team’s safety and productivity.