Skip to content
Rack Middleware for handling Cross-Origin Resource Sharing (CORS), which makes cross-origin AJAX possible.
JavaScript Ruby CSS Other
Branch: master
Clone or download

Latest commit

Latest commit b528e2b May 28, 2020

Files

Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
examples Added Rails6 example May 22, 2020
lib/rack Update version.rb Mar 20, 2020
test Added Rails6 example May 22, 2020
.gitignore Updating rails3 example Sep 7, 2014
.rubocop.yml Rubocop apocalypse Mar 16, 2020
.travis.yml Actually run the test suite in Travis CI Mar 20, 2020
CHANGELOG.md Up gem version Dec 30, 2019
Gemfile Rubocop apocalypse Mar 16, 2020
LICENSE.txt
README.md Update README.md May 29, 2020
Rakefile Rubocop apocalypse Mar 16, 2020
rack-cors.gemspec Rubocop apocalypse Mar 16, 2020

README.md

Rack CORS Middleware Build Status

Rack::Cors provides support for Cross-Origin Resource Sharing (CORS) for Rack compatible web applications.

The CORS spec allows web applications to make cross domain AJAX calls without using workarounds such as JSONP. See Cross-domain Ajax with Cross-Origin Resource Sharing

Installation

Install the gem:

gem install rack-cors

Or in your Gemfile:

gem 'rack-cors'

Configuration

Rails Configuration

For Rails, you'll need to add this middleware on application startup. A practical way to do this is with an initializer file. For example, the following will allow GET, POST, PATCH, or PUT requests from any origin on any resource:

# config/initializers/cors.rb

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', headers: :any, methods: [:get, :post, :patch, :put]
  end
end

We use insert_before to make sure Rack::Cors runs at the beginning of the stack to make sure it isn't interfered with by other middleware (see Rack::Cache note in Common Gotchas section). Basic setup examples for Rails 5 & Rails 6 can be found in the examples/ directory.

See The Rails Guide to Rack for more details on rack middlewares or watch the railscast.

Note about Rails 6: Rails 6 has support for blocking requests from unknown hosts, so origin domains will need to be added there as well.

Rails.application.config.hosts << "product.com"

Read more about it here in the Rails Guides

Rack Configuration

NOTE: If you're running Rails, updating in config/application.rb should be enough. There is no need to update config.ru as well.

In config.ru, configure Rack::Cors by passing a block to the use command:

use Rack::Cors do
  allow do
    origins 'localhost:3000', '127.0.0.1:3000',
            /\Ahttp:\/\/192\.168\.0\.\d{1,3}(:\d+)?\z/
            # regular expressions can be used here

    resource '/file/list_all/', :headers => 'x-domain-token'
    resource '/file/at/*',
        methods: [:get, :post, :delete, :put, :patch, :options, :head],
        headers: 'x-domain-token',
        expose: ['Some-Custom-Response-Header'],
        max_age: 600
        # headers to expose
  end

  allow do
    origins '*'
    resource '/public/*', headers: :any, methods: :get

    # Only allow a request for a specific host
    resource '/api/v1/*',
        headers: :any,
        methods: :get,
        if: proc { |env| env['HTTP_HOST'] == 'api.example.com' }
  end
end

Configuration Reference

Middleware Options

  • debug (boolean): Enables debug logging and X-Rack-CORS HTTP headers for debugging.
  • logger (Object or Proc): Specify the logger to log to. If a proc is provided, it will be called when a logger is needed. This is helpful in cases where the logger is initialized after Rack::Cors is initially configured, like Rails.logger.

Origin

Origins can be specified as a string, a regular expression, or as '*' to allow all origins.

*SECURITY NOTE: Be careful when using regular expressions to not accidentally be too inclusive. For example, the expression /https:\/\/example\.com/ will match the domain example.com.randomdomainname.co.uk. It is recommended that any regular expression be enclosed with start & end string anchors (\A\z).

Additionally, origins can be specified dynamically via a block of the following form:

  origins { |source, env| true || false }

A Resource path can be specified as exact string match (/path/to/file.txt) or with a '*' wildcard (/all/files/in/*). To include all of a directory's files and the files in its subdirectories, use this form: /assets/**/*. A resource can take the following options:

  • methods (string or array or :any): The HTTP methods allowed for the resource.
  • headers (string or array or :any): The HTTP headers that will be allowed in the CORS resource request. Use :any to allow for any headers in the actual request.
  • expose (string or array): The HTTP headers in the resource response can be exposed to the client.
  • credentials (boolean, default: false): Sets the Access-Control-Allow-Credentials response header. Note: If a wildcard (*) origin is specified, this option cannot be set to true. Read this security article for more information.
  • max_age (number): Sets the Access-Control-Max-Age response header.
  • if (Proc): If the result of the proc is true, will process the request as a valid CORS request.
  • vary (string or array): A list of HTTP headers to add to the 'Vary' header.

Common Gotchas

Positioning in the Middleware Stack

Positioning of Rack::Cors in the middleware stack is very important. In the Rails example above we put it above all other middleware which, in our experience, provides the most consistent results.

Here are some scenarios where incorrect positioning have created issues:

  • Serving static files. Insert before ActionDispatch::Static so that static files are served with the proper CORS headers. NOTE: this might not work in production as static files are usually served from the web server (Nginx, Apache) and not the Rails container.

  • Caching in the middleware. Insert before Rack::Cache so that the proper CORS headers are written and not cached ones.

  • Authentication via Warden Warden will return immediately if a resource that requires authentication is accessed without authentication. If Warden::Manageris in the stack before Rack::Cors, it will return without the correct CORS headers being applied, resulting in a failed CORS request.

You can run the following command to see what the middleware stack looks like:

bundle exec rake middleware

Note that the middleware stack is different in production. For example, the ActionDispatch::Static middleware will not be part of the stack if config.serve_static_assets = false. You can run this to see what your middleware stack looks like in production:

RAILS_ENV=production bundle exec rake middleware

Serving static files

If you trying to serve CORS headers on static assets (like CSS, JS, Font files), keep in mind that static files are usually served directly from web servers and never runs through the Rails container (including the middleware stack where Rack::Cors resides).

In Heroku, you can serve static assets through the Rails container by setting config.serve_static_assets = true in production.rb.

You can’t perform that action at this time.