TypedHeader - Typed HTTP Header Extraction in Axum

Learn how to use the TypedHeader extractor from axum-extra to safely parse HTTP headers into strongly typed Rust values, including setup, usage patterns, handling missing or invalid headers, and common beginner mistakes.

HTTP headers are small pieces of text that travel with every request. They tell the server things like what kind of browser is calling, what format the client wants back, or what credentials the caller is presenting. Raw header tools give you bytes and strings. TypedHeader goes one step further: it parses a header into a specific Rust type so you can work with it using methods and fields instead of string manipulation.

TypedHeader lives in the axum-extra crate, not in the core axum crate. That separation keeps the main framework lean while still offering a rich set of typed header tools when you need them. The idea is simple: instead of grabbing a HeaderValue for user-agent and then manually splitting on / or checking for substrings, you extract a UserAgent value that wraps the raw header string and gives it back through as_str(). It does not parse the browser name or version out of the string; if you need those parts, you parse the string yourself.

What Problem TypedHeader Solves

Raw headers are just strings. Parsing them correctly is error‑prone because every header has its own grammar. The Authorization header can be Basic base64... or Bearer token.... The Accept header can contain quality values, wildcards, and multiple comma‑separated entries. The User-Agent string has a format that varies wildly between browsers and tools.

If you hand‑write that parsing inside every handler, you end up repeating code and risking subtle bugs. TypedHeader centralizes the parsing logic in types that come from the well‑tested headers crate. When you write TypedHeader<UserAgent>, Axum looks up the user-agent header, passes its value to the UserAgent type's decode implementation, and only calls your handler if parsing succeeds. If the header is absent or malformed, your handler never runs; Axum returns an error response automatically.

This is the same pattern you saw with Path<u32> and Query<T>: the framework validates and converts before your business logic begins. Your handler receives a value you can trust.

Where TypedHeader Lives:

TypedHeader is not part of the main axum crate. You must add axum-extra as a dependency and enable its typed-header feature. This page assumes you already have an Axum project set up. If you only have axum in your Cargo.toml, you will need to add one more line.

Adding axum-extra with the typed-header Feature

Before you can use TypedHeader, your project needs two crates: axum (which you already have) and axum-extra. The axum-extra crate is split into features so you only pull in what you use. The feature you need is called typed-header.

1

Open your Cargo.toml

Navigate to the Cargo.toml file at the root of your Axum project. This file lists all dependencies and their versions.

[package]
name = "my-axum-app"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
2

Add the axum-extra dependency

Add axum-extra to the [dependencies] section. In addition to the crate itself, specify the feature typed-header.

