2017-09-09
Passing an API Key to Heroku Node Application
blogentry, programming, apikey, deployment
blogentry, programming, apikey, deployment
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.
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.
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
getAuth = () => { | |
const password = process.env.GITHUB_DEVELOPER_KEY; | |
return { | |
username: "dance2die", | |
password: password | |
}; | |
} |
In Windows, you can set the environment variable as follows
C:\Users\dance2die>set GITHUB_DEVELOPER_KEY=abc | |
C:\Users\dance2die>echo %GITHUB_DEVELOPER_KEY% | |
abc |
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.
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.
c:\> heroku config:set GITHUB_DEVELOPER_KEY=abc | |
Adding config vars and restarting myapp... done, v12 | |
GITHUB_USERNAME: abc | |
c:\> heroku config | |
GITHUB_DEVELOPER_KEY: abc |
Now your node app will use that config var value set on Heroku application.
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.