×
By the end of this chapter, you should be able to:
dotenv
moduleWorking with environment variables is a great way to configure different aspects of your Node.js application. Many cloud hosts (Heroku, Azure, AWS, now.sh, etc.) and Node.js modules use environment variables.
Hosts, for example, will set a PORT variable that specifies on which port the server should listen to properly work. Your application might have different behaviors (like logging, error handling, error reporting) depending on the value of an environment variable.
When you authenticate through external providers (login through facebook, linkedin, twitter etc), you will be granted a "secret key" which those services will use to authenticate your application. Very very bad things can happen if those keys get into the hands of a hacker so it's essential to isolate certain variable definitions from where your code is.
dotenv
To handle environment variables we're going to use the dotenv module. Here are the steps we need.
npm install dotenv
.env
file.env
to your .gitignore
!.env
filerequire('dotenv').config()
process.env
Let's imagine we have the following as our .env
file:
SECRET_KEY=dfjklfjjf32hnanf PORT=3000 USERNAME=elie
Notice above that there are no spaces between the equal sign and the value. In our node/express application, heres how we would use these values:
require("dotenv").config(); console.log(process.env.SECRET_KEY); // dfjklfjjf32hnanf console.log(process.env.PORT); // 3000 console.log(process.env.USERNAME); // elie
When our application is deployed on Heroku, we do not load our environment variables from a .env
file. Instead, we tell Heroku the name of the variable using the following syntax.
heroku config:set NAME_OF_VARIABLE=VALUE -a NAME_OF_YOUR_HEROKU_APP
When you're ready, move on to Writing API Tests with Jest