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! 🙂
This how you can use these variables in your Node JS porject.
Run it on your command linenpm 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 consoleconsole.log(process.env);
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
})
!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)
Very useful and simple, dude thanks !
Welcome :)
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.
Yes, it is usefull