Step by Step guide to Hiding API key in Rails and React

Allison Anzalone
3 min readJan 16, 2022

Keeping your API key a secret is essential part of any application. Exposing your key may result in others using it for free, clogging up your traffic and using up all your credits if you have limited amount. It also makes you vulnerable to Attackers, which may use your credentials for attacks and the blame goes on you, since you are connected to that specific key.

A practical approach to hiding an API key is to keep it in an environmental variable and using a .gitignore file. This will allow you to use your API key in your application, but once the application is pushed to Github the environmental file is ignored and not pushed to your repository. So lets jump into how!

  1. Install dotenv-rails gem. This enables us to access the variable from anywhere in the app. You can either add it to your gemfile directly like below. Or type, gem install dotenv in your applications terminal.
If you used create-react-app to create your application, dotenv is already part of the script, so double check your gemfile to see if it is already exists.

2. Create a .env file and if your project does not already have one, a .gitignore file in the root directory

3. The .env file is where your variable will live. The name of your variable will need to be ALL_CAPS. In my project, I was using two different APIs, So I created two env variables to hold those values

Above are examples of what your env. variables might look like. (not real keys, I made them up!)

4. Add your .env to the .gitignore file

Your application might have a .gitignore file already established, if so, simply just add .env to it like above.

5. To reference your key, use ENV[‘VARIABLE’] syntax. Below are some examples of what it will look like in your rails application. In mine, I needed to call the APIs in different places, so to DRY up my code, I created a module and and used class methods to make my API calls. But same syntax could be used if you called the API in a rails model or controller.

In the first image, I was making calls to AlphaVantage API. In the second image, I was using a stock_quote gem

It is best practice to make calls to an API on the backend of your application. In my example, I was creating a Full Stack stock projection application using a Rails backend and a React frontend. In my controller, I called the module that contains my API class method, and then on my frontend, I made a GET request to my backend to get the data that I need.

stock_controller.rb and Dashboard.js

And there you have it! You can now hide your API keys to be used throughout your own application.

--

--