Hiding API Keys in A Rails App with Figaro and Heroku

Matt Eva
3 min readJan 20, 2022

Keeping API keys secret is essential to ensuring your application remains secure. Here’s a quick walkthrough of how you can secure your API keys in a Rails application using the Figaro gem and Heroku.

To start, add the figaro gem to your gemfile:

gem 'figaro'

Next, run bundle install.

The figaro gem includes a generator, which sets up an application.yml in your config folder and adds it to your .gitignore file, which prevents it from getting pushed up to GitHub. Keeping API keys out of GitHub is crucial to maintaining app security, even if your git repository is private.

To run this generator, run bundle exec figaro install.

Then, in this new application.yml file, you can assign your API key to an environment variable using “key value pair” syntax. Make sure to specify that you want to access this variable in the development environment.

To access your API key within your code, use the syntax ENV["API_KEY"].

Since this file has been added to a .gitignore file, it won’t be pushed up to your GitHub, and therefore won’t get pushed up to Heroku. Fortunately, Heroku allows you to declare config variables that can be used in your production environment.

To set these config vars, log in to your heroku account and select the application you’re working on.

Next, select “settings” from the menu bar.

Scroll down until you see a section titled “config vars”. Select “Reveal Config Vars”. This will reveal all the configuration variables associated with this app.

At the bottom of this list, there’s a section where you can add new config variables. One input is labelled “key”, while the other is labelled “value”.

Place your API key in the “value” section, and the key you’re using in your code in the “key” section. This should be the exact same key you’ve defined in your application.yml file. (In keeping with the example above, I’d use the key “API_KEY”.) If the name is different than the name you use in your code, your code won’t be able to access your API key in your production environment.

Try it out for yourself! Don’t get discouraged if you run into any errors. Just be patient and double check your work (or take a break, drink some water, and eat a snack). Happy coding!

(Note: you can also use the Heroku CLI and functionality within the Figaro gem itself to set up environment variables in Heroku.)

--

--

Matt Eva

I write about coding, web development, and various other programming topics!