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.
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));
}
}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).awaitran the handler; the function then added thex-checkedheader 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
Jsonwould 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,
middlewaremodule: https://docs.rs/axum/0.8.9/axum/middleware/index.html (read 2026-12-05)