In this post, we will learn how to use .env files in our Node projects.
What is a .env file?
A .env file, also known as a dot env file, is a file that contains environment variables that can be used in your Node application. Examples of this include database credentials, API keys, and other sensitive information.
If you don't already have a .env file, create one at the root of your project.
Here is an example .env file:
BASH
API_KEY=KEY
API_SECRET=SECRET
Load the .env file
To load our .env file, we will use the dotenv package. dotenv is a popular open-source library that will handle the reading and parsing of .env files for us.
To get started, install the dotenv package in your project.
BASH
npm install dotenv
Or if you are using yarn:
BASH
yarn add dotenv
Now we just need to use the dotenv package to load the .env file.
JAVASCRIPT
import dotenv from"dotenv";
dotenv.config();
The config() method will automatically load the .env file and set the environment variables for you.
Using environment variables
Now that you've loaded your .env file, you can use the environment variables in your Node application.
Here's how to load the API_KEY and API_SECRET environment variables into variables: