Difficulty: Intermediate
What is middleware in FastAPI, how do you add it, and what are typical use cases?
Middleware is code that wraps every request and response passing through the app: it runs before the request reaches any route and after the response is produced. In FastAPI you add it with @app.middleware("http") for a quick function, or app.add_middleware(SomeMiddleware, **options) for a class such as CORSMiddleware, GZipMiddleware or TrustedHostMiddleware.
Middleware forms layers around the app, like an onion:
await call_next(request)).Order matters. With app.add_middleware, the last one added is the outermost and runs first on the way in. If you add a logging middleware after CORS, logging sees requests before CORS does. Starlette also wraps everything in ServerErrorMiddleware (outermost) and ExceptionMiddleware (innermost).
X-Request-ID, log method, path, status and duration.GZipMiddleware(minimum_size=1000).TrustedHostMiddleware, HTTPSRedirectMiddleware.SessionMiddleware for signed cookie sessions.| Aspect | Middleware | Dependency |
|---|---|---|
| Runs for | Every request, including 404s | Only routes that declare it |
| Sees response | Yes | Only indirectly |
| Access to parsed params | No, raw request only | Yes, typed values |
| Shows in OpenAPI | No | Yes |
| Good for | Cross-cutting HTTP concerns | Auth, DB sessions, per-route logic |
Authentication usually belongs in a dependency, so routes declare it explicitly and docs show the security scheme.
@app.middleware("http") uses Starlette's BaseHTTPMiddleware. It is convenient but adds overhead and historically had issues with streaming responses and context variables. For hot paths, write a pure ASGI middleware (a class with async def __call__(self, scope, receive, send)).await request.body() in middleware consumes the stream; be careful if handlers also need it.Access-Control-Allow-Origin: * together with credentials, so list explicit origins when allow_credentials=True.import time
import uuid
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://app.example.in", "http://localhost:5173"],
allow_credentials=True, # so explicit origins, never "*"
allow_methods=["GET", "POST", "PATCH", "DELETE"],
allow_headers=["Authorization", "Content-Type"],
)
app.add_middleware(GZipMiddleware, minimum_size=1000)
@app.middleware("http") # added last, so it is the outermost
async def request_context(request: Request, call_next):
request_id = request.headers.get("X-Request-ID", str(uuid.uuid4()))
start = time.perf_counter()
response = await call_next(request) # everything inside runs here
elapsed_ms = (time.perf_counter() - start) * 1000
response.headers["X-Request-ID"] = request_id
response.headers["X-Process-Time-ms"] = f"{elapsed_ms:.1f}"
return response
The decorator-based middleware wraps CORS and GZip because it was registered last. perf_counter is the right clock for measuring durations.
class SecurityHeadersMiddleware:
def __init__(self, app):
self.app = app
async def __call__(self, scope, receive, send):
if scope["type"] != "http":
return await self.app(scope, receive, send)
async def send_with_headers(message):
if message["type"] == "http.response.start":
headers = message.setdefault("headers", [])
headers.append((b"x-content-type-options", b"nosniff"))
await send(message)
await self.app(scope, receive, send_with_headers)
# app.add_middleware(SecurityHeadersMiddleware)
Pure ASGI middleware avoids BaseHTTPMiddleware overhead and works correctly with streaming responses.
middleware, CORSMiddleware, middleware order, BaseHTTPMiddleware, pure ASGI middleware