fromextractorwith_state - Stateful Extractor Middleware in Axum

Learn how axum middleware from_extractor_with_state runs an extractor with application state before handlers, with API key checks, user lookups, and custom rejections

Some checks need more than the request. An API key check needs the expected key, which is configuration. A token check needs a list of valid tokens, which lives in a database or a map. A permission check needs roles, which live in state. The plain extractor middleware cannot help there, because its extractor receives no state. middleware::from_extractor_with_state is the same gate with state added. It runs an extractor before the handler, hands that extractor the application state, and returns the extractor's rejection when the check fails.

The Shape of a Stateful Extractor Gate

A stateful extractor implements FromRequestParts<S>, where S is the application state type, instead of FromRequestParts<()>. The middleware is built with a function that takes the state as a required argument.

pub fn from_extractor_with_state<E, S>(state: S) -> FromExtractorLayer<E, S>

The two type parameters are E for the extractor and S for the state. The function takes one value argument, the state, and returns a layer. Every call site must pass the state value. Leaving it out fails to compile with an error saying the function takes one argument but zero were supplied. That error is easy to fix once it is expected, and it is the first thing to check when a call to this function does not compile.

Think of a guard at a door who now holds a list of valid passes. The list is the state. The guard checks the visitor's pass against the list, lets the visitor through when it matches, and turns the visitor away when it does not. The handler inside still never sees the pass unless the extractor leaves a copy behind in the request extensions. The discard rule from the plain form applies here too. The middleware runs the extractor and drops the returned value. Only what the extractor stores in parts.extensions reaches the handler.

The Smallest Example, an API Key Check

Start with a state struct that holds one expected API key, and an extractor that compares the x-api-key header against it. 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-with-state-demo"
version = "0.1.0"
edition = "2021"

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

#[derive(Clone)]
struct AppState {
    expected_api_key: String,
}

struct ValidApiKey;

impl FromRequestParts<AppState> for ValidApiKey {
    type Rejection = (StatusCode, &'static str);

    async fn from_request_parts(
        parts: &mut Parts,
        state: &AppState,
    ) -> Result<Self, Self::Rejection> {
        let provided = parts
            .headers
            .get("x-api-key")
            .and_then(|value| value.to_str().ok());
        if provided == Some(state.expected_api_key.as_str()) {
            Ok(ValidApiKey)
        } else {
            Err((StatusCode::UNAUTHORIZED, "missing or invalid api key"))
        }
    }
}

async fn protected_handler() -> &'static str {
    "Welcome to the protected area"
}

