how to use dotenv

How to Use dotenv

In this post, we will discuss how to use dotenv, a popular npm package for managing environment variables in Node.js applications. This package allows developers to store sensitive information such as API keys, database credentials, and other configuration variables outside of their codebase.

Step 1: Install dotenv

First, start by installing the dotenv package using npm or yarn:

bash
$ npm install dotenv

or

bash
$ yarn add dotenv

Step 2: Create a .env File

Next, create a .env file at the root of your project directory. This file will contain all your environment variables in the KEY=VALUE format. For example:

dotenv
API_KEY=your_api_key
DB_HOST=localhost
DB_USER=user
DB_PASS=password

Make sure not to include any quotes around the values or any whitespace in the variable names. Also, make sure not to commit this file to your version control system to keep your secrets private.

Step 3: Load Environment Variables

To load the variables defined in the .env file, require and configure dotenv at the very beginning of your application’s entry point file. This is usually the file where you start your server or define your application’s configurations.

For example, in your index.js file:

javascript
require('dotenv').config();

By calling config() on the dotenv module, it will read the .env file and set the defined environment variables in process.env.

Step 4: Access Environment Variables

Once the dotenv package is loaded and the environment variables are set, you can access them using process.env.VARIABLE_NAME. For example, to access the DB_HOST environment variable:

javascript
console.log(process.env.DB_HOST);

This will output localhost.

Conclusion

dotenv provides a simple and effective way to manage environment variables in Node.js applications. By following the steps mentioned above, you can securely store sensitive information separate from your codebase. Remember to always keep your .env file private and not commit it to a public repository.

I hope this guide helps you get started with using dotenv in your projects!