API calls from a Rails App on Heroku Pt. 1

Photo by Maxwell Nelson on Unsplash

In a previous article, I broke down how one would use the Faraday Gem to make calls to a third-party API from your Rails application when it is in the development stages. If you deploy your application to Heroku then you will need to implement certain solutions to make sure your API calls function properly. In this article, I will show you how I approached this challenge.

What is the problem?

Now let say you have a frontend and a Rails backend. In this app, you want to have your backend handle all of the API calls that require client ids and secrets. You want your backend to simply send the data back to the front end.

Now let’s say we have a Rails app in development running on http://localhost:3000. When you make an HTTP request to an API, say, for example, the free Petfinder API to get a list of available dogs for adoption, this is essentially what is happening:

Working API Response Cycle

Now things will change a bit once this backend is deployed on Heroku. How is that, you might say?

When you deploy an app to Heroku you receive some arbitrary Heroku sub-domain, like https://cliff-hanger-43432–432.heroku.com. If you try to do an API call from this free Heroku URL, you will never get a response back. Rather your response will be received at the root address which is simply https://heroku.com. It looks like this:

Broken API Response Cycle

The Fix

ElsIf this is an app with a back-end handling the API calls as an intermediary with the front-end, as mentioned at the beginning of this article, there are a couple more steps. But why?

Chances are your front end is deployed using one of the various services such as Netlify, Firebase, or Github pages. All of these options automatically provides a secure HTTPS address. When you purchase a custom domain for your back end API, the default setting for that URL, after you point your site to it, will be the ol’ HTTP.

This is the type of error that you will receive in the browser when trying to run the production build:

xhr.js:184 Mixed Content: The page at 'https://frontend.netlify.app/' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://backendapi.com/content'. This request has been blocked; the content must be served over HTTPS.

HTTPS cannot make a request to endpoints served with HTTP. It is not secure and is a dangerous practice for production builds. You will need to acquire an SSL certificate for that domain, and add that certificate to your project on Heroku, your hosting provider.

If you are successful, your flow should look more like this:

Working API Response Cycle

Conclusion

If you need more help adding an SSL certificate to your Heroku project please check out part 2 of this post.

Full-Stack Software Engineer and Lifelong Learner