Skip to main content

Middleware

Trait Middleware 

Source
pub trait Middleware: Send + Sync {
    // Provided methods
    fn before<'a>(
        &'a self,
        _ctx: &'a RequestContext,
        _req: &'a mut Request,
    ) -> BoxFuture<'a, ControlFlow> { ... }
    fn after<'a>(
        &'a self,
        _ctx: &'a RequestContext,
        _req: &'a Request,
        response: Response,
    ) -> BoxFuture<'a, Response> { ... }
    fn name(&self) -> &'static str { ... }
}
Expand description

The core middleware trait.

Middleware wraps request handling with pre-processing and post-processing hooks. Implementations must be thread-safe (Send + Sync) as middleware may be shared across concurrent requests.

§Implementation Guide

  • before: Inspect/modify the request, optionally short-circuit
  • after: Inspect/modify the response

Both methods have default implementations that do nothing, so you can implement only what you need.

§Cancel-Safety

Middleware should check ctx.checkpoint() for long operations to support graceful cancellation when clients disconnect or timeouts occur.

§Example: Request Timing

use std::time::Instant;
use fastapi_core::middleware::{Middleware, ControlFlow};

struct TimingMiddleware;

impl Middleware for TimingMiddleware {
    async fn before(&self, ctx: &RequestContext, req: &mut Request) -> ControlFlow {
        // Store start time in request extensions (future feature)
        ControlFlow::Continue
    }

    async fn after(&self, _ctx: &RequestContext, _req: &Request, mut resp: Response) -> Response {
        // Add timing header
        resp = resp.header("X-Response-Time", b"42ms".to_vec());
        resp
    }
}

Provided Methods§

Source

fn before<'a>( &'a self, _ctx: &'a RequestContext, _req: &'a mut Request, ) -> BoxFuture<'a, ControlFlow>

Called before the handler executes.

§Parameters
  • ctx: Request context with cancellation support
  • req: Mutable request that can be inspected or modified
§Returns
  • ControlFlow::Continue to proceed to the next middleware/handler
  • ControlFlow::Break(response) to short-circuit and return immediately
§Default Implementation

Returns ControlFlow::Continue (no-op).

Source

fn after<'a>( &'a self, _ctx: &'a RequestContext, _req: &'a Request, response: Response, ) -> BoxFuture<'a, Response>

Called after the handler executes.

§Parameters
  • ctx: Request context with cancellation support
  • req: The request (read-only at this point)
  • response: The response from the handler or previous after hooks
§Returns

The response to pass to the next after hook or to return to the client.

§Default Implementation

Returns the response unchanged (no-op).

Source

fn name(&self) -> &'static str

Returns the middleware name for debugging and logging.

Override this to provide a meaningful name for your middleware.

Implementors§