elefcode
← All guides

Web & APIs · 5 min read

CORS Explained

Few errors waste more developer time than a CORS message in the console. The crucial thing to understand is that CORS is not a bug in your code — it is the browser enforcing a security rule, and it can only be resolved on the server.

This guide explains what is happening and how to fix it properly.

Try it yourself with the related tool.

Browse HTTP status codes →

Advertisement

The same-origin policy

By default, a page can only read responses from its own origin — the same scheme, host, and port. Without this rule, any site you visited could quietly make requests to your bank using your cookies and read the results. CORS is the controlled way for a server to opt in to being read by other origins.

How the server opts in

The server sends an Access-Control-Allow-Origin header naming which origins may read the response. If it matches the requesting page, the browser hands the data over; if not, the browser blocks it — even though the request often succeeded and the server did the work.

That is why a request can appear fine in your server logs while the browser still refuses to give you the response.

Preflight requests

For anything beyond a simple GET or POST — a custom header, a JSON content type, or a PUT or DELETE — the browser first sends an OPTIONS request asking permission. The server must answer with the allowed origins, methods, and headers. If your OPTIONS route is missing or unhandled, the real request never happens, which is a very common cause.

Fixing it properly

Configure the CORS headers on the API you control, allowing exactly the origins you intend. During development a proxy is a reasonable workaround. What you should not do is reach for a browser extension that disables CORS or set Access-Control-Allow-Origin: * on an authenticated API — the first only masks the problem on your machine, and the second removes a real protection.

Related guides