Full answer
An origin is scheme + host + port: https://app.college.edu and https://api.college.edu are different origins. Browsers apply the same-origin policy: a page's JavaScript can send requests to another origin, but cannot read the response unless that server allows it through CORS headers.
CORS does not protect your API from other servers, scripts or curl. It only controls what browsers let web pages read. Authentication still has to protect data.
How it works:
- Simple requests (GET or POST with simple headers) are sent directly; the browser checks
Access-Control-Allow-Originon the response. - Other requests (PUT, DELETE, JSON
Content-Type,Authorizationheader) trigger a preflightOPTIONSrequest first. The server answers with allowed methods and headers, and the browser then sends the real request.
FastAPI setup:
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.college.edu", "http://localhost:5173"],
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["Authorization", "Content-Type"],
allow_credentials=True,
expose_headers=["X-Total-Count"],
max_age=600,
)Settings explained:
allow_origins: exact origins.allow_origin_regexfor patterns like preview deployments.allow_credentials=True: lets the browser send cookies or HTTP auth. The spec forbidsAccess-Control-Allow-Origin: *with credentials, so use explicit origins.expose_headers: response headers JavaScript may read beyond the basic set.max_age: how long browsers cache preflight results, reducing OPTIONS traffic.
Add CORSMiddleware so it wraps everything (adding it last makes it outermost); otherwise error responses produced by inner layers may lack CORS headers, and the browser reports a CORS error that hides the real error.
from fastapi import FastAPI, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.testclient import TestClient
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.college.edu", "http://localhost:5173"],
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["Authorization", "Content-Type"],
allow_credentials=True,
expose_headers=["X-Total-Count"],
max_age=600,
)
@app.get("/notices")
def notices(response: Response):
response.headers["X-Total-Count"] = "2"
return ["Exam on Monday", "Library closed Sunday"]
c = TestClient(app)
pre = c.options("/notices", headers={"Origin": "https://app.college.edu",
"Access-Control-Request-Method": "PUT",
"Access-Control-Request-Headers": "authorization"})
print("preflight:", pre.status_code, pre.headers["access-control-allow-origin"],
pre.headers["access-control-allow-methods"], pre.headers["access-control-max-age"])
r = c.get("/notices", headers={"Origin": "https://app.college.edu"})
print("allowed origin:", r.headers.get("access-control-allow-origin"),
r.headers.get("access-control-allow-credentials"), r.headers.get("access-control-expose-headers"))
r = c.get("/notices", headers={"Origin": "https://evil.example"})
print("other origin header present:", "access-control-allow-origin" in r.headers, "| status:", r.status_code)
Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. The request from the unknown origin still returns 200; the browser, not the server, blocks the page from reading it. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): preflight: 200 https://app.college.edu GET, POST, PUT, DELETE 600 allowed origin: https://app.college.edu true X-Total-Count other origin header present: False | status: 200
Key points
- CORS lets browsers read cross-origin responses
- It is not an access control for non-browser clients
- Preflight OPTIONS for non-simple requests
- No wildcard origin with credentials
- expose_headers and max_age are often forgotten
Common mistakes
- Thinking CORS protects the API from non-browser clients
- Using allow_origins=['*'] together with allow_credentials=True
- Forgetting expose_headers, so the front end cannot read custom headers
- Misdiagnosing a server error as a CORS error because the error response lacks CORS headers
Follow-ups
- Why does a JSON POST trigger a preflight request?
- How would you allow all preview deployments like pr-123.app.college.edu?
- Why is CORS not a security boundary for your API?
Tips
- Define origin precisely
- Explain preflight and the credentials rule
- Say clearly what CORS does not protect