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
Back to the full FastAPI cheat sheet