Local NodeJS Environment Variables

Local NodeJS Environment Variables

The DotEnv is an NPM package which allows you to load local NodeJS Environment Variables in your project. It is based on The Twelve-Factor App Methodology - Storing configuration in environment separate from code.


The installation is as easy as any other NPM Package

npm install dotenv
yarn add dotenv


Create a .env file in your root directory. Add any env vars you want in that file. For eg.


Load the variables

Now in your starting JS file (which you run using node <filename>.js) add the following line of code


What this does is, it imports the dotenv module using the CommonJS syntax and then calls the config function on it. This loads up the dotenv variables in the .env file created earlier. You can also pass an object as an argument into it which you can find here

Use the variables

You can use the variables inside that file now like any other env variable using the Global Object process and the object env inside it in the following way:


Note that you can use the env variables inside the .env file only after calling the config function in the dotenv module. So the above line of code needs to come after the require('dotenv').config() function.