How to use .env files in Node
In this post, we will learn how to use
.env files in our Node projects.
What is a .env file?
.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
Load the .env file
To load our
.env file, we will use the
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.
npm install dotenv
Or if you are using yarn:
yarn add dotenv
Now we just need to use the
dotenv package to load the
import dotenv from "dotenv"; dotenv.config();
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_SECRET environment variables into variables:
import dotenv from "dotenv"; dotenv.config(); const API_KEY = process.env.API_KEY; const API_SECRET = process.env.API_SECRET; console.log(API_KEY); // KEY console.log(API_SECRET); // SECRET
That's all there is to it! Now you have access to your environment variables from your
.env file inside your Node project.
This allows different users of the application to have different environment variables and still be able to use the same application.
We've seen how to define a
.env file, load it, and use the environment variables in our Node application.
Hopefully, you've found this post helpful to you!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!
Leave us a message!