#[tokio::main]
async fn main() {
    let state = AppState {
        expected_api_key: "super-secret-key".to_string(),
    };
    let app = Router::new()
        .route("/protected", get(protected_handler))
        .route_layer(middleware::from_extractor_with_state::<ValidApiKey, AppState>(
            state.clone(),
        ))
        .with_state(state);
    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 401 with the body "missing or invalid api key". With -H "x-api-key: super-secret-key" the response is a 200 with the body "Welcome to the protected area".

Walk through the pieces. AppState derives Clone, because Axum needs to clone state wherever a copy is required. ValidApiKey is an empty struct, because it carries no data and only runs the check. Its FromRequestParts<AppState> implementation receives state: &AppState as its second argument, which is the reference the middleware passes in. The rejection type is a tuple of a status code and a message, which converts into a response on its own. The handler never mentions ValidApiKey. It runs only when the key matched. The router setup passes state.clone() to the layer and the original state to .with_state, because the value is needed in both places and Rust does not let one value be moved twice.

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

If the request without a key gets a 401 and the request with the right key gets the handler body, the extractor is reading state and gating the route. If both requests get a 401, check that the state value and the header value match exactly, including any stray spaces.

How the Middleware Runs the Extractor With State

When the layer is attached, each request to a covered route goes through the same four steps as the plain form, with state added to step two. The layer takes the request parts. It runs the extractor on those parts, passing a reference to the stored state. 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.

The state the extractor receives is a reference, &AppState, not an owned copy. That matters for what the extractor can return. It cannot hand the handler a reference into state, because the borrow ends when the extractor returns. It must clone the data it needs into an owned value, which is what the user lookup example does next. The layer itself holds a clone of the state, made when from_extractor_with_state was called, and it passes a reference to that clone into the extractor on every request.

The State Type Must Match in Three Places

The state type appears in three places, and all three must agree. It appears in the extractor implementation, as the S in FromRequestParts<AppState>. It appears in the layer call, as the second type parameter in from_extractor_with_state::<ValidApiKey, AppState>. It appears in the router setup, as the value passed to .with_state(state). When any one of them names a different type, the compiler reports a trait bound failure, and the error usually points at the router creation or the layer call rather than at the line that is actually wrong.

Check all three state types when the router fails to compile:

If the compiler reports a trait bound failure at the router or at the serve call, compare the state type in the extractor implementation, in the from_extractor_with_state type parameters, and in the .with_state argument. One of them names a different type. The error message rarely names the mismatch directly, so the three-way check is the fastest way to find it.

The state argument itself is easy to forget, because the plain form takes no arguments at all. The call from_extractor_with_state::<ValidApiKey, AppState>() with no value fails with an error saying the function takes one argument but zero were supplied. The fix is to pass state.clone(). Cloning is needed because the same state value is usually also passed to .with_state, and a value can only be moved once.

Passing Extracted Data to the Handler

The minimal example validated the key and threw the result away. The handler had no idea who the caller was. Many applications need the handler to know. The way to pass data from the extractor to the handler is the request extensions map, and the extractor writes to it itself, inside from_request_parts. The example below keeps a user name in state, builds an AuthenticatedUser from it when the key is valid, and stores a clone in the extensions. The handler reads it back with the Extension extractor.

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

#[derive(Clone)]
struct AppState {
    expected_api_key: String,
    user_name: String,
}

#[derive(Clone)]
struct AuthenticatedUser {
    name: String,
}

impl FromRequestParts<AppState> for AuthenticatedUser {
    type Rejection = (StatusCode, &'static str);

    async fn from_request_parts(
        parts: &mut Parts,
        state: &AppState,
    ) -> Result<Self, Self::Rejection> {
        let provided = parts
            .headers
            .get("x-api-key")
            .and_then(|value| value.to_str().ok());
        if provided != Some(state.expected_api_key.as_str()) {
            return Err((StatusCode::UNAUTHORIZED, "missing or invalid api key"));
        }
        let user = AuthenticatedUser {
            name: state.user_name.clone(),
        };
        parts.extensions.insert(user.clone());
        Ok(user)
    }
}

async fn protected_handler(Extension(user): Extension<AuthenticatedUser>) -> String {
    format!("Welcome, {}! You are authenticated.", user.name)
}

#[tokio::main]
async fn main() {
    let state = AppState {
        expected_api_key: "super-secret-key".to_string(),
        user_name: "Alice".to_string(),
    };
    let app = Router::new()
        .route("/protected", get(protected_handler))
        .route_layer(middleware::from_extractor_with_state::<AuthenticatedUser, AppState>(
            state.clone(),
        ))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request with the right key returns "Welcome, Alice! You are authenticated." A request without the key gets a 401, and the handler never runs. The line parts.extensions.insert(user.clone()) is the whole mechanism. The middleware discards the returned user, so the extension map holds the only copy the handler can reach. The user.clone() call is necessary because the extractor returns the value after inserting it. Without the insert, the same request would pass the gate and then fail in the handler with a 500, because Extension<AuthenticatedUser> would find nothing stored. That 500 is a runtime failure, not a compile error, so test the happy path with a real request rather than trusting the types.

A missing insert turns a passing request into a 500:

When the handler declares Extension<AuthenticatedUser> but the extractor never called parts.extensions.insert, every request that passes the gate fails in the handler with a 500. The middleware succeeded and the handler failed, which makes the cause hard to see in logs. Always pair an Extension in a handler with an insert in the extractor.

A Realistic Example, Looking Up a User by Token

Real authentication rarely compares one fixed key. It looks a token up in a store and finds the user behind it. The example below keeps that store in state as a HashMap from token strings to user records. The extractor parses the Authorization header, strips the Bearer prefix, looks the token up, and either builds an AuthenticatedUser or rejects the request. Two routes share the layer, and one handler checks the user's role.

src/main.rs
use axum::{
    extract::{Extension, FromRequestParts},
    http::{request::Parts, StatusCode},
    middleware,
    routing::get,
    Router,
};
use std::collections::HashMap;

#[derive(Clone)]
struct User {
    id: u64,
    name: String,
    role: String,
}

#[derive(Clone)]
struct AppState {
    users: HashMap<String, User>,
}

#[derive(Clone)]
struct AuthenticatedUser {
    id: u64,
    name: String,
    role: String,
}

impl FromRequestParts<AppState> for AuthenticatedUser {
    type Rejection = (StatusCode, &'static str);

    async fn from_request_parts(
        parts: &mut Parts,
        state: &AppState,
    ) -> Result<Self, Self::Rejection> {
        let token = parts
            .headers
            .get("authorization")
            .and_then(|value| value.to_str().ok())
            .and_then(|value| value.strip_prefix("Bearer "))
            .ok_or((StatusCode::UNAUTHORIZED, "missing bearer token"))?;
        let user = state
            .users
            .get(token)
            .ok_or((StatusCode::UNAUTHORIZED, "invalid token"))?;
        let authenticated = AuthenticatedUser {
            id: user.id,
            name: user.name.clone(),
            role: user.role.clone(),
        };
        parts.extensions.insert(authenticated.clone());
        Ok(authenticated)
    }
}

async fn admin_dashboard(Extension(user): Extension<AuthenticatedUser>) -> String {
    if user.role != "admin" {
        return "You do not have admin access".to_string();
    }
    format!("Admin dashboard for {} (ID {})", user.name, user.id)
}

async fn user_profile(Extension(user): Extension<AuthenticatedUser>) -> String {
    format!("Profile for {} (ID {})", user.name, user.id)
}

#[tokio::main]
async fn main() {
    let mut users = HashMap::new();
    users.insert(
        "token-alice".to_string(),
        User {
            id: 1,
            name: "Alice".to_string(),
            role: "admin".to_string(),
        },
    );
    users.insert(
        "token-bob".to_string(),
        User {
            id: 2,
            name: "Bob".to_string(),
            role: "member".to_string(),
        },
    );
    let state = AppState { users };
    let app = Router::new()
        .route("/admin", get(admin_dashboard))
        .route("/profile", get(user_profile))
        .route_layer(middleware::from_extractor_with_state::<AuthenticatedUser, AppState>(
            state.clone(),
        ))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Test it with curl. Alice's token on /admin returns "Admin dashboard for Alice (ID 1)". Bob's token on /admin returns "You do not have admin access". Both tokens pass the middleware, because both are valid, and the handler decides what the role allows. Bob's token on /profile returns "Profile for Bob (ID 2)". A request with no token gets a 401 with "missing bearer token", and a request with an unknown token gets a 401 with "invalid token".

Two details in the extractor are worth noticing. The .ok_or(...)? calls turn a missing value into an early rejection, so the function reads top to bottom without nested matching. The name and role fields are cloned out of state, because the extractor receives state by reference and must return owned data. In a real application the HashMap would be a database pool, and the lookup would be an async query instead of a map read, but the shape stays the same. The state holds the store, the extractor queries it, and the handler trusts the result.

A Custom Rejection That Returns JSON

The examples so far used a tuple of status and message as the rejection, which renders as plain text. A custom error type gives a consistent JSON error format. The example below defines an ApiError with a status and a message, implements IntoResponse for it so it renders as a JSON object with an error field, and uses it as the rejection of the ValidApiKey extractor. The serde_json crate must be declared in Cargo.toml for the json! macro, and Json is imported from the axum crate itself.

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(Clone)]
struct AppState {
    expected_api_key: String,
}

struct ValidApiKey;

struct ApiError {
    status: StatusCode,
    message: &'static str,
}

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

impl FromRequestParts<AppState> for ValidApiKey {
    type Rejection = ApiError;

    async fn from_request_parts(
        parts: &mut Parts,
        state: &AppState,
    ) -> Result<Self, Self::Rejection> {
        let provided = parts
            .headers
            .get("x-api-key")
            .and_then(|value| value.to_str().ok());
        if provided == Some(state.expected_api_key.as_str()) {
            Ok(ValidApiKey)
        } else {
            Err(ApiError {
                status: StatusCode::UNAUTHORIZED,
                message: "missing or invalid api key",
            })
        }
    }
}

async fn protected_handler() -> &'static str {
    "Welcome to the protected area"
}

#[tokio::main]
async fn main() {
    let state = AppState {
        expected_api_key: "super-secret-key".to_string(),
    };
    let app = Router::new()
        .route("/protected", get(protected_handler))
        .route_layer(middleware::from_extractor_with_state::<ValidApiKey, AppState>(
            state.clone(),
        ))
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request without the key now gets a 401 with the body {"error":"missing or invalid api key"}. A request with the right key 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. Leaving serde_json out of Cargo.toml while using json! fails to compile, so the dependency line is part of the example, not an afterthought.

Covering Some Routes and Leaving Others Public

The layer can be attached to a whole router with .layer, or to the routes already added with .route_layer. A whole-router layer wraps every route added before the call, including public ones, so a public route added before it would demand a key too. When some routes are public and others are protected, the cleanest shape is two small routers merged into one. Each router holds its own routes, the protected one carries the layer, and the state is registered once on the merged router.

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

#[derive(Clone)]
struct AppState {
    expected_api_key: String,
}

struct ValidApiKey;

impl FromRequestParts<AppState> for ValidApiKey {
    type Rejection = (StatusCode, &'static str);

    async fn from_request_parts(
        parts: &mut Parts,
        state: &AppState,
    ) -> Result<Self, Self::Rejection> {
        let provided = parts
            .headers
            .get("x-api-key")
            .and_then(|value| value.to_str().ok());
        if provided == Some(state.expected_api_key.as_str()) {
            Ok(ValidApiKey)
        } else {
            Err((StatusCode::UNAUTHORIZED, "missing or invalid api key"))
        }
    }
}

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

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

#[tokio::main]
async fn main() {
    let state = AppState {
        expected_api_key: "super-secret-key".to_string(),
    };
    let protected = Router::new()
        .route("/protected", get(protected_handler))
        .route_layer(middleware::from_extractor_with_state::<ValidApiKey, AppState>(
            state.clone(),
        ));
    let public = Router::new().route("/public", get(public_handler));
    let app = Router::new()
        .merge(protected)
        .merge(public)
        .with_state(state);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

A request to /public answers with no key at all. A request to /protected without a key gets a 401, and with the right key it gets the protected text. The merge call combines the two routers into one, and .with_state is called once on the result. The same grouping works for any set of routes that share a gate. The rule behind it is worth remembering. route_layer only covers routes added before it is called, so a route added after the call escapes the layer. Add the protected routes first, then the layer, or group them in their own router as shown here.

Routes added after route_layer escape it:

A layer only wraps the routes that already exist when it is applied. A route added after the route_layer call runs with no middleware. Add all protected routes before the call, or put them in their own router and merge, so no route slips through unguarded.

What the Extractor Can and Cannot Do

The extractor implements FromRequestParts<S>, not FromRequest. The difference is the body. FromRequestParts sees the method, the URI, the headers, and the extensions, and leaves the body untouched for the handler. FromRequest consumes the body, which would leave the handler with nothing to read. An extractor that reads the body, such as Json<T>, does not compile with this middleware, because the middleware only receives the request parts. Keep body extraction in the handler.

The extractor runs on every request to the covered routes, so expensive work inside it is paid on every request. A database query per request adds up fast. When the same data is needed again and again, cache it in state at startup, or keep the lookup cheap. The extractor also receives state by reference, so anything it returns must be owned. Clone the fields it needs, or build a fresh owned value from them.

The plain extractor middleware and this stateful form differ in exactly one place, the state. When the extractor needs nothing from the application, the plain form is simpler, because it takes no state argument. When the extractor reads configuration, a store, or a cache, this form is the one to use. Everything else, the discard rule, the extensions channel, the rejection handling, and the scoping, is identical.

Common Mistakes and How to Fix Them

The first mistake is calling the function without the state argument. It fails to compile with an error saying the function takes one argument but zero were supplied. Pass state.clone().

The second mistake is writing a handler that expects the extracted value without an insert. The middleware discards the value, so the handler finds nothing in the extensions and fails with a 500. Add parts.extensions.insert inside the extractor.

The third mistake is using FromRequest instead of FromRequestParts. A body extractor does not compile here, and the fix is to move the body extraction into the handler.

The fourth mistake is putting the state type in only some of the three places it belongs. The extractor implementation, the layer type parameters, and the .with_state argument must all name the same type, or the router fails to compile.

The fifth mistake is adding a route after route_layer and expecting it to be protected. It is not covered. Add the route before the call, or group protected routes in their own router.

The sixth mistake is returning a reference to state-owned data from the extractor. The borrow checker rejects it, because the state reference ends when the extractor returns. Clone the data into an owned value instead.

Summary

The choice between the two extractor middlewares turns on one question, whether the extractor needs application state. When the answer is no, the plain form is enough, and passing state would add noise. When the answer is yes, this form is the answer, and the shape is always the same. Implement FromRequestParts<S> for the state type, pass state.clone() to from_extractor_with_state, register the state with .with_state, and let the rejection decide what the client sees when the check fails. The two rules that save the most debugging time are the ones this page verified directly. The state argument is required at every call site, and the extracted value is discarded, so anything the handler needs must be stored in the extensions by the extractor itself. With those two rules in hand, a stateful extractor gate is a small, predictable piece of code, and the handler behind it can trust that every request it sees already passed the check.