Environment variables, or keeping your secrets secret in a Node.js app

Imagine you have some Node.js code that uses an external API which needs an API key:

If we commit the above code to GitHub we divulge our secret API key allowing someone to use our account. This isn’t a rare event — many developers accidentally commit their credentials and others seek them out for nefarious purposes!

Keeping your secrets secret

Credentials are usually hidden in environment variables that your application can pick up when it runs. Our code now looks like this:

We expect an environment variable called MYAPIKEY to be there when our code runs. This file can now be safely committed to git.

Setting environment variables

On the command-line, environment variables can be set using export on Mac/Linux and set on Windows e.g.

export MYAPIKEY=ndsvn2g8dnsb9hsg

Once set, you can run your application in the usual way e.g node app.js.

As a shortcut, you can define environment variables and run the app in a single line:

MYAPIKEY=ndsvn2g8dnsb9hsg node app.js

Using the dotenv package

A simple way of defining multiple environment variables on your local machine is to use the dotenv package.

Create a .env file at the top of your project containing the environment variables you want to set:

MYAPIKEY=ndsvn2g8dnsb9hsg 
DEBUG=true
DEBUGLEVEL=5

Then at the entry point in your code add:

require('dotenv').config();

which loads the values from the .env file into your application's process.env.

The .env file can be excluded from any git commits by adding a .env line to your .gitignore file.

Environment variables in Bluemix

Bluemix sends its configuration to its CloudFoundry applications through environment variables:

  • VCAP_SERVICES - a JSON-encoded object describing the services that are paired with your application
  • VCAP_APPLICATION - a JSON-encoded object describing your application's meta data
  • custom environment variables can be defined in the Bluemix dashboard and are available to read in your application’s process.env

The cfenv library is often used to parse the CloudFoundry environment variables. Read more on how to use cfenv here.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.