Understanding CORS: Data Security & The Preflight Headache
Cross-Origin Resource Sharing (CORS) is the #1 cause of 'Network Error' messages for modern developers. Learn exactly how it works and how to fix it securely.
What is CORS?
CORS stands for Cross-Origin Resource Sharing. It is a security mechanism implemented by browsers that allows or restricts requested resources on a web page to be requested from another domain outside the domain from which the first resource was served.
Legacy browsers strictly followed the Same-Origin Policy (SOP), which barred a script on domain-a.com from ever touching an API on domain-b.com. CORS provides a safe way to 'poke holes' in that policy for legitimate cross-domain communication.
The Core Headers
CORS is controlled primarily through HTTP response headers sent by the server. Here are the heavy hitters:
Access-Control-Allow-Origin: The most critical header. It specifies which origins are allowed to access the resource.Access-Control-Allow-Methods: A comma-separated list of allowed HTTP methods (GET, POST, etc.).Access-Control-Allow-Headers: Specifies which custom headers can be sent in the actual request.
Why use '*' is dangerous
Setting Access-Control-Allow-Origin: * allowed anyone to call your API. While useful for public data, it should never be used for authenticated endpoints as it allows malicious sites to attempt credential-based attacks via CSRF.
The Preflight Request (OPTIONS)
Ever noticed a mysterious OPTIONS request in your Network tab before your actual POST request? That is a Preflight Request.
The browser sends this request automatically to verify that the server understands and permits the 'risky' request you are about to make. A request is preflighted if:
- It uses a method other than GET, HEAD, or POST.
- It uses custom headers (like
AuthorizationorX-API-Key). - The Content-Type is not one of:
application/x-www-form-urlencoded,multipart/form-data, ortext/plain.
Common Fixes for Developers
If you are seeing 'Access to fetch at ... has been blocked by CORS policy', here is your checklist:
- Check the Protocol: Origins are sensitive.
http://localhostandhttps://localhostare different origins. - Server-Side Middleware: Use standard libraries like
corsfor Express orCORSMiddlewarefor FastAPI rather than manual header injection. - Trailing Slashes: Ensure your allowed origin in the server config perfectly matches the URL in the browser (down to the trailing slash).
Summary
CORS is not a bug; it is a shield. By understanding the handshake between the browser and the server, you can build secure, cross-domain applications without pulling your hair out.