from_extractor - Turning an Extractor Into Middleware in Axum

Learn how axum middleware from_extractor runs an extractor as a validation gate before handlers, why the value is discarded, and how to pass data through extensions

An extractor is a type that pulls one piece of data out of a request. A handler that takes Query<Params> as a parameter uses an extractor. A handler that takes a HeaderMap uses an extractor. middleware::from_extractor turns an extractor into middleware, so the same extraction runs before the handler, on every route the layer covers. The idea sounds like a shortcut for sharing extracted data with handlers. It is not that. It is a gate. Understanding the difference is the whole topic, and getting it wrong produces a confusing 500 error that looks like nothing is broken.

The Contract, Stated Before Any Example

The official Axum documentation describes from_extractor in one sentence. "If the extractor succeeds the value will be discarded and the inner service will be called. If the extractor fails the rejection will be returned and the inner service will not be called." The value is discarded. That is the documented behaviour, not a bug and not a limitation to work around by accident. The middleware runs the extractor, throws the extracted value away, and calls the handler with the original request. When the extractor fails, the rejection becomes the response and the handler never runs.

Think of it as a ticket checker at a venue door. The checker looks at your ticket, decides it is valid, and lets you in. The checker does not hand your ticket to the usher inside. The usher knows you were allowed in, but never sees the ticket itself. If the handler needs the ticket, the extractor must leave a copy of it somewhere the handler can find it, and that place is the request extensions map. This page shows both shapes, the pure gate and the gate that also leaves data behind.

The Smallest Example, a Gate That Checks a Token

Start with the built-in style of extractor that the official documentation uses, a small type that checks the authorization header and rejects the request when the token is wrong. 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-extractor-demo"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
src/main.rs
use axum::{
    extract::FromRequestParts,
    http::{header, request::Parts, StatusCode},
    middleware,
    routing::get,
    Router,
};

struct RequireAuth;

impl FromRequestParts<()> for RequireAuth {
    type Rejection = StatusCode;

    async fn from_request_parts(parts: &mut Parts, _state: &()) -> Result<Self, Self::Rejection> {
        let auth_header = parts
            .headers
            .get(header::AUTHORIZATION)
            .and_then(|value| value.to_str().ok());
        match auth_header {
            Some(auth_header) if auth_header == "Bearer good-token" => Ok(Self),
            _ => Err(StatusCode::UNAUTHORIZED),
        }
    }
}

async fn handler() -> &'static str {
    "You are authorized."
}

#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(handler))
        .route_layer(middleware::from_extractor::<RequireAuth>());
    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 try both requests with curl. Without the header the response is a bare 401. With -H "authorization: Bearer good-token" the response is a 200 with the body "You are authorized."

A few pieces deserve attention. RequireAuth is an empty struct. It carries no data, because its only job is to run the check. It implements FromRequestParts<()>, which is the trait for extractors that read the request parts, the method, the URI, the headers, and the extensions, but not the body. The () in FromRequestParts<()> is the state type, and () means the extractor needs no application state. The associated type Rejection is what the extractor returns when it fails, and StatusCode works because it converts into a response on its own. The handler never mentions RequireAuth. It runs only when the check passed, and that is all it knows.

A 401 without the header and a 200 with it means the gate works:

If the request without a token gets a 401 and the request with the right token gets the handler body, the extractor is running as middleware and the gate is doing its job. The handler itself holds no auth logic at all.

How the Middleware Runs the Extractor

The function from_extractor::<E>() returns a layer, and its full type is FromExtractorLayer<E, ()>, with two type parameters, the extractor and the state type (). When the layer is attached to a router, it wraps the routes in that router's scope. For each incoming request the layer's service does four things in order. It takes the request parts, everything except the body. It runs the extractor on those parts. When extraction succeeds, it discards the extracted value and calls the inner service with the request rebuilt from the same parts. When extraction fails, it turns the rejection into a response and returns it at once, skipping the inner service entirely.

