Robert's Homepage

How to Add CORS to Rails

#ruby-on-rails #how-to #software development

By default Rails blocks cross origin resource sharing requests (CORs) to protect applications from malicious requests.

However, when developing a SPA frontend using a framework like React or Vue.JS and a headless Rails API backend we will need to make requests from a different port serving our app on our local host. To allow these requests to reach our server, we will add a piece of middleware as a gem called rack-cors.

This gem will enable us to allow list request origins and their methods. Add the rack-cors (1.1.1) gem to your Gemfile then run bundle install afterwords. Once the gem is installed, open, and uncomment the config/initializer/rack-cors.rb file.

The Rails defaults are reasonable so the only modification required is allowing requests from the origin localhost:8080 (the port of your frontend app) instead of .