Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 29, 2022 09:44 pm GMT

How to use .env file in node.js

Using .env file to store secret variables in software applications is a good common practice in software development. These variables can be database credentials, urls, ip addresses or hosts, secret keys for third party integrations etc.

In this tutorial, we are going to look at how to store secret variables in .env file and make use of them in a node.js application.

First of all, install an npm package called dotenv using the following command in your node.js project root directory;

npm install dotenv --save

dotenv package automatically loads environment variables from .env file into process object in node.js applications.

Create a .env file in your project root directory

DB_NAME=studentsDB_USERNAME=dallingtonDB_PASSWORD=fdggavcyyatexcda

In the above example of .env, I have database secret variables; database name (DB_NAME), database username (DB_USERNAME) and database password (DB_PASSWORD) but you can add as many variables as per your project needs.

You can then access your environment variables in any file of your node.js application as follows;

require('dotenv').config()console.log(`Database name is ${process.env.DB_NAME}`);console.log(`Database username is ${process.env.DB_USERNAME}`);console.log(`Database password is ${process.env.DB_PASSWORD}`);

In the above code example, we import and configure dotenv using require; which is a built-in node.js function used to load modules. We then access our environment variables through process which is a global object in node.js.

Output

Database name is studentsDatabase username is dallingtonDatabase password is fdggavcyyatexcda

Note:
Since this file contains secret variables, we don't push it to git/github so remember to include .env file in your .gitignore file under your project root directory.

This is the basic example or tutorial of how you use .env file in node.js application. Thank you for reading through this tutorial and happy coding!


Original Link: https://dev.to/dallington256/how-to-use-env-file-in-nodejs-578h

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To