Built-in middleware
FastrAPI includes four production-ready middleware implementations powered by Rust for optimal performance:CORS
Cross-Origin Resource Sharing configuration
GZip
Response compression
Sessions
Cookie-based session management
TrustedHost
Host header validation
Adding middleware
Use theadd_middleware() method to add middleware to your application. Middleware is executed in the order it’s added.
Middleware is processed in the order it’s added. The first middleware added wraps all subsequent middleware and routes.
CORS middleware
Configure Cross-Origin Resource Sharing (CORS) to control which domains can access your API.CORS configuration options
List of origins that are allowed to make cross-origin requests. Use
["*"] to allow all origins.HTTP methods that are allowed for cross-origin requests. Use
["*"] to allow all methods.HTTP headers that are allowed in cross-origin requests. Use
["*"] to allow all headers.Whether to allow cookies and authentication headers in cross-origin requests.
Headers that are exposed to the browser in the response.
Maximum number of seconds the browser can cache the CORS preflight response.
GZip middleware
Compress responses with GZip to reduce bandwidth usage and improve load times.GZip configuration options
Minimum response size in bytes to trigger compression. Responses smaller than this won’t be compressed.
Compression level from 1 (fastest) to 9 (best compression). Higher levels use more CPU but produce smaller responses.
Session middleware
Manage user sessions with secure, signed cookies.Session configuration options
Secret key used to sign session cookies. Must be long and random. Never commit this to version control.
Name of the session cookie.
Session lifetime in seconds. Default is 14 days (1209600 seconds).
Cookie path. Use
/ to make the session available across your entire application.SameSite cookie attribute. Options:
'strict', 'lax', or 'none'.Whether to only send cookies over HTTPS. Set to
true in production.Cookie domain. Set this to share sessions across subdomains.
TrustedHost middleware
Validate theHost header to prevent host header injection attacks.
TrustedHost configuration options
List of allowed host values. Use
["*"] to allow all hosts (not recommended in production).Whether to redirect
example.com to www.example.com.Combining multiple middleware
You can stack multiple middleware layers. They’re executed in the order added:Middleware execution order:
- TrustedHost validates the host header
- CORS handles preflight and adds headers
- Your route handler executes
- GZip compresses the response
- Session sets/reads cookies
Custom middleware
You can create custom middleware using Python functions:Performance
All built-in middleware is implemented in Rust and integrated with Axum’s Tower middleware system, providing:- Zero-copy operations where possible
- Minimal allocations
- Native async/await support
- Efficient header manipulation
Best practices
Order matters
Order matters
Add middleware in order of importance. Security middleware (TrustedHost) should come first, followed by CORS, then compression and sessions.
Use environment variables for secrets
Use environment variables for secrets
Never hardcode secret keys. Use environment variables:
Enable HTTPS in production
Enable HTTPS in production
Always set
https_only=True for SessionMiddleware in production environments.Tune compression settings
Tune compression settings
Balance compression level with CPU usage. Level 6 is often a good compromise:
Related resources
Request handling
Understand request processing
Background tasks
Execute tasks asynchronously
API reference
Middleware API documentation
Error handling
Handle middleware errors