CORS

suggest change

Cross-Origin Resource Sharing (CORS) is a browser security mechanism that restricts web applications running at one origin (domain, protocol, or port) from making requests to resources hosted on a different origin. When building API backends in Ruby, you must configure CORS headers so client-side frontend applications (such as React, Vue, or mobile web views) can access your endpoints.

How CORS Works

  1. Simple Requests: For basic GET or POST requests with standard content types, browsers send the request with an Origin header. The server responds with Access-Control-Allow-Origin.
  2. Preflight Requests: For requests that modify data (PUT, DELETE, PATCH) or include custom headers (such as Authorization: Bearer <token> or Content-Type: application/json), browsers first send an HTTP OPTIONS preflight request to verify server permissions before sending the actual request.

Using rack-cors Middleware

The standard, idiomatic way to handle CORS in Ruby is the rack-cors gem. Because almost all modern Ruby web frameworks (Sinatra, Hanami, Rails, and Roda) are built on top of Rack, rack-cors works seamlessly across them.

Install the gem:

gem install rack-cors

Or add it to your Gemfile:

gem 'rack-cors', require: 'rack/cors'

Configuring in config.ru (Rack, Sinatra, Hanami)

In your application's config.ru (or framework middleware stack):

require 'rack'
require 'rack/cors'
require_relative 'app'

use Rack::Cors do
  # Allow requests from frontend development servers and production domains
  allow do
    origins 'localhost:3000', 'https://myapp.example.com'

    resource '/api/*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head],
      credentials: true,
      max_age: 86400 # Cache preflight response for 24 hours
  end

  # Public read-only endpoints allowing any origin
  allow do
    origins '*'
    resource '/public/*',
      headers: :any,
      methods: [:get, :options]
  end
end

run App.new

Key Configuration Options

Pure Rack Implementation

If you want to handle CORS manually without external gems, you can create a custom Rack middleware:

class CorsMiddleware
  def initialize(app, allowed_origin: '*')
    @app = app
    @allowed_origin = allowed_origin
  end

  def call(env)
    # Intercept HTTP OPTIONS preflight request
    if env['REQUEST_METHOD'] == 'OPTIONS'
      return [204, cors_headers, []]
    end

    status, headers, body = @app.call(env)
    [status, headers.merge(cors_headers), body]
  end

  private

  def cors_headers
    {
      # Rack 3 requires lowercase header names
      'access-control-allow-origin'  => @allowed_origin,
      'access-control-allow-methods' => 'GET, POST, PUT, DELETE, OPTIONS',
      'access-control-allow-headers' => 'Content-Type, Authorization, X-Requested-With',
      'access-control-max-age'       => '86400'
    }
  end
end

Security Best Practices

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents