Hassle Free Development: Manage Environment in Node App

Get the final source code from here

Environment Variable

Environment variables are injected from outside the application. These variables are varied in a different stage of the application. For example, a web app has separate database addresses for

  • Development Mode

  • Testing Mode

  • Staging Mode

  • Execution Mode

So when you are developing an app, definitely you do not want to mess up with production database. In this criteria, managing environment variable comes handy.


To manage the environment variable, here we are going to use the following tools

  • Visual Studio Code (code editor)

  • dotenv (npm package)

  • DotENV (editor extension)

Light, Camera, Action

  1. Install the editor for your suitable platform

  2. Install Node.js in your machine

  3. Make sure both node and npm is installed in your system

  4. Open Visual Studio Code and install the dotEnv extension.

To install dotENV extension in Visual Studio Code

  • Open the code editor

  • Open vs code extension panel (Crtl+Shift+X)

  • Search for dotENV

  • Install the extension

Prepare Project

Create a directory, manageEnvironment and enter the directory.

mkdir manageEnvironment

cd manageEnvironment

Now in the root directory, create the project

npm init -y

Now open the directory in your code editor.

Create two files named index.js and .env

Your project directory should look like

├── ...
├── manageEnvironment                        
│   ├── index.js
│   ├── .env             
│   └── package.json
├── ...

Install the npm package dotenv from the root directory.

npm i dotenv

Manage Environment

Update your .env file with an environment variable and your .env file should look like


And now invoke the dotEnv and read the environment variable. Your index.js file should be look like

const dotenv = require(“dotenv”);



Now run your node app by

node index.js

In your console, output should be looked like,



Always put the .env file in .gitIgnore

So create the .gitIgnore file and add the .env file.

Your .gitIgnore file should be looked like,



So when your code is in development, testing, staging or production phase, use the appropriate environment variable.

Final Word

Stay tuned and if there is a confusing term or something, the response below. I will replay ASAP.