DEV Community

Cover image for What is .env file in node JS
aadilraza339
aadilraza339

Posted on • Updated on

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

Top comments (4)

Collapse
 
walterfcarvalho profile image
Valter f Carvalho

Very useful and simple, dude thanks !

Collapse
 
aadilraza339 profile image
aadilraza339

Welcome :)

Collapse
 
mgrachev profile image
Grachev Mikhail

What do you think about a linter for .env files?
github.com/dotenv-linter/dotenv-li...
It can check, fix and compare .env files. I think it might be useful.

Collapse
 
aadilraza339 profile image
aadilraza339

Yes, it is usefull