Node.js Cross-Environment Configuration with dotenv

Managing different database credentials, API keys, and port numbers across development, testing, and production environments is a critical requirement for modern Node.js applications. This article provides a straightforward, step-by-step guide on how to configure and manage cross-environment variables in Node.js using the popular dotenv package alongside cross-env for seamless cross-platform execution.

Step 1: Install the Required Packages

To manage environment variables dynamically, you need to install dotenv. Additionally, because setting environment variables in terminal commands differs between Windows, macOS, and Linux, installing cross-env ensures your scripts run on any operating system.

Run the following command in your project root:

npm install dotenv
npm install --save-dev cross-env

Step 2: Create Environment-Specific Files

Instead of relying on a single .env file, create separate files for each of your deployment environments in your project root directory.

Create a .env.development file:

PORT=3000
DATABASE_URL=mongodb://localhost:27017/dev_db
ANALYTICS_KEY=dev_key_123

Create a .env.production file:

PORT=8080
DATABASE_URL=mongodb://mongodb-prod-server:27017/prod_db
ANALYTICS_KEY=prod_key_789

Step 3: Configure the Entry Point to Load Dynamic Files

In your main application file (e.g., index.js or app.js), use Node’s native path module and process.env.NODE_ENV to load the appropriate .env file at runtime.

Add this configuration at the very top of your entry file:

const dotenv = require('dotenv');
const path = require('path');

// Determine the current environment, defaulting to 'development'
const environment = process.env.NODE_ENV || 'development';

// Load the environment-specific .env file
dotenv.config({
  path: path.resolve(__dirname, `.env.${environment}`)
});

// Access variables as usual
console.log(`Running in ${environment} mode`);
console.log(`Server Port: ${process.env.PORT}`);
console.log(`Database URL: ${process.env.DATABASE_URL}`);

Step 4: Set Up package.json Scripts

To easily switch between your configured environments, define dedicated scripts in your package.json file. Use cross-env to set the NODE_ENV variable dynamically before launching the node process.

Update your package.json file:

{
  "scripts": {
    "start:dev": "cross-env NODE_ENV=development node index.js",
    "start:prod": "cross-env NODE_ENV=production node index.js"
  }
}

Now, running npm run start:dev will load the development configurations, while running npm run start:prod will apply your production settings instantly.