Environment Variables and dotenv – Node.js Tutorial 12
In this tutorial, we will learn about environment variables and how to use dotenv
in a Node.js application.
Environment Variables
Environment variables are global variables that are used by the operating system to pass information to processes. In Node.js, we can use environment variables to store configuration variables, sensitive information such as API keys, and other application settings.
Environment variables are accessed using the process.env
object in Node.js. We can set environment variables using the command line before running our Node.js application, or by loading them from a file using dotenv
.
dotenv
dotenv
is a Node.js module that allows us to load environment variables from a .env
file into process.env
. This makes it easy to manage and configure environment variables for our Node.js application.
To use dotenv
, we first need to install it using npm:
npm install dotenv
Once installed, we can create a .env
file in the root directory of our Node.js application and add our environment variables in the following format:
API_KEY=your_api_key
DB_HOST=your_db_host
Then, in our Node.js application, we can use dotenv
to load these variables into process.env
by requiring it at the top of our script:
require('dotenv').config();
Now, we can access our environment variables using process.env.API_KEY
and process.env.DB_HOST
throughout our application.
Conclusion
Using environment variables and dotenv
in our Node.js applications allows us to securely manage our configuration settings, API keys, and other sensitive information. This helps keep our code clean and organized, and makes it easy to configure our application for different environments.
I hope this tutorial has been helpful in understanding how to use environment variables and dotenv
in Node.js applications. Happy coding!
⭐Check out Filestack – https://calcur.tech/filestack
Node.js YouTube Playlist – https://calcur.tech/nodejs
Great video. I love it
because of the NODE_ENV !==production requirement, will need an OR option for the connection string for Mongodb something like const CONNECTION = process.env.CONNECTION || 'mongodb://localhost:<port#>/'
Hey Caleb, where the value of the connection string would come from if we were actually in production?
Thanks for the content! Very good!