Extension Request-Scoped Data
Learn how to pass per-request data through Axum handlers using the Extension extractor with practical examples and clear beginner explanations
Axum's Extension extractor lets you attach extra data to a single HTTP request and read it back inside your handler. This page walks through what request-scoped data actually means, how it differs from application-wide state, and how to build it into a real Axum route. You will start with the smallest possible example and then layer on realistic patterns like middleware-injected values, request IDs, and typed wrappers.
What Request-Scoped Data Means
A request in Axum is a complete incoming HTTP message: the method, the URI, the headers, and often a body. When your server receives that message, Axum builds a collection of internal metadata around it. That collection is called Extensions. It behaves like a small storage bag that travels with the request from the moment routing begins until the handler finishes.
Request-scoped data is anything you put into that bag that exists only for the lifetime of that one request. The next request gets a fresh bag. This is different from application state, which lives for the entire lifetime of the server and is shared across every request. If you store a database connection pool in application state, every request reads the same pool. If you store a request ID in an extension, every request gets its own ID.
The word "extension" comes from the idea that you are extending the request with information that was not in the raw HTTP bytes. The client did not send this data. Your server produced it - perhaps in middleware, perhaps in the router, perhaps in an earlier part of the handler pipeline - and attached it so later code can read it.
A First Extension Example
Start with the absolute minimum. You will create a route that inserts a value into the request extensions, then a handler that extracts it. The value can be any Rust type as long as it implements Clone and Send + Sync. For the first example, use a simple String.
Here is the complete program:
# Cargo.toml
[package]
name = "extension-basics"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
use axum::{
extract::Extension,
routing::get,
Router,
};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.layer(Extension(String::from("hello from an extension")));
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();
}
async fn handler(Extension(message): Extension<String>) -> String {
message
}
The .layer(Extension(...)) call is doing the heavy lifting. It wraps the router so that every request entering any route gets a copy of the String inserted into its extensions bag. The handler then declares Extension<String> as a parameter. Axum sees that parameter type, looks inside the request's extensions bag for a value of type String, and gives it to the handler. If you run this program and open http://127.0.0.1:3000, the browser displays hello from an extension.
Notice the pattern match in the handler signature: Extension(message). The Extension is a wrapper type. You destructure it to get the inner value. If you wrote message: Extension<String> instead, you would have to call message.0 to reach the String. Destructuring is the idiomatic Axum style and the one used throughout the documentation.
The .layer() method applies the extension to the whole router. If you have many routes under that router, they all receive the same extension. This is the simplest way to make request-scoped data available, but it has a limitation: every request sees the same value. The next section explores how to make each request get a different value.
Why Clone Matters:
The Extension layer requires the inner type to implement Clone. Axum does not move your original value into every request - it clones it. For cheap values like String or an Arc, this is fast. If your type cannot be cloned cheaply, wrap the expensive part in Arc and clone the handle instead.
Inserting Extensions Without a Layer
The layer approach puts a value into every request before routing. But sometimes you want to insert an extension from inside a route handler or from a custom piece of code. You can do that directly on the request: http::Request has an extensions_mut() method that gives mutable access to the extensions bag.
Here is a program that inserts the extension inside one specific route's handler:
use axum::{
extract::Extension,
routing::get,
Router,
};
use axum::http::Request;
use axum::body::Body;
use axum::middleware::Next;
use axum::response::Response;
async fn insert_extension_manually(
request: Request<Body>,
next: Next,
) -> Response {
let mut request = request;
request.extensions_mut().insert(String::from("inserted manually"));
next.run(request).await
}
async fn handler(Extension(message): Extension<String>) -> String {
message
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.layer(axum::middleware::from_fn(insert_extension_manually));
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 introduces middleware. The insert_extension_manually function receives the raw request, calls request.extensions_mut() to get mutable access to the extensions bag, and inserts a String. Then it calls next.run(request).await to pass the modified request onward to the route handler. The handler sees the extension because the middleware ran first.
This pattern is the foundation for all request-scoped data that changes per request. The middleware can read headers, query parameters, or even the request body (though body reading is a separate topic) and then decide what to insert.
Inserting Extensions in Handlers Does Not Help:
A common beginner mistake is trying to insert an extension inside the final handler and then extract it later in the same handler. Extensions are populated before your handler runs. Inserting one inside handler and then trying to read it from another parameter in the same function will not work because Axum has already resolved all the extractor parameters by the time the function body starts. Put insertion in middleware, not in the handler that consumes the extension.
Request-Scoped Values That Change Per Request
The previous examples all inserted the same value for every request. The real power of request-scoped extensions comes from generating something unique per request. A request ID is the canonical example.
Here is a complete program that generates a unique ID for every request and makes it available to handlers:
use axum::{
extract::Extension,
routing::get,
Router,
};
use axum::http::Request;
use axum::body::Body;
use axum::middleware::Next;
use axum::response::Response;
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(1);
#[derive(Clone, Debug)]
struct RequestId(u64);
async fn attach_request_id(
request: Request<Body>,
next: Next,
) -> Response {
let request_id = COUNTER.fetch_add(1, Ordering::SeqCst);
let mut request = request;
request.extensions_mut().insert(RequestId(request_id));
next.run(request).await
}
async fn handler(Extension(request_id): Extension<RequestId>) -> String {
format!("Your request ID is {}", request_id.0)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.layer(axum::middleware::from_fn(attach_request_id));
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();
}
Each time a request arrives, the middleware increments the counter and wraps the new number in a RequestId struct. That struct goes into the extensions bag. The handler extracts Extension<RequestId> and formats the number. Refresh the browser a few times and the number increases.
The key idea here is type-based access. You did not give the extension a name like "request_id". You inserted a value of type RequestId, and Axum found it because the handler asked for Extension<RequestId>. The type itself is the key. This is why you must use a unique type for each distinct piece of request-scoped data. If you insert two different String values with different meanings, the second one replaces the first.
Type Collisions Replace Values Silently:
Extensions hold at most one value per Rust type. If you insert a String meaning "username" and later insert another String meaning "request ID," the second insert silently overwrites the first. No warning, no error. To avoid this, define a new struct for each semantic value, like RequestId(u64) and UserId(u64), even if the inner type is the same.
Using Extensions for Per-Request Logging Context
A practical production use case is structured logging. Suppose every request should produce log lines that include the request URI, the user agent, and a unique request ID. The middleware extracts the URI and user agent from the raw request, generates the ID, bundles all three into a RequestContext, and inserts that context as an extension. Handlers then read the extension and pass it to the logger.
Here is a complete program that prints a log line with the request context before calling the handler:
use axum::{
extract::Extension,
routing::get,
Router,
};
use axum::http::Request;
use axum::body::Body;
use axum::middleware::Next;
use axum::response::Response;
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(1);
#[derive(Clone, Debug)]
struct RequestContext {
request_id: u64,
user_agent: String,
uri: String,
}
async fn build_request_context(
request: Request<Body>,
next: Next,
) -> Response {
let request_id = COUNTER.fetch_add(1, Ordering::SeqCst);
let user_agent = request
.headers()
.get("user-agent")
.and_then(|v| v.to_str().ok())
.unwrap_or("unknown")
.to_string();
let uri = request.uri().to_string();
let context = RequestContext {
request_id,
user_agent,
uri,
};
println!(
"Incoming request id={} uri={} agent={}",
context.request_id, context.uri, context.user_agent
);
let mut request = request;
request.extensions_mut().insert(context);
next.run(request).await
}
async fn handler(Extension(context): Extension<RequestContext>) -> String {
format!(
"Handled request {} to {} (agent: {})",
context.request_id, context.uri, context.user_agent
)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.layer(axum::middleware::from_fn(build_request_context));
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 middleware reads the user-agent header. Most browsers and tools like curl send one, but it is optional, so some clients omit it entirely, which is why the code falls back to "unknown". The URI is just the path and query string the client requested. The middleware prints an "Incoming request" line using println! to keep the example simple. In a real system, you would replace println! with a structured logging library, but the structure of reading an extension remains identical.
The handler also reads the extension and shows that the data made it through. This proves the extension mechanism is working end to end. When you open http://127.0.0.1:3000 in a browser, your terminal shows the incoming request line, and the browser shows the handled request line.
Multiple Extension Types in One Handler
A handler can extract more than one extension, as long as each has a distinct type. This is where defining new structs instead of using raw String pays off.
Here is an example with two extensions:
use axum::{
extract::Extension,
routing::get,
Router,
};
use axum::http::Request;
use axum::body::Body;
use axum::middleware::Next;
use axum::response::Response;
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(1);
#[derive(Clone, Debug)]
struct RequestId(u64);
#[derive(Clone, Debug)]
struct StartTime(std::time::Instant);
async fn attach_extensions(
request: Request<Body>,
next: Next,
) -> Response {
let request_id = COUNTER.fetch_add(1, Ordering::SeqCst);
let start = std::time::Instant::now();
let mut request = request;
request.extensions_mut().insert(RequestId(request_id));
request.extensions_mut().insert(StartTime(start));
let response = next.run(request).await;
let elapsed = start.elapsed();
println!("Request {} completed in {:?}", request_id, elapsed);
response
}
async fn handler(
Extension(request_id): Extension<RequestId>,
Extension(start_time): Extension<StartTime>,
) -> String {
format!(
"Request {} started at {:?}",
request_id.0,
start_time.0
)
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.layer(axum::middleware::from_fn(attach_extensions));
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 two extensions have completely different types: RequestId and StartTime. The handler extracts both in a single parameter list. Axum processes each extractor in order, left to right, looking up the types in the extensions bag. If a type is missing, the request fails with a 500 runtime error and the handler never runs.
The StartTime example shows another useful pattern: storing a timestamp at the beginning of the request and reading it in the handler or in middleware after the handler completes. The middleware here records the start time, inserts it, waits for the handler to finish, then calculates elapsed time. The handler also reads the start time and prints it. This is request-scoped timing made trivial by extensions.
Distinct Types Are the Safest Pattern:
When every semantic value has its own struct - RequestId, StartTime, UserId, TenantId - you can never accidentally overwrite one extension with another. The Rust type system prevents collisions. This is the recommended way to use extensions in any real application.
Comparing Extension to Application State
Axum has another mechanism called State for sharing data with handlers. It is easy to confuse the two, so a clear comparison helps.
Application state is set with .with_state(...) and lives for the whole server lifetime. Every request can read the same value. You use it for things like database pools, configuration, or a global cache. The value is cloned for each request, but the underlying data is shared. In Axum 0.8, state is typically wrapped in Arc and stored once.
Extensions, by contrast, are part of the request's metadata. They are created after the request arrives and destroyed when the request completes. They can be different for every request. They are ideal for data that is derived from the request itself - request IDs, parsed authentication results, timing information, tenant resolution.
Here is a small program that uses both to make the distinction concrete:
use axum::{
extract::{Extension, State},
routing::get,
Router,
};
use axum::http::Request;
use axum::body::Body;
use axum::middleware::Next;
use axum::response::Response;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
static COUNTER: AtomicU64 = AtomicU64::new(1);
#[derive(Clone)]
struct AppState {
app_name: String,
}
#[derive(Clone, Debug)]
struct RequestId(u64);
async fn attach_request_id(
request: Request<Body>,
next: Next,
) -> Response {
let request_id = COUNTER.fetch_add(1, Ordering::SeqCst);
let mut request = request;
request.extensions_mut().insert(RequestId(request_id));
next.run(request).await
}
async fn handler(
State(state): State<Arc<AppState>>,
Extension(request_id): Extension<RequestId>,
) -> String {
format!("{} handling request {}", state.app_name, request_id.0)
}
#[tokio::main]
async fn main() {
let shared_state = Arc::new(AppState {
app_name: "My API".to_string(),
});
let app = Router::new()
.route("/", get(handler))
.layer(axum::middleware::from_fn(attach_request_id))
.with_state(shared_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();
}
The AppState is created once in main, wrapped in Arc, and passed via .with_state. Every request receives a clone of that Arc, so they all see the same app_name. The RequestId is generated fresh in middleware for each request, so it differs every time. The handler takes both. This illustrates the division clearly: State for shared server-level data, Extension for per-request data.
The naming can feel backward at first. You might expect "state" to mean "request state" and "extension" to mean "server extension." In Axum, remember it as: State is the server's state, Extension extends the request with extra per-request information.
State Is Different From Extension:
State accepts any value that is Clone + Send + Sync + 'static, so plain structs work fine; wrapping it in an Arc is a common choice for large or shared state, not a requirement. If you read older tutorials that show Extension being used for database pools, understand that in Axum 0.8 that pattern has been largely replaced by State. Use State for shared resources and Extension for request-specific data.
Common Mistakes and How to Avoid Them
The most frequent beginner errors with request-scoped extensions all stem from a few misunderstandings. Naming them explicitly will save you debugging time.
First, expecting a layer-applied extension to be per-request. If you call .layer(Extension(MyValue::new())) where MyValue::new() generates a random number, you will get the same number for every request. The value is created once when the router is built, then cloned for every request. To get a fresh value per request, generate it in middleware using request.extensions_mut().insert(...).
Second, inserting an extension too late. If you insert in the final handler, you cannot also extract it in the same handler. The extraction happens before the handler body runs. Insert in middleware or in an earlier part of the request pipeline.
Third, type collisions. Inserting two values of the same type silently replaces the first. Define a new struct for each semantic meaning.
Fourth, forgetting Clone. The type you put in an extension must implement Clone and Send + Sync. Most simple types do, but custom types holding Mutex or other non-cloneable items may not. Wrap the inner value in Arc or use a different synchronization primitive.
Fifth, confusing Extension with State. If you need the same value for every request and it is expensive to create, use State. If the value changes per request or is derived from the request itself, use Extension.
When to Use Extension Request-Scoped Data
Request-scoped extensions are the right tool when three conditions hold: the data is produced after the request arrives, it is consumed inside a handler, and it differs per request or is specific to one request. The request ID and request context examples in this page satisfy all three.
They are also useful for passing data from one middleware to another or from middleware to a handler without threading extra function parameters. Because the extensions bag is part of the Request object, any middleware that receives the request can read from or write to it. The handler then sees whatever the middleware left behind.
One real-world pattern is authentication. A middleware validates a token, looks up the user, and inserts a User struct into the extensions. Handlers that need the current user extract Extension<User>. They never touch the token logic. The raw HTTP request did not contain a User struct - the middleware created it and extended the request with it.
Extensions Do Not Survive Redirects or Subrequests:
Extensions live only inside the memory of the current request. If your handler issues an HTTP redirect, the browser makes a new request to the new location. That new request gets a fresh extensions bag. Extensions are not cookies and not session state. For data that must persist across multiple requests from the same client, use a session store or cookies, which are different mechanisms entirely.
Summary
Extension request-scoped data solves a specific problem: passing information that is derived from or specific to a single request into the code that handles that request. The pattern has three parts - insert the value in middleware using request.extensions_mut().insert(...), extract it in the handler using Extension<MyType>, and define a unique struct for each distinct semantic value so type-based lookup cannot collide. Compare this to State, which shares server-level data across all requests, and to middleware parameter threading, which becomes unwieldy as the number of values grows. If you remember that extensions are a per-request bag keyed by Rust type, you will know exactly when to reach for them and when to choose a different tool.