Setting up multiple environments in NodeJs app using DotEnv

Ragesh R
2 min readJan 15, 2022

--

Its always good to have multiple environments configured for our backend projects. This ensures that we do not disturb the production environment when we need to implement new features.

The ideal setup would be to have 3 environments as below

  • Development -> This environment is for running in the local machine. This comes with the advantage of not needing to deploy each small change to a server and testing it out there.
  • Staging -> This environment depicts running of code in server. This is a secondary server setup that mimics the production server in all the sense but computing power and storage can be much lower as this is only for testing by the developer, QA and few alpha testers if needed.
  • Production -> This is the actual server where the backend is hosted for the end users.

Managing keys for multiple server might get complicated as we might need to change keys manually before deploying to environments. Thats where dotenv package helps us.

Dotenv is a module that loads environment variables from a .env file.

Using dotenv in nodejs

Installation

npm install dotenv --save

with npm

yarn add dotenv

with yarn

We can have multiple .env files based upon our environments like below

.env files

In the above image we are setting up .env files for 4 environments -> development, production, staging and test.

Setting up dotenv is just one line code in app.js

require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` });

Now that we have setup the file. We need to mention the node env in the process while starting the server like below.

NODE_ENV=development nodemon ./bin/www"

Here we are using nodemon to start the server. If you dont want to use nodemon you can start the server using node alone

NODE_ENV=development node ./bin/www"

If you liked this article please clap and follow for a weekly nodejs article.

Happy Coding!

--

--

Ragesh R

Android Enthusiast | Node Monk | Self motivated Idealist