Because the middleware works at the parts level, the extractor can only be one that implements FromRequestParts. An extractor that needs the body, such as Json<T>, implements a different trait called FromRequest, and it does not compile with from_extractor. The body is the one part of the request the middleware never sees. The other consequence of the rebuild is that anything the extractor inserted into parts.extensions survives into the handler, because the extensions are part of the parts. The returned value does not survive, because the middleware drops it. That split is exactly what the next sections use.

A Custom Extractor That Validates a Header

The gate becomes useful when the extractor carries real validation logic. The example below defines a UserId extractor that reads an x-user-id header, parses it as a number, and rejects the request with a 400 when the header is missing or not a number. The handler does not receive the id. It only runs when the header was valid, and it says so.

src/main.rs
use axum::{
    extract::FromRequestParts,
    http::{request::Parts, StatusCode},
    middleware,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};

#[derive(Debug, Clone)]
pub struct UserId(pub u64);

impl FromRequestParts<()> for UserId {
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, _state: &()) -> Result<Self, Self::Rejection> {
        let user_id = parts
            .headers
            .get("x-user-id")
            .and_then(|value| value.to_str().ok())
            .and_then(|value| value.parse::<u64>().ok())
            .ok_or_else(|| {
                (StatusCode::BAD_REQUEST, "Missing or invalid x-user-id header").into_response()
            })?;
        Ok(UserId(user_id))
    }
}

async fn handler() -> &'static str {
    "Your user ID header was valid."
}

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

A request with -H "x-user-id: 42" gets a 200 and the message. A request without the header, or with a header that is not a number, gets a 400 with the text "Missing or invalid x-user-id header", and the handler never runs. The FromRequestParts trait declares from_request_parts as an async function, so the implementation is written directly with no extra attribute or macro. The rejection type here is Response, which is the most flexible choice, because any status and body can be built into it. The handler is deliberately simple. It cannot print the id, because the middleware discarded it. That is the point the next section proves with a failing example.

The handler knows the request passed, nothing more:

After a from_extractor layer, a handler that runs has proof the request passed validation, and nothing else. The handler cannot see the extracted value, because the middleware dropped it. When the handler needs the value, the extractor has to store it explicitly, which the next two sections cover.

The Trap, Expecting the Handler to Receive the Value

The mistake almost every beginner makes with from_extractor is writing a handler that expects the extracted value to be waiting for it. The handler below declares Extension<BareUserId>, which asks Axum to pull a BareUserId out of the request extensions. The middleware runs the BareUserId extractor, the extractor succeeds, the middleware discards the value, and the handler then finds nothing in the extensions. Axum answers with a 500 status.

src/main.rs
use axum::{
    extract::{Extension, FromRequestParts},
    http::{request::Parts, StatusCode},
    middleware,
    response::{IntoResponse, Response},
    routing::get,
    Router,
};

#[derive(Debug, Clone)]
pub struct BareUserId(pub u64);

impl FromRequestParts<()> for BareUserId {
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, _state: &()) -> Result<Self, Self::Rejection> {
        let user_id = parts
            .headers
            .get("x-user-id")
            .and_then(|value| value.to_str().ok())
            .and_then(|value| value.parse::<u64>().ok())
            .ok_or_else(|| {
                (StatusCode::BAD_REQUEST, "Missing or invalid x-user-id header").into_response()
            })?;
        Ok(BareUserId(user_id))
    }
}

async fn handler(Extension(id): Extension<BareUserId>) -> String {
    format!("Your user ID is: {}", id.0)
}

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

Send a request with a valid header, -H "x-user-id: 42", and the response is a 500, not the user id. This was checked at runtime. The extractor ran, the header was valid, the middleware discarded the value, and the handler failed because the extension was never stored. The 500 is confusing because nothing about the request was wrong. The validation passed. The failure is in the assumption that the middleware delivers the value. It does not, and the compiler cannot warn about it, because the handler compiles fine on its own.

