How to configure CORS in FastAPI for frontend integration
CORSMiddleware, allow_origins, allow_methods, allow_headers, allow_credentials, preflight requests, wildcard origins, production vs development config
CORS Configuration in FastAPI
CORS (Cross-Origin Resource Sharing) allows browsers to call your API from a different domain. Without it, requests from your frontend domain will be blocked by the browser.
Adding CORSMiddleware
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://myapp.com", "http://localhost:3000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
The middleware intercepts preflight OPTIONS requests and responds with the correct headers before the actual request is processed.
Configuration rules
In development, add http://localhost:3000 (or your Vite/CRA port). In production, list only exact allowed origins. Never use allow_origins=["*"] with allow_credentials=True — browsers block this combination because it would allow any site to send credentialed requests to your API.
# Development only — do not use in production with credentials
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=False,
allow_methods=["GET", "POST"],
allow_headers=["*"],
)
If your frontend sends cookies or Authorization headers, you need allow_credentials=True and an exact origin list — wildcards are disallowed by the CORS spec in that case.
