How to use .env files in Node

Updated onbyAlan Morel
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?

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:

JAVASCRIPT
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.

Conclusion

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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.