CORS
Cross-Origin Resource Sharing (CORS) is the browser rule that lets a page on one origin call an API on another. The server opts in with Access-Control-Allow-* headers. Python frameworks expose this as middleware.
Detailed Explanation
A browser treats https://app.example.com and https://api.example.com as different origins (scheme + host + port). A fetch from the app to the API is cross-origin. The browser sends the request (or a preflight OPTIONS first) and hides the response from JavaScript unless the API's response lists the app's origin in Access-Control-Allow-Origin.
A simple GET with a few headers may go without a preflight. A JSON POST, a custom header, or Authorization triggers OPTIONS. The preflight must succeed (204 or 200 with the right allow headers) or the real request never happens. Middleware must handle OPTIONS and not send it to a view that 405s.
Access-Control-Allow-Origin: * cannot be used with Access-Control-Allow-Credentials: true. If you send cookies, echo the specific origin and be explicit about Allow-Credentials. Wildcarding credentials is a browser-blocked combination, not a shortcut.
Flask-CORS, FastAPI's CORSMiddleware, and Django's django-cors-headers set these headers. Configure an allowlist of origins, not * on an authenticated API. Allow the methods and headers you actually use. Max-Age caches the preflight.
CORS is a browser policy. curl and server-to-server calls ignore it. It is not authentication. An allowed origin can still be a malicious site if you also allow cookies and have a CSRF gap. For cookie sessions, CSRF tokens remain required. For bearer tokens in Authorization, do not also enable credentials unless you know why.
Debug with the browser console. "blocked by CORS" is a missing or wrong response header, often only on the preflight.
Code Examples
# Starlette / FastAPI
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.example.com"],
allow_methods=["GET", "POST"],
allow_headers=["Authorization", "Content-Type"],
allow_credentials=False,
)# Manual header on a tiny WSGI app
def app(environ, start_response):
headers = [
("Content-Type", "application/json"),
("Access-Control-Allow-Origin", "https://app.example.com"),
]
start_response("200 OK", headers)
return [b'{"ok":true}']Common Gotchas
Views that do not handle OPTIONS
preflight gets 405 and the console says CORS. Add middleware.
Postman will succeed when Chrome fails
CORS is not a server-only check.