User-Agent header

How to extract the User-Agent header from HTTP requests in Axum, using HeaderMap, TypedHeader, optional extraction, and custom extractors

The User-Agent header is one of the most common pieces of information a browser or HTTP client sends with every request. It identifies the software that made the request: the browser name, version, operating system, and sometimes more. This page shows you how to pull that value out of an incoming request in Axum so you can use it in your handler logic.

What Is the User-Agent Header?

Every time your browser fetches a web page, it sends an HTTP request. That request includes a set of headers - key-value pairs that describe the request itself. One of those headers is User-Agent. Its value is a string that looks something like this:

Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36

This tells the server that the client is Chrome 120 running on Windows 10 64-bit. The User-Agent header has been part of HTTP since the early days, originally meant to let servers adapt content to different browsers. Today it's used for analytics, device detection, security checks, and sometimes for serving lightweight versions of a site to old browsers.

In Axum, a handler can receive the User-Agent header just like any other extractor. The approach you choose depends on whether you want raw access to the string, a typed wrapper, optional handling, or a fully custom extractor.

Basic Extraction with HeaderMap

The most direct way to get any header in Axum is to use the HeaderMap extractor. It gives you a map of all headers present in the request. To read the User-Agent specifically, you use the USER_AGENT constant from axum::http::header.

Here's a complete runnable example:

// main.rs
use axum::{
    http::HeaderMap,
    http::header::USER_AGENT,
    routing::get,
    Router,
};
async fn show_user_agent(headers: HeaderMap) -> String {
    match headers.get(USER_AGENT) {
        Some(value) => format!("Your User-Agent is: {}", value.to_str().unwrap_or("(invalid UTF-8)")),
        None => "No User-Agent header found".to_string(),
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(show_user_agent));
    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();
}

The handler takes a HeaderMap as its only argument. Inside, headers.get(USER_AGENT) returns an Option<&HeaderValue>. If the header is present, we convert the HeaderValue to a string using to_str(), which returns a Result because header values might contain bytes that aren't valid UTF-8. In most cases, User-Agent is plain ASCII, so unwrap_or is safe enough for an example. If the header is missing, the None branch handles it.

Run the server and visit http://127.0.0.1:3000 with any browser. You'll see the browser's own user agent string printed. You can also test with curl:

curl http://127.0.0.1:3000

The output will be something like:

Your User-Agent is: curl/8.5.0

The exact version number depends on the curl installed on your machine.

This is the simplest possible method. It works, but it's a bit manual - you have to deal with Option, convert the value to a string, and handle the possibility of missing or invalid data. For a more ergonomic approach, Axum offers typed header extraction through the axum-extra crate.

Typed Extraction with axum-extra

The axum-extra crate provides a TypedHeader extractor that can deserialize headers into well-typed Rust values. For the User-Agent header, the headers crate (a dependency of axum-extra) defines a UserAgent type. Instead of working with raw strings, you get a structured value you can inspect programmatically.

First, add axum-extra and headers to your Cargo.toml:

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

Now use the typed extractor in a handler:

// main.rs
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("/", get(show_user_agent));
    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();
}

The handler parameter TypedHeader(user_agent) is a destructuring pattern. TypedHeader is a wrapper that tells Axum to extract the header and parse it into the inner type, here UserAgent. The UserAgent type from headers has an as_str() method that returns the original string.

This approach is cleaner because Axum handles the header lookup and any parsing automatically. If the User-Agent header is missing, the extraction fails and Axum returns a 400 Bad Request response by default. If the header is present, you get a UserAgent value that you can use directly.

TypedHeader Just Works:

When the request includes a valid User-Agent header, TypedHeader<UserAgent> succeeds without any extra code. You don't need to call .get() or handle Option - Axum does that for you.

The UserAgent type also implements Display, so you could write format!("Your User-Agent is: {user_agent}") instead of using as_str(). Both do the same thing.

Making the User-Agent Optional

Sometimes you want to accept requests even when the User-Agent header is missing. The default TypedHeader extractor rejects the request if the header is absent. To make it optional, wrap the extractor in Option:

// main.rs
use axum::{routing::get, Router};
use axum_extra::{headers::UserAgent, TypedHeader};
async fn show_user_agent(user_agent: Option<TypedHeader<UserAgent>>) -> String {
    match user_agent {
        Some(TypedHeader(ua)) => format!("Your User-Agent is: {}", ua.as_str()),
        None => "No User-Agent header was sent".to_string(),
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(show_user_agent));
    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();
}

Here the handler receives an Option<TypedHeader<UserAgent>>. If the header exists and parses correctly, you get Some(TypedHeader(user_agent)). If it's missing, you get None. The request never fails just because the header is absent. This is useful for endpoints that don't strictly require a user agent, like public APIs or health checks.

The axum-extra crate implements the OptionalFromRequestParts trait for TypedHeader, which is what allows this Option behavior. Not all extractors can be made optional - only those that explicitly opt in.

Creating a Custom User-Agent Extractor

