DEV Community

Dallington Asingwire
Dallington Asingwire

Posted on

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
Enter fullscreen mode Exit fullscreen mode

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=students
DB_USERNAME=dallington
DB_PASSWORD=fdggavcyyatexcda
Enter fullscreen mode Exit fullscreen mode

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}`);

Enter fullscreen mode Exit fullscreen mode

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 students
Database username is dallington
Database password is fdggavcyyatexcda
Enter fullscreen mode Exit fullscreen mode

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!😊

Top comments (1)

Collapse
 
undqurek profile image
undqurek • Edited

Also, You can use solution available here:
dirask.com/posts/Node-js-read-env-...
or:
dirask.com/snippets/Node-js-custom...

I like it because:

  • lets to access process.env variables in .env file,
  • lest to define own one constants
  • lest to reuse local variables in .env file