middleware from_fn - Writing Custom Middleware in Axum

Learn how to write custom middleware in Axum with middleware from_fn, from logging and timing to authentication, short-circuiting, and Result returns

A web handler answers one request. It reads what the client sent and builds a response. Middleware is the code that runs around a handler. It sees the request before the handler does, and it sees the response after the handler builds it. Logging every request, checking an API key, adding a header, and measuring how long a handler took are all middleware jobs. middleware::from_fn is the plainest way to write middleware in Axum. You write an ordinary async function, hand it to from_fn, and Axum runs it around your handlers.

What a from_fn Middleware Function Looks Like

A from_fn middleware function takes two values. The first is the incoming Request, which is the full HTTP request with its method, path, headers, and body. The second is a Next value. Next stands for everything inside this middleware, the layers below it and the handler at the end. You call next.run(request).await to pass the request inward, and that call gives you back the Response the handler produced. The function returns something that can be turned into a response, most often a Response itself.

The official Axum documentation lists five requirements for the function you pass to from_fn. It must be an async function. It may take zero or more extractors that read from the request parts, such as a HeaderMap. It must take exactly one extractor that reads the whole request, and that is the Request itself. It must take Next as its last argument. It must return something that implements IntoResponse, which is the trait that turns a value into an HTTP response. A Response qualifies, and so does a Result<Response, E> when the error type E also implements IntoResponse. That last point matters, because it means the function can return a Result and use ? inside it.

Think of the middleware as a guard at a door. The guard looks at the visitor, decides whether to let the visitor through, watches the visitor come back out, and can turn the visitor away at the door. The Request is the visitor arriving, next.run is opening the door, and the Response is the visitor leaving. Every example on this page fits that picture.

The Smallest Example That Does Something

Start with a middleware that logs the method and path of each request, then logs the status of the response. Create a project with the dependencies below. The file Cargo.toml sits at the root of the project, and src/main.rs holds the code.

Cargo.toml
[package]
name = "from-fn-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
src/main.rs
use axum::{
    extract::Request,
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};

async fn log_requests(request: Request, next: Next) -> Response {
    let method = request.method().clone();
    let uri = request.uri().clone();
    println!("Request: {} {}", method, uri);
    let response = next.run(request).await;
    println!("Response status: {}", response.status());
    response
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "Hello, world!" }))
        .layer(middleware::from_fn(log_requests));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Listening on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Run it with cargo run and open http://127.0.0.1:3000/ in a browser. The terminal shows two lines, one before the handler runs and one after.

Request: GET /
Response status: 200 OK

The function log_requests reads the method and the URI from the request and prints them. Then next.run(request).await hands the request to the handler, which returns the text "Hello, world!" with status 200. The middleware prints that status and returns the response unchanged. The line .layer(middleware::from_fn(log_requests)) is what attaches the function to the router. Without it, the function is just an unused function and nothing logs. The Request type comes from axum::extract, which is the import to use in middleware. A bare http::Request from the http crate needs a body type parameter and does not work as a plain parameter type here.

Logging lines mean the middleware is running:

If the terminal shows the request line and then the response status line for each visit, the middleware is attached and running in the right order. If nothing prints, check that the .layer call is present and that the route was added before it.

Building a Middleware in Three Steps

Writing and attaching a from_fn middleware always follows the same order. First you write the async function with the Request and Next parameters. Then you turn it into a layer with middleware::from_fn and attach it with .layer. Then you run the server and watch the behaviour. Each step depends on the one before it, because there is nothing to attach until the function exists, and nothing to observe until the server runs.

1

Step 1: Write the async function

Define an async function that takes a Request and a Next, calls next.run(request).await, and returns a Response. The function below adds a custom header to the response after the handler runs.

async fn add_custom_header(request: Request, next: Next) -> Response {
    let mut response = next.run(request).await;
    response.headers_mut().insert(
        "x-custom-header",
        "hello-from-middleware".parse().unwrap(),
    );
    response
}
2

Step 2: Apply the middleware with .layer()

Convert the function into a layer with middleware::from_fn and attach it to the router. The route is added first, then the layer, so the layer wraps that route.

let app = Router::new()
    .route("/", get(handler))
    .layer(middleware::from_fn(add_custom_header));
3

Step 3: Run the server and check the header

Start the server and request the page with curl. The custom header appears in the response.

curl -i http://127.0.0.1:3000/
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
x-custom-header: hello-from-middleware
content-length: 13

That header example also shows the two halves of a middleware function. Everything before next.run happens on the way in, while the request is travelling toward the handler. Everything after next.run happens on the way out, while the response is travelling back to the client. The next sections use each half on its own.

Changing the Request Before the Handler Sees It

Because from_fn hands you the whole request, you can change it before passing it on. A common change is adding a header that the handler reads. The example below adds an x-request-id header with a fixed value, and the handler reads it back. A real application would generate a fresh id per request, but the fixed value keeps the moving parts visible.

src/main.rs
use axum::{
    extract::Request,
    http::HeaderMap,
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};

async fn add_request_id(mut request: Request, next: Next) -> Response {
    request
        .headers_mut()
        .insert("x-request-id", "12345".parse().unwrap());
    next.run(request).await
}

async fn handler(headers: HeaderMap) -> String {
    let id = headers
        .get("x-request-id")
        .and_then(|value| value.to_str().ok())
        .unwrap_or("not-found");
    format!("Request ID was: {}", id)
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(handler))
        .layer(middleware::from_fn(add_request_id));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Visiting / prints Request ID was: 12345 in the browser. The middleware ran first, added the header, and passed the changed request inward. The handler then read the header through the HeaderMap extractor, which is a type that gives a handler the request headers as a map. The parameter is written mut request: Request because the function changes the request, and Rust requires the mut keyword for that. Once the request is passed into next.run, it is moved, which means the middleware cannot use it again afterwards. If you need a value from the request after the handler runs, read it out before calling next.run and keep it in a local variable.

Read what you need before calling next.run:

The request moves into next.run, so code after that call cannot touch it. Pull out the method, the path, or any header value you need for the after half before you pass the request inward, or the compiler will stop you with a use-after-move error.

Changing the Response After the Handler Runs

The response that comes back from next.run is yours to change. You can add headers, log the status, or replace the body. The example below measures how long the handler took and adds the result as a response header. The handler sleeps for 50 milliseconds to simulate real work, so the header value lands near 50.

src/main.rs
use axum::{
    extract::Request,
    http::HeaderValue,
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};
use std::time::Instant;

async fn timing_middleware(request: Request, next: Next) -> Response {
    let start = Instant::now();
    let mut response = next.run(request).await;
    let millis = start.elapsed().as_millis().to_string();
    response.headers_mut().insert(
        "x-elapsed-ms",
        HeaderValue::from_str(&millis).unwrap(),
    );
    response
}

async fn handler() -> String {
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;
    "Done".to_string()
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(handler))
        .layer(middleware::from_fn(timing_middleware));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request to / returns "Done" with a header like x-elapsed-ms: 50. The timer starts before next.run and stops after it returns, so the measured time covers the handler and everything inside this middleware. The response is declared mut because the header is inserted into it. This shape is the basis of real timing and logging middleware. One thing to keep in mind is that the response body is a stream, so a header added here is cheap, but reading the whole body to inspect it would force the body to be buffered, which is slow for large downloads.

Stopping a Request Early Without Calling the Handler

A middleware function does not have to call next.run. When it returns its own response instead, the handler never runs. That is called short-circuiting, and it is the normal way to enforce authentication. The example below checks for an x-api-key header. A missing or wrong key gets a 401 response straight away. A correct key lets the request through to the handler.

src/main.rs
use axum::{
    extract::Request,
    http::StatusCode,
    middleware::{self, Next},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};

async fn require_api_key(request: Request, next: Next) -> Response {
    let valid_key = "secret-key-123";
    let header_is_valid = request
        .headers()
        .get("x-api-key")
        .and_then(|value| value.to_str().ok())
        .map(|value| value == valid_key)
        .unwrap_or(false);
    if !header_is_valid {
        return (StatusCode::UNAUTHORIZED, "Missing or invalid API key").into_response();
    }
    next.run(request).await
}

async fn secret_handler() -> &'static str {
    "This is top secret data!"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/secret", get(secret_handler))
        .layer(middleware::from_fn(require_api_key));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Try it with curl. Without the header the client gets a 401 and the body "Missing or invalid API key". With the header -H "x-api-key: secret-key-123" it gets a 200 and the secret text. The client does not wait forever in the first case. It receives the 401 immediately, because the middleware returned a complete response. The return keyword is doing real work here. Without it, execution would fall through to next.run and the handler would run even for a bad key. A short-circuit only works when the code path that fails never reaches next.run.

A missing return lets bad requests through:

If the check fails but the function still calls next.run, the handler runs anyway and the check does nothing. Structure the code so the failing path returns early, or put next.run inside the branch that only runs when the check passes. Test both the failing and the passing request with curl before trusting the middleware.

Returning a Result and Using the Question Mark Operator

A middleware function can return Result<Response, E> instead of a plain Response, as long as the error type E implements IntoResponse. The official Axum documentation shows exactly this shape, with a middleware that returns Result<Response, StatusCode>. That makes ? available inside the middleware. The ? operator is Rust shorthand for "if this failed, return the error from the function right now". When the function returns a Result, the error becomes the response the client receives, and the handler never runs.

src/main.rs
use axum::{
    extract::Request,
    http::StatusCode,
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};

async fn load_config() -> Result<String, StatusCode> {
    Ok("config-value".to_string())
}

async fn checked_middleware(request: Request, next: Next) -> Result<Response, StatusCode> {
    let config = load_config().await?;
    let mut response = next.run(request).await;
    response
        .headers_mut()
        .insert("x-config", config.parse().unwrap());
    Ok(response)
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "Hello, world!" }))
        .layer(middleware::from_fn(checked_middleware));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Here load_config stands in for any step that can fail, such as reading a file or calling another service. When it succeeds, the middleware adds the config value as a response header and returns Ok(response). When it fails, ? returns the StatusCode error at once, Axum turns that status into a response, and the handler never runs. If the error type does not implement IntoResponse, for example a database error type, the code will not compile until the error is mapped to something that does, such as .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?. That is the same rule handlers follow. A match on the result works too, and it is the better choice when the failure needs a custom body instead of a bare status code.

Reading Extractors Before the Request

The function passed to from_fn may take extractors before the Request parameter. An extractor is a type that pulls one piece of data out of a request, such as the headers or the query string. The official documentation shows an auth middleware that takes a HeaderMap first, reads the authorization header from it, and only then decides whether to call next.run. The Request must still come after those extractors, and Next must come last.

src/main.rs
use axum::{
    extract::Request,
    http::{HeaderMap, StatusCode},
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};

async fn auth(headers: HeaderMap, request: Request, next: Next) -> Result<Response, StatusCode> {
    let token = headers
        .get("authorization")
        .and_then(|value| value.to_str().ok());
    match token {
        Some("Bearer good-token") => Ok(next.run(request).await),
        _ => Err(StatusCode::UNAUTHORIZED),
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(|| async { "ok" }))
        .route_layer(middleware::from_fn(auth));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request with the header authorization: Bearer good-token gets a 200. Any other request gets a 401, and the handler never runs. The HeaderMap extractor runs before the middleware body, so the token check reads from headers instead of digging into the request. Note the use of .route_layer here instead of .layer. It attaches the middleware to the route added just before the call, so only that route is guarded, while .layer on the router would wrap every route added before it. One detail worth remembering is that Next can only be used once, because run takes Next by value and consumes it. Calling next.run twice does not compile, so a middleware function passes the request onward at most once.

State is the one extractor from_fn cannot use:

The State extractor, which reads shared application state, does not work with from_fn. The documentation states this directly. When middleware needs shared state, the stateful form of this same function is the tool for it, and it takes the state as a separate argument when the layer is built.

Passing Data From Middleware to the Handler

Middleware often learns something the handler needs, such as who the caller is. The way to hand that data over is the request extensions map. Extensions are a type-keyed storage area attached to each request, where a value is stored under its own type. The middleware inserts a value, and the handler pulls it out with the Extension extractor. The example below checks a bearer token, stores a CurrentUser in the extensions, and the handler greets that user by name.

src/main.rs
use axum::{
    extract::{Extension, Request},
    http::StatusCode,
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};

#[derive(Clone)]
struct CurrentUser {
    name: String,
}

async fn auth_insert(mut req: Request, next: Next) -> Result<Response, StatusCode> {
    let token = req
        .headers()
        .get("authorization")
        .and_then(|value| value.to_str().ok());
    match token {
        Some("Bearer alice-token") => {
            req.extensions_mut().insert(CurrentUser {
                name: "alice".to_string(),
            });
            Ok(next.run(req).await)
        }
        _ => Err(StatusCode::UNAUTHORIZED),
    }
}

async fn me_handler(Extension(user): Extension<CurrentUser>) -> String {
    format!("Hello, {}!", user.name)
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/me", get(me_handler))
        .route_layer(middleware::from_fn(auth_insert));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request with authorization: Bearer alice-token returns Hello, alice!. A request without the token gets a 401. The insert happens before next.run, so the handler sees the value. The type must derive Clone, because the Extension extractor requires the stored type to be cloneable. If the handler declares Extension<CurrentUser> but no middleware ever inserted one, the handler fails at runtime with a 500 status, because the extension is missing. That failure is silent at compile time, so test the happy path with a real request rather than trusting the types alone.

Applying Middleware to Every Route or to One Route

The same middleware function can guard a whole router or a single route. .layer on a Router wraps every route that was added before the call. .route_layer on a single method router wraps only that route. The example below protects /private while leaving /public open. The layer is created once and attached to one route.

src/main.rs
use axum::{
    extract::Request,
    http::StatusCode,
    middleware::{self, Next},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};

async fn require_auth(request: Request, next: Next) -> Response {
    if request.headers().contains_key("authorization") {
        next.run(request).await
    } else {
        (StatusCode::UNAUTHORIZED, "No auth header").into_response()
    }
}

async fn public_handler() -> &'static str {
    "Public data"
}

async fn private_handler() -> &'static str {
    "Private data"
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/public", get(public_handler))
        .route("/private", get(private_handler).route_layer(middleware::from_fn(require_auth)));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request to /public returns "Public data" with no header at all. A request to /private without an authorization header returns 401, and with any authorization header it returns "Private data". The order of the calls matters in both directions. A route added after a .layer call is not wrapped by that layer, because the layer only wraps the routes that already exist when it is applied. So the safe habit is to add all routes first and attach layers last.

Routes added after a layer escape it:

A layer wraps the routes present at the time it is applied. If a new route is added after the .layer call, that route runs with no middleware at all. This is a common source of unprotected endpoints. Add routes first, layers last, and test the newest route without credentials to be sure it is covered.

The Order Multiple Middleware Run In

When several from_fn layers are stacked with repeated .layer() calls, the last one added runs first on the way in and last on the way out, and inside a ServiceBuilder they run in the order they are listed. That single rule decides the order of any stack built from the functions on this page, so when two of them depend on each other, check which one was added last before trusting the order.

Common Mistakes and How to Fix Them

Four mistakes show up again and again. The first is forgetting next.run on the normal path. The handler never runs, and the client receives whatever the middleware returned instead. That is not a hang. The client gets a response, just not the one the handler would have built. Check that every normal path reaches next.run, and that only deliberate short-circuits return early.

The second is passing a plain synchronous closure instead of an async function. from_fn requires an async function, so a closure such as |request, next| { next.run(request) } fails with a trait error. Write async fn or an async move closure. The synchronous closure shape belongs to a different helper, the tower combinator that shares the map_request name, not to from_fn.

The third is using the wrong Request type. The parameter must be axum::extract::Request. A bare http::Request without a body type does not compile, and a request typed with the wrong body produces confusing trait errors at the .layer call.

The fourth is trying to use the request after moving it into next.run. The compiler rejects it, and the fix is to read out whatever is needed before the call. A related trap is calling next.run twice. That also fails to compile, because run consumes Next, so the value is gone after the first call.

A short-circuit that still calls next.run is not a short-circuit:

The most consequential mistake on this page is a guard that returns an error response on one path but still falls through to next.run. The handler runs, the protected data goes out, and the 401 never reaches the client. Always test the guarded route without credentials and confirm the handler body is absent from the response.

Summary

The choice between the middleware helpers comes down to what the function needs to touch. When the work is a plain async function that reads the request, optionally changes it, calls next.run, and optionally changes the response, from_fn is the tool. When the function also needs shared application state, the stateful form takes over, because from_fn cannot extract State. When the work is only a change to the request with no need to see the response, a request-only helper fits better, and when the work is only a change to the response, a response-only helper fits better. Inside from_fn itself, the rule that decides most designs is simple. Everything before next.run shapes what the handler sees, everything after it shapes what the client sees, and anything that must stop the request does so by returning its own response instead of calling next.run at all.