Extension in the handler is empty unless the extractor stored it:

A handler that declares Extension<T> after a from_extractor layer returns 500 when the extractor never inserted T into the extensions. The middleware discards the extracted value, so the extension map is the only channel, and the extractor has to write to it. The fix is one line inside from_request_parts, shown in the next section.

Passing the Value to the Handler Through Extensions

The only way for the handler to see the extracted value is for the extractor to store a clone of it in parts.extensions itself, inside from_request_parts. The extensions map is part of the request parts, and it survives the rebuild the middleware performs. The change to the UserId extractor is a single line, plus the clone that the line needs.

impl FromRequestParts<()> for UserId {
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, _state: &()) -> Result<Self, Self::Rejection> {
        let user_id = parts
            .headers
            .get("x-user-id")
            .and_then(|value| value.to_str().ok())
            .and_then(|value| value.parse::<u64>().ok())
            .ok_or_else(|| {
                (StatusCode::BAD_REQUEST, "Missing or invalid x-user-id header").into_response()
            })?;
        let user = UserId(user_id);
        parts.extensions.insert(user.clone());
        Ok(user)
    }
}

The user.clone() call is necessary because the extractor returns the value after inserting it, and the middleware discards the returned copy. The extension map holds its own clone, so the handler still finds one. With that line added, the handler below works.

use axum::extract::Extension;

async fn handler(Extension(user_id): Extension<UserId>) -> String {
    format!("Your user ID is: {}", user_id.0)
}

A request with -H "x-user-id: 42" now returns a 200 with the body "Your user ID is: 42". A request without the header still gets a 400, because the extractor rejects it before the handler runs. The two behaviours together are the complete picture. Validation decides whether the handler runs, and the explicit insert decides what the handler can see. Forgetting the insert is the single most common cause of a 500 in code that uses this middleware.

A Custom Rejection That Returns JSON

The rejection type is whatever the extractor declares, as long as it implements IntoResponse. A plain StatusCode gives a bare status with an empty body. A Response gives full control. A custom error type gives a consistent error format across the application. The example below defines an ApiError that renders as a JSON object with an error field, and uses it as the rejection of an auth extractor. The serde_json crate must be declared in Cargo.toml for the json! macro.

Cargo.toml
[dependencies]
axum = "0.8"
serde_json = "1"
tokio = { version = "1", features = ["full"] }
src/main.rs
use axum::{
    extract::FromRequestParts,
    http::{request::Parts, StatusCode},
    middleware,
    response::{IntoResponse, Response},
    routing::get,
    Json, Router,
};
use serde_json::json;

#[derive(Debug)]
pub struct ApiError {
    status: StatusCode,
    message: String,
}

impl IntoResponse for ApiError {
    fn into_response(self) -> Response {
        (self.status, Json(json!({ "error": self.message }))).into_response()
    }
}

struct RequireAuth;

impl FromRequestParts<()> for RequireAuth {
    type Rejection = ApiError;

    async fn from_request_parts(parts: &mut Parts, _state: &()) -> Result<Self, Self::Rejection> {
        let ok = parts
            .headers
            .get("authorization")
            .and_then(|value| value.to_str().ok())
            .map(|value| value == "Bearer good-token")
            .unwrap_or(false);
        if ok {
            Ok(RequireAuth)
        } else {
            Err(ApiError {
                status: StatusCode::UNAUTHORIZED,
                message: "missing or invalid token".to_string(),
            })
        }
    }
}

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

A request without the token gets a 401 with the body {"error":"missing or invalid token"}. A request with the right token gets the handler body. The middleware converts the rejection into the response automatically, so the extractor author decides the error format once and every route behind the layer shares it. The Json import comes from the axum crate itself, and the json! macro comes from serde_json, which is why both the import and the dependency matter. Leaving serde_json out of Cargo.toml while using json! fails to compile.

