Skip to main content
The from_fn module provides a simple way to create middleware from async functions, allowing you to intercept and modify requests before they reach handlers and responses before they’re returned to clients.

Core functions

from_fn

Create a middleware from an async function without state access. Requirements:
  1. Must be an async fn
  2. Take zero or more FromRequestParts extractors
  3. Take exactly one FromRequest extractor as the second to last argument
  4. Take Next as the last argument
  5. Return something that implements IntoResponse
Basic example:

from_fn_with_state

Create a middleware from an async function with state access. Example with state:

Request/response handling patterns

Modifying requests

Insert headers or modify the request before it reaches handlers:

Processing request body

Consume and inspect the request body:

Processing request and response

Handle both request and response in the same middleware:

Running extractors

Use extractors to access request data:

Passing data to handlers

Use request extensions to pass data from middleware to handlers:

Tracking metrics

Implement request tracking and metrics:

The Next type

Represents the remainder of the middleware stack, including the handler.

Methods

run

Execute the remaining middleware stack and return the response.

Types

FromFnLayer

A tower::Layer created from an async function. Created with from_fn or from_fn_with_state.

FromFn

The middleware service created from an async function.

ResponseFuture

The future type returned by FromFn.

See also