Skip to main content

Module middleware

Module middleware 

Source
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:

  1. before hooks run in registration order (first registered, first run)
  2. Handler executes
  3. after hooks 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§

AddResponseHeader
Middleware that adds a custom header to all responses.
CacheControlBuilder
Builder for constructing Cache-Control header values.
CacheControlConfig
Configuration for the Cache Control middleware.
CacheControlMiddleware
Middleware for setting HTTP cache control headers.
CompositeKeyExtractor
A composite key extractor that combines multiple extractors.
ConditionalInterceptor
Wrapper that applies an interceptor only when a condition is met.
ConditionalStatus
Middleware that sets response status code based on a condition.
ConnectedIpKeyExtractor
Rate limit by the actual TCP connection IP address.
Cors
CORS middleware.
CorsConfig
Cross-Origin Resource Sharing (CORS) configuration.
CsrfConfig
Configuration for CSRF protection middleware.
CsrfMiddleware
CSRF protection middleware.
CsrfToken
CSRF token stored in request extensions.
DebugInfoInterceptor
Interceptor that adds debug information headers.
ETagConfig
Configuration for ETag middleware.
ETagMiddleware
Middleware for ETag generation and conditional request handling.
ErrorResponseTransformer
Interceptor that transforms error responses.
HeaderKeyExtractor
Rate limit by a specific header value (e.g., X-API-Key).
HeaderTransformInterceptor
An interceptor that transforms response headers.
HttpsRedirectConfig
Configuration for HTTPS redirect behavior.
HttpsRedirectMiddleware
Middleware that redirects HTTP requests to HTTPS and sets HSTS headers.
InMemoryRateLimitStore
In-memory rate limit store.
IpKeyExtractor
Rate limit by client IP address from X-Forwarded-For or X-Real-IP headers.
Layer
A layer that can wrap handlers with middleware.
Layered
A handler wrapped with middleware via a Layer.
MiddlewareStack
A stack of middleware that wraps a handler.
NoopMiddleware
No-op middleware that does nothing.
PathKeyExtractor
Rate limit by request path.
PathPrefixFilter
Middleware that limits request processing based on path prefix.
RateLimitBuilder
Builder for RateLimitConfig.
RateLimitConfig
Configuration for the rate limiting middleware.
RateLimitMiddleware
Rate limiting middleware.
RateLimitResult
Result of a rate limit check.
RemoteAddr
The remote address (peer IP) of the TCP connection.
RequestId
A request ID that was extracted or generated for the current request.
RequestIdConfig
Configuration for request ID middleware.
RequestIdMiddleware
Middleware that adds unique request IDs to requests and responses.
RequestInspectionMiddleware
Development middleware that logs detailed, human-readable request/response information using arrow-style formatting.
RequestResponseLogger
Middleware that logs requests and responses with configurable redaction.
RequireHeader
Middleware that requires a specific header to be present.
ResponseBodyTransform
A response transformer that applies a function to the response body.
ResponseInterceptorContext
Context provided to response interceptors.
ResponseInterceptorMiddleware
Adapter that wraps a ResponseInterceptor as a Middleware.
ResponseInterceptorStack
A stack of response interceptors that run in order.
SecurityHeaders
Middleware that adds security-related HTTP headers to responses.
SecurityHeadersConfig
Configuration for the Security Headers middleware.
ServerTimingBuilder
Builder for constructing Server-Timing headers with multiple metrics.
ServerTimingEntry
A single entry in the Server-Timing header.
TimingHistogram
A histogram for collecting timing distributions.
TimingHistogramBucket
Simple histogram bucket for collecting timing distributions.
TimingInterceptor
Interceptor that adds response timing headers.
TimingMetrics
Collected timing metrics for a single request.
TimingMetricsConfig
Configuration for the timing metrics middleware.
TimingMetricsMiddleware
Middleware that collects and exposes timing metrics.
TraceRejectionMiddleware
Middleware that rejects HTTP TRACE requests to prevent Cross-Site Tracing (XST) attacks.
TrustedProxyIpKeyExtractor
Rate limit by client IP with trusted proxy validation.

Enums§

CacheDirective
Individual Cache-Control directives.
CachePreset
Common cache control presets for typical use cases.
ControlFlow
Control flow for middleware before hooks.
CsrfMode
CSRF protection mode.
ETagMode
Configuration for ETag generation strategy.
InspectionVerbosity
Verbosity level for the request inspection middleware.
OriginPattern
Origin matching pattern for CORS.
RateLimitAlgorithm
Rate limiting algorithm.
ReferrerPolicy
Referrer-Policy header value.
XFrameOptions
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.
ResponseInterceptor
A response interceptor that processes responses after handler execution.

Type Aliases§

BoxFuture
A boxed future for async middleware operations.