1.CORS (Cross-Origin Resource Sharing)
CORS is a browser-enforced relaxation of the same-origin policy — by default a browser blocks a page on one origin from reading a response from a different origin, and CORS is the set of response headers a server can send to explicitly allow specific other origins to read its responses.
Key features
- CORS is enforced by the BROWSER, not the server — curl or a Python script ignores it entirely; only a page running in a browser is restricted
- Access-Control-Allow-Origin on the response is the core header — either a specific origin or "*" (any origin, no credentials allowed)
- "Simple" requests (GET/POST with plain form content types) go straight through; other requests trigger a preflight OPTIONS request first
- A preflight OPTIONS request asks "would you accept this?" before the real request is sent — the server answers with Access-Control-Allow-Methods/-Headers
- Access-Control-Allow-Credentials: true is required (alongside a SPECIFIC origin, never "*") for a cross-origin request to send/receive cookies
Key CORS response headers
- Page JS → Browser: fetch("https://api.example.com/data")
- Browser → Server: GET /data (Origin: https://app.example.com)
- Server → Browser: Access-Control-Allow-Origin: https://app.example.com (origin is on the server's allowlist)
- Browser → Page JS: response readable
- Browser → Page JS: blocked — no matching header (the HTTP request still reached the server either way)
Command
# a minimal, framework-agnostic CORS response for one specific origin
def cors_headers(origin: str) -> dict:
allowed = {'https://app.example.com'}
if origin not in allowed:
return {}
return {
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Methods': 'GET, POST',
'Access-Control-Allow-Credentials': 'true',
}CORS is enforced by the browser, not the server — reflect a specific validated origin (never "*") whenever credentials are involved.