Task-local variables
Learn how to share data with handlers and response types using task-local variables in Axum with Tokio, including setup, middleware, and common pitfalls.
Sometimes you need to pass data down a deep chain of async function calls without adding extra parameters everywhere. Task-local variables let you do exactly that inside a Tokio async runtime. This page shows how to use them in an Axum application, why they are useful, and what to watch out for.
What task-local variables are
A task-local variable is a piece of data that is attached to the current asynchronous task, which is a lightweight unit of work managed by Tokio. You can think of a task as a small thread that runs your async functions. Just like a thread-local variable is visible only to the thread that set it, a task-local variable is visible only to the task that is currently executing.
When an Axum request arrives, Tokio runs all the middleware, handlers, and response building for that request inside a single task. That means you can set a task-local value early in the request pipeline - for example, in middleware that reads the authenticated user - and then later, in the handler or in a custom IntoResponse implementation, read that same value without passing it explicitly through function arguments.
Task-locals are not part of the Rust standard library. They are provided by the async runtime. In this guide we use tokio::task_local!, because Axum is built on top of Tokio.
Task-local vs thread-local:
A thread-local variable is attached to an operating system thread. A task-local variable is attached to an asynchronous task, which may be moved between different threads during its lifetime. Tokio manages this mapping for you, so the variable always follows the logical flow of your async code.
Why use task-locals in Axum
The most common way to share application state in Axum is the State extractor. It works great when your data lives for the entire lifetime of the application, like a database connection pool. But sometimes the data you want to share is created for each request, not once at startup. That is exactly where task-locals shine.
Consider an authentication middleware. It inspects the request headers, determines who the current user is, and then you want every part of the request handling - including custom response types - to know about that user. Passing the user object as an extractor to every handler would work, but it becomes tedious, and it is impossible to inject into a custom IntoResponse implementation because that trait method receives no arguments.
Task-locals solve this by letting you store the user in a scope that wraps the rest of the request handling. Any code that runs inside that scope can read the value with a simple closure call, no function signature changes needed.
Another advantage is dynamism. With State, the type of shared data is fixed at compile time and must be present. With task-locals, you can decide at runtime whether to set a value, and different requests may set different types of data. That flexibility comes at the cost of less compile-time safety - we will discuss that later.
How task-locals work under the hood
Tokio provides a task_local! macro that declares a static variable of a special type. This variable is not a normal static; it knows how to store a value per task. You cannot assign to it directly. Instead, you create a scope:
USER.scope(current_user, async {
// Inside this block, USER.with(|u| ...) can access current_user
}).await;
The scope function takes two arguments: the value you want to set, and a future. It runs the future with that value available to the current task. When the future completes, the value is removed and any nested tasks spawned without the scope will not see it.
Inside the scoped future, you read the value using with:
let name = USER.with(|u| u.name.clone());
The closure passed to with receives a reference to the stored value. The closure itself is synchronous, so you cannot call .await inside it. If you need to use the value in async code, extract what you need first and then proceed.
Setting up a basic example
Let's build a minimal complete Axum application that uses a task-local variable. The scenario: a middleware reads a username from a custom header, stores it in a task-local, and a handler reads that username and greets the person.
We need four pieces:
- A struct to hold the current user data.
- A
task_local!declaration for it. - Middleware that sets the task-local for each request.
- A handler that reads the task-local.
We will also include a custom response type to show how IntoResponse can access the same data.
Step 1: Add dependencies
Create a new Rust project and add Axum and Tokio. The task_local! macro is part of Tokio, so no extra crate is needed.
# Cargo.toml
[package]
name = "task-local-example"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
Tokio features:
You need at least the rt feature for the async runtime and the macros feature for #[tokio::main]. Using full is the simplest for learning.
Step 2: Define the struct and task-local
Create a struct that represents the current user. It can be as simple or complex as you like. For now, just a name.
// src/main.rs
use axum::{
extract::Request,
http::StatusCode,
middleware::{self, Next},
response::{IntoResponse, Response},
routing::get,
Router,
};
use tokio::task_local;
#[derive(Clone)]
struct CurrentUser {
name: String,
}
task_local! {
pub static USER: CurrentUser;
}
The task_local! macro expands into a static variable named USER. The pub keyword is optional; here we keep it pub so other modules could use it, but in this single-file example it's just for illustration. The type inside is what will be stored.
Step 3: Write middleware that sets the value
The middleware reads an x-username header. If the header is missing or invalid, it returns 401 Unauthorized. If present, it creates a CurrentUser and calls USER.scope(user, next.run(req)).
// src/main.rs (continuing)
async fn auth(req: Request, next: Next) -> Result<Response, StatusCode> {
// Get the value of the "x-username" header
let username = req
.headers()
.get("x-username")
.and_then(|value| value.to_str().ok())
.ok_or(StatusCode::UNAUTHORIZED)?;
let current_user = CurrentUser {
name: username.to_string(),
};
// Run the rest of the request with USER set to current_user
Ok(USER.scope(current_user, next.run(req)).await)
}
When next.run(req) runs the remaining middleware, router, and handler, the task-local USER is available inside all of that code. After the future completes, the scope ends and USER is no longer accessible.
Step 4: Read the task-local in a handler
Now the handler can access the user with USER.with(). Because with is synchronous, we extract the name into a String before returning it.
// src/main.rs (continuing)
async fn handler() -> String {
let user_name = USER.with(|u| u.name.clone());
format!("Hello, {}!", user_name)
}
Step 5: Build the router and run the server
Finally, assemble everything. We use route_layer to apply the middleware to all routes.
// src/main.rs (continuing)
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.route_layer(middleware::from_fn(auth));
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();
}
Now run the server with cargo run. Test with curl:
curl -H "x-username: Alice" http://127.0.0.1:3000/
You should see:
Hello, Alice!
If you omit the header, the middleware returns a 401 Unauthorized and the handler never runs.
Using task-locals in a custom IntoResponse
One of the strongest reasons to choose task-locals is to make data available to custom response types. In Axum, a handler can return any type that implements IntoResponse. That trait requires a method into_response(self) -> Response with no arguments, so you cannot easily pass the current user into it using normal function parameters. Task-locals solve this elegantly.
Let's modify the previous example so the handler returns a custom UserResponse instead of a plain string, and UserResponse reads the task-local.
First, define the response type:
// src/main.rs (new types)
struct UserResponse;
impl IntoResponse for UserResponse {
fn into_response(self) -> Response {
let current_user = USER.with(|u| u.clone());
(StatusCode::OK, current_user.name).into_response()
}
}
The USER.with call works because USER is still in scope when into_response is called. Axum calls into_response after the handler returns, but it happens within the same task and still inside the middleware's USER.scope. So the value is available.
Change the handler to return UserResponse:
// src/main.rs (modify handler)
async fn handler() -> UserResponse {
UserResponse
}
No other changes are needed. The complete main.rs now looks like:
// src/main.rs - full example
use axum::{
extract::Request,
http::StatusCode,
middleware::{self, Next},
response::{IntoResponse, Response},
routing::get,
Router,
};
use tokio::task_local;
#[derive(Clone)]
struct CurrentUser {
name: String,
}
task_local! {
pub static USER: CurrentUser;
}
async fn auth(req: Request, next: Next) -> Result<Response, StatusCode> {
let username = req
.headers()
.get("x-username")
.and_then(|value| value.to_str().ok())
.ok_or(StatusCode::UNAUTHORIZED)?;
let current_user = CurrentUser {
name: username.to_string(),
};
Ok(USER.scope(current_user, next.run(req)).await)
}
struct UserResponse;
impl IntoResponse for UserResponse {
fn into_response(self) -> Response {
let current_user = USER.with(|u| u.clone());
(StatusCode::OK, current_user.name).into_response()
}
}
async fn handler() -> UserResponse {
UserResponse
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.route_layer(middleware::from_fn(auth));
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();
}
Run and test again. The response is now just the name, without the greeting, because UserResponse returns current_user.name on its own:
curl -H "x-username: Alice" http://127.0.0.1:3000/
Alice
You have successfully used task-locals:
If you see Alice in the response, the task-local value flowed from the middleware into the IntoResponse implementation without being passed as a function argument. That is the core benefit.
Reading task-locals in middleware after the handler
Sometimes you want to access the task-local value after the handler has run, perhaps to log the user who made the request or to add a header to the response. That only works if the logging code runs inside the scope call, because the value stops being available the moment the scope ends. Code that runs after USER.scope(...).await returns can no longer read USER.
So put the logging inside the scoped future, after next.run(req) resolves but before the scope ends:
// corrected auth middleware with logging after handler
async fn auth(req: Request, next: Next) -> Result<Response, StatusCode> {
let username = req
.headers()
.get("x-username")
.and_then(|value| value.to_str().ok())
.ok_or(StatusCode::UNAUTHORIZED)?;
let current_user = CurrentUser {
name: username.to_string(),
};
let response = USER
.scope(current_user, async {
let response = next.run(req).await;
// Now we can read USER because we are still inside the scope
let user = USER.with(|u| u.clone());
println!("Request completed for user: {}", user.name);
response
})
.await;
Ok(response)
}
This prints the username after the handler and response body have been produced but before the response is returned to the client. If you instead wrote the println! after the USER.scope(...).await line, it would panic, because the scope has already ended there.
Multiple task-local variables
You can declare more than one task-local and set them all for a single request. Each one is independent and can hold a different type.
use tokio::task_local;
#[derive(Clone)]
struct RequestId(u64);
#[derive(Clone)]
struct CurrentUser {
name: String,
}
task_local! {
pub static REQUEST_ID: RequestId;
pub static USER: CurrentUser;
}
To set both, you nest the scope calls. Tokio's task_local! does not provide a way to set several variables in one call, so nesting is the only option:
let request_id = RequestId(42);
let current_user = CurrentUser { name: "Bob".to_string() };
let response = REQUEST_ID.scope(request_id, async {
let response = USER.scope(current_user, async {
// Both REQUEST_ID and USER are available here
next.run(req).await
}).await;
// REQUEST_ID is still available, USER is not
response
}).await;
Inside the inner async block, both variables are available. Outside the inner block but still inside the outer block, only REQUEST_ID is available. This nesting can get messy, so consider whether you really need multiple task-locals. Often one is enough.
Accessing a task-local without setting it
What happens if you try to read a task-local variable outside of any scope? The USER.with() call will panic, because there is no value stored for the current task. This is a runtime error, not a compile-time error. That is the main downside compared to the State extractor, which ensures at compile time that the state is available.
For example, remove the middleware from the router:
// This will panic at runtime because USER is never set
let app = Router::new().route("/", get(handler));
A request to / will panic inside the handler, because USER.with() panics when no value has been set for the current task. Axum does not catch that panic and does not turn it into a 500 Internal Server Error. The panic unwinds the task that was handling the connection, so the client gets an empty reply and the connection is dropped. If you want panics to become 500 responses, add tower_http::catch_panic::CatchPanicLayer to your router. To avoid the panic entirely, you can use try_with, which returns a Result instead of panicking:
use tokio::task_local;
task_local! {
pub static USER: CurrentUser;
}
fn get_user_name() -> Option<String> {
USER.try_with(|u| u.name.clone()).ok()
}
try_with returns Ok(value) if the task-local is set, or Err(()) if not. You can then handle the missing value gracefully, perhaps returning a default or an error response.
Forgetting to set a task-local causes a panic:
Always ensure that the code path that reads a task-local is only executed inside the corresponding scope. If you forget to add the middleware or the scope does not cover the handler, USER.with() will panic, the request's task unwinds, and the client gets an empty reply instead of a response. Use try_with in situations where the value might legitimately be absent.
Task-locals and spawned tasks
A crucial limitation: if you spawn a new Tokio task inside the scoped future using tokio::spawn, the new task does not inherit the task-local value. Each spawned task starts with a fresh set of task-locals. So if you do this:
async fn handler() -> String {
// The task-local USER is available here
let name = USER.with(|u| u.name.clone());
// Spawn a new task
tokio::spawn(async move {
// USER is NOT available here! This will panic.
let _ = USER.with(|u| u.name.clone());
});
name
}
The spawned task will panic when it tries to read USER. To share data with spawned tasks, you must explicitly pass the needed data into the task (for example, clone the value and move it into the async block), or use a different sharing mechanism like Arc.
Spawned tasks do not inherit task-locals:
If you need the value inside a tokio::spawn, copy or clone the needed data before spawning and move it into the task. Do not rely on the task-local being present in the child task.
Task-locals vs other sharing methods
It is useful to know when to choose task-locals over the alternatives. Here is a quick comparison based on common scenarios:
| Method | Compile-time safety | Per-request data | Use in IntoResponse | Dynamic (runtime decided) |
|---|---|---|---|---|
State extractor | Yes | No (global app state) | No | No |
| Request extensions | No (runtime check) | Yes | No | Yes |
| Closure captures | Yes | Can be per-route but static | No | No |
| Task-locals | No (runtime check) | Yes | Yes, easily | Yes |
Task-locals excel when you need to pass request-scoped data into many layers without threading it through function arguments, especially custom response types. They are less suitable when you need compile-time guarantees or when you spawn many subtasks.
A realistic use case: request tracing
Imagine you are building a logging system that automatically adds a request ID to every log entry for a given request. Instead of passing the request ID through every function, you can store it in a task-local and have a logging wrapper read it.
Here is a complete version using a custom logger. The middleware generates a request ID from a counter, reads the user agent header, and sets the CONTEXT task-local for the rest of the request:
// src/main.rs
use axum::{
extract::Request,
middleware::{self, Next},
response::Response,
routing::get,
Router,
};
use std::sync::atomic::{AtomicU64, Ordering};
use tokio::task_local;
#[derive(Clone)]
struct RequestContext {
request_id: String,
user_agent: String,
}
task_local! {
pub static CONTEXT: RequestContext;
}
static COUNTER: AtomicU64 = AtomicU64::new(1);
fn log_message(message: &str) {
// Read context if available, otherwise use placeholder
let ctx = CONTEXT.try_with(|c| c.clone()).unwrap_or(RequestContext {
request_id: "unknown".to_string(),
user_agent: "unknown".to_string(),
});
println!("[{}] [{}] {}", ctx.request_id, ctx.user_agent, message);
}
async fn trace_middleware(req: Request, next: Next) -> Response {
let request_id = COUNTER.fetch_add(1, Ordering::SeqCst).to_string();
let user_agent = req
.headers()
.get("user-agent")
.and_then(|value| value.to_str().ok())
.unwrap_or("unknown")
.to_string();
let context = RequestContext {
request_id,
user_agent,
};
CONTEXT.scope(context, next.run(req)).await
}
async fn handler() -> String {
log_message("Handling request");
"done".to_string()
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handler))
.layer(middleware::from_fn(trace_middleware));
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();
}
Run it and send a request with a user agent header:
curl -H "User-Agent: demo-client" http://127.0.0.1:3000/
The response is done, and the server prints a log line that already carries the request context:
[1] [demo-client] Handling request
Any call to log_message inside the handler or response code automatically includes that request ID without extra plumbing. The try_with fallback matters here: if log_message is ever called outside a request, for example during startup, it prints unknown instead of panicking.
Common mistakes and misconceptions
- Assuming task-locals are global or shared across all tasks. They are per-task. Each request is handled inside its own task-local scope, so different requests can safely hold different values. (Note that axum serves each connection from one task, so sequential requests on the same keep-alive connection run in the same task, but each request still gets its own fresh scope.)
- Trying to use task-locals with non-Tokio runtimes. Axum is built on Tokio, so this is usually fine, but if you use
smolor another async runtime,tokio::task_local!will not work. You would need an alternative likeasync-scopedortask-local-extensions. - Accessing a task-local outside its scope. This causes a panic. Always use
try_withif there is any chance the value is not set. - Forgetting to clone before spawning. Spawned tasks lose the task-local, so move any needed data explicitly.
- Overusing task-locals for everything. They make code harder to reason about because data flow is implicit. For global application state that lives forever,
Stateis often better.
Task-locals hide data flow:
Because task-locals bypass explicit function parameters, it becomes harder for someone reading the code to see where data comes from. Use them sparingly and document clearly which task-locals exist and when they are set.
Alternatives to tokio::task_local!
Tokio's macro is the most common because it integrates directly with Axum's Tokio runtime. However, other crates provide similar functionality with slightly different APIs. For example, task-local-extensions allows storing multiple values of different types in a single container with type-based keys. But for most Axum projects, the built-in Tokio macro is sufficient and requires no extra dependencies.
If you need to support multiple async runtimes or want a more flexible API, you might look into async-scoped or the tracing crate's Span which also provides per-task storage through the tracing context. But those are beyond the scope of this page.
When to avoid task-locals
- If your data is global and never changes (like a database pool), use
State. - If you need compile-time guarantees that a value exists, use
StateorExtensionwith proper type checks. - If you spawn many child tasks per request and need the data in them, passing an
Arcmay be simpler and safer.
Task-locals are a tool for ergonomics, not a replacement for all state sharing.
Summary
Choosing between the sharing tools in this chapter is now a short checklist. If the data lives for the whole life of the application, use State: the compiler checks that it exists. If the data changes per request and only handlers need it, use a request extension: middleware inserts it and handlers extract it by type. If the data changes per request and code that takes no arguments must also see it, such as a custom IntoResponse implementation or a helper buried deep in a call chain, use a task-local: only it can reach into those places. And if a spawned task needs the value, none of these will carry it there, so clone the data and move it into the task explicitly.
That last rule points at the real cost of task-locals. They hide data flow, they fail at runtime instead of compile time, and they vanish at the edge of the scope. So use them for exactly one job, passing per-request data into code that cannot receive parameters, and keep everything else on State or extensions. When a task-local panic does happen, the fix is almost always one of two things: the scope does not wrap the reader, or the reader should have used try_with.