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!
- Getting Started with TypeScript
- Managing PHP Dependencies with Composer
- How to Serve Static Files with Nginx and Docker
- How to Set Up Cron Jobs in Linux
- How to deploy an Express app using Docker
- Using Puppeteer and Jest for End-to-End Testing
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js
- Learn how to build a Slack Bot using Node.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with React