CORS & Custom Middleware in Python
From the FastAPI cheat sheet ยท Middleware & CORS ยท verified Jul 2026
CORS & Custom Middleware
Configure CORS and write custom middleware for logging, timing, etc.
python
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"],
allow_methods=["*"],
allow_headers=["*"],
allow_credentials=True,
)๐ก Middleware runs on every request/response โ use for logging, timing, auth checks
โก Set allow_origins to specific domains in production โ never use ["*"] with credentials
๐ Middleware order matters โ they execute in reverse order of how they're added
๐ข Built-in middleware: CORSMiddleware, TrustedHostMiddleware, HTTPSRedirectMiddleware
corsmiddleware