Rack-CORS and You!

Kevin Gleeson
2 min readDec 5, 2020

Are you tired of getting this error in your Rails Applications?

Does not knowing what CORS is got you down?

Well, have a seat over there and let’s take a look at…

…RACK-CORS AND YOU!!!

And how! Little Timmy.

To get an understanding of why we’re getting this error. It’s important to know what CORS is and what it does for our applications. For starters, CORS stands for Cross Origin Resource Sharing. CORS is essentially a security feature located in our browsers that limits access to our apis from the frontend by monitoring which requests can be allowed through to our backends.

Sounds simple enough

But what about that error?

Don’t be scared, Little Suzie. We’ll learn about that error now!

According to MDN “CORS failures result in errors, but for security reasons, specifics about the error are not available to JavaScript. All the code knows is that an error occurred. The only way to determine what specifically went wrong is to look at the browser’s console for details.” This is the main reason why you’re having trouble accessing your backend through your frontend.

Typically when we look at our console, we see the error from the top of the article. Javascript has an issue with this sort of access and if you’re building out a full stack application you’ll likely need to set up your backend the following way:

Step 1. Install the “rack-cors” gem

That’s as simple as including gem ‘rack-cors’ in your gem file and doing a fresh bundle install.

Step 2. Find cors.rb

Go to your config file, and inside the initializers find the cors.rb file.

Step 3. Set cors to allow all origins.

When you go to your cors.rb file you’ll see something that looks like this:

Take a look at line 10, Little Suzie.

What line 10 is saying is that our backend will only allow requests coming from ‘example.com’. All we need to do to change this is allow our origins to come from anywhere. This can be done by replacing ‘example.com’ with an asterisk. ‘*’

You can edit out some of the methods that you want users to have access to this way, too!

Now our backend should be able to communicate properly with our frontend.

See kids, that wasn’t so bad.

Tune in next week for another blog!

Loving the colors on your frontend, Suzie! Keep working hard, Timmy!

--

--

Kevin Gleeson

Software Engineering Graduate from Flatiron School. Former expatriate and music teacher.