Environment Variables, or Keeping Your Secrets Secret in a Node.js App

Glynn Bird
Feb 10, 2017 · 2 min read

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:


Then at the entry point in your code add:


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

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

Center for Open Source Data and AI Technologies

Things we made with data at IBM’s Center for Open Source…

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store