Working with Environment Variables in Node.js

Learn how to effectively use environment variables in Node.js to manage configurations, enhance security, and streamline your web development workflow.


Back to Home

Table of content

Introduction

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.

Why Use Environment Variables?

  • Security: Keep sensitive info out of your codebase.
  • Flexibility: Easily change configuration without code changes.
  • Portability: Move your app between environments (development, testing, production) effortlessly.

Accessing Environment Variables in Node.js

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!');
}

Setting Environment Variables

On Unix/Linux/macOS

export PORT=3000
node app.js

On Windows (CMD)

set PORT=3000
node app.js

On Windows (PowerShell)

$env:PORT=3000
node app.js

Using a .env File with dotenv

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.

Installation

npm install dotenv

Usage

// 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.

Best Practices

  • Don’t commit secrets: Keep .env files out of source control.
  • Document required variables: List them in a .env.example file.
  • Validate variables: Use runtime checks or tools like envalid for type-safety.
  • Use prefixes for app-specific variables: For monorepos or serverless environments, e.g., MYAPP_DB_HOST.

Example: Config Management in Node.js

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}`);

Conclusion

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.

configuration
dotenv
environment variables
Node.js
nodejs best practices
security
Web Development