dotenv package – Environment Variables in Node JS App

Environment variables are used to keep the secret keys safe. While creating a Node JS app, we may need many keys/ passwords and other secrets for the encryption and authorization. These keys must be kept safe withing the project.

For serving this safety purpose the environment variables are used.

Dotenv Module is used for this purpose

Install Dotenv Package in Node JS Project

npm i dotenv

Reference: https://www.npmjs.com/package/dotenv

Using dotenv Package

require('dotenv').config()

eg:

require('dotenv').config();
const express = require("express");
const bodyParser = require("body-parser");

Create a file named .env in the root directory

Using the below terminal command we can create this file easily. Run this command in the root directory the project.

code .env

Now the environment variables can be added to this file. We can Add the environment-specific variables on new lines in the form of NAME=VALUE

eg:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
SECRET=Thisismysecretcode

Using env variables code:

userSchema.plugin(encrypt, {
  secret: process.env.SECRET,
   encryptedFields: ['password']
});

Add .env file to gitignore file

In order to avoid sharing the Environment variables file to the public, this file should be ignored. So to avoid getting pushed to the repository, we can ignore this file by adding it to the .gitignore file.

About the Author: smartcoder

You might like

Leave a Reply

Your email address will not be published. Required fields are marked *