Back to Tutorials
Node.js
20 min read
Sahasransu Satpathy
5/1/2026

Environment Variables & Config Management in Node.js

Learn how to securely manage environment variables and configuration in Node.js applications

Introduction

Managing environment variables and configurations is essential for keeping sensitive data secure and making applications flexible across different environments (development, testing, production).


Step 1: Using Environment Variables

Access environment variables in Node.js using process.env:

console.log(process.env.PORT); // Access the PORT variable

Create a .env file at the root of your project:

PORT=3000
DB_URL=mongodb://localhost:27017/mydb
SECRET_KEY=mysecretkey

Install the dotenv package:

npm install dotenv

Load variables in your app:

require('dotenv').config();

const port = process.env.PORT || 3000;
console.log("Server running on port:", port);

Step 2: Config Management

Centralize settings in a config file per environment:

// config.js
const config = {
  development: {
    port: process.env.PORT || 3000,
    dbUrl: process.env.DB_URL,
  },
  production: {
    port: process.env.PORT || 8000,
    dbUrl: process.env.DB_URL,
  },
};

module.exports = config[process.env.NODE_ENV || 'development'];

Step 3: Using Config in Your App

const config = require('./config');
const express = require('express');
const app = express();

app.listen(config.port, () => {
  console.log(`Server running on port ${config.port}`);
});

Step 4: Best Practices

  • Never commit .env files to version control.
  • Use .env.example to document required variables.
  • Validate environment variables at startup.
  • Keep secrets out of your codebase (API keys, passwords, etc.).

Step 5: Advanced Tools

  • dotenv-safe: Ensures all required env variables are defined.
  • config package: Hierarchical config management per environment.
  • Vault / AWS Secrets Manager: Secure secret management in production.

Conclusion

Proper environment variable and configuration management makes Node.js applications secure, maintainable, and environment-flexible.


SEO Suggestions:

  • Main keywords: Node.js environment variables, dotenv Node.js, configuration management, secure Node.js config
  • Meta description: Learn how to manage environment variables and configurations in Node.js for development, testing, and production. Step-by-step guide with best practices.
  • Catchy title suggestions: "Node.js Environment Variables & Config Management Guide", "Manage Configurations & Secrets in Node.js Effectively"

Previous Tutorial

Browse All Tutorials