Rails Rack CORS
Rails simplifies many time consuming tasks that developers spent time and energy wrestling with in the past. One of these simplified tasks is performed by Rack CORS.
Rack CORS handles Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests. How do I know this? Because Rails makes that comment directly in the cors.rb file located in your auto-generated Rails app folder inside config / initializers / cors.rb:
# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests.
Rails extends it’s helpful support by also commenting:
# Be sure to restart your server when you modify this file.
# Read more: https://github.com/cyu/rack-cors
The suggested Github site further explains that Rack CORS is Middleware that provides support for CORS for Rack compatible web applications. I’ve stated what CORS stands for but what is Rack? Rack is a web server interface. According to Wikipedia:
Rack is a modular interface between web servers and web applications developed in the Ruby programming language. With Rack, application programming interfaces (APIs) for web frameworks and middleware are wrapped into a single method call handling HTTP requests and responses.
Rack CORS, simply put, allows a Rack compatible front end app to request information from your Rails back end. Your data is stored in your back end so when a user is clicking around on a front end app, those clicks send fetch requests to your Rails back end to perform tasks and collect data. This action is characterized as Cross-origin because the request is originating from an entity your Rails back end is not familiar with. Rack CORS allows this request to happen and gives you control over who can make requests and what kind of requests can be made.
For instance you may allow a request to see a list of names but not allow a request to add a name to the list. You can also allow requests from any origin for any resource by using an asterisk (*).
To implement Rack CORS in your Rails back end, uncomment or add the following to your Gemfile:
gem ‘rack-cors’
Run bundle update to install this gem. Then inside of your cors.rb file, uncomment the CORS middleware and ensure origins and resource has asterisks if you want to allow all requests:
That’s it! Now fetch requests can be made to your Rails back end giving users a full interactive experience.
So as you design and build your Rails back end API, keep your user in mind and set up Rack CORS to reflect how they will use or interface with your data.
Documentation on Rack can be found at:
https://guides.rubyonrails.org/rails_on_rack.html
Documentation on CORS can be found at:
https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS