Setting Up Env Variables
Defining and using environment-specific configuration variables within code files is less than ideal due to security reasons as well as the coupling of environment-specific configuration and application code. In this lesson, we'll avoid declaring our MongoDB environment variables directly in our database connection file and instead use the popular dotenv package to load environment variables from a .env file.
In the last lesson, we hard-coded MongoDB environment configuration values directly into our code. We created a
user variable, a
userPassword variable, and a
cluster variable in our
src/database/index.ts file. We obtained the values of these variables directly from our MongoDB Atlas dashboard.
Having these database configuration values in our code is a bad idea for a couple of reasons.
Database environment variables should be confidential so we should be wary of having our values publicly available especially if we start to consider pushing our source code to an online repository.
As the name suggests, environment variables are for setting up our app's runtime environment. They don't have anything to do with our app's logic. What if we wanted to change our MongoDB's user password when our application has already been built? We would want to update the environment variable without having to go back into the source code and changing it. This will help limit the need to modify and redeploy an app due to changes in configuration data when an app is already deployed.
process is a global object with information about the currently running process.
process.env is an object within
process that contains information representative of the state of the Node environment. During runtime, the reference to an environment variable within
process.env is replaced with the actual value of the variable.
Environment variables defined within
process can be specified both in a development setting as well as in a production setting. The
dotenv library is a popular package that helps load variables from a
.env file for Node.js projects, which is helpful during development.
We'll head to the terminal and install the
dotenv library as a development dependency. We'll also install the type declaration file of
dotenv as a development dependency.
dotenvlibrary as a
devDependencysince when we deploy our app, our cloud management solution - Heroku will automatically save environment variables defined in the dashboard into
process.env. As a result, we won't need the
dotenvlibrary in our production code. However, if you choose to use another method to deploy your app that may require a
.envfile, you might need to install
dotenvas a regular dependency!