If you need more control than HeaderMap or TypedHeader provides, you can implement your own extractor using the FromRequestParts trait. This is the most flexible method: you decide exactly how to read the header, what to do when it's missing, and what error to return.

The Axum documentation includes an example that extracts the User-Agent header into a custom struct. Here's a slightly expanded version with detailed explanations:

// main.rs
use axum::{
    extract::FromRequestParts,
    http::{
        header::{HeaderValue, USER_AGENT},
        request::Parts,
        StatusCode,
    },
    routing::get,
    Router,
};
// Our custom extractor type. It wraps a HeaderValue.
struct ExtractUserAgent(HeaderValue);
// Implement FromRequestParts for our type.
impl<S> FromRequestParts<S> for ExtractUserAgent
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        if let Some(user_agent) = parts.headers.get(USER_AGENT) {
            Ok(ExtractUserAgent(user_agent.clone()))
        } else {
            Err((StatusCode::BAD_REQUEST, "`User-Agent` header is missing"))
        }
    }
}
async fn handler(ExtractUserAgent(user_agent): ExtractUserAgent) -> String {
    format!(
        "Your User-Agent is: {}",
        user_agent.to_str().unwrap_or("(invalid UTF-8)")
    )
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(handler));
    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();
}

Let's walk through this code piece by piece:

  • struct ExtractUserAgent(HeaderValue); defines a tuple struct that contains a HeaderValue - the raw value of the header.
  • The impl<S> FromRequestParts<S> for ExtractUserAgent block tells Axum how to create an ExtractUserAgent from the request parts. The generic S represents the application state type; we don't use state here, so we just require S: Send + Sync.
  • Inside from_request_parts, we access parts.headers to get the HeaderMap. We look for the USER_AGENT header. If found, we clone the value (since parts is borrowed mutably) and wrap it. If not found, we return an error tuple (StatusCode::BAD_REQUEST, "User-Agent header is missing").
  • The handler then takes ExtractUserAgent(user_agent) directly, exactly like built-in extractors.

This custom extractor gives you full control over the rejection response. In this example, a missing header results in a 400 Bad Request with a plain text body. You could change that to any status code or even a JSON error response by returning a different Rejection type that implements IntoResponse.

Why Clone the HeaderValue?:

HeaderValue is not Copy, and we only have a reference to it from parts.headers.get(). We need to store the value inside our extractor, so we call .clone(). This is a cheap operation because HeaderValue internally uses reference counting for the underlying bytes.

If you compare this to the TypedHeader approach, the custom extractor is more verbose but offers complete flexibility. You might choose it when you need a specific error message, when you want to combine multiple headers, or when you need to perform additional validation that UserAgent doesn't do.

Handling a Missing User-Agent in a Custom Extractor

In the custom extractor above, a missing User-Agent results in a 400 response. But what if you want the handler to run even without the header? You can make your custom extractor optional by wrapping it in Option in the handler. However, that requires the extractor to implement the OptionalFromRequestParts trait, not just FromRequestParts. Implementing that trait is straightforward. Here is the complete program, with the same ExtractUserAgent struct from the previous section plus the new optional implementation:

// main.rs
use axum::extract::{FromRequestParts, OptionalFromRequestParts};
use axum::http::{header::{HeaderValue, USER_AGENT}, request::Parts, StatusCode};
use axum::{routing::get, Router};
use std::convert::Infallible;
// Our custom extractor type. It wraps a HeaderValue.
struct ExtractUserAgent(HeaderValue);
// The strict version: a missing header is a 400 error.
impl<S> FromRequestParts<S> for ExtractUserAgent
where
    S: Send + Sync,
{
    type Rejection = (StatusCode, &'static str);
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        if let Some(user_agent) = parts.headers.get(USER_AGENT) {
            Ok(ExtractUserAgent(user_agent.clone()))
        } else {
            Err((StatusCode::BAD_REQUEST, "`User-Agent` header is missing"))
        }
    }
}
// The optional version: a missing header becomes None instead of an error.
impl<S> OptionalFromRequestParts<S> for ExtractUserAgent
where
    S: Send + Sync,
{
    type Rejection = Infallible;
    async fn from_request_parts(
        parts: &mut Parts,
        _state: &S,
    ) -> Result<Option<Self>, Self::Rejection> {
        Ok(match parts.headers.get(USER_AGENT) {
            Some(value) => Some(ExtractUserAgent(value.clone())),
            None => None,
        })
    }
}
async fn handler(user_agent: Option<ExtractUserAgent>) -> String {
    match user_agent {
        Some(ExtractUserAgent(ua)) => format!("Your User-Agent is: {}", ua.to_str().unwrap_or("(invalid)")),
        None => "No User-Agent provided".to_string(),
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(handler));
    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();
}

This is a more advanced pattern, but it demonstrates that you can tailor the extractor's optional behavior precisely. The OptionalFromRequestParts implementation returns Ok(None) when the header is absent, and Ok(Some(...)) when present. The rejection type is Infallible, meaning this optional extraction never fails on its own - it only returns None or Some.

