The Next Type in Axum
Learn what axum middleware Next is, how next run passes control to the rest of the middleware stack, and how to short-circuit or post-process responses with it
When you write middleware as an async function, your function receives two arguments, the incoming request and a value called Next. Next is the thing that makes the whole pattern work. It represents everything that comes after your middleware, the rest of the middleware stack, including the handler, and calling it is how you pass control onward.
This page is about that one type, what Next is, what its single method does, and the mistakes people make with it. The helper that hands you a Next is a way to turn an async function into middleware. Here the focus stays on the value it hands you.
What Next Is
The official documentation describes Next in one line:
"The remainder of a middleware stack, including the handler."
That is the whole definition, and it is worth reading carefully. Next is not the handler, and it is not the next middleware function. It is the remainder, every layer still to run, plus the handler at the end, bundled into a single value you can call. When your middleware calls next.run(request).await, the request travels through all of those remaining layers, the handler produces a response, and the response travels back to your middleware.
Next is a struct with private fields:
pub struct Next { /* private fields */ }
You never construct a Next yourself. Axum builds one for you and passes it into your middleware function. You also cannot look inside it. There are no public fields and no accessor methods other than run. Its only job is to be run, once, with a request.
A middleware function that receives Next always has the same shape. The request comes first, then Next last:
use axum::{
extract::Request,
middleware::Next,
response::Response,
};
async fn my_middleware(request: Request, next: Next) -> Response {
let response = next.run(request).await;
response
}
With state, the shape is the same, with the State extractor first:
use axum::{
extract::{Request, State},
middleware::Next,
response::Response,
};
async fn my_middleware(
State(state): State<AppState>,
request: Request,
next: Next,
) -> Response {
let response = next.run(request).await;
response
}
Next always comes last, after the request. That is the same extractors first, moving part last rule that the request and response helpers follow, only here the moving part is the rest of the stack instead of a single request or response.
Running Next, the One Method That Matters
Next has exactly one method you will use:
pub async fn run(mut self, req: Request) -> Response
Three details in that signature carry the whole behaviour of the type. First, run takes self, not &self. It consumes the Next value. Each Next can only be run once. After you call run, the value is gone, and the compiler will stop you from calling it again. That is what single-use means in practice, one Next, one trip through the rest of the stack.
Second, it takes the Request by value. The request is moved into run, so you cannot use request after that line. Anything you need after the handler runs, the method, the URI, a start timestamp, must be cloned or captured before the call. The compiler enforces this the same way it enforces every other move in Rust.
Third, it returns a Response directly, not a Result. There is no error to handle. The remaining stack always produces a response, so run gives you one back with no wrapping. Your middleware function can then inspect it, change it, and return it, or return something else entirely.
Here is the smallest complete example that uses all three facts. It records a start time, runs the rest of the stack, and adds the elapsed time as a header on the response. It needs only Axum and Tokio:
[package]
name = "next-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "=0.8.9"
tokio = { version = "=1.54.1", features = ["full"] }
use axum::{
extract::Request,
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 response = next.run(request).await;
let elapsed = start.elapsed();
let (mut parts, body) = response.into_parts();
parts.headers.insert(
"x-elapsed-ms",
elapsed.as_millis().to_string().parse().unwrap(),
);
Response::from_parts(parts, body)
}
async fn handler() -> &'static str {
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
"done"
}
#[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();
}
Everything before next.run(request).await runs on the request, on the way in. Everything after it runs on the response, on the way out. That pivot point is the most important line in any middleware function of this shape, and Next is what makes it possible. A request to this server returns the body done and a header such as x-elapsed-ms: 51, showing that the handler ran between the two halves of the middleware.
Next is the pivot:
When you remember one line from this page, remember the pivot. Everything before next.run(request).await is the request path, and everything after it is the response path. An auth check usually does all of its work before the pivot. A timing middleware splits its work across it.
Short-Circuiting, Returning Without Running Next
You do not have to call run. When your middleware returns a response without calling it, the rest of the stack never runs. The handler never executes, and the client gets whatever your middleware returned. That is called short-circuiting, and it is how auth checks, rate limiters, and validation middleware stop a request at the gate.
use axum::{
extract::Request,
http::StatusCode,
middleware::{self, Next},
response::{IntoResponse, Response},
routing::get,
Router,
};
async fn auth_check(request: Request, next: Next) -> Response {
let allowed = request
.headers()
.get("authorization")
.and_then(|value| value.to_str().ok())
== Some("Bearer secret-token");
if !allowed {
return (StatusCode::UNAUTHORIZED, "missing or invalid token").into_response();
}
next.run(request).await
}
async fn me_handler() -> &'static str {
"Hello, alice!"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/me", get(me_handler))
.layer(middleware::from_fn(auth_check));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
A request without the right token gets a 401 Unauthorized and never reaches me_handler. A request with the token passes through next.run(request).await and gets the handler's response. There is no separate reject method on Next. Not calling run is the rejection.
Short-circuiting is also why forgetting run is such a confusing bug. A middleware that never calls run compiles fine and returns whatever its own code produces, often an empty or default response, while the handler silently never runs. When every request returns an empty response and your handler's logs are quiet, check the success path first. Does it actually call next.run(request).await? Forgetting it means the handler never runs and the client gets only what the middleware produced. It does not by itself cause the request to hang. A hang needs something else, such as an await that never completes.
Not calling run is a decision, not an accident:
Returning early is a deliberate short-circuit. When your middleware returns without calling run on the success path, the handler never runs and the client gets only what your middleware produced. That is correct for an auth gate and a bug everywhere else.
What Happens After run Returns
Once run returns, you hold the response the rest of the stack produced, and you can do anything with it. Add headers, change the status code, log it, or replace it entirely. This is the post-processing half of middleware written in this shape, and it is the same work a response-only helper does, only here you also had the chance to run code before the handler.
A common post-processing pattern is logging the status code together with request data you captured before the call:
use axum::{
extract::Request,
middleware::{self, Next},
response::Response,
routing::get,
Router,
};
use std::time::Instant;
use tracing::info;
async fn log_requests(request: Request, next: Next) -> Response {
let method = request.method().clone();
let uri = request.uri().clone();
let start = Instant::now();
let response = next.run(request).await;
let latency = start.elapsed();
let status = response.status();
info!(
method = %method,
uri = %uri,
status = %status,
latency_ms = latency.as_millis() as u64,
"request completed"
);
response
}
async fn hello() -> &'static str {
"Hello, world!"
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt::init();
let app = Router::new()
.route("/", get(hello))
.layer(middleware::from_fn(log_requests));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Notice the clones before run. method, uri, and start are all captured first, because request is moved into run and cannot be used afterward. When you try to read request.method() after next.run, the compiler stops you. That error is the borrow checker doing its job. Capture what you need before the pivot, not after it.
This snippet needs tracing = "0.1" and tracing-subscriber = "0.3" in Cargo.toml. The % sigil in the info! macro tells tracing to record the value using its Display implementation, which is what you want for types like Method, Uri, and StatusCode.
Next Is Clone, but Each Handle Runs Only Once
Here is the part that surprises people who have read older explanations of Next. In Axum 0.8, Next derives Clone and Debug:
#[derive(Debug, Clone)]
pub struct Next { /* private fields */ }
So Next is cloneable. Cloning it gives you a second handle to the same remainder of the stack, and each handle can be run once, because run still consumes whichever handle you call it on. You cannot run the same handle twice. The compiler rejects that. But you can clone a handle and run the clone as well, which runs the rest of the stack a second time. The handler executes once per run call, so cloning and running both handles calls the handler twice.
async fn run_twice(request: Request, next: Next) -> Response {
let second = next.clone();
let first_response = next.run(request).await;
let request_again = Request::builder()
.uri("/")
.body(axum::body::Body::empty())
.unwrap();
let _second_response = second.run(request_again).await;
first_response
}
That example is deliberately artificial. Running the stack twice is almost never what you want, and the second run needs a fresh request because the first one was consumed. It is shown here only to make the rule precise. The single-use limit applies to each Next value, not to the stack behind it, and Clone is what lets you hold more than one value. In normal middleware you will never clone Next. You will run it exactly once. But when you see next.clone() in someone else's code, it is legal, and now you know what it does.
Why does Clone exist at all, when running twice is rarely useful? Because Next also implements Tower's Service trait for requests, and services in Tower are expected to be cloneable so they can be shared across tasks. That is an implementation detail you can safely ignore in day-to-day middleware. The practical rule is simpler. Run your Next once, and do not clone it unless you have a specific reason to run the stack again.
Clone does not mean reusable:
Next being Clone does not make a single Next reusable. run consumes self, so each handle still runs only once. Cloning gives you a new handle. It does not reset the one you already used.
Next and the Rest of the Stack, Ordering
When several layers of this shape are stacked, each one receives a Next that represents everything inside it, the inner middleware layers and the handler. The outermost middleware runs first, calls run, and that call enters the next middleware, which receives its own Next, and so on until the handler. The responses then unwind back out in reverse order.
request -> outer middleware -> inner middleware -> handler
response <- outer middleware <- inner middleware <-
Concretely, with two layers:
use axum::{
extract::Request,
middleware::{self, Next},
response::Response,
routing::get,
Router,
};
async fn outer(request: Request, next: Next) -> Response {
println!("outer: before");
let response = next.run(request).await;
println!("outer: after");
response
}
async fn inner(request: Request, next: Next) -> Response {
println!("inner: before");
let response = next.run(request).await;
println!("inner: after");
response
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "hello" }))
.layer(middleware::from_fn(inner))
.layer(middleware::from_fn(outer));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
A request prints outer: before, then inner: before, then the handler runs, then inner: after, then outer: after. Each Next is a smaller remainder than the one before it. The layer added last is outermost, so outer runs first on the request and last on the response, and inner runs second on the request and first on the response.
Returning a Result Instead of a Response
A middleware function that receives a Next does not have to return a plain Response. It can return a Result<Response, E> where the error type implements IntoResponse. That shape fits auth checks well, because every rejection becomes a short return Err(...) line and every success ends with the same next.run call.
use axum::{
extract::Request,
http::StatusCode,
middleware::{self, Next},
response::Response,
routing::get,
Router,
};
async fn auth_check(request: Request, next: Next) -> Result<Response, StatusCode> {
let allowed = request
.headers()
.get("authorization")
.and_then(|value| value.to_str().ok())
== Some("Bearer secret-token");
if !allowed {
return Err(StatusCode::UNAUTHORIZED);
}
Ok(next.run(request).await)
}
async fn me_handler() -> &'static str {
"Hello, alice!"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/me", get(me_handler))
.layer(middleware::from_fn(auth_check));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
A request without the right token gets a plain 401 Unauthorized response, because Axum converts the StatusCode error into a response automatically. A request with the token reaches the handler, and the handler's response is wrapped in Ok and returned. The error type can also be a tuple, such as (StatusCode, &str), when the rejection needs a message body. The rule is the same as everywhere else in Axum middleware. The error type must implement IntoResponse, and StatusCode and status-plus-body tuples already do.
Extractors Run Before Next
A middleware function can take extractors before the request and Next. Those extractors run on the request before the handler, exactly like the extractors in a request-only helper. The State extractor is the most common one, and it is how state reaches a bracketing middleware function.
use axum::{
extract::{Request, State},
http::StatusCode,
middleware::{self, Next},
response::Response,
routing::get,
Router,
};
#[derive(Clone)]
struct AppState {
required_token: String,
}
async fn auth_check(
State(state): State<AppState>,
request: Request,
next: Next,
) -> Result<Response, StatusCode> {
let allowed = request
.headers()
.get("authorization")
.and_then(|value| value.to_str().ok())
.map(|value| value == format!("Bearer {}", state.required_token))
.unwrap_or(false);
if !allowed {
return Err(StatusCode::UNAUTHORIZED);
}
Ok(next.run(request).await)
}
async fn me_handler() -> &'static str {
"Hello, alice!"
}
#[tokio::main]
async fn main() {
let state = AppState {
required_token: "secret-token".to_string(),
};
let app = Router::new()
.route("/me", get(me_handler))
.route_layer(middleware::from_fn_with_state(state.clone(), auth_check))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The argument order is fixed. Extractors first, then the request, then Next last. The state value is passed twice here, once to the layer through from_fn_with_state and once to the router through .with_state, for the same reason it is passed twice in the state-aware request and response helpers. The layer needs its own copy before the router knows its state, and the router needs one for the handlers.
Path, Query, and HeaderMap work in the same position. What cannot appear here are extractors that consume the request body, such as Json<T>, because the body still has to reach the handler through next.run.
Common Mistakes
Forgetting to Call run
When the function compiles but every request returns an empty response, or the handler's code never seems to execute, check that the success path actually calls next.run(request).await. A middleware that never calls run is a dead end. The request stops there, and only the middleware's own return value reaches the client.
Using the Request After run
The request is moved into run. Any data you need after that call, such as the method or URI, must be cloned or captured before the call. The compiler error points at the use after the move. The fix is to move the clone above the run line.
Trying to Run the Same Next Twice
run takes self, so a second next.run(...) on the same binding does not compile. When you genuinely need the stack to run twice, which is rare, clone the Next first and run each handle once. In almost every case, though, a second run is a mistake. Restructure the middleware so one pass is enough.
Expecting Next in a Request-Only or Response-Only Helper
Next only appears in middleware written as an async function that brackets the handler. Request-only and response-only helpers do not receive one. They transform a request or a response and return it, and Axum itself passes control onward. When you find yourself wanting a Next inside one of those functions, you actually want the bracketing form.
Returning Early on the Wrong Path
Short-circuiting is a decision. Make sure the early return only happens on the failure path, a missing token or a failed check, and that the success path always reaches next.run(request).await. An inverted condition here locks every user out, or lets every request through, with no error to point at the cause.
A second run on the same Next is a compile error:
run consumes self, so calling next.run(request).await twice on the same binding fails to compile. The error message talks about a moved value. The fix is almost always to call run once and reuse the response it returns, not to run the stack again.
How Next Relates to the Other Middleware Helpers
Next is the mechanism underneath middleware written as an async function that brackets the handler. The other helpers in this area are built on different mechanisms. Request-only and response-only helpers transform one side of the exchange and return it, with no Next involved. A helper that turns an extractor into middleware validates a value and discards it, again with no Next. When you need the pivot, code before and after the handler, or the ability to stop the request, you need a helper that gives you a Next, and that means the bracketing form.
One run, one response, no surprises:
When your middleware calls next.run(request).await exactly once on the success path and returns early only on the failure path, the shape is right. The handler runs once, the response unwinds through your code once, and the client sees exactly one response.
Summary
Next is "the remainder of a middleware stack, including the handler", a single value that represents everything after your middleware. You receive it as the last argument of a bracketing middleware function, and you pass control onward by calling next.run(request).await, which consumes the Next, moves the request into the rest of the stack, and returns a Response directly. Returning without calling run short-circuits the request, so the handler never runs. Code before the call runs on the request, and code after it runs on the response. Next derives Clone, so you can hold a second handle and run that once too, but each individual handle runs only once.
The decision framework is short. When you need code on both sides of the handler, or the power to stop a request, you need a Next, so use the bracketing form. When the work touches only the request, or only the response, the one-sided helpers are smaller and clearer, because they never hand you a Next at all. And when you do hold a Next, run it exactly once on the success path, return early only on the failure path, and capture everything you need from the request before the pivot, because the request is gone after the call.