Click Below to subscribe

How to Create Multiple Environments In Node.js 2023

In Software development, almost all applications have a need for multiple environments. In this article, we gonna learn how to manage multiple environments in a node application.

1. Install env-cmd npm package.

npm i env-cmd

2. Create .env files in the root of your application.

 .env.development
 .env.staging 
 .env.production

.env.development

PORT=3001

.env.staging

PORT=3002

.env.production

PORT=3003

3. Update package.json scripts.

"scripts": {
    "start": "env-cmd -f .env.development node ./bin/www",
    "start:staging": "env-cmd -f .env.staging node ./bin/www",
    "start:production": "env-cmd -f .env.production node ./bin/www"
},

Syntax:- 

env-cmd -f .env_file command

-f is the alias for --file

4. Finally test your application.

development

npm start

staging

npm run start:staging

production

npm run start:production

Checkout:- https://github.com/ultimateakash/node-multiple-env

Extras:-

1. You can also use npm_config_ environment variable.

windows

%npm_config_my_variable%

linux/mac

$npm_config_my_variable

2. Now in package.json we can use this variable.

windows

"scripts": {
    "start": "env-cmd -f .env.%npm_config_env% node ./bin/www"
},

linux/mac

"scripts": {
    "start": "env-cmd -f .env.$npm_config_env node ./bin/www"
},

3. Now you can pass environment as an argument.

npm start --env=staging

Leave Your Comment