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:
- Ensure that the .env file is in the root directory of your project.
- Employ proper error handling to catch cases where required variables are not defined.
- 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