Hiding Rails API Keys in Heroku

I have just completed making a Rails application using an API and best practices for utilizing an API in your app is to hide your personal API key in your code so that no one can maliciously access and use your API key.  Currently, I still have my API key in my Rails adapter and thus I need to yank it.

An easy way to do this is to use environmental variables.  Replace your key in your Rails adapter with an environmental variable:

app/adapters/igdb_api.rb

  "X-Mashape-Key" => ENV["IGDB_API_KEY"]

Above, I just made up an environmental variable within the quotes and removed my personal API key.  Then I need to add an environmental variable to Heroku in one of two ways:

  1. Use the terminal by using the command heroku config:set IGDB_API_KEY=<personal key>.
    Screen Shot 2017-05-07 at 2.11.46 PMDon’t keep a space between the equal sign, the variable and the value, otherwise you will get the below error:
    Screen Shot 2017-05-07 at 2.05.25 PM.png
  2. Use the web by going to the settings for your Heroku app.  In the “Config Variables” section, click the button that says “Reveal Config Vars”.
    Screen Shot 2017-05-07 at 2.15.52 PM
    Then just add your made-up variable in the “Key” text field and your personal API key in the “Value” text field and click the “Add” button.
    Screen Shot 2017-05-07 at 2.19.01 PM.png

Make sure that you push your app changes to both Github and Heroku and then try making API calls again and you should be good to go!

 

Leave a comment