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:
BASHAPI_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.
BASHnpm install dotenv
Or if you are using yarn:
BASHyarn add dotenv
Now we just need to use the dotenv
package to load the .env
file.
JAVASCRIPTimport 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:
JAVASCRIPTimport 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!
- Git Tutorial: Learn how to use Version Control
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- Getting Started with Deno
- Getting Started with Sass
- Getting Started with Handlebars.js
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Setting Up Stylus CSS Preprocessor
- Getting Started with Moon.js