Passing an API Key to Heroku Node Application

featured
September 09, 2017
💫 Originally posted here. Broken? Let me know ~

I was learning how to publish a node app, GitHub Traffic View(source on GitHub), which requires a GitHub API key to be passed to Heroku application.

Problem

Initially, the API key is stored in a file, which is untracked by Git. It was fine until when I found out that Heroku requires files to be published to be tracked by Git.

I didn’t want to expose my secret string to GitHub, which is very easily searchable as Jamie Taylor points out in his blog post, User Secrets – What Are They And Why Do I Need Them? (Jamie talks about how to use User Secrets, please refer to it if you are dealing with .NET Core).

So the alternative is to use an environment variable and make it available on Heroku.

Recap of Accessing API key locally

In a previous blog post, Hiding API Keys on GitHub, I wrote about how to hide an API using an environment variable.

Suppose that your node app access a key via an environment variable, process.env.GITHUB_DEVELOPER_KEY

In Windows, you can set the environment variable as follows

But the problem is that, GITHUB_DEVELOPER_KEY is available only in your local machine and won’t be available after publishing to Heroku.

So after publishing your application to Heroku, you need to set an environment variable for GITHUB_DEVELOPER_KEY on deployed Heroku application, as well.

How do we set the environment variable on Heroku?

When publishing to Heroku, you need to use Heroku CLI. One of the options for the command is to set a configuration variable.

The command is heroku config:set<ENVIRONMENT_VARIABLE>=<VALUE> and the documentation is available on Heroku Dev Center page.

After deploying the node application, just set the configuration variable as shown below.

  • heroku config:set lets you set an environment variable on Heroku application, while
  • heroku config:get retrieves the environment variable value.
  • heroku config will return all the configuration values set for the application.

Now your node app will use that config var value set on Heroku application.

Conclusion

I just showed you one of the ways to use Heroku config vars, which is to hide an API key.

You can use it to configure your app differently or pass other sensitive information such as database connection string.