How to use .env file in node.js
Dallington Asingwire
Posted on June 29, 2022
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=students
DB_USERNAME=dallington
DB_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 students
Database username is dallington
Database 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!😊
Posted on June 29, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024