Applying the Gate to Some Routes and Not Others

A gate is rarely wanted on every route. A public home page should not demand a user id, while the API routes behind it should. The layer can be attached to a nested router, so it runs only for requests that match that router. The example below uses the UserId extractor with the explicit extensions insert, so the protected handlers can read the id.

src/main.rs
use axum::{
    extract::{Extension, FromRequestParts},
    http::{request::Parts, StatusCode},
    middleware,
    response::{Html, IntoResponse, Response},
    routing::get,
    Router,
};

#[derive(Debug, Clone)]
pub struct UserId(pub u64);

impl FromRequestParts<()> for UserId {
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, _state: &()) -> Result<Self, Self::Rejection> {
        let user_id = parts
            .headers
            .get("x-user-id")
            .and_then(|value| value.to_str().ok())
            .and_then(|value| value.parse::<u64>().ok())
            .ok_or_else(|| {
                (StatusCode::BAD_REQUEST, "Missing or invalid x-user-id header").into_response()
            })?;
        let user = UserId(user_id);
        parts.extensions.insert(user.clone());
        Ok(user)
    }
}

async fn home() -> Html<&'static str> {
    Html("Welcome, anonymous visitor!")
}

async fn list_users(Extension(user_id): Extension<UserId>) -> Html<String> {
    Html(format!("Listing users for user {}", user_id.0))
}

async fn list_posts(Extension(user_id): Extension<UserId>) -> Html<String> {
    Html(format!("Listing posts for user {}", user_id.0))
}

