Expand description
Middleware abstraction for request/response processing.
This module provides a flexible middleware system that allows:
- Pre-processing requests before handlers run
- Post-processing responses after handlers complete
- Short-circuiting to return early without calling handlers
- Composable middleware stacks with defined ordering
§Design Philosophy
The middleware system follows these principles:
- Zero-cost when empty: No overhead if no middleware is configured
- Async-native: All hooks are async for I/O operations
- Cancel-aware: Integrates with asupersync’s cancellation
- Composable: Middleware can be stacked and layered
§Ordering Semantics
Middleware executes in a specific order:
beforehooks run in registration order (first registered, first run)- Handler executes
afterhooks run in reverse order (last registered, first run)
This creates an “onion” model where the first middleware wraps everything:
Request → MW1.before → MW2.before → MW3.before → Handler
↓
Response ← MW1.after ← MW2.after ← MW3.after ← Response§Example
ⓘ
use fastapi_core::middleware::{Middleware, ControlFlow};
use fastapi_core::{Request, Response, RequestContext};
struct LoggingMiddleware;
impl Middleware for LoggingMiddleware {
async fn before(&self, ctx: &RequestContext, req: &Request) -> ControlFlow {
println!("Request: {} {}", req.method(), req.path());
ControlFlow::Continue
}
async fn after(&self, _ctx: &RequestContext, _req: &Request, resp: Response) -> Response {
println!("Response: {}", resp.status().as_u16());
resp
}
}Structs§
- AddResponse
Header - Middleware that adds a custom header to all responses.
- Cache
Control Builder - Builder for constructing Cache-Control header values.
- Cache
Control Config - Configuration for the Cache Control middleware.
- Cache
Control Middleware - Middleware for setting HTTP cache control headers.
- Composite
KeyExtractor - A composite key extractor that combines multiple extractors.
- Conditional
Interceptor - Wrapper that applies an interceptor only when a condition is met.
- Conditional
Status - Middleware that sets response status code based on a condition.
- Connected
IpKey Extractor - Rate limit by the actual TCP connection IP address.
- Cors
- CORS middleware.
- Cors
Config - Cross-Origin Resource Sharing (CORS) configuration.
- Csrf
Config - Configuration for CSRF protection middleware.
- Csrf
Middleware - CSRF protection middleware.
- Csrf
Token - CSRF token stored in request extensions.
- Debug
Info Interceptor - Interceptor that adds debug information headers.
- ETag
Config - Configuration for ETag middleware.
- ETag
Middleware - Middleware for ETag generation and conditional request handling.
- Error
Response Transformer - Interceptor that transforms error responses.
- Header
KeyExtractor - Rate limit by a specific header value (e.g.,
X-API-Key). - Header
Transform Interceptor - An interceptor that transforms response headers.
- Https
Redirect Config - Configuration for HTTPS redirect behavior.
- Https
Redirect Middleware - Middleware that redirects HTTP requests to HTTPS and sets HSTS headers.
- InMemory
Rate Limit Store - In-memory rate limit store.
- IpKey
Extractor - Rate limit by client IP address from
X-Forwarded-FororX-Real-IPheaders. - Layer
- A layer that can wrap handlers with middleware.
- Layered
- A handler wrapped with middleware via a Layer.
- Middleware
Stack - A stack of middleware that wraps a handler.
- Noop
Middleware - No-op middleware that does nothing.
- Path
KeyExtractor - Rate limit by request path.
- Path
Prefix Filter - Middleware that limits request processing based on path prefix.
- Rate
Limit Builder - Builder for
RateLimitConfig. - Rate
Limit Config - Configuration for the rate limiting middleware.
- Rate
Limit Middleware - Rate limiting middleware.
- Rate
Limit Result - Result of a rate limit check.
- Remote
Addr - The remote address (peer IP) of the TCP connection.
- Request
Id - A request ID that was extracted or generated for the current request.
- Request
IdConfig - Configuration for request ID middleware.
- Request
IdMiddleware - Middleware that adds unique request IDs to requests and responses.
- Request
Inspection Middleware - Development middleware that logs detailed, human-readable request/response information using arrow-style formatting.
- Request
Response Logger - Middleware that logs requests and responses with configurable redaction.
- Require
Header - Middleware that requires a specific header to be present.
- Response
Body Transform - A response transformer that applies a function to the response body.
- Response
Interceptor Context - Context provided to response interceptors.
- Response
Interceptor Middleware - Adapter that wraps a
ResponseInterceptoras aMiddleware. - Response
Interceptor Stack - A stack of response interceptors that run in order.
- Security
Headers - Middleware that adds security-related HTTP headers to responses.
- Security
Headers Config - Configuration for the Security Headers middleware.
- Server
Timing Builder - Builder for constructing Server-Timing headers with multiple metrics.
- Server
Timing Entry - A single entry in the Server-Timing header.
- Timing
Histogram - A histogram for collecting timing distributions.
- Timing
Histogram Bucket - Simple histogram bucket for collecting timing distributions.
- Timing
Interceptor - Interceptor that adds response timing headers.
- Timing
Metrics - Collected timing metrics for a single request.
- Timing
Metrics Config - Configuration for the timing metrics middleware.
- Timing
Metrics Middleware - Middleware that collects and exposes timing metrics.
- Trace
Rejection Middleware - Middleware that rejects HTTP TRACE requests to prevent Cross-Site Tracing (XST) attacks.
- Trusted
Proxy IpKey Extractor - Rate limit by client IP with trusted proxy validation.
Enums§
- Cache
Directive - Individual Cache-Control directives.
- Cache
Preset - Common cache control presets for typical use cases.
- Control
Flow - Control flow for middleware
beforehooks. - Csrf
Mode - CSRF protection mode.
- ETag
Mode - Configuration for ETag generation strategy.
- Inspection
Verbosity - Verbosity level for the request inspection middleware.
- Origin
Pattern - Origin matching pattern for CORS.
- Rate
Limit Algorithm - Rate limiting algorithm.
- Referrer
Policy - Referrer-Policy header value.
- XFrame
Options - X-Frame-Options header value.
Traits§
- Handler
- A handler that processes requests into responses.
- KeyExtractor
- Extracts a rate limit key from a request.
- Middleware
- The core middleware trait.
- Response
Interceptor - A response interceptor that processes responses after handler execution.
Type Aliases§
- BoxFuture
- A boxed future for async middleware operations.