What is .env file in node JS

aadilraza339

aadilraza339

Posted on May 22, 2021

What is .env file in node JS

Its environment variables file. In simple term, it is a variable text file. In this file we set a variable with value and that you wouldn’t want to share with anyone, purpose of file is keep as secret and secure because in .env file we store our database password, username, API key etc…

how you can set variable
create a file called .env
open it in any editer
Then
You can easily set your environment variables and values with the syntax ENV_VARIABLE=VALUE and boom! 🙂
.env

This how you can use these variables in your Node JS porject.
Run it on your command line npm i dotenv --save
require('dotenv').config() Is required in the file where you want to use.
To see if you have connected with your .env simply console console.log(process.env);
OUTPUT

See some more example 👇

require('dotenv').config()
const db = require('db')
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})
Enter fullscreen mode Exit fullscreen mode

!NOTE
.env includes sensitive information, so it should not be pushed with your code/GIT repo. Please make sure!
This is how you can avoid .env to push in your repo using GIT.

Create a file called .gitignore in the root directory of your project, then open it, then write .env in it. Now git will avoid pushing your .env file, you can know more about how .gitignore works here

HAPPY CODE LIFE

💖 💪 🙅 🚩
aadilraza339
aadilraza339

Posted on May 22, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related