#[tokio::main]
async fn main() {
    let api_routes = Router::new()
        .route("/users", get(list_users))
        .route("/posts", get(list_posts))
        .layer(middleware::from_extractor::<UserId>());
    let app = Router::new()
        .route("/", get(home))
        .nest("/api", api_routes);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Test the three routes with curl. The home page answers without any header. /api/users without a header returns a 400. /api/users with -H "x-user-id: 7" returns "Listing users for user 7". Nesting is the mechanism here. The nest call mounts the small router under /api, and the layer on that small router covers only its routes. The same grouping works with any set of routes that share a gate, and it keeps the public routes untouched.

What the Extractor Is Allowed to Need

The requirements on the extractor are smaller than most beginners expect. It needs to implement FromRequestParts<S> for the state type the layer uses, which is () here, and it needs to be 'static, which means it holds no borrowed data with a limited lifetime. It does not need to be Clone, Send, or Sync. Axum's own tests assert that a layer built from an extractor that is neither Send nor Sync still works, because the extractor type itself is never cloned or shared between threads. Do not add derives to satisfy a bound that does not exist.

The state type is fixed to () for this function. An extractor that needs application state, such as a list of valid tokens held in state, cannot be used here. The stateful form of the same function takes the state as an argument and passes it into the extractor. That is the one difference between the two forms, and it is the only reason to switch.

The body rule is the other hard limit. An extractor that reads the request body cannot run in this middleware, because the middleware only receives the request parts. Trying from_extractor::<Json<Payload>>() fails to compile with an error saying Json<Payload> does not implement FromRequestParts<()>. That error is the compiler telling the truth about the design. Body data belongs in the handler, where the full request is available.

A body extractor will not compile here:

Json<T>, String, and other extractors that read the body implement FromRequest, not FromRequestParts, so from_extractor rejects them at compile time. Keep body extraction in the handler, and keep this middleware for checks that only need the method, the URI, the headers, or the extensions.

The Same Extractor as Middleware and as a Handler Parameter

The official documentation points out the situation from_extractor is made for. You have a type that you sometimes want to use as an extractor and sometimes as middleware. The UserId extractor from this page works in both roles, because the same FromRequestParts implementation serves both. As a handler parameter it delivers the value directly, with no extensions bookkeeping and no discarded copy.

src/main.rs
use axum::{
    extract::FromRequestParts,
    http::{request::Parts, StatusCode},
    response::{IntoResponse, Response},
    routing::get,
    Router,
};

#[derive(Debug, Clone)]
pub struct UserId(pub u64);

impl FromRequestParts<()> for UserId {
    type Rejection = Response;

    async fn from_request_parts(parts: &mut Parts, _state: &()) -> Result<Self, Self::Rejection> {
        let user_id = parts
            .headers
            .get("x-user-id")
            .and_then(|value| value.to_str().ok())
            .and_then(|value| value.parse::<u64>().ok())
            .ok_or_else(|| {
                (StatusCode::BAD_REQUEST, "Missing or invalid x-user-id header").into_response()
            })?;
        Ok(UserId(user_id))
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new().route(
        "/",
        get(|UserId(id): UserId| async move { format!("Your user ID is: {}", id) }),
    );
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request with -H "x-user-id: 9" returns "Your user ID is: 9". A request without the header gets a 400, because the same rejection runs in the handler path too. This version is simpler than the middleware version whenever only one or two handlers need the value, because the extractor runs once and hands the value straight to the handler. The middleware version earns its place when many routes share the same check, or when the check must run for handlers that do not declare the extractor at all. A router can even mix the two. One route can carry the middleware layer while another route takes the extractor as a parameter, and both enforce the same rule, because both run the same implementation.

When to Use from_extractor and When Not To

Use from_extractor when one extractor should guard several routes and the handler does not need the extracted value. An auth check that only needs to say yes or no is the cleanest case. A header format check that every route behind the layer must pass is another. The value of the tool is that the check is written once, in the extractor, and applied by one layer, instead of being repeated in every handler signature.

Do not use it when the handler needs the extracted value and the extractor is cheap to run again. In that case, taking the extractor directly as a handler parameter is simpler, and it delivers the value without any extension bookkeeping. The middleware form earns its place when the same check guards many routes, or when the check must run even for handlers that do not declare the extractor. When the handler does need the value, add the explicit parts.extensions.insert line and accept the extra moving part, because there is no other channel.

A plain async function middleware is the alternative when the work does not fit the extractor shape at all, for example when the middleware must change the response after the handler runs, or when it must read the body. The extractor form only runs before the handler, and it only sees the parts. That narrow shape is its strength when the job is validation, and its limit when the job is anything else.

Common Mistakes and How to Fix Them

The first mistake is expecting the handler to receive the extracted value. The value is discarded. Either insert it into parts.extensions inside the extractor, or take the extractor as a handler parameter instead.

The second mistake is using a body extractor such as Json<T> with from_extractor. It does not compile, because the middleware only sees the request parts. Move the body extraction into the handler.

The third mistake is declaring a rejection type that does not implement IntoResponse. The middleware must turn the rejection into a response, so a type without that trait fails to compile at the layer. Use Response, a StatusCode, a tuple of status and body, or a custom type with an IntoResponse implementation.

The fourth mistake is adding Clone, Send, or Sync derives to the extractor because a tutorial said they were required. They are not required, and adding them changes nothing. The real bounds are FromRequestParts<S> and 'static.

The fifth mistake is applying the layer to the whole router when only some routes need the gate. Use a nested router for the guarded group, so the public routes stay open and the gate only runs where it belongs.

Summary

The decision to use from_extractor turns on one question, and it is not whether the extractor is convenient. It is whether the handler needs the value. When the answer is no, the function is the tidiest gate Axum offers, because the extractor is written once and the layer enforces it across every route it covers, with the rejection deciding what the client sees. When the answer is yes, the choice branches. A cheap extractor is best taken directly as a handler parameter, which delivers the value with no extra machinery. A gate that must also deliver its value needs the explicit extensions insert, one line inside from_request_parts, and the handler reads it back with Extension. That single line is the difference between a 200 that greets the user by id and a 500 that hides the cause.