philiprehberger-cors

Tests Gem Version Last updated

CORS middleware with origin validation and preflight handling

Requirements

  • Ruby >= 3.1

Installation

Add to your Gemfile:

gem "philiprehberger-cors"

Or install directly:

gem install philiprehberger-cors

Usage

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

Wildcard Origins

use Philiprehberger::Cors::Middleware, origins: '*'

Multiple Origins

use Philiprehberger::Cors::Middleware,
  origins: ['https://app.example.com', 'https://admin.example.com']

Regex Origins

use Philiprehberger::Cors::Middleware,
  origins: [/\.example\.com$/, "http://localhost:3000"]

Expose Headers

use Philiprehberger::Cors::Middleware,
  origins: "*",
  expose_headers: ["X-Request-Id", "X-Total-Count"]

Reflect Request Headers

Echo whatever the client sent in Access-Control-Request-Headers:

use Philiprehberger::Cors::Middleware,
  origins: ['https://app.example.com'],
  headers: :reflect

Private Network Access

Opt into Chrome's Private Network Access preflight extension:

use Philiprehberger::Cors::Middleware,
  origins: ['https://app.example.com'],
  allow_private_network: true

With Credentials

use Philiprehberger::Cors::Middleware,
  origins: ['https://app.example.com'],
  credentials: true

Inspecting Configured Origins

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

API

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

Options

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

Development

bundle install
bundle exec rspec
bundle exec rubocop

Support

If you find this project useful:

Star the repo

🐛 Report issues

💡 Suggest features

❤️ Sponsor development

🌐 All Open Source Projects

💻 GitHub Profile

🔗 LinkedIn Profile

License

MIT