CORS Explained: Why It's a Browser Problem (and How to Fix It on the Server)
CORS (Cross-Origin Resource Sharing) is responsible for more confused developer Stack Overflow questions than almost any other browser feature. The error messages are cryptic, the behavior is counterintuitive, and the fix is almost always on the server — not the browser. This guide covers how CORS actually works, why you're seeing these errors, and how to configure it correctly. What Is a…
CORS (Cross-Origin Resource Sharing) is a common source of confusion for developers, with cryptic error messages and counterintuitive behavior. The issue typically lies on the server side, not the browser. This guide explains how CORS works, why errors occur, and how to configure it correctly.
A cross-origin request occurs when two URLs share different origins due to differences in protocol, host, port, or subdomain. When JavaScript in a browser makes a fetch/XHR request to a different origin, the browser enforces CORS rules, even if the request succeeds on the server.
There are two types of CORS requests: simple and preflighted. Simple requests are straightforward, using GET, POST, or HEAD methods and specific content types. The browser sends the request and checks the Access-Control-Allow-Origin header in the response. If the header matches or is wildcard (*), the browser allows JavaScript to read the response.
Preflighted requests, on the other hand, involve more complex methods like PUT or DELETE, custom headers, or JSON content types. The browser first sends an OPTIONS preflight request to determine if the actual request is safe to send. The server must respond to the preflight before proceeding with the actual request. If the preflight response is missing or incorrect, the actual request won't fire.
Common CORS error messages include the absence of the Access-Control-Allow-Origin header, using wildcard (*) when credentials mode is "include," the DELETE method not being allowed by Access-Control-Allow-Methods, and the Authorization header being disallowed by Access-Control-Allow-Headers.
To fix CORS issues, server-side configuration is required. In Express (Node.js), the cors middleware can be used to add the necessary headers. Specify allowed origins, methods, headers, and credentials mode as needed. In Nginx, add the appropriate headers for origin, credentials, methods, and headers, and handle OPTIONS requests appropriately.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.