Closure Captures in Axum - Passing Data Directly to Handlers
Learn how to share application state with Axum handlers using closure captures, with clear examples and beginner-friendly explanations for absolute beginners.
When you build a web server with Axum, you often need to give your request handlers access to some data they wouldn't otherwise have. That data might be a database connection pool, a configuration value, or a counter that many requests need to update. Axum gives you several ways to share that data, and one of the most direct is called closure captures. The name sounds technical, but the idea is simple: you take a variable that already exists in your main function (or anywhere else), and you make it available inside a handler by "capturing" it in a closure. This page is a complete, beginner-friendly guide to doing exactly that.
A Quick Refresher on Closures in Rust
Before jumping into Axum, we need to talk about closures themselves. In Rust, a closure is an anonymous function - a function without a name - that can also capture variables from the surrounding scope. If you have ever written a small inline function in JavaScript or a lambda in Python, you already have the intuition.
Here is a simple Rust closure that does not capture anything:
let say_hello = || {
println!("Hello");
};
say_hello();
The || is the closure's parameter list (it's empty here), and the body is between braces. Now here is a closure that captures a variable:
let name = String::from("Axum");
let greet = || {
println!("Hello, {}!", name);
};
greet();
The closure greet uses name even though name was not passed as an argument. That's a capture. When you use a capture in Rust, the compiler automatically decides how to borrow or move the variable. For our purposes with Axum, we will always use the move keyword to force the closure to take ownership of the captured variables. We'll see why that matters soon.
Closures vs. Functions:
Regular functions in Rust have an explicit signature and cannot capture variables from their surroundings. Closures can. Axum's routing methods accept both, but when you need to pass extra data into a handler, a closure capture is the most direct way.
Why We Need Something Like Closure Captures
Axum handlers are ordinary async functions. They can take extractors - special arguments like Path, Query, Json, or State - to pull data out of the incoming HTTP request. But sometimes you want to give a handler data that is not part of the request at all. It's just something the server already knows, like a shared counter or a read-only configuration string.
For example, imagine you have a server that tells users the name of your application. The name never changes and is known when the program starts. You could hardcode that name inside the handler, but then you would have to change the source code if you ever wanted a different name. Better to store it in a variable once and let the handler use that variable.
One way to do that is by passing the variable through the application state with the State extractor. Another way is closure captures: you literally "bake" the variable into the handler by creating a closure that captures the variable and then moving that closure into the route definition.
The main advantage of closure captures is that they are simple, explicit, and work without any extra traits or layers. The main disadvantage is that they are the most verbose of the four common methods. But for small projects or for per-route configuration, verbosity is often a fine tradeoff for clarity.
Your First Closure Capture: A Simple Number
Let's start with the smallest possible example. We'll create a variable holding an integer, then use a closure that captures that integer and returns it in the HTTP response.
Create a new Rust project with cargo new closure-capture-demo, add the dependencies to Cargo.toml:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
Now replace src/main.rs with:
// src/main.rs
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let port_number: u16 = 8080;
let app = Router::new().route(
"/",
get(move || async move {
format!("This server runs on port {}", port_number)
}),
);
let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Let's unpack what happens here. The variable port_number is declared inside main. We then create a closure with move || async move { ... }. The outer move captures port_number by moving it into the closure. The inner async move moves the already-captured port_number into the future that the async block creates. That may sound redundant, but it's necessary because the closure returns a different future each time it's called. The get function receives this closure and stores it. When a request comes in, Axum calls the closure to produce a future, then polls that future.
Since port_number is a u16, which is a Copy type, moving it into the closure does not cause any ownership problems. The closure can be called many times and always has its own copy of port_number. Run the program, then open http://localhost:8080/ in a browser or use curl. You'll see the response This server runs on port 8080.
Everything is working:
If you see exactly that string in the response, your first closure capture is working correctly. The handler had access to a variable from main without any extractor or state setup.
Capturing a String: Why move and clone Matter
The previous example used a Copy type, so the closure could hold the value directly. But most real-world data is not Copy. Strings, vectors, and custom structs are owned and cannot be duplicated implicitly. If you try to capture a String without thinking about ownership, you will quickly run into compile errors.
Consider this naive attempt:
// This code will NOT compile
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app_name = String::from("My Axum App");
let app = Router::new().route(
"/",
get(|| async {
format!("Welcome to {}", app_name)
}),
);
// ...
}
This fails because the closure tries to borrow app_name, but the closure is required to be 'static (more on that later). The compiler rejects it with error[E0373]: closure may outlive the current function, but it borrows `app_name`, which is owned by the current function. To fix it, we must move app_name into the closure:
// This version compiles: the closure owns app_name by move
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app_name = String::from("My Axum App");
let app = Router::new().route(
"/",
get(move || async move {
format!("Welcome to {}", app_name)
}),
);
// ...
}
Now the closure owns app_name. This version compiles and works. The reason it works is that Axum clones the handler for each request, and each clone owns its own copy of the String. Moving that copy into the response future is safe because no other request shares it. Because String is Clone, the closure itself is Clone, which Axum requires of handlers.
But there is a limitation worth noticing. Every clone of this closure carries its own separate copy of the String. If you register the same pattern on several routes, each route gets its own independent copy of the data, and changes made through one route would never be visible to the others. To share one single value across multiple routes, wrap it in an Arc. Arc stands for "Atomically Reference Counted" and allows multiple owners of the same data with cheap clones. We'll use Arc extensively. An Arc on its own is read-only: you cannot change the text through it. To let handlers update shared data, wrap it in a Mutex or RwLock, as shown below.
Capturing Shared State with Arc
In a real application, you almost never want each handler clone to have its own separate copy of the data. You want them to share the same data. That's what Arc is for. The official Axum documentation uses Arc<AppState> in its closure capture example. Let's build a similar example step by step.
First, define a struct to hold your application state. For now, it can be empty or contain a simple string.
// src/main.rs
use axum::{routing::get, Router};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
app_name: String,
}
#[tokio::main]
async fn main() {
let shared_state = Arc::new(AppState {
app_name: String::from("My Shared App"),
});
let app = Router::new().route(
"/",
get({
let shared_state = Arc::clone(&shared_state);
move || async move {
format!("Welcome to {}", shared_state.app_name)
}
}),
);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Notice the pattern. We create an Arc<AppState> called shared_state. Then inside the route definition, we write a block { ... } that first clones the Arc into a new variable also named shared_state (shadowing). Then we return a closure that captures that clone by move. The closure returns an async block that uses the shared_state clone. Because the Arc is cheap to clone (it just increments a reference count), we can create many clones for different routes without copying the underlying AppState.
When you run this and visit /, you'll see "Welcome to My Shared App".
Don't forget the move:
If you omit the move keyword, the closure will try to borrow shared_state from the surrounding scope. Since the closure must be 'static, that borrow will fail to compile. Always use move when capturing variables in Axum handlers.
Capturing Multiple Values
Often you need more than one piece of data. The same closure capture technique works for any number of variables. Just clone each Arc (or move each value) before the move closure.
Here is an example that captures both an application name and a version string:
// src/main.rs
use axum::{routing::get, Router};
use std::sync::Arc;
#[derive(Clone)]
struct AppConfig {
name: String,
version: String,
}
#[tokio::main]
async fn main() {
let config = Arc::new(AppConfig {
name: String::from("Closure Capture Demo"),
version: String::from("1.0.0"),
});
let app = Router::new().route(
"/info",
get({
let config = Arc::clone(&config);
move || async move {
format!("{} version {}", config.name, config.version)
}
}),
);
// ...
}
If you have multiple independent pieces of data, you can capture them all:
let counter = Arc::new(std::sync::atomic::AtomicUsize::new(0));
let server_name = Arc::new(String::from("localhost"));
let app = Router::new().route(
"/status",
get({
let counter = Arc::clone(&counter);
let server_name = Arc::clone(&server_name);
move || async move {
let count = counter.load(std::sync::atomic::Ordering::SeqCst);
format!("Server {} has served {} requests", server_name, count)
}
}),
);
Here we captured two separate Arcs. Each is cloned once inside the block, then moved into the closure. The closure owns both clones.
The Mechanics Behind the Scenes
When you write get(move || async move { ... }), you are giving Axum a closure that implements the Handler trait. Axum requires handlers to be Clone + Send + Sync + 'static. Let's break that down:
Clone: Axum may need to make copies of the handler. For example, when the router is cloned for each worker thread. A closure isCloneonly if everything it captures isClone.ArcisClone, so closures capturingArcs are cloneable. That's why we almost always wrap shared data inArc.Send: The handler may be moved between threads. Tokio's multi-threaded runtime runs tasks on different threads. A closure isSendif all its captured variables areSend.Arc<T>isSendifTisSend + Sync. OurAppStatestructs need to beSend + Sync. Most simple structs with onlyStringfields satisfy that automatically.'static: The handler cannot borrow any data that might disappear. The closure must own all its data (or own anArcto it). That's why we usemoveandArcinstead of references.
So the typical pattern is: create your data once, wrap it in Arc, then clone the Arc for each closure capture. This satisfies all three bounds and gives shared, safe access to the same data.
Step-by-Step: Adding a Closure Capture to a Route
To make the process concrete, here is a walkthrough for taking an existing route and adding shared state via closure capture.
Step 1: Define your shared data type
Create a struct (or use a primitive) to hold the data you want to share. Derive Clone if needed (though with Arc you often don't need the struct itself to be Clone because you clone the Arc, not the inner data; but it doesn't hurt and is useful if you want to clone the data inside).
Step 2: Create the data and wrap it in `Arc`
In your main function, instantiate the data and wrap it in Arc::new(...). This gives you a shared pointer that can be cloned cheaply.
Step 3: Clone the `Arc` inside a block before the closure
For each route that needs the data, write a block { let my_data = Arc::clone(&original_data); ... }. This creates a new Arc pointing to the same data.
Step 4: Write the closure with `move` and `async move`
Inside that block, return a closure: move || async move { ... }. Use the cloned Arc inside the async block. The move ensures the closure owns the clone.
Step 5: Pass the closure to the routing method
The block evaluates to the closure, which you pass directly to get, post, or any other routing method.
Here is a complete, runnable example following those steps:
// src/main.rs
use axum::{routing::get, Router};
use std::sync::Arc;
#[derive(Clone)]
struct SharedMessage {
text: String,
}
#[tokio::main]
async fn main() {
// Step 2
let message = Arc::new(SharedMessage {
text: String::from("Hello from shared state"),
});
// Steps 3-5 for one route
let app = Router::new().route(
"/",
get({
let message = Arc::clone(&message); // Step 3
move || async move { // Step 4
message.text.clone() // Step 5 (implicit)
}
}),
);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
This returns the text from the shared state. The text itself is fixed here, because a plain Arc only shares read access. To let routes change shared data, the next section wraps the value in a Mutex, which is the standard way to add mutability behind an Arc.
Capturing Mutable State: Using Arc<Mutex<T>> or Arc<RwLock<T>>
So far our shared data has been read-only. But what if you need to update a counter or a list of items from within a handler? Then you need interior mutability. In Rust, you cannot mutate data behind an Arc directly because Arc only provides shared references. The standard solution is to wrap the mutable data in a Mutex or RwLock inside the Arc.
Here is an example with a counter using Arc<Mutex<u32>>. We'll capture that Arc in a closure and increment the counter on each request.
// src/main.rs
use axum::{routing::get, Router};
use std::sync::{Arc, Mutex};
#[tokio::main]
async fn main() {
let counter = Arc::new(Mutex::new(0u32));
let app = Router::new().route(
"/count",
get({
let counter = Arc::clone(&counter);
move || async move {
let mut count = counter.lock().unwrap();
*count += 1;
format!("This page has been visited {} times", *count)
}
}),
);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
When you visit /count repeatedly, the number increases. The lock().unwrap() acquires the mutex, blocking if another request is currently holding it. After incrementing, the mutex is released when count goes out of scope at the end of the async block. This is safe and works across threads.
Don't lock across await points:
If you hold a standard std::sync::Mutex guard across an .await, you will get a compile error because the guard is not Send. In this simple example, the lock is acquired and released within the same synchronous section of the async block, so it's fine. But if you need to hold a lock across an await, use tokio::sync::Mutex instead.
Complete Example: A Small API with Two Handlers
Let's build a slightly larger example that shows closure captures in action with multiple routes and shared data. We'll create an in-memory list of users that can be appended to via a POST endpoint and read via a GET endpoint. This uses Arc<Mutex<Vec<String>>>.
First, the Cargo.toml includes axum, tokio, and serde for JSON extraction:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
Now the full src/main.rs:
// src/main.rs
use axum::{
extract::Json,
http::StatusCode,
response::IntoResponse,
routing::{get, post},
Router,
};
use serde::Deserialize;
use std::sync::{Arc, Mutex};
#[derive(Clone)]
struct AppState {
users: Arc<Mutex<Vec<String>>>,
}
#[derive(Deserialize)]
struct CreateUser {
name: String,
}
#[tokio::main]
async fn main() {
let shared_state = Arc::new(AppState {
users: Arc::new(Mutex::new(Vec::new())),
});
let app = Router::new()
.route(
"/users",
get({
let shared_state = Arc::clone(&shared_state);
move || list_users(shared_state.clone())
}),
)
.route(
"/users",
post({
let shared_state = Arc::clone(&shared_state);
move |Json(payload): Json<CreateUser>| create_user(payload, shared_state.clone())
}),
);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn list_users(state: Arc<AppState>) -> impl IntoResponse {
let users = state.users.lock().unwrap();
let user_list = users.join(", ");
(StatusCode::OK, format!("Users: [{}]", user_list))
}
async fn create_user(payload: CreateUser, state: Arc<AppState>) -> impl IntoResponse {
let mut users = state.users.lock().unwrap();
users.push(payload.name.clone());
(StatusCode::CREATED, format!("User {} created", payload.name))
}
This demonstrates the pattern of using a block to clone the Arc, then passing that clone to an async function inside the closure. Note that the closure returns the future produced by calling list_users or create_user. We could have written the logic directly inside the closure, but extracting it to a named function makes the code cleaner.
Why clone inside the closure?:
In the get route, the closure is move || list_users(shared_state.clone()). Inside the closure, we clone the Arc again before passing it to list_users. Why? Because list_users expects an owned Arc<AppState>, and the closure's captured shared_state is already an Arc. If we just moved it, the closure would lose its copy after the first call. Cloning inside keeps the closure's captured Arc intact for future calls. Alternatively, we could have list_users take a reference, but then we'd need to manage lifetimes, so owned Arc is simpler.
This example is fully runnable. You can test it with curl:
curl http://localhost:3000/usersinitially returnsUsers: [].curl -X POST http://localhost:3000/users -H "Content-Type: application/json" -d '{"name":"Alice"}'returnsUser Alice created.curl http://localhost:3000/usersnow returnsUsers: [Alice].
Common Mistakes and How to Fix Them
Closure captures in Axum are straightforward once you understand the ownership rules, but beginners often hit a few specific errors.
Forgetting move
The most common mistake is writing a closure without move. You'll get a borrow-checker error saying the captured variable does not live long enough. Always use move when capturing variables.
Using a Non-Clone Type
If the closure captures something that is not Clone, the closure itself will not implement Clone. Axum requires Clone. Wrap the data in Arc to make it cloneable (since Arc is always Clone). Even if the inner type is not Clone, Arc<T> is Clone.
Capturing a MutexGuard Across an Await
If you accidentally write code that holds a std::sync::MutexGuard across an .await, you'll get a Send error. The future returned by the async block must be Send, but the guard is not. To fix, either don't await while holding the lock, or use tokio::sync::Mutex.
Trying to Capture a Mutable Variable
A tempting shortcut is to capture a plain mutable variable and increment it inside the closure:
// src/main.rs
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let mut x = 0u32;
let app = Router::new().route(
"/",
get(move || async move {
x += 1;
format!("count {}", x)
}),
);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Surprisingly, this compiles. But it does not count requests. Every request returns the same answer:
curl http://localhost:3000/ → count 1
curl http://localhost:3000/ → count 1
curl http://localhost:3000/ → count 1
The reason is the cloning rule from the previous section. Axum clones the handler for each request, and each clone owns its own separate copy of x, starting at 0. Each request increments its own private copy once and then throws it away, so the count never accumulates. The closure compiles because u32 is Clone, so the closure itself is Clone, but cloning copies the value instead of sharing it. If you want a counter that all requests share, capture an Arc<Mutex<T>> or an Arc<AtomicUsize> instead, as shown above.
Overcomplicating with Multiple Clones
Some beginners clone the Arc both inside and outside the closure unnecessarily. The clean pattern is: clone once in the block before the move, then use that clone inside the closure. You don't need to clone again unless you are passing ownership to another function.
When Should You Use Closure Captures?
The Axum documentation lists four common ways to share state: State extractor, request extensions, closure captures, and task-local variables. Closure captures are a good choice when:
- You have a small amount of data that only one or two routes need.
- You want to keep the data local to the route definition, without setting up application-wide state.
- You are already using closures for other reasons (e.g., custom logic).
- You want to avoid the extra type machinery of
State(thoughStateis often more ergonomic for large apps).
The main downside is verbosity. For a large application with many routes, using State is usually cleaner because you don't repeat the clone-and-move boilerplate. But closure captures are perfectly fine for quick prototypes, small tools, or when you need per-route configuration.
Not a substitute for State:
Closure captures and the State extractor are not mutually exclusive; they solve similar problems in different ways. If you find yourself capturing the same Arc<AppState> in a dozen routes, consider switching to .with_state() and the State extractor.
Summary
Closure captures give you a direct, low-level way to pass data into Axum handlers. You create a closure that captures the needed variables (usually wrapped in Arc for shared ownership), mark it with move, and hand it to the router. The closure becomes the handler, and every request that hits that route will execute the closure, which has access to the captured data. This pattern is explicit, flexible, and easy to understand once you grasp Rust's ownership and the Clone + Send + Sync + 'static requirements.
The key insight is that Axum handlers are just values that implement certain traits. Closures can implement those traits if their captures are chosen carefully. By always using Arc and move, you sidestep most problems. If you need mutable shared state, add a Mutex or RwLock inside the Arc. This knowledge opens the door to building all sorts of shared, stateful handlers without any magic - just plain Rust ownership rules applied consistently.