Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 38 ยท State and Middleware

Middleware in Axum with from_fn

Write Axum middleware as async functions with from_fn: run code before and after handlers, return early, share state, apply layers to groups, and learn the layer order.

Middleware is code that wraps your handlers. It sees the request on the way in and the response on the way out, so it is the right place for things every request needs: logging, timing, authentication, rate limits, request ids, compression. Each handler stays focused on its own job.

You met the theory behind this in the Tower lesson: middleware is a Service that wraps another service, installed with .layer(...). Implementing Service by hand is verbose, so Axum offers the friendly route: axum::middleware::from_fn, which turns an ordinary async function into a layer.

The shape of a middleware function

Rust
use axum::{extract::Request, middleware::Next, response::Response};

async fn log_requests(req: Request, next: Next) -> Response {
    println!("--> {} {}", req.method(), req.uri());

    let response = next.run(req).await;       // call the rest of the stack

    println!("<-- {}", response.status());
    response
}
  • The function receives the Request and a Next, which represents "everything inside this middleware": the other layers and finally the handler.
  • next.run(req).await calls the inner part and returns its Response.
  • Code before the call sees the request. Code after it sees the response.
  • Returning without calling next.run short-circuits: the handler is never reached.

Install it with from_fn:

Rust
use axum::{middleware, routing::get, Router};

let app = Router::new()
    .route("/", get(|| async { "hello" }))
    .layer(middleware::from_fn(log_requests));

Extractors in middleware

A from_fn function may take extractors before the final Request and Next arguments, just like a handler:

Rust
use axum::{
    extract::Request,
    http::{header::AUTHORIZATION, StatusCode},
    middleware::Next,
    response::Response,
};

async fn require_token(req: Request, next: Next) -> Result<Response, StatusCode> {
    let token = req
        .headers()
        .get(AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer "));

    match token {
        Some("secret-token") => Ok(next.run(req).await),
        _ => Err(StatusCode::UNAUTHORIZED),               // handler never runs
    }
}

With extractors:

Rust
use axum::extract::{ConnectInfo, State};
use std::net::SocketAddr;

async fn count_clients(
    State(state): State<AppState>,
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    req: Request,
    next: Next,
) -> Response {
    state.record(addr.ip());
    next.run(req).await
}

Because this one reads State, install it with from_fn_with_state:

Rust
let app = Router::new()
    .route("/", get(home))
    .layer(middleware::from_fn_with_state(state.clone(), count_clients))
    .with_state(state);

Changing the response

Anything after next.run can modify the response, for example to add a header:

Rust
use axum::http::HeaderValue;
use std::time::Instant;

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

Passing data to handlers: extensions

A middleware can compute something (the authenticated user, a request id) and hand it down by inserting it into the request's extensions:

Rust
async fn authenticate(mut req: Request, next: Next) -> Result<Response, StatusCode> {
    let user = lookup_user(&req).ok_or(StatusCode::UNAUTHORIZED)?;
    req.extensions_mut().insert(user);       // store a CurrentUser value
    Ok(next.run(req).await)
}

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

The extensions lesson goes deeper.

layer versus route_layer

Method Applies to A request to an unknown path
Router::layer(l) every route and the fallback passes through the middleware, then gets the 404
Router::route_layer(l) only matched routes never reaches the middleware, gets the 404 directly

For authentication, route_layer is usually right: you do not want anonymous clients to get 401 for URLs that do not exist, or to learn nothing about which paths are real. For logging, use layer so 404s are logged too.

To protect part of an app, build a sub-router, call route_layer on it, and merge it, as shown in the nesting lesson.

Order of layers

This is the part that surprises people. In

Rust
let app = Router::new()
    .route("/", get(handler))
    .layer(A)
    .layer(B)
    .layer(C);

the request goes C, then B, then A, then the handler, and the response comes back A, B, C. The layer added last is the outermost. Think of wrapping a gift: each .layer wraps the previous result in one more layer of paper. ServiceBuilder reverses this and reads top-to-bottom in the order of execution:

Rust
use tower::ServiceBuilder;

let app = Router::new().route("/", get(handler)).layer(
    ServiceBuilder::new()
        .layer(A)      // runs first
        .layer(B)
        .layer(C),     // runs last before the handler
);

Many teams prefer ServiceBuilder for exactly that readability. Typical order, outermost first: request id, tracing, timeout, compression, CORS, authentication.

Stand-in: from_fn and the onion

The real Next is an async service. This model keeps the structure with plain closures so you can run it: a Handler returns a response, a Middleware receives the request and a Next it may or may not call, and layer wraps one around another. Watch the order of the log lines and the early return.

Rust Stand-in: middleware, Next and the order of layers

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The layering order in the code is A, B, require_token, add_header (each wrapping the previous), so add_header is outermost and the logger A is closest to the handler. In the second request the token check short-circuits: loggers A and B never run, because they sit inside the authentication layer. The header is still added, because add_header is outside it.

Stand-in: measuring time and counting with shared state

This second model combines timing, a request counter in shared state (as in the previous lesson) and a request id handed down to the handler through an "extensions" map.

Rust Stand-in: timing, counters and extensions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Practical advice

  • Put cheap rejections (authentication, rate limits) before expensive work such as body parsing.
  • For concerns Tower already solves (timeouts, compression, CORS, tracing), use tower-http layers instead of writing your own.
  • Never hold up next.run(req): do slow, non-essential work in a spawned task so the response is not delayed.
  • Remember that middleware runs for every matched request. Keep it quick.
  • Return the same JSON error shape from middleware that handlers return; see error handling.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a from_fn middleware do to skip the handler?

    Next represents the rest of the stack. If you never call it, the inner layers and the handler do not run.
  2. 2. With .layer(A).layer(B).layer(C), which layer sees the request first?

    The layer added last is the outermost, so C sees the request first and the response last.
  3. 3. Which method keeps an auth middleware from running for URLs that do not match any route?

    route_layer wraps only matched routes, so unknown paths get a normal 404 without reaching the middleware.
  4. 4. A middleware needs the shared AppState. What do you use to install it?

    from_fn_with_state passes the state so the function can extract State<AppState> like a handler.

Summary

  • middleware::from_fn(async fn(Request, Next) -> Response) turns a function into a layer; next.run(req).await calls the rest of the stack.
  • Code before next.run sees the request, code after it sees the response; skipping next.run short-circuits.
  • Use from_fn_with_state when the middleware needs State, and extensions to pass per-request values on.
  • route_layer affects only matched routes; layer also covers the fallback.
  • The last .layer(...) is the outermost; ServiceBuilder lists layers in execution order.

Next: Middleware with tower-http