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

Type
conceptual
Topic
cors
Frequency
common
Tags
FastAPI, CORS, middleware, security, HTTP
Answer

CORS is a browser security mechanism that blocks cross-origin requests unless the server explicitly allows them. FastAPI adds CORS headers via CORSMiddleware. In production, whitelist specific origins — never use allow_origins=['*'] together with allow_credentials=True.

Explanation

CORS is enforced by the browser, not the server — API calls from curl or server-to-server code are unaffected. A preflight OPTIONS request is sent by the browser before POST/PUT/DELETE or when custom headers like Authorization are present; the server must respond with the correct Access-Control-Allow-* headers. The combination of allow_origins=['*'] and allow_credentials=True is blocked by browsers. Middleware is added in LIFO order — the last added runs first — so middleware order matters when combining auth, logging, and CORS.

Follow-upYour React frontend at localhost:3000 can't reach your FastAPI at localhost:8000. What is the issue?
Follow-upWhat is a preflight OPTIONS request?
Follow-upWhy can't you use allow_origins=['*'] with allow_credentials=True?