[dependencies]
axum = "0.8"
axum-extra = { version = "0.12", features = ["typed-header"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
3

Run cargo build to fetch the new crates

Save the file, then run cargo build in your terminal. This downloads axum-extra, the headers crate it depends on, and compiles everything. If you see errors about version conflicts, update your axum version to match what axum-extra expects. The latest versions are designed to work together.

Dependency Added Correctly:

After a successful build, you can import TypedHeader from axum_extra::TypedHeader. You will also need specific header types from axum_extra::headers, such as UserAgent, Authorization, or ContentType.

Your First TypedHeader Example: Extracting User-Agent

Start with the simplest possible use: a handler that logs which browser made the request. The User-Agent header is sent by virtually every HTTP client, so it is a safe first choice.

use axum::{routing::get, Router};
use axum_extra::{headers::UserAgent, TypedHeader};
async fn show_user_agent(TypedHeader(user_agent): TypedHeader<UserAgent>) -> String {
    format!("Your user agent is: {}", user_agent.as_str())
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/ua", get(show_user_agent));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

Run the server and make a request with curl:

curl http://127.0.0.1:3000/ua

You will see output like:

Your user agent is: curl/8.5.0

The handler receives a TypedHeader<UserAgent> extractor. Because TypedHeader is a tuple struct, you destructure it with TypedHeader(user_agent) to get the inner UserAgent value. That value is a thin wrapper around the raw header string: it gives you as_str() to get the original string back, but it does not parse the browser name or version out of it. If you need those parts, you have to parse the string yourself.

What happened behind the scenes? Axum saw the TypedHeader<UserAgent> argument, looked for the user-agent header in the incoming request, found its HeaderValue, passed that value to UserAgent's decoding function, and inserted the parsed result into your handler. If the header was missing, Axum would have returned a 400 Bad Request response before your handler ever ran.

How TypedHeader Works Under the Hood

TypedHeader<T> implements FromRequestParts for any T that implements the Header trait from the headers crate. The Header trait has three required parts:

  • fn name() -> &'static HeaderName - tells Axum which header to look for.
  • fn decode<'i, I>(values: &mut I) -> Result<Self, Error> - parses the header value(s) into Self.
  • fn encode<E>(&self, values: &mut E) - used when you want to write a header (not needed for extraction, but defined for symmetry).

TypedHeader itself is a wrapper that contains a value of type T. When Axum extracts it, it calls T::decode with the header value(s) found in the request. If decoding succeeds, you get TypedHeader(T). If the header is missing, Axum produces a rejection. If the header exists but cannot be decoded, Axum also produces a rejection. In both cases your handler is not called; instead, a default error response is sent back.

The headers crate provides dozens of pre‑made header types, each with the correct decoding logic. That means you never have to write a parser for User-Agent, Authorization, Content-Type, Content-Length, ETag, or many others. You just import the type and let the crate do the work. (There is no Accept type in the headers crate, so an Accept header still needs manual parsing through HeaderMap.)

TypedHeader is not a body extractor:

Because TypedHeader reads only request parts (the headers), it does not consume the request body. You can combine it with other extractors that read the body, such as Json or String, as long as you follow the rule that body-consuming extractors come last in the parameter list.

Common Typed Headers You Can Extract

The headers crate (re‑exported as axum_extra::headers) contains a wide variety of header types. Here are a few that you will likely use in real applications.

Authorization

The Authorization header carries credentials. The headers crate gives you Authorization<Bearer> for token‑based auth and Authorization<Basic> for username/password auth. Extracting this header lets you access the token or credentials directly.

use axum::{routing::get, Router};
use axum_extra::headers::authorization::{Authorization, Bearer};
use axum_extra::TypedHeader;
async fn protected_route(TypedHeader(auth): TypedHeader<Authorization<Bearer>>) -> String {
    format!("Bearer token received: {}", auth.token())
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/protected", get(protected_route));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Test with:

curl -H "Authorization: Bearer my-secret-token" http://127.0.0.1:3000/protected

Output:

Bearer token received: my-secret-token

The auth.token() method returns the token as a &str. You can then validate it against your own user database or use it as an opaque identifier.

Content-Type

The Content-Type header tells the server what kind of data is in the request body. When you use Json or Form extractors, they check this header themselves. But sometimes you want to branch on the content type before choosing how to parse the body. You can extract it as a typed value.

use axum::{routing::post, Router};
use axum_extra::headers::ContentType;
use axum_extra::TypedHeader;
async fn inspect_content_type(TypedHeader(content_type): TypedHeader<ContentType>) -> String {
    format!("Content type is: {}", content_type)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/inspect", post(inspect_content_type));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Send a request:

curl -X POST -H "Content-Type: application/json" http://127.0.0.1:3000/inspect

Response:

Content type is: application/json

The ContentType type understands MIME types and provides methods like essence_str() to get the main type/subtype without parameters. This is useful when you need to differentiate between application/json; charset=utf-8 and application/json.

Content-Length

The Content-Length header tells the server how many bytes the request body contains. The headers crate provides ContentLength, a wrapper around a u64 that parses the value for you.

use axum::{routing::get, Router};
use axum_extra::headers::ContentLength;
use axum_extra::TypedHeader;
async fn show_length(TypedHeader(ContentLength(len)): TypedHeader<ContentLength>) -> String {
    format!("Body is {} bytes", len)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/len", get(show_length));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

If the header is missing or not a number, the request is rejected with a 400 Bad Request before your handler runs.

Handling Missing Headers

By default, if a required header is absent, TypedHeader rejects the request with a 400 Bad Request. That means your handler never runs. This is often what you want: you are declaring that the header must be present, and Axum enforces it for you.

But sometimes a header is optional. Maybe you want to personalize a greeting when the User-Agent is present, but still serve the request when it is missing. For that, wrap the extractor in Option<TypedHeader<T>>.

use axum::{routing::get, Router};
use axum_extra::{headers::UserAgent, TypedHeader};
async fn maybe_user_agent(user_agent: Option<TypedHeader<UserAgent>>) -> String {
    match user_agent {
        Some(TypedHeader(ua)) => format!("Client is: {}", ua.as_str()),
        None => "No User-Agent header provided".to_string(),
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/maybe", get(maybe_user_agent));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Now test both scenarios. With a header:

curl -H "User-Agent: my-custom-client/1.0" http://127.0.0.1:3000/maybe

Response: Client is: my-custom-client/1.0

Without the header:

curl http://127.0.0.1:3000/maybe

Response: No User-Agent header provided

The Option wrapper changes the behavior: missing header now yields None instead of a rejection. Your handler runs and can decide what to do.

Optional does not mean invalid values are ignored:

If the header is present but its value cannot be parsed into the target type, Option<TypedHeader<T>> still rejects the request. Only a completely absent header becomes None. For example, if you use Option<TypedHeader<Authorization<Bearer>>> and the client sends Authorization: NotBearer abc, the request will be rejected because the value is present but invalid.

Handling Invalid Header Values

When a header is present but malformed, TypedHeader rejects with a 400 Bad Request. But what does the response body look like? For a missing header the body names it, for example Header of type `user-agent` was missing. For a header that is present but cannot be decoded, the body is generic, for example invalid HTTP header (authorization) when a Basic scheme is sent where Bearer was expected:

If you want to customize that error, you can use a Result<TypedHeader<T>, TypedHeaderRejection> as your extractor, similar to how you handle rejections for Json. However, the rejection type for TypedHeader is TypedHeaderRejection from axum_extra. This gives you control over the response.

use axum::{http::StatusCode, response::{IntoResponse, Response}, routing::get, Router};
use axum_extra::typed_header::TypedHeaderRejection;
use axum_extra::{headers::UserAgent, TypedHeader};
async fn custom_error_handler(
    result: Result<TypedHeader<UserAgent>, TypedHeaderRejection>,
) -> Response {
    match result {
        Ok(TypedHeader(ua)) => format!("Valid user agent: {}", ua.as_str()).into_response(),
        Err(rejection) => (
            StatusCode::BAD_REQUEST,
            format!("Could not parse User-Agent: {}", rejection),
        )
            .into_response(),
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/custom-error", get(custom_error_handler));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

TypedHeaderRejection implements Display, so you can include it in your own error message. This is useful when you want to return JSON errors or a specific error code instead of the plain text Axum sends by default.

Using Option<TypedHeader<T>> in Combination with Other Extractors

Because TypedHeader is a FromRequestParts extractor, you can place it before a body-consuming extractor like Json. The order rule still applies: all extractors that read headers, path, query, or state must come before any extractor that consumes the body.

use axum::{extract::Json, routing::post, Router};
use axum_extra::{headers::ContentType, TypedHeader};
use serde::Deserialize;
#[derive(Deserialize)]
struct LoginPayload {
    username: String,
    password: String,
}
async fn login(
    TypedHeader(content_type): TypedHeader<ContentType>,
    Json(payload): Json<LoginPayload>,
) -> String {
    format!(
        "Received login for {} with content type {}",
        payload.username, content_type
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/login", post(login));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Send a valid request:

curl -X POST \
  -H "Content-Type: application/json" \
  -d '{"username":"alice","password":"secret"}' \
  http://127.0.0.1:3000/login

Response:

Received login for alice with content type application/json

The TypedHeader runs first, checks the header, and only if it passes does Axum continue to the Json extractor, which then consumes the body. If the Content-Type header is missing or not a valid media type, the handler never runs and you get a 400.

TypedHeader and Authorization: A Practical Example

Authentication is one of the most common uses for typed headers. Here is a more complete example that extracts a bearer token and checks it against a fixed expected value. This illustrates how you can combine TypedHeader with your own logic.

use axum::{http::StatusCode, response::{IntoResponse, Response}, routing::get, Router};
use axum_extra::headers::authorization::{Authorization, Bearer};
use axum_extra::TypedHeader;
const EXPECTED_TOKEN: &str = "supersecret";
async fn admin_dashboard(
    TypedHeader(auth): TypedHeader<Authorization<Bearer>>,
) -> Response {
    if auth.token() == EXPECTED_TOKEN {
        "Welcome to the admin dashboard".into_response()
    } else {
        (StatusCode::UNAUTHORIZED, "Invalid token").into_response()
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/admin", get(admin_dashboard));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Test with the correct token:

curl -H "Authorization: Bearer supersecret" http://127.0.0.1:3000/admin

Output: Welcome to the admin dashboard

Test with a wrong token:

curl -H "Authorization: Bearer wrong" http://127.0.0.1:3000/admin

Output: Invalid token with HTTP status 401.

Notice that the handler returns a Response because we need to vary both the status code and the body. The typed extraction itself succeeded; our business logic then decided whether the token was acceptable. This separation keeps parsing concerns out of your authorization code.

Creating Your Own Custom Typed Header

The headers crate covers many standard headers, but sometimes you have a custom header like X-Request-ID. You can define your own type by implementing the Header trait. This is an advanced topic, but a small example shows the pattern.

use axum::{http::HeaderName, routing::get, Router};
use axum_extra::{headers::{Error, Header}, TypedHeader};
static X_REQUEST_ID: HeaderName = HeaderName::from_static("x-request-id");
#[derive(Debug, Clone)]
struct RequestId(String);
impl Header for RequestId {
    fn name() -> &'static HeaderName {
        &X_REQUEST_ID
    }
    fn decode<'i, I>(values: &mut I) -> Result<Self, Error>
    where
        I: Iterator<Item = &'i axum::http::HeaderValue>,
    {
        let value = values
            .next()
            .ok_or_else(Error::invalid)?;
        let str_value = value.to_str().map_err(|_| Error::invalid())?;
        Ok(RequestId(str_value.to_string()))
    }
    fn encode<E: Extend<axum::http::HeaderValue>>(&self, values: &mut E) {
        if let Ok(value) = axum::http::HeaderValue::from_str(&self.0) {
            values.extend(std::iter::once(value));
        }
    }
}
async fn show_request_id(TypedHeader(request_id): TypedHeader<RequestId>) -> String {
    format!("Request ID: {}", request_id.0)
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/rid", get(show_request_id));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

Test:

curl -H "x-request-id: abc-123" http://127.0.0.1:3000/rid

Response: Request ID: abc-123

This custom type reads the first value of the header and stores it as a String. You could add validation (for example, length limits or format checks) inside decode. Implementing encode is required by the trait but is not used during extraction; it is there for symmetry when you want to write a header in a response.

Custom Header trait implementations are for advanced users:

Implementing the Header trait yourself gives you full control but also full responsibility. You must handle empty headers, multiple values, non‑UTF8 bytes, and any validation rules your header requires. For most standard headers, the built‑in types in axum_extra::headers are already correct and heavily tested. Prefer those before writing your own.

Common Mistakes and Misconceptions

Forgetting the typed-header feature flag

If you add axum-extra without the feature, the TypedHeader type and the headers module are not available. Your code will fail to compile with errors like could not find TypedHeader in axum_extra. Always check your Cargo.toml includes features = ["typed-header"].

Assuming Option<TypedHeader<T>> means "invalid values become None"

As explained earlier, Option only affects a missing header. A present but unparsable header still causes a rejection. This is a frequent source of confusion for beginners.

Using the wrong header type for the data you actually receive

For example, extracting TypedHeader<Authorization<Bearer>> when clients send Basic credentials will cause a 400 rejection because the Bearer type expects the Bearer scheme. Always match the type to what your clients will actually send.

Mixing TypedHeader with a body extractor in the wrong order

TypedHeader is a FromRequestParts extractor, so it can appear before Json, String, or Bytes. But body-consuming extractors must always be last. If you put Json before TypedHeader, the compiler will complain because TypedHeader does not implement FromRequest.

Treating TypedHeader as a replacement for all header access

Sometimes you need raw access to multiple headers, or you need to iterate over all headers regardless of type. In those cases, HeaderMap is still the right tool. TypedHeader shines when you know exactly which header you want and you want its value parsed into a structured type.

When TypedHeader Is the Right Choice

Use TypedHeader when:

  • You are building an endpoint that requires a specific header (like Authorization for an authenticated route).
  • You need to make decisions based on a header's parsed value (like Content-Type or Content-Length).
  • You want to avoid manual string parsing and get the benefit of well‑tested header definitions.
  • You are already using axum-extra for other features and want consistency.

For simple cases where you only need the raw string and do not care about parsing, HeaderMap with .get(USER_AGENT) may be simpler. But as soon as you start splitting strings or checking prefixes, TypedHeader becomes cleaner and less error‑prone.

Summary

TypedHeader bridges the gap between raw HeaderValue and meaningful Rust data. By relying on the headers crate's typed definitions, you let the framework handle parsing, error detection, and early rejection of malformed requests. Your handlers receive values they can trust, and you avoid repeating header‑parsing logic across routes.

The single most important insight from this page is that TypedHeader<T> is a contract. When you write it as a handler argument, you are saying: "This request must contain this header, and it must be a valid instance of this specific type." Axum enforces that contract before your handler runs. Use Option<TypedHeader<T>> when the header is optional, and use Result<TypedHeader<T>, TypedHeaderRejection> when you need to customize the error response.

From here, the next logical step in learning Axum extractors is to explore how to combine TypedHeader with application state, middleware, or more complex authorization flows. But for now, you have a solid foundation for extracting any standard HTTP header in a safe and ergonomic way.