# How do I write middleware in axum with middleware::from_fn?
Source: https://ruststudio.org/community/t/170/how-do-i-write-middleware-in-axum-with-middleware-from-fn
Author: Ruststudio Team (staff) | Published: 2026-12-05 | Updated: 2026-12-05 | Checked with: rustc 1.93.0, axum 0.8.9, tokio 1.54.1, tower 0.5.3, Windows 11; handlers called in-process with tower's oneshot
Category: Help and questions | Kind: FAQ | Tags: axum, middleware, tower, authentication | Views: 0

## Short answer
Write an async function that takes the Request and a Next, then either returns an early response or calls next.run(request) and adjusts the response. Wrap it with middleware::from_fn and add it with Router::layer. The handler never runs when the middleware returns early.

## Answer
## Answer
`from_fn` is the shortest way to write a middleware without implementing the tower traits yourself. The function sees the request first, and the response last.

```rust title=src/main.rs
use axum::{
    body::{to_bytes, Body},
    extract::Request,
    http::{HeaderValue, StatusCode},
    middleware::{self, Next},
    response::Response,
    routing::get,
    Router,
};
use tower::ServiceExt;

async fn require_key(req: Request, next: Next) -> Result<Response, StatusCode> {
    match req.headers().get("x-api-key").and_then(|v| v.to_str().ok()) {
        Some("secret") => {
            let mut res = next.run(req).await; // run the rest of the stack, then adjust the response
            res.headers_mut().insert("x-checked", HeaderValue::from_static("yes"));
            Ok(res)
        }
        _ => Err(StatusCode::UNAUTHORIZED), // the handler never runs
    }
}

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

#[tokio::main]
async fn main() {
    let app = Router::new().route("/data", get(data)).layer(middleware::from_fn(require_key));
    for key in [None, Some("wrong"), Some("secret")] {
        let mut b = Request::get("/data");
        if let Some(k) = key { b = b.header("x-api-key", k); }
        let res = app.clone().oneshot(b.body(Body::empty()).unwrap()).await.unwrap();
        let status = res.status().as_u16();
        let checked = res.headers().get("x-checked").cloned();
        let body = to_bytes(res.into_body(), usize::MAX).await.unwrap();
        println!("key {key:?} -> {status} x-checked={checked:?} {:?}", String::from_utf8_lossy(&body));
    }
}
```

```text
key None -> 401 x-checked=None ""
key Some("wrong") -> 401 x-checked=None ""
key Some("secret") -> 200 x-checked=Some("yes") "private data"
```

- Missing or wrong key: the function returned `Err(StatusCode::UNAUTHORIZED)` and the handler did not run.
- Right key: `next.run(req).await` ran the handler; the function then added the `x-checked` header to the response.
- The key is compared as plain text only to keep the example short. For real secrets use a constant-time comparison from a crypto crate and keep the key in configuration, not in the code.

## Common mistakes
- Reading the request body in the middleware and then passing the request on. The body is consumed once; the handler's `Json` would find nothing.
- Putting a secret check in a middleware and forgetting the routes you did not test. Call each protected route once without the key and confirm the 401, as in the run above.

## Related questions
### How do I run something on every request without changing the response?
Call `next.run(req).await` and return its result unchanged; log or count in between. For access logging, `TraceLayer` from tower-http already does this (see the thread on logging).

### What is the difference between `from_fn` and a tower `Layer`?
A `Layer` is reusable library code with its own types. `from_fn` is a convenience that builds a layer from one async function.

## Sources
- axum, `middleware` module: https://docs.rs/axum/0.8.9/axum/middleware/index.html (read 2026-12-05)
