Skip to content
Devgo

CORS

Cross-Origin Resource Sharing — a browser security mechanism that controls when a web page can make requests to a different domain. Without CORS headers, browsers block cross-origin API calls. CORS prevents malicious sites from reading data from other sites you're logged into.

When to use
  • Any API called from a browser on a different origin.
  • Cross-origin font/image loading.
When not to
  • Same-origin requests (no CORS needed).
  • Server-to-server (CORS is browser-only).

Definition

CORS is a browser-enforced policy. When on origin A fetches from origin B, the browser checks if B's response includes Access-Control-Allow-Origin headers permitting A. Simple requests go through; complex requests (POST, custom headers) trigger a preflight OPTIONS check.

Why it exists

The same-origin policy prevents scripts from reading responses from other origins, stopping attacks where a malicious page reads your bank's API. CORS lets servers opt-in to allowing specific cross-origin requests safely.

How it works

Browser sends the request with an Origin header. Server responds with Access-Control-Allow-Origin (the allowed origin or *). For non-simple requests, browser sends a preflight OPTIONS; server responds with allowed methods/headers. Without proper headers, the browser blocks the response.

Scaling limits

Preflight adds a round trip. Misconfigured CORS blocks legitimate requests or (worse) opens too widely. Credentials (cookies) require explicit, non-wildcard origins.

Cost shape

Free. The cost is configuration and debugging misconfigured headers.

Alternatives

  • Proxy through your backend — Avoids CORS by same-origin proxying, but adds a hop.
  • JSONP — Legacy hack, insecure — avoid.

Failure modes

  • Allowing * with credentials (browsers reject this).
  • Missing preflight handling.
  • Server not sending headers on error responses.

, ,