Isometric illustration of a frontend panel on one platform and an API server on another, joined by an orange pipe that passes through a dark gate with a green shield badge

Rails CORS configuration is what lets a frontend on another origin, like a Next.js app on localhost:3001 or app.example.com, call your Rails API from the browser. Without it, the browser blocks the response even though Rails returned 200. This guide sets up rack-cors for development and production, adds cookie-based requests and fixes the three errors you’ll actually see.

TL;DR

  • Add rack-cors and configure it in config/initializers/cors.rb with insert_before 0, so CORS headers are added before anything else can respond.
  • List exact origins from an environment variable; never use origins "*" on an API that uses cookies.
  • CORS is enforced by the browser only: it doesn’t protect your API from curl or other servers, so keep authentication and CSRF protection.

When does a Rails app need CORS?

When JavaScript in a browser calls your Rails app from a different origin, meaning a different scheme, host or port. http://localhost:3001 calling http://localhost:3000 is cross-origin; a Rails app rendering its own views with Hotwire is not, and needs no CORS at all.

For “non-simple” requests (JSON bodies, Authorization headers, PUT/PATCH/DELETE), the browser first sends an OPTIONS preflight. Rails must answer it with the right Access-Control-Allow-* headers, or the real request never happens.

Prerequisites

  • A Rails 7.2 or 8.x app (API-only or full stack). The examples were tested on Rails 8.1 with rack-cors 3.0.
  • The URL of each frontend that will call the API.

Step 1: Add rack-cors

# Gemfile
gem "rack-cors"
bundle install

rails new --api already generates a fully commented config/initializers/cors.rb; replace its contents in the next step.

Step 2: Configure the allowed origins

# config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins(*ENV.fetch("CORS_ORIGINS", "http://localhost:3001").split(","))

    resource "/api/*",
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head],
      expose: ["link", "current-page", "total-count"],
      max_age: 7200
  end
end
# production environment variables
CORS_ORIGINS=https://app.example.com,https://admin.example.com

What each option does:

Option Purpose
origins Exact origins (no trailing slash), regexes or a block
resource "/api/*" Paths CORS applies to; keep it narrow
headers: :any Request headers the client may send, e.g. Authorization
expose Response headers JavaScript may read (pagination headers, for example)
max_age Seconds the browser caches the preflight; fewer OPTIONS requests

Need preview deployments on subdomains? Use an anchored regex, because an unanchored one also matches example.com.evil.net:

origins "https://app.example.com", %r{\Ahttps://[a-z0-9-]+\.preview\.example\.com\z}

Pro Tip: insert_before 0 matters. If Devise/Warden or another middleware returns a 401 before Rack::Cors runs, the browser reports it as a CORS error and hides the real status. Check the order with bin/rails middleware.

Do I need an OPTIONS route for preflight requests?

No. Rack::Cors answers preflight OPTIONS requests itself, before they reach the router, so config/routes.rb doesn’t need match "*path", via: :options. If you added one for an older setup, it’s dead code now: with insert_before 0, Rack::Cors responds first and the route never runs.

Step 3: Allow cookies and credentials

If the frontend authenticates with a session cookie instead of a bearer token, the browser must send cookies cross-origin. That needs three changes.

# config/initializers/cors.rb (inside the allow block)
resource "/api/*",
  headers: :any,
  methods: [:get, :post, :put, :patch, :delete, :options, :head],
  credentials: true
# config/initializers/session_store.rb
Rails.application.config.session_store :cookie_store,
  key: "_app_session",
  same_site: :none,
  secure: true
// frontend
fetch("https://api.example.com/api/me", { credentials: "include" })

SameSite=None requires HTTPS, and cookies sent cross-site bring CSRF back into play. If the frontend and API share a parent domain (app.example.com and api.example.com), they’re same-site, so same_site: :lax works and is safer. The InvalidAuthenticityToken guide covers CSRF for API clients, and the Google Auth with Rails API and Next.js guide shows a complete cross-origin login.

Verify it works

Send a preflight the way the browser does:

curl -i -X OPTIONS http://localhost:3000/api/books \
  -H "Origin: http://localhost:3001" \
  -H "Access-Control-Request-Method: GET" \
  -H "Access-Control-Request-Headers: Authorization"

You should get a 200 with headers like these:

access-control-allow-origin: http://localhost:3001
access-control-allow-methods: GET, POST, PUT, PATCH, DELETE, OPTIONS, HEAD
access-control-allow-headers: Authorization
access-control-max-age: 7200

Repeat with -H "Origin: https://evil.com": the response has no access-control-* headers, which is how rack-cors rejects an origin. It also adds Vary: Origin, so caches don’t serve one origin’s response to another.

Troubleshooting

“No ‘Access-Control-Allow-Origin’ header is present on the requested resource”

The origin isn’t on the list, or it doesn’t match exactly: https vs http, a missing port or a trailing slash. If the origin is correct, the response probably came from something before Rack::Cors, such as an auth failure or a proxy error page. Check the status in the Network tab.

“Must not be the wildcard ‘*’ when the request’s credentials mode is ‘include’”

The frontend sends cookies but the server answers with *. List exact origins. rack-cors refuses the combination itself at boot with CorsMisconfigurationError: Allowing credentials for wildcard origins is insecure.

The frontend can’t read pagination headers

The request works but response.headers.get("total-count") returns null. Browsers only expose a few safe headers to JavaScript; add the rest to expose.

Author Perspective

Most “CORS bugs” I’ve been asked to fix weren’t CORS bugs. They were 500s or 401s that happened before the CORS middleware ran, so the browser showed a CORS error instead of the real one. Now I always check the status code in the Network tab first and read the origin list from an environment variable, so adding a preview URL is a config change, not a deploy. And I keep reminding teams that CORS isn’t access control; it’s a browser rule.

FAQ

How do I allow all origins in Rails CORS?

Use origins “*” in the allow block, but only for public, read-only endpoints that don’t use cookies. Browsers reject wildcard responses for requests with credentials, and rack-cors raises an error if you combine them.

Do I need CORS for a Rails app with Hotwire?

No. Turbo and Stimulus requests go to the same origin that served the page, so the browser doesn’t apply CORS. You only need it when another origin, such as a separate SPA or a mobile web view on another domain, calls the app.

Can I configure CORS in Nginx instead of Rails?

Yes, but you then have to handle preflights, Vary and credentials by hand in the proxy config. Keeping it in rack-cors puts the rules next to the routes and tests them with the app.

Sources