What is CORS and how do you configure it in FastAPI?medium
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.
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.