Cross Origin Resource Sharing with Sinatra

29 Dec

It’s no lie that I think highly of the potential of Cross Origin Resource Sharing. One of the great things about it is that it doesn’t take much re-wiring of existing server (or client-side) apps to start working cross domain.

Enabling your server app is as simple as including a few extra headers when you detect a cross origin request. How do you know it’s a cross origin request? You’ll see the Origin: header — all CORS requests will have it. From there, response headers depend on the specifics of the request, but I won’t go over those here — check out the Mozilla Developer Center treatment for in-depth information.

I’ve been working with Sinatra a lot lately, so I put together an extension for Sinatra that makes enabling Cross Origin requests even easier.

sudo gem install sinatra-cross_origin

There are two ways to use the extension: globally or per-route.

Global

For when you want to share all your endpoints cross-domain.


require 'sinatra/base'
require 'sinatra/cross_origin'

class MyApp < Sinatra::Base
  register Sinatra::CrossOrigin

  enable cross_origin

  get '/' do
    "This is available to cross domain javascript requests automatically"
  end
end

Per Route

For when you want to share only some of your routes cross-domain.


require 'sinatra/base'
require 'sinatra/cross_origin'

class MyApp < Sinatra::Base
  register Sinatra::CrossOrigin

  get '/' do
    cross_origin
    "This is available to cross domain javascript requests"
  end
end

Configuration

You can mix and match app-wide config and request specific config.


require 'sinatra/base'
require 'sinatra/cross_origin'

class MyApp < Sinatra::Base
  register Sinatra::CrossOrigin

  configure do
    # Comma separate list of remote hosts that are allowed.
    # :any will allow any host
    set :allow_origin, :any

    # HTTP methods allowed
    set :allow_methods, [:get, :post]

    # Allow cookies to be sent with the requests
    set :allow_credentials, true
  end

  get '/' do
    # Only available to GET requests originating from
    # http://example.com.  No cookies allowed.
    cross_origin :allow_origin => 'http://example.com',
      :allow_methods => [:get],
      :allow_credentials => false
    "This is available to cross domain javascripts"
  end
end

Grab the source at Github: britg/sinatra-cross_origin.

blog comments powered by Disqus