Archi's Academy

BLACK FRIDAY

85% Discount for all November

clock-icon
00days
00hours
00minutes
00seconds
Get in touch

Software Development

Coding

One of the best ways to use sensitive information in open source repositories without hard-coding the information within publicly available repositories is setting environment variables.

Environment Variables are variables that are set by the Operating System. They are decoupled from application logic. They can be accessed from applications and programs through various APIs. There is a Node.js library called dotenv that helps you manage and load environment variables. Dotenv is a module that loads environment variables from a .env file into process.env. In Node.js, process.env is a global variable that is injected during runtime. When we set an environment variable, it is loaded into process.env during runtime and can later be accessed.

Now we can see how it is done.

dotenv can be added to your Node.js project by installing it using npm or yarn:

npm install dotenv

or with Yarn

yarn add dotenv

As early as possible in your application, require and configure dotenv.

require('dotenv').config()

Create a .env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE. For example:

DB_HOST=localhost

After you set the Environment variable, now your question is how you can access that environment variable? It is easy to access the variable in your project. process.env now has the keys and values you defined in your .env file. Now it can be accessed using

process.env.DB_HOST

Surumi-skill-training

Surumi Riju

Thursday, Jun 3, 2021