DEV Community

Cover image for What is .env file in node JS

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
You can easily set your environment variables and values with the syntax ENV_VARIABLE=VALUE and boom! 🙂

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

See some more example 👇

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

.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


Discussion (3)

mgrachev profile image
Grachev Mikhail

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

aadilraza339 profile image
aadilraza339 Author

Yes, it is usefull

walterfcarvalho profile image
Valter f Carvalho

Very useful and simple, dude thanks !