However, for most use cases, the simpler Option<TypedHeader<UserAgent>> from axum-extra is sufficient and saves you from writing all this boilerplate.

Common Mistakes and Misconceptions

Working with the User-Agent header seems simple, but a few pitfalls catch beginners.

Assuming User-Agent Is Always Present:

Not every client sends a User-Agent header. Some API clients, bots, or privacy-focused tools omit it deliberately. If you use TypedHeader<UserAgent> without Option, your endpoint will return 400 Bad Request for such clients. Always decide whether you truly need the header or can default to something else.

Another misconception is about case sensitivity. HTTP header names are case-insensitive per the specification, so User-Agent, user-agent, and USER-AGENT all refer to the same header. Axum and the http crate handle this correctly - using the USER_AGENT constant ensures you get the right header regardless of how the client wrote it.

Forgetting the axum-extra Dependency:

TypedHeader is not part of the core axum crate. If you try to use it without adding axum-extra to your Cargo.toml, your code won't compile. This is one of the most common errors when first using typed headers.

Some beginners also try to extract the User-Agent using the Json extractor or as a path parameter, which doesn't make sense. Headers are part of the request metadata, not the body or the URL. Stick to HeaderMap, TypedHeader, or a custom FromRequestParts implementation.

Real-World Usage Examples

Now that you know how to extract the User-Agent, let's look at a couple of practical scenarios where you might use it in a real Axum application.

Serving Different Content Based on Browser

Imagine you have a web application that needs to serve a simplified version to older browsers. You can check the User-Agent string to detect if the browser is too old and respond accordingly:

use axum::{routing::get, Router};
use axum_extra::{headers::UserAgent, TypedHeader};
async fn home(user_agent: Option<TypedHeader<UserAgent>>) -> &'static str {
    match user_agent {
        Some(TypedHeader(ua)) => {
            let ua_str = ua.as_str();
            if ua_str.contains("MSIE 6") || ua_str.contains("MSIE 7") {
                "Sorry, this site requires a modern browser."
            } else {
                "Welcome to our modern site!"
            }
        }
        None => "Welcome, unknown browser!",
    }
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(home));
    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();
}

This example uses Option<TypedHeader<UserAgent>> to handle missing headers gracefully, then inspects the string for legacy Internet Explorer markers. In a real app, you'd probably use a proper user agent parsing library, but this shows the basic idea.

Logging User Agents for Analytics

You might want to log every request's User-Agent for later analysis. With a custom extractor that never rejects, you can access the value in a middleware or handler without worrying about missing headers:

use axum::{extract::FromRequestParts, http::{header::{HeaderValue, USER_AGENT}, request::Parts}, routing::get, Router};
use std::convert::Infallible;
struct MaybeUserAgent(Option<HeaderValue>);
impl<S> FromRequestParts<S> for MaybeUserAgent
where
    S: Send + Sync,
{
    type Rejection = Infallible;
    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        Ok(MaybeUserAgent(parts.headers.get(USER_AGENT).cloned()))
    }
}
// Then in a handler:
async fn log_request(user_agent: MaybeUserAgent) -> String {
    if let Some(ua) = user_agent.0 {
        println!("Request from: {}", ua.to_str().unwrap_or("(invalid)"));
    } else {
        println!("Request from unknown client");
    }
    "Logged".to_string()
}
#[tokio::main]
async fn main() {
    let app = Router::new().route("/", get(log_request));
    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();
}

Because the rejection type is Infallible, this extractor can never fail, making it safe to use in many places without worrying about error handling.

Choosing the Right Approach

You have several ways to extract the User-Agent header, each with trade-offs:

  • HeaderMap - low-level, manual, always works, good for one-off access or when you need multiple headers at once.
  • TypedHeader<UserAgent> - high-level, automatic parsing, requires axum-extra, fails with 400 if header missing. Best for when the header is required.
  • Option<TypedHeader<UserAgent>> - typed and optional, perfect for endpoints where the header may be absent.
  • Custom extractor - full control over rejection and parsing, more code, best for specialized needs or reusable logic.

As a beginner, start with HeaderMap to understand the underlying mechanics. Then move to TypedHeader for ergonomic development. Use Option when you don't want to reject requests. Only write a custom extractor when the built-ins don't meet your exact requirements.

Summary

The User-Agent header identifies the client software that made the request. Extracting it in Axum is straightforward, and the method you choose depends on how strict or flexible you need to be. The raw HeaderMap gives you direct access to the string value; TypedHeader from axum-extra gives you a typed, safe wrapper; Option makes the extraction optional; and a custom FromRequestParts implementation gives you complete control over both success and failure paths.

One insight that ties these methods together: all header extraction ultimately reads from the same HeaderMap inside the request parts. The higher-level extractors are just convenient wrappers that handle the lookup and error mapping for you. Understanding that underlying mechanism helps you decide when to use a built-in extractor and when to write your own.

If you find yourself needing to extract multiple headers or combine User-Agent with other request metadata, you can chain several extractors in a single handler - just remember that only the last one can consume the body, but headers are always safe to extract in any position.