Posted on • Originally published atlivecode247.com on
Local NodeJS Environment Variables
TheDotEnv is an NPM package which allows you to load local NodeJS Environment Variables in your project. It is based onThe Twelve-Factor App Methodology - Storing configuration in environment separate from code.
Installation
The installation is as easy as any other NPM Package
npm install dotenv# YARNyarn add dotenv
Setup
Create a.env
file in your root directory. Add any env vars you want in that file. For eg.
DB_HOST=localhostDB_PORT=3306DB_USER=rootDB_PASSWORD=password
Load the variables
Now in your starting JS file (which you run usingnode <filename>.js
) add the following line of code
require('dotenv').config()
What this does is, it imports thedotenv
module using the CommonJS syntax and then calls theconfig
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 findhere
Use the variables
You can use the variables inside that file now like any other env variable using the Global Objectprocess
and the objectenv
inside it in the following way:
console.log(process.env.DB_HOST)
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 therequire('dotenv').config()
function.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse