CORS (Cross-Origin Resource Sharing)
An HTTP-header security mechanism that lets a server explicitly declare which external origins (scheme, host, port) a browser may allow to read its API responses
Table of Contents
Structure Diagram
What is CORS (Cross-Origin Resource Sharing)?
An HTTP-header security mechanism that lets a server explicitly declare which external origins (scheme, host, port) a browser may allow to read its API responses. It is a core concept in APIs & Networking within Web Dev.
Core Principles
Browsers enforce the Same-Origin Policy (SOP) so a malicious site cannot silently read sensitive responses from another origin (defined by scheme + host + port).
CORS (Cross-Origin Resource Sharing) is the standard mechanism for servers to relax SOP safely. By returning headers such as Access-Control-Allow-Origin, the server tells the browser which external origins may read the response. For non-simple requests (e.g., JSON bodies or Authorization headers), the browser sends an OPTIONS preflight request first to verify permissions.
Practical Takeaways
- Wildcard
*fails with credentials: When sending cookies (credentials: 'include'),Access-Control-Allow-Origin: *is rejected by browsers. ReturnAccess-Control-Allow-Credentials: truepaired with the exact whitelisted origin (never blindly reflect any arbitraryOriginheader). - Cache preflight responses: Set
Access-Control-Max-Age(e.g.,86400) so browsers don't waste an extraOPTIONSround-trip before every API call. - CORS is browser-enforced, not an API firewall:
curl, bots, and server-to-server callers ignore CORS completely—always enforce authentication and authorization on the server.
Notable Examples
- Decoupled frontend & API domains: Allowing
https://app.example.comto callhttps://api.example.comsecurely. - Direct browser-to-S3 uploads: Configuring bucket CORS rules so web clients can upload files via presigned
PUTURLs.