CORS errors are among the most confusing messages in web development, mostly because people misunderstand what the mechanism is for.
The same-origin policy
An origin is the scheme, host and port together. By default a page from https://app.example can send requests to another origin, but the browser will not let its JavaScript read the response unless that other origin agrees. This stops a random site from reading your data from services where you are logged in.
What CORS is
Cross-Origin Resource Sharing is the way a server opts in to being read from other origins, using response headers.
Access-Control-Allow-Origin: https://app.example
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 600Simple requests and preflight
Simple requests, such as a basic GET or a form-style POST, are sent directly and the browser checks the response headers afterwards. Anything else, for example JSON with a custom header or a PUT, triggers a preflight: the browser first sends an OPTIONS request asking whether the real request is allowed. Your server must answer it with the headers above.
Credentials
If the request includes cookies or HTTP authentication, the server must send Access-Control-Allow-Credentials: true and name one exact origin. The wildcard * is not allowed together with credentials.
Common mistakes
- Reflecting the Origin header back for every request, which in effect allows every site to read credentialed responses. Check against an explicit allow-list.
- **Using
*for private data.** A wildcard is fine only for public content that anyone may read. - Treating CORS as access control. It restricts browsers only. A script, curl or another server ignores it, so you still need authentication and authorisation.
- Forgetting the preflight route, so the real request is never sent.
ALLOWED = ["https://app.example"].freeze
def cors_origin(request_origin)
ALLOWED.include?(request_origin) ? request_origin : nil
end
puts cors_origin("https://app.example").inspect
puts cors_origin("https://evil.example").inspectTakeaway
CORS relaxes the browser's same-origin protection for chosen origins. Keep an explicit allow-list, handle preflight, and never confuse it with authentication.
Comments