Request Extensions in Axum
Learn how to share request-scoped data using Axum's Extension type, including layer setup, extraction, and common mistakes.
When building a web server with Axum, you often need to pass extra information along with an HTTP request. Maybe you want to attach a user ID after authentication, a request ID for logging, or some configuration object that only applies to a small group of handlers. Request extensions give you a way to hang arbitrary data onto an incoming request so that handlers can later retrieve it.
Unlike application state, which is shared across every request, request extensions are scoped to a single request. That makes them perfect for data that changes per request, like the current user or a unique trace identifier.
What Are Request Extensions?
In Axum, a request extension is a value stored inside the HTTP request object. Internally, Axum (through the http crate) keeps a type‑safe map for each request. You can insert a value of any type, and later retrieve it by specifying that same type. The type itself acts as the key, so you can store many different types simultaneously.
The mechanism is built on top of the tower middleware system. You add an Extension layer to your router (or to a specific route), and that layer inserts a value into the request extensions map before the handler runs. The handler then uses an Extension extractor to pull the value back out.
Type‑Safe by Design:
Because the extension map is keyed by Rust's type system, each type has its own slot, so two different types can never collide. But the compiler cannot check that a value of a given type was actually inserted. If you extract a type that was never inserted, you get a runtime error, a 500 Internal Server Error response.
Why Use Request Extensions?
Imagine you have a middleware that authenticates a user and then needs to pass that user information to the handler. You cannot use State because the user differs for each request. You could pass the user through the handler's arguments directly, but that would mean every handler that needs the user must explicitly receive it - and that can become tedious and error‑prone.
Request extensions solve this elegantly: the middleware inserts the user into the request, and any handler that wants it can simply extract it by type. The handler does not need to know where the value came from; it only needs to know the type.
Extensions are also useful when integrating with libraries that already attach data to requests. For example, tower-http's tracing middleware might insert a span, or a custom auth layer might insert a token.
How Request Extensions Work
The flow looks like this:
- You create a value you want to share (e.g., a
Userstruct). - You add an
Extensionlayer to your router, providing that value. This layer runs before every request handled by routes in that router. - When a request arrives, the layer inserts the value into the request's extension map.
- A handler that needs the value declares a parameter of type
Extension<User>. - Axum's extractor system looks inside the request's extension map for a value of type
User. If found, it passes the value to the handler. - If not found, Axum returns a
500 Internal Server Error.
Because the value is stored in the request, it lives only for the duration of that single request. Once the response is sent, the request and its extensions are dropped.
A First Example
Let's start with the simplest possible case: attaching a string to every request and then reading it in a handler.
Create a new Axum project and replace main.rs with:
# Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
use axum::{
extract::Extension,
routing::get,
Router,
};
#[tokio::main]
async fn main() {
// Create the value we want to share. It can be anything: a string, a struct, etc.
let shared_value = "Hello from extension".to_string();
// Build the router and add an Extension layer.
let app = Router::new()
.route("/", get(handler))
.layer(Extension(shared_value));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn handler(Extension(value): Extension<String>) -> String {
format!("The extension says: {}", value)
}
When you run this and visit http://localhost:3000, you'll see:
The extension says: Hello from extension
Here's what happens step by step. The shared_value is a String. The .layer(Extension(shared_value)) wraps the router with a middleware that, for every incoming request, inserts that String into the request's extension map. The handler's parameter Extension(value): Extension<String> tells Axum, "Please find a String in the request extensions and give it to me as value." Since the layer inserted exactly a String, the extraction succeeds.
Everything Works:
If you see the expected message, your extension layer and extractor are correctly aligned. The type String was inserted and then retrieved without errors.
Using Custom Types
Storing a plain string is fine for learning, but real applications usually share structured data. Any Rust type that is Clone + Send + Sync + 'static can be used in an extension. Let's define a User struct and share that.
use axum::{
extract::Extension,
routing::get,
Router,
};
#[derive(Clone)]
struct User {
id: u64,
name: String,
}
#[tokio::main]
async fn main() {
let user = User {
id: 42,
name: "Alice".to_string(),
};
let app = Router::new()
.route("/", get(handler))
.layer(Extension(user));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn handler(Extension(user): Extension<User>) -> String {
format!("User {} has id {}", user.name, user.id)
}
This works the same way as the string example, but now the type is User. The handler receives a clone of the User instance that was inserted. Because User derives Clone, Axum can clone it for each extraction. If you didn't derive Clone, you couldn't use it this way because extracting would require moving the value out of the request, which may be needed by other extractors or middlewares later.
Deriving Clone Is Essential:
Almost all types used in extensions should implement Clone. The extension extractor returns a clone of the stored value, so the original remains available for other potential extractors. If your type cannot be cloned, consider wrapping it in an Arc (which is itself cheap to clone) or redesigning.
Storing Multiple Extensions
You can attach several different types to the same request. Each type occupies its own slot in the extension map. For instance, you might want both a User and a RequestId.
use axum::{
extract::Extension,
routing::get,
Router,
};
#[derive(Clone)]
struct User {
name: String,
}
#[derive(Clone)]
struct RequestId(u64);
#[tokio::main]
async fn main() {
let user = User { name: "Bob".into() };
let request_id = RequestId(12345);
let app = Router::new()
.route("/", get(handler))
// Multiple Extension layers can be added; each inserts a different type.
.layer(Extension(user))
.layer(Extension(request_id));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn handler(
Extension(user): Extension<User>,
Extension(request_id): Extension<RequestId>,
) -> String {
format!("User {} with request id {}", user.name, request_id.0)
}
Notice the handler now has two Extension parameters. Axum's extractor system processes them independently. It will look for a User and a RequestId in the request extensions. Both are present because we added two layers. The order of the extractor parameters does not matter, and the order of the layers also does not matter because each type is distinct.
Layer Ordering:
When adding multiple Extension layers, the order in which you call .layer() does not affect correctness. Each layer inserts its own type. However, if you inserted the same type twice (which you shouldn't), the second insertion overwrites the first, because the map holds only one value per type.
Where to Add the Extension Layer
You can add an Extension layer at different levels of your router:
- Global: Use
.layer(Extension(value))on the mainRouter. This applies to all routes in that router. - Scoped: Use
.route_layer(Extension(value))on a specific route. This applies only to that route. - Nested: If you have nested routers with
.nest(), you can add the layer to the nested router, affecting only those routes.
Let's see a scoped example. Suppose we have two routes: /public and /private. We want the User extension to be available only in /private.
use axum::{
extract::Extension,
routing::get,
Router,
};
#[derive(Clone)]
struct User {
name: String,
}
#[tokio::main]
async fn main() {
let user = User { name: "Carol".into() };
let app = Router::new()
.route("/public", get(public_handler))
.route("/private", get(private_handler).route_layer(Extension(user)));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn public_handler() -> &'static str {
"This is public, no extension needed."
}
async fn private_handler(Extension(user): Extension<User>) -> String {
format!("Private area for {}", user.name)
}
Now, if you visit /private, you'll get Private area for Carol. Visiting /public works fine because that handler doesn't ask for User. The route_layer ensures only the /private route has the extension inserted. If you tried to extract User inside public_handler, you would get a 500 Internal Server Error because the extension does not exist there.
Missing Extension Causes Runtime Error:
If a handler extracts a type that was never inserted, Axum returns a 500 Internal Server Error. This happens at runtime, not compile time. So if you forget to add the correct Extension layer for a route, your handler will fail. Always ensure that every route that uses an extension also has the corresponding layer attached, either globally or via route_layer.
Extracting Extensions from Middleware
Handlers are not the only place you can use extensions. Middleware can also access them. This is often how extensions are created: a middleware authenticates the user and inserts the user as an extension for downstream handlers.
Let's build a small authentication middleware that reads a fake token from a header, creates a User, and inserts it as an extension.
use axum::{
extract::{Extension, Request},
http::StatusCode,
middleware::{self, Next},
response::Response,
routing::get,
Router,
};
#[derive(Clone)]
struct User {
name: String,
}
async fn auth_middleware(mut req: Request, next: Next) -> Result<Response, StatusCode> {
// In a real app, you'd verify a token or session here.
let user = User { name: "Dave".into() };
// Insert the user into the request extensions.
req.extensions_mut().insert(user);
// Continue to the next middleware/handler.
Ok(next.run(req).await)
}
async fn handler(Extension(user): Extension<User>) -> String {
format!("Authenticated user: {}", user.name)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.layer(middleware::from_fn(auth_middleware));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
In this example, we don't use an Extension layer at all. Instead, our custom middleware accesses req.extensions_mut() and inserts the User directly. The handler still extracts it with Extension<User>. This demonstrates that request extensions are not tied to the Extension layer; they are a general mechanism available from any middleware or handler that has access to the request.
Middleware Signatures in Axum 0.8:
In axum 0.8, a from_fn middleware takes a plain Request and a plain Next, with no type parameter on either: async fn auth(req: Request, next: Next) -> Result<Response, StatusCode>. The older Request<B> and Next<B> forms from axum 0.7 do not compile in 0.8, because Next is no longer generic and Next::run expects a Request with axum's Body type.
Extensions Are Mutable in Middleware:
Inside middleware, you can add or remove extensions using req.extensions_mut(). That's the typical way to create per‑request data based on request headers or other logic. The Extension layer we used earlier is just a convenience middleware that inserts a fixed value.
Common Mistakes and Misconceptions
Let's address the most frequent pitfalls beginners encounter.
1. Wrong Type Extraction
Because the extension map is keyed by type, extracting Extension<i32> when the stored value is a String compiles without any complaint: the compiler cannot know what the layer inserted. The failure only shows up at runtime, when a request arrives and Axum finds no i32 in the extension map, and returns a 500 Internal Server Error with the body Missing request extension: Extension of type `i32` was not found. Perhaps you forgot to add it? See `axum::Extension`. That is the key difference from State, where a type mismatch is a compile error. If you store a type and then later change its name or definition, you must update all extractor signatures accordingly, but the compiler will not catch a mismatch for you.
2. Missing Layer for a Route
As noted above, if a handler extracts a type that wasn't inserted, you get a 500 Internal Server Error. This is easy to overlook when you add new routes. Always ensure the layer is applied to every route that needs it, or use a global layer.
3. Trying to Mutate the Extracted Value
The Extension<T> extractor gives you a clone of the stored value. Modifying that clone does not affect the original stored in the request. If you need to change the extension for downstream handlers, you must do so in middleware before calling next.run(), using req.extensions_mut().
4. Forgetting Clone or Send + Sync
For a type to be used in an extension, it must be Clone + Send + Sync + 'static. If your type contains non‑thread‑safe data (like Rc or raw pointers), you'll get compile errors. Most normal structs with owned data satisfy these bounds automatically, but watch out for types from other crates that might not.
Trait Bounds Matter:
If you see errors like "the trait bound MyType: Send is not satisfied" or "MyType cannot be shared between threads safely," it's because the type doesn't meet the required traits. Fix it by using Arc<MyType> or redesigning to own its data.
Request Extensions vs. State: When to Use Which
Now that you've seen both State and request extensions, you might wonder which one to choose. The rule of thumb is simple:
- Use State for data that is the same for every request and shared across the whole application (e.g., database pools, configuration). It is type‑checked at compile time: the router knows its state type, and handlers extract it with
State<T>. If you forget to set the state, the router won't type‑check. - Use Request extensions for data that varies per request or is inserted by middleware (e.g., current user, request ID). Because extensions are stored in the request, they are naturally scoped to a single request. However, they are not as type‑safe as
Stateat the router level; a missing extension leads to a runtime error.
In many applications, you'll use both: State for global resources, and extensions for request‑specific information.
Practical Use Case: Request ID Tracing
A common real‑world scenario is generating a unique request ID for logging or tracing. A middleware can generate an ID, store it as an extension, and also log it. Then handlers can include that ID in their responses or logs.
Here's a complete example using a simple counter to generate IDs (in production you'd use a proper UUID crate, but this keeps it self‑contained):
use axum::{
extract::{Extension, Request},
http::StatusCode,
middleware::{self, Next},
response::Response,
routing::get,
Router,
};
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Clone)]
struct RequestId(u64);
static COUNTER: AtomicU64 = AtomicU64::new(1);
async fn trace_middleware(mut req: Request, next: Next) -> Result<Response, StatusCode> {
let id = COUNTER.fetch_add(1, Ordering::SeqCst);
let request_id = RequestId(id);
// Optionally log the ID here.
req.extensions_mut().insert(request_id);
let response = next.run(req).await;
Ok(response)
}
async fn handler(Extension(request_id): Extension<RequestId>) -> String {
format!("Handling request {}", request_id.0)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.layer(middleware::from_fn(trace_middleware));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Each request to / will get a different ID. The AtomicU64 is safe to share across concurrent requests because atomic operations never race, and the static counter lives for the whole program. The extension takes ownership of the RequestId, and the handler receives its own clone when it extracts it, so nothing else needs to keep a copy.
Summary
The decision to reach for extensions comes down to two questions. Does the value change from one request to the next? Is it produced by middleware while the request is already in flight? If either answer is yes, an extension is the right carrier: a fixed layer value for the first case, req.extensions_mut() in middleware for the second. If both answers are no, the value is really application-wide data, and State fits better because the compiler then checks that it exists instead of letting a missing value surface as a 500 at runtime.
That trade is the single most important insight on this page. Extensions buy per-request flexibility by giving up compile-time checking, so a 500 with a "missing request extension" body is never a mystery. It means exactly one of two things: the layer was never attached to that route, or the handler asks for a different type than the one that was inserted. Check those two places first and the fix is usually a one-line change.