CORS headers in Rails stack ?

When working with API it’s important to set up CORS headers to support Web Client (Browser) requests.

Common solution for most of Rails developers is to create

1
before_action
with custom headers.

def enable_cross_resource sharing
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Headers'] = 'GET, POST, PUT, DELETE, OPTIONS'
  headers['Access-Control-Allow-Methods'] = 'Origin, Accept, Content-Type, X-Requested-With, X-CSRF-Token'
end

Well that’s WRONG.

What you should do instead is to setup CORS at the (Rack)[http://rack.github.io] middleware level before your Rails routes. Routes only accessible after HTTP OPTIONS method succeeded on the web client.

Rack Cors is helpful if you don’t want to write your own middleware.

In

1
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
1
Warden::Manager
instead of
1
0
).

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*',
      :headers => :any,
      :methods => [:get, :post, :delete, :put, :options, :head]
  end
end

All above is an OK setup for Heroku, (Aptible)[https://www.aptible.com] or other services that allow you to deploy your app with cli gem but won’t let you access higher stack like Nginx or Apache

“The proper way” of handling Cross-origin is to set it up at the Nginx level. So your Rails app is only busy with serving API.

Make use of add_header in the

1
location
context (or
1
server
if all your server does is serving API)

add_header Access-Control-Allow-Headers "X-Requested-With";
add_header Access-Control-Allow-Methods "GET, HEAD, OPTIONS";
add_header Access-Control-Allow-Origin "*";

Phoenix On A Raspberry Pi with Exrm

## Intro> Before you read this be sure to look at:>> 1. [Phoenix Advanced Deployment](http://www.phoenixframework.org/docs/advanced-deplo...… Continue reading