DEV Community

M-Shkreli21
M-Shkreli21

Posted on

Hiding API keys with Rails

As developers, we tend to use API's to help us bring in the necessary data for our applications. API's themselves are a great resource that every developer should learn to use. Most API's require something that is called an API key, this 'key' is essentially a code that gives you as the developer access to use said API. However, due to the key being specific to each user that has signed up for one, this can pose a huge security concern if you try to use a simple fetch in your front end with the key in the url. There are plenty of ways that developers can hide API keys, but the one that I have used and found to be the most productive is to hide it in the backend.

By setting up your API calls in your backend, you enable yourself to create custom routes that can be used in your front end fetches. There are a few steps that need to happen in order to successfully hide your 'keys' in the backend of your app.

Step 1: if one doesn't already exist, create a .ENV file in which you will assign a variable to each API that you will be using.

Step 2: In your application should exist a .gitignore file in which you can choose what in your application gets pushed to github for other developers to view. Within that git ignore file we add the simple line of .env. Now when you commit and push changes to github the .env file will not be pushed with it.

Step 3: Once you have the env file setup and ignored, we can create an "API_controller" file that will enable us to write methods for each api path we plan on using. Within the url we will assign that variable from the env file for the actual API url. Example below:
Image description

Step 4: Now that our controller has been set up our next step is to create custom routes that go to that respective api method. When creating routes it could be as simple as get "/company_profile, to: "api#[custom api method]. Whats important to remember is that each custom route must have an HTTP method like GET, POST, PATCH, DELETE.

Step 5: Now the final step, with the backend successfully hiding each api we can use our fetches efficiently in the front end. instead of having the long api url in our fetch we can simply set it as fetch('/company_profile) and our app will know to go to the backend method, communicate to the api and bring in the necessary data without jeopardizing the security of our application.

Top comments (0)