CORS middleware with origin validation and preflight handling
gem install philiprehberger-corsCORS middleware with origin validation and preflight handling
Add to your Gemfile:
gem "philiprehberger-cors"
Or install directly:
gem install philiprehberger-cors
require "philiprehberger/cors"
use Philiprehberger::Cors::Middleware,
origins: ['https://example.com'],
methods: %w[GET POST PUT DELETE],
headers: %w[Content-Type Authorization],
credentials: true,
max_age: 86_400
use Philiprehberger::Cors::Middleware, origins: '*'
use Philiprehberger::Cors::Middleware,
origins: ['https://app.example.com', 'https://admin.example.com']
use Philiprehberger::Cors::Middleware,
origins: [/\.example\.com$/, "http://localhost:3000"]
use Philiprehberger::Cors::Middleware,
origins: "*",
expose_headers: ["X-Request-Id", "X-Total-Count"]
Echo whatever the client sent in Access-Control-Request-Headers:
use Philiprehberger::Cors::Middleware,
origins: ['https://app.example.com'],
headers: :reflect
Opt into Chrome's Private Network Access preflight extension:
use Philiprehberger::Cors::Middleware,
origins: ['https://app.example.com'],
allow_private_network: true
use Philiprehberger::Cors::Middleware,
origins: ['https://app.example.com'],
credentials: true
Expose the configured origin list for logging or diagnostics:
middleware = Philiprehberger::Cors::Middleware.new(app, origins: ['https://app.example.com'])
middleware.allowed_origins # => ["https://app.example.com"]
wildcard = Philiprehberger::Cors::Middleware.new(app, origins: '*')
wildcard.allowed_origins # => :any
Unit-test your CORS policy without building a Rack env:
middleware = Philiprehberger::Cors::Middleware.new(app, origins: [/\.example\.com$/])
middleware.allows_origin?('https://api.example.com') # => true
middleware.allows_origin?('https://evil.test') # => false
Cors::Middleware| Method | Description |
|---|---|
.new(app, origins:, methods:, headers:, credentials:, max_age:, expose_headers:, allow_private_network:) | Create CORS middleware |
#allowed_origins | Return the configured origins (Array) or :any when wildcard |
#allows_origin?(origin) | Return true if the given origin is permitted by the configured policy |
| Option | Default | Description |
|---|---|---|
origins | '*' | Allowed origins (string or array) |
methods | GET POST PUT PATCH DELETE HEAD OPTIONS | Allowed HTTP methods |
headers | Content-Type Accept Authorization | Allowed request headers, or :reflect to echo Access-Control-Request-Headers |
credentials | false | Allow credentials |
max_age | 86400 | Preflight cache duration in seconds |
expose_headers | [] | Array of header names clients can read |
allow_private_network | false | Enable Chrome's Private Network Access preflight header |
bundle install
bundle exec rspec
bundle exec rubocop
If you find this project useful: