skip to content

In a Rails API app, how do you configure rack-cors in config/initializers/cors.rb for a single-page app served from another origin?

level: middleimportance: must knowfreq 55%

answer

  1. uncomment the gem and the block
  2. insert_before 0, Rack::Cors
  3. origins with scheme, no trailing slash
  4. methods: defaults to GET only
  5. credentials: true rejects origins "*"

basics

~20 s

Uncomment gem "rack-cors" and the block in config/initializers/cors.rb, then insert Rack::Cors at position 0 with an allow block naming the SPA's exact origin and a resource listing the paths, methods and request headers it may use.

solid answer

~40 s

An `--api` app ships `# gem "rack-cors"` and a fully commented `config/initializers/cors.rb`. You uncomment both and write `Rails.application.config.middleware.insert_before 0, Rack::Cors do ... end` with an `allow` block: `origins "https://app.tracker.example"` (scheme included, no trailing slash), then `resource "/api/*", headers: :any, methods: [:get, :post, :patch, :delete, :options]`. Defaults bite: leave out `methods:` and only GET is allowed; leave out `headers:` and a preflight asking for `Authorization` is refused. `insert_before 0` puts Rack::Cors first, so it answers preflight OPTIONS requests itself and adds headers before any other middleware can respond. Add `credentials: true` only for cookie auth; with `origins "*"` that raises `Rack::Cors::Resource::CorsMisconfigurationError` at boot. A native mobile client ignores CORS entirely.

code

ruby · 12 lines
ruby
# config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins "https://app.tracker.example", /\Ahttp:\/\/localhost:\d+\z/

    resource "/api/*",
      headers: ["authorization", "content-type"],
      methods: [:get, :post, :patch, :delete, :options, :head],
      expose: ["Link"],
      max_age: 600
  end
end

go deeper

for a junior

Know where the config lives, that the gem ships commented out, and that only browsers enforce CORS.

for a middle

Explain insert_before 0, the methods and headers defaults, exact origin matching and why credentials refuses a wildcard.

for a senior

Keep origins in configuration per environment, debug preflights with curl and debug: true, and place Rack::Cors ahead of anything that answers early.

for a principal

Decide whether the SPA should be same-origin behind one host, removing CORS altogether, or cross-origin with a tightly scoped allow-list.

## Who needs CORS here Browsers enforce the **same-origin policy**: script on `https://app.tracker.example` may not read a response from `https://api.tracker.example` unless the API says so in `Access-Control-Allow-*` response headers. For requests that are not simple (a JSON body, an `Authorization` header, PATCH or DELETE), the browser first sends a **preflight** `OPTIONS` request and only proceeds if the answer allows it. The protocol itself is covered elsewhere; this answer is about producing those headers in Rails. A native mobile app does not enforce CORS, so the fitness app's iOS and Android clients need nothing from this file. The single-page app does. ## Turning it on An app generated with `rails new --api` already contains the pieces, commented out: 1. In the `Gemfile`, uncomment `gem "rack-cors"` and run `bundle install`. 2. In `config/initializers/cors.rb`, uncomment the block and replace the example origin. 3. Restart the server; initializers are read only at boot. ```ruby Rails.application.config.middleware.insert_before 0, Rack::Cors do allow do origins ENV.fetch("SPA_ORIGIN", "http://localhost:5173") resource "/api/*", headers: :any, methods: [:get, :post, :patch, :delete, :options, :head], expose: ["Link"], max_age: 600 end end ``` ## Why insert_before 0 `insert_before 0` places **`Rack::Cors`** at the very top of the middleware stack. That matters because: - When an `OPTIONS` request carries an `Origin` and `Access-Control-Request-Method`, Rack::Cors answers it **itself** with status 200 and returns. The preflight never reaches the router, the controller or any `before_action` that would demand a token. - For actual requests, it calls the rest of the app and merges its headers onto whatever response comes back, including error pages produced further down the stack. - Middleware that can answer early, such as a cache or an authentication layer, would otherwise send responses without CORS headers. `config.middleware.use` would append it after everything else, which is the wrong end of the stack for this job. ## The options and their defaults | Option | Default in rack-cors 3.0 | Notes | |---|---|---| | `origins` | none | string, regex or block; `"*"` allows any origin | | `methods:` | `[:get]` | `:any` means GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS | | `headers:` | nil | only `accept`, `accept-language`, `content-language` and `content-type` pass; use `:any` or list `authorization` | | `expose:` | nil | response headers script may read, such as `Link` for pagination | | `credentials:` | `false` | sends `Access-Control-Allow-Credentials: true` | | `max_age:` | `7200` | seconds the browser may cache the preflight | | `if:` | nil | a proc on `env` that must return true for the rule to apply | Rack::Cors also appends `Origin` to the `Vary` header for matching paths, so shared caches keep per-origin copies. ## Origin matching traps - A string **with** a scheme, such as `"https://app.tracker.example"`, must equal the `Origin` header exactly. A trailing slash never matches, because browsers send origins without one. - A string **without** a scheme, such as `"app.tracker.example"`, is compiled to a regex that accepts any scheme for that host. - A regex must be anchored with `\A` and `\z`; an unanchored `/tracker\.example/` also matches `tracker.example.attacker.test`. - `origins "*"` together with `credentials: true` raises **`Rack::Cors::Resource::CorsMisconfigurationError`** when the middleware stack is built, so the mistake fails at boot rather than in production traffic. ## Debugging in Rails Run `bin/rails middleware` to confirm `Rack::Cors` is first. Pass `debug: true` to `Rack::Cors` (as `insert_before 0, Rack::Cors, debug: true`) to log each decision and add an `X-Rack-CORS` header explaining hits and misses. A preflight that matches no rule still gets a 200, just with no `Access-Control-Allow-*` headers, so the browser blocks the call while the server logs look healthy. When testing with curl, send an `Origin` header; without one Rack::Cors adds no `Access-Control-*` headers at all. ## Several rules in one file A `Rack::Cors` block may hold several `allow` blocks, each with its own `origins` and `resource` lines. For each request Rack::Cors walks the blocks in order, skips those whose origins do not match, and uses the **first** resource whose path matches. That lets you write a narrow rule for the SPA and a broad public one: - `allow { origins "https://app.tracker.example"; resource "/api/*", headers: :any, methods: :any }` - `allow { origins "*"; resource "/public/*", methods: :get }` Order the specific blocks first, because a broad block listed earlier would win for every origin and path it matches.

  • What changes in cors.rb when the SPA authenticates with the session cookie instead of a token?
    Add `credentials: true` to the resource and list explicit origins, because `origins "*"` with credentials raises `Rack::Cors::Resource::CorsMisconfigurationError`. Rack::Cors then echoes the matching origin and sends `Access-Control-Allow-Credentials: true`. The session middleware must also be back in the api_only stack, and the cookie needs cross-site attributes.
  • A teammate put Rack::Cors after a token-checking middleware and preflights now fail; why?
    The token check runs first and rejects the `OPTIONS` preflight, which carries no credentials, before Rack::Cors can answer it. Even when it passes, its early responses carry no CORS headers. Moving Rack::Cors to `insert_before 0` lets it answer preflights and decorate every response before anything else runs.
  • How do you allow several environments' origins without editing code?
    Read them from configuration, for example `origins(*ENV.fetch("CORS_ORIGINS").split(","))`, or pass a block `origins { |source, env| ALLOWED.include?(source) }`. Keep each entry an exact scheme-and-host string or an anchored regex, never a substring match.

Rack::Cors is the reception desk in the lobby: it checks a visitor's origin against the guest list and answers "may I come up?" questions itself, so those questions never reach the offices upstairs.

  • Leaving out methods: lets every HTTP method through.
  • origins "https://app.tracker.example/" matches the SPA's requests.
  • config.middleware.use Rack::Cors is just as good as insert_before 0.
  • The mobile app needs CORS headers before it can call the API.
  • origins "*" with credentials: true makes Rack::Cors echo the origin instead.
  • Preflight OPTIONS requests reach the controller's before_action first.