Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 38 ยท State and Middleware

Request Extensions and Request IDs in Axum

Pass per-request data from middleware to handlers with Axum extensions, build a CurrentUser pattern, add request ids for log correlation, and use ConnectInfo and MatchedPath.

Shared state holds things that live as long as the server: pools, configuration, caches. But some data belongs to a single request: who the caller is, which request id was assigned, what the matched route pattern was. Axum carries such values in the request's extensions, a small type-indexed map attached to every http::Request.

This lesson shows how middleware writes into extensions, how handlers read from them, how request ids make logs readable, and which built-in extractors read request metadata.

What extensions are

The request has a method, a URI, headers and a body. It also has extensions(): a map from a type to one value of that type. You insert a value with req.extensions_mut().insert(value) and read it with req.extensions().get::<T>(). Because the key is the type, you create a distinct type (a newtype) for each piece of data:

Rust
#[derive(Clone, Debug)]
struct RequestId(String);

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

Two rules follow from the design: a type holds at most one value (inserting a second RequestId replaces the first), and values must be Clone + Send + Sync + 'static.

The Extension extractor

Rust
use axum::{extract::Extension, routing::get, Router};

async fn me(Extension(user): Extension<CurrentUser>) -> String {
    format!("hello {} (id {})", user.name, user.id)
}

Extension<T> clones T out of the request. If nothing inserted a T, the extractor fails with a 500 Internal Server Error, because a missing extension means the programmer forgot a layer, not that the client did something wrong. Use Option<Extension<T>> for values that are truly optional.

The authentication pattern

The most common use of extensions: a middleware authenticates, stores the user, and handlers simply ask for the user.

Rust
use axum::{
    extract::{Request, State},
    http::{header::AUTHORIZATION, StatusCode},
    middleware::{self, Next},
    response::Response,
};

async fn authenticate(
    State(state): State<AppState>,
    mut req: Request,
    next: Next,
) -> Result<Response, StatusCode> {
    let token = req
        .headers()
        .get(AUTHORIZATION)
        .and_then(|v| v.to_str().ok())
        .and_then(|v| v.strip_prefix("Bearer "))
        .ok_or(StatusCode::UNAUTHORIZED)?;

    let user = state.sessions.find(token).ok_or(StatusCode::UNAUTHORIZED)?;
    req.extensions_mut().insert(user);        // CurrentUser
    Ok(next.run(req).await)
}

fn protected(state: AppState) -> Router<AppState> {
    Router::new()
        .route("/me", get(me))
        .route_layer(middleware::from_fn_with_state(state, authenticate))
}

The handler me can only run after authenticate put a CurrentUser into the request. If you ever register me outside the protected router, the Extension extractor fails at run time with 500. A common refinement is a custom extractor CurrentUser that implements FromRequestParts and reads the extension itself, so the failure becomes 401. You will see the full version in the JWT and authentication middleware lessons.

Request ids

When ten requests run at once, log lines from different requests interleave. A request id is a short unique value generated for each request and included in every log line and in the response, so you can follow one request through your logs and a customer can quote the id when something fails.

The usual recipe has three steps:

  1. Take the client's x-request-id header if it is present and well-formed (so a gateway's id survives), otherwise generate a UUID.
  2. Store it as a RequestId extension and in a tracing span.
  3. Copy it into the response headers.

tower-http has layers for steps 1 and 3 (see the previous lesson). Doing it with from_fn shows the mechanics:

Rust
use tracing::Instrument;

async fn request_id(mut req: Request, next: Next) -> Response {
    let id = req
        .headers()
        .get("x-request-id")
        .and_then(|v| v.to_str().ok())
        .filter(|v| v.len() <= 64)
        .map(str::to_owned)
        .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());

    req.extensions_mut().insert(RequestId(id.clone()));

    let span = tracing::info_span!("request", id = %id, method = %req.method(), path = %req.uri().path());
    let mut res = next.run(req).instrument(span).await;

    res.headers_mut().insert("x-request-id", id.parse().unwrap());
    res
}

Everything logged while the request runs (inside handlers too, thanks to the span) now carries id=.... Also include the id in your error responses; it is the single most helpful field in a support ticket.

Other request metadata extractors

Extractor Gives you Notes
ConnectInfo<SocketAddr> the peer address needs into_make_service_with_connect_info::<SocketAddr>() when serving; behind a proxy use x-forwarded-for instead
MatchedPath the route pattern, e.g. /users/{id} ideal as a metrics label because it has low cardinality
OriginalUri the full URI before nesting strips a prefix for logs and absolute links
Host (axum-extra) the host name tenant-per-subdomain apps
Request the entire request for middleware or total control

Stand-in: a typed extensions map and a missing value

The Extension extractor is just a typed lookup that can fail. This model reproduces it, including the "500 when the layer is missing" behaviour and the "second insert replaces the first" rule.

Rust Stand-in: typed extensions, insert, replace and missing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Stand-in: request ids and log correlation

Here four "requests" run interleaved on purpose (as if concurrent), each with its own id. Without ids the output is a jumble; with ids you can group the lines per request. The model uses a thread-safe counter to create ids the way a layer would, and honours a client-supplied id when it is valid.

Rust Stand-in: request ids make interleaved logs readable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Common mistakes

  • Storing mutable shared data in an extension and expecting changes to be seen by other requests. Extensions live and die with one request; use state for shared data.
  • Using a bare String or u64 as an extension: any other middleware that inserts a String replaces yours. Always use a newtype.
  • Trusting a client-supplied request id blindly: restrict length and characters, as the model does.
  • Forgetting that Extension fails with 500, not 401, when the middleware was not applied. Test the protected routes without credentials and make sure you see 401.

This is the last lesson of the first half of the course. The next chapter explains the machinery underneath everything you have written so far: futures, Tokio tasks and Tower services.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the key of the extensions map?

    Extensions are indexed by type, so each kind of data needs its own type, usually a newtype.
  2. 2. What happens if a handler uses Extension<CurrentUser> but no middleware inserted one?

    A missing extension is a programming error, answered with 500. A custom extractor can turn it into a 401.
  3. 3. When should data live in State rather than in extensions?

    State lasts as long as the application and is shared. Extensions carry data of one request.
  4. 4. Why is MatchedPath a good label for metrics?

    Using the raw URI would create one label value per id and overwhelm a metrics system.

Summary

  • Extensions are a per-request, type-indexed map: middleware inserts values, handlers read them with Extension<T>.
  • Use newtypes for each value; a missing extension causes a 500, so install the layer on every route that needs it.
  • The authentication pattern is middleware that inserts CurrentUser, applied with route_layer.
  • Request ids (header, extension, tracing span, response header) make interleaved logs traceable.
  • ConnectInfo, MatchedPath and OriginalUri expose request metadata.

Next: Async, Await and Futures