Step by Step guide to Hiding API key in Rails and React
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!
- 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.
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
4. Add your .env to the .gitignore file
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.
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.
And there you have it! You can now hide your API keys to be used throughout your own application.