Skip to content
Software Testing Journal
Software Testing Journal

Your daily dose of learning!

  • Blog
  • Help Center
  • Video Playlist
  • Podcast & FAQ
  • Privacy Policy
Software Testing Journal

Your daily dose of learning!

How to handle multiple environments in the Node.js framework?

Dheeraj Gambhir, 2023-12-112023-12-11

There are multiple ways to achieve it but one of the simplest ways is to use the Dotenv module.

Dotenv is a lightweight and zero-dependency module that automatically loads environment variables from a .env file into the process.env object. Handling multiple environments using dotenv involves creating separate .env files for each environment (e.g., dev, testing, staging, production) and dynamically loading the appropriate file based on the current environment.

Here’s a step-by-step guide to follow:

Step 1: Install dotenv Package (recommended- locally):
npm install dotenv –save

Step 2: Create separate .env files for each environment. For example:
.env.dev for development
.env.test for testing
.env.stage for staging
.env.prod for production

Each file should contain environment-specific configuration variables. For instance:

Step 3: Configure your application to read environment-specific variables:

Here’s an example:

Step 4: How to access the environment variables?
Accessing your variables is very easy. They are attached to the process.env object, so you can access them using process.env.KEY. For example:

Step 5: Set the active environment:

Notes:

  1. Ensure that the .env file is in the root directory of your project.
  2. Employ proper error handling to catch cases where required variables are not defined.
  3. Exclude .env files from version control (e.g., add them to .gitignore) to avoid exposing sensitive data like authentication keys and passwords.

Read more here: https://www.npmjs.com/package/dotenv

If you find this post helpful, please share them with your colleagues and friends.

  • Facebook
  • Twitter
  • LinkedIn
  • Email
Automation dotenvnodejsTips

Post navigation

Previous post
Next post
©2025 Software Testing Journal | WordPress Theme by SuperbThemes