← Back to FastAPI, page 2

fastapi-0024 · Medium mid

What is CORS, and how do you configure it correctly in FastAPI?

CORS (Cross-Origin Resource Sharing) is how a server tells browsers that JavaScript from another origin may read its responses. Without it, the browser's same-origin policy blocks those reads. In FastAPI, add CORSMiddleware with an explicit allow_origins list, the methods and headers you need, and allow_credentials=True only when cookies or auth headers must be sent; wildcard origins cannot be combined with credentials.

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-Origin on the response.
  • Other requests (PUT, DELETE, JSON Content-Type, Authorization header) trigger a preflight OPTIONS request first. The server answers with allowed methods and headers, and the browser then sends the real request.

FastAPI setup:

python
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_regex for patterns like preview deployments.
  • allow_credentials=True: lets the browser send cookies or HTTP auth. The spec forbids Access-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.

python
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