Cross-Origin Resource Sharing (CORS) is a mechanism that allows a server to indicate which origins are permitted to load its resources. Browsers enforce the same-origin policy by default and use CORS headers to relax it.

See also: HTTP — CORS, REST

Key Points

  • When allowing credentials, you must specify the exact origin, headers, and methods — wildcards (*) are disallowed for Access-Control-Allow-Origin, Access-Control-Allow-Headers, and Access-Control-Allow-Methods
  • Respond to preflight requests with 204 No Content
  • Preflight (OPTIONS) is triggered by non-simple requests (e.g. custom headers, PUT/DELETE methods, application/json content type)
  • Access-Control-Allow-Origin — which origins may access the resource
  • Access-Control-Allow-Methods — permitted HTTP methods (disallows * when credentials are enabled)
  • Access-Control-Allow-Headers — permitted request headers
  • Access-Control-Allow-Credentials: true — allows cookies, Authorization headers, or TLS client certificates on cross-origin requests
  • Access-Control-Expose-Headers — response headers that browser JavaScript is permitted to read beyond CORS-safelisted defaults
  • Access-Control-Max-Age — how long preflight results can be cached
  • Vary: Origin — always set when dynamically reflecting the request’s Origin header, preventing CDNs and proxy caches from serving a cached response to the wrong origin (cache poisoning)