Home/Glossary/CORS (Cross-Origin Resource Sharing)

CORS (Cross-Origin Resource Sharing)

A browser security mechanism that controls how web pages can request resources from different domains, preventing unauthorized cross-site data access.

Web SecurityAlso called: "cross-origin resource sharing", "cors policy", "same-origin policy"

CORS is a security feature implemented by browsers that restricts web pages from making requests to a different domain than the one serving the page, unless explicitly allowed.

Why it matters

  • Prevents malicious websites from reading sensitive data from other sites you're logged into.
  • Misconfigured CORS can expose your API to unauthorized access.
  • Common source of developer frustration when integrating APIs.
  • Critical for Single Page Applications (SPAs) that call backend APIs.

How CORS works

  1. Browser sends a request with an Origin header.
  2. Server responds with Access-Control-Allow-Origin header.
  3. Browser checks if the origin is allowed.
  4. If allowed, browser permits the response; if not, it blocks it.

Key CORS headers

  • Access-Control-Allow-Origin: Specifies allowed origins (or * for any).
  • Access-Control-Allow-Methods: HTTP methods allowed (GET, POST, etc.).
  • Access-Control-Allow-Headers: Custom headers the client can send.
  • Access-Control-Allow-Credentials: Whether cookies/auth can be sent.
  • Access-Control-Max-Age: How long preflight results can be cached.

Preflight requests For "non-simple" requests (methods other than GET/POST, custom headers), browsers first send an OPTIONS request to check if the actual request is allowed.

Common misconfigurations

  • Using Access-Control-Allow-Origin: * with credentials (not allowed).
  • Reflecting the Origin header without validation (security vulnerability).
  • Allowing all origins in production (defeats the purpose).
  • Not handling preflight OPTIONS requests.

Secure configuration

  • Whitelist specific trusted origins.
  • Never use wildcard with credentials.
  • Validate origins against an allowlist server-side.
  • Set appropriate Access-Control-Max-Age to reduce preflight requests.