{ Environment Variables. }

Objectives:

By the end of this chapter, you should be able to:

  • Explain what an environment variable is
  • Create and read environment variables using the dotenv module

Introduction

Working 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.

Using dotenv

To handle environment variables we're going to use the dotenv module. Here are the steps we need.

  1. npm install dotenv
  2. In the root of your application create a .env file
  3. Make sure you add .env to your .gitignore!
  4. Add your environment variables to your .env file
  5. As early as possible in your application, require and configure dotenv, using require('dotenv').config()
  6. You should now be able to access your environment variables with 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

Setting environment variables on Heroku

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

Continue

Creative Commons License