.env

Lucas Saladini
2 min readDec 5, 2021

When coding in web languages it’s common to use a file called .env where you store all your environment variables like connections with your database, users, password and passwords for your cryptography (see here a story that I wrote about CryptoJS package).

Using this file makes your system more secure and less prone to get your confidential information stoled. This is a secure way to store sensitive information inside your root directory without any other steps needed.

Where does get the dotenv package comes in here?

This package only facilitates the way to use the information stored in .env file inside your other files in JavaScript. Think of it like a router, fetching the information from one place and delivering it to the other where is needed.

To start using it you need to install it with the command


npm install dotenv

Or


yarn add dotenv

After that just import it with the basic and common import commando on the top of the JS file you are working.
Let’s say you want to connect to your database, using dotenv package and .env file is very simple, first if you don’t have the .env file, create it (obviously!) and open it. Inside the file insert your information like this:

DB_HOST = localhost
DB_USER = root
DB_PASSWORD = 123456789

After that, open your JS file and stablish the connection this way?

const db = require(‘db’);
db.connect({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD
})

There you go! Your connection is secure, the information is secure and you don’t need to worry.
Probably just worry about trying to SQLInject your DB, but that is another topic for another text.

--

--

Lucas Saladini

Starting in programming life. Has a background in HTML, PHP, CSS and JS. Loves to share his thoughts and opinions.