CORS headers in Rails stack ?
When working with API which is bombarded by XHR requests, which often come from various subdomains, one turns CORS headers.
Common solution for most of Rails developers is to create
before_action with custom headers.
This is an alright solution but I’d suggest moving that into a (Rack)[http://rack.github.io] middleware layer before your Rails router kicks in. Issue with the controller method is that you must enable OPTIONS response in the rails router to handle requests.
If you don’t want to write your own middleware, Rack Cors comes quite handy.
application.rb make sure that you serve CORS at the top of the stack or at least before middleware you need (in my case I had
Warden::Manager instead of
The proper way of handling Cross-origin is to set it up at the Nginx/Load-balancer level. So your Rails app is only busy with serving text but not the headers.
For NGINX you can make use of add_header in the
location context (or
server if all your server does is serving API)