Middleware Decorator
The simplest way to create middleware is using the@app.middleware("http") decorator:
The middleware function receives the
request and a call_next function that will pass the request to the corresponding path operation, then return the response.How It Works
- The middleware receives the incoming request
- You can perform operations before calling
call_next - Call
await call_next(request)to pass the request to the path operation - The path operation returns a response
- You can modify the response before returning it
- Return the response
Common Use Cases
Logging Requests
Adding Custom Headers
Request Modification
Built-in Middleware
FastAPI includes several pre-built middleware classes:HTTPSRedirectMiddleware
Redirects all HTTP requests to HTTPS:TrustedHostMiddleware
Enforces that all requests have a validHost header:
GZipMiddleware
Compresses responses for clients that support gzip:Advanced: ASGI Middleware
For more complex scenarios, you can create pure ASGI middleware:Middleware Execution Order
Middleware executes in the order it’s added:- FirstMiddleware (in)
- SecondMiddleware (in)
- ThirdMiddleware (in)
- custom_middleware (in)
- Path operation
- custom_middleware (out)
- ThirdMiddleware (out)
- SecondMiddleware (out)
- FirstMiddleware (out)
Best Practices
- Keep middleware focused on cross-cutting concerns (logging, auth, timing)
- Avoid heavy computation in middleware
- Always call
await call_next(request)to ensure the request is processed - Handle exceptions appropriately to prevent breaking the request/response cycle
- Order middleware carefully based on dependencies
Exception Handling in Middleware
See Also
- CORS Middleware - Configure Cross-Origin Resource Sharing
- Behind a Proxy - Running FastAPI behind a reverse proxy
- Events - Application startup and shutdown events