State Extractor Overview
A beginner-friendly guide to sharing application state in Axum using the State extractor, with complete examples and walkthroughs
A web server often needs to remember things between requests. A blog needs to know where its articles are stored. An API needs to know its database connection details. A rate limiter needs to keep a running count of requests. In Axum, the State extractor is the primary tool for giving your handlers access to this shared information.
When you write handler functions in Axum, each function is an isolated unit. It receives a request, produces a response, and then disappears. There is no global variable you can read, and no built-in way for two different handlers to access the same data. The State extractor solves this by letting you attach any Rust value to your router once, and then have every handler access it simply by adding a parameter.
Why Handlers Need Shared Data
Imagine you are building a small API that returns the name of your application. The handler that responds to GET / might need to know the app name. You could hardcode the string directly in the handler:
async fn index() -> String {
"Welcome to My App".to_string()
}
That works for one handler. But now you add a second route, GET /about, that also needs the app name. You could copy the string into both handlers:
async fn index() -> String {
"Welcome to My App".to_string()
}
async fn about() -> String {
"My App is the best app ever".to_string()
}
This approach has a real problem. When someone wants to change the app name from "My App" to "My Amazing App", you have to find every handler that uses the old name and update each one. In a small program with two handlers, that is manageable. In a real application with fifty handlers, a configuration change becomes a code change spread across dozens of files.
The solution is to store the app name in one place, at the application level, and pass it to every handler automatically. That is exactly what the State extractor does.
State Is Not a Global Variable:
Shared state in Axum is not the same as a global variable. You never declare a static or use unsafe code. Instead, you create a value, give it to the router once, and Axum passes a clone of it to each handler. This keeps the sharing visible in the type system and avoids many pitfalls of global mutable data.
What the State Extractor Is
An extractor in Axum is any type that can pull data from the incoming HTTP request. You have already seen extractors like Path (which reads values from the URL) and Query (which reads query parameters). The State extractor works differently. It does not read from the request body or the URL. Instead, it pulls the shared application state out of a special compartment that Axum attaches to every request.
When you call .with_state(your_data) on a Router, you are telling Axum: "Here is the data my handlers will need. When any handler asks for it, give it to them." The State<T> extractor is the matching half of that promise. A handler that declares a parameter like State(state): State<AppState> is asking Axum to retrieve the AppState you registered and place it into the variable state.
The key mechanism is cloning. Axum clones the shared state for every incoming request. This means each handler receives its own copy of the state value. If your state is a simple struct with a few strings, cloning is cheap and you can derive Clone on the struct. If your state is large or contains expensive-to-copy resources, you wrap it in an Arc so that cloning only copies a pointer, not the entire data.
Your First State Example
Start with the simplest possible state: a single String. A String in Rust already implements Clone, so you can use it directly without any extra work.
Here is a complete Axum application that shares a single string with one handler:
// src/main.rs
use axum::{extract::State, routing::get, Router};
#[tokio::main]
async fn main() {
// Create the shared state
let app_name = String::from("My Awesome App");
// Build the router and attach the state
let app = Router::new()
.route("/", get(index))
.with_state(app_name);
// Start the server
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
async fn index(State(state): State<String>) -> String {
format!("Welcome to {}", state)
}
# Cargo.toml
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
When you run this and visit http://localhost:3000, the response is:
Welcome to My Awesome App
Walk through the code step by step. In main, you create a plain String containing the app name. You pass it to .with_state(app_name), which attaches it to the router. In the handler, the parameter State(state): State<String> tells Axum to retrieve the String from the state storage and bind it to the variable state. The handler then formats the string into a response.
The crucial detail is the type match. When you call .with_state(app_name), the type of the state is String. When the handler declares State<String>, the types must match exactly. If you pass a String but try to extract a &str, or vice versa, the program will not compile.
Using a Custom Struct for State
A single string is useful for learning, but real applications need to share many values at once. The natural next step is to define a custom struct that holds all the shared data.
// src/main.rs
use axum::{extract::State, routing::get, Router};
#[derive(Clone)]
struct AppState {
app_name: String,
version: String,
author: String,
}
#[tokio::main]
async fn main() {
let state = AppState {
app_name: String::from("My Awesome App"),
version: String::from("1.0.0"),
author: String::from("TechXcelerate"),
};
let app = Router::new()
.route("/", get(index))
.route("/version", get(show_version))
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
async fn index(State(state): State<AppState>) -> String {
format!("Welcome to {} by {}", state.app_name, state.author)
}
async fn show_version(State(state): State<AppState>) -> String {
format!("Version {}", state.version)
}
The #[derive(Clone)] line on AppState is essential. When you call .with_state(state), Axum stores the state and prepares to clone it for every incoming request. If AppState does not implement Clone, the compiler will reject your code with an error. Deriving Clone gives Axum the ability to make copies.
Notice that both handlers use the same type, State<AppState>. They each receive their own clone of the full struct, even if they only use one field. For a struct with three strings, this is trivially cheap. For larger state, you would wrap the struct in an Arc to make cloning more efficient.
When you visit http://localhost:3000, the output is:
Welcome to My Awesome App by TechXcelerate
When you visit http://localhost:3000/version, the output is:
Version 1.0.0
Multiple Handlers Sharing the Same State
One of the main reasons to use the State extractor is that it allows many handlers to access the same data without any manual wiring. The router stores the state once, and every handler that declares State<T> in its parameter list gets access automatically.
Here is an example with four routes, all sharing the same AppState:
// src/main.rs
use axum::{extract::State, routing::get, Router};
#[derive(Clone)]
struct AppState {
app_name: String,
database_url: String,
max_upload_size_mb: u64,
}
#[tokio::main]
async fn main() {
let state = AppState {
app_name: String::from("File Vault"),
database_url: String::from("postgres://localhost/files"),
max_upload_size_mb: 100,
};
let app = Router::new()
.route("/", get(index))
.route("/settings", get(settings))
.route("/health", get(health))
.route("/limits", get(limits))
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
async fn index(State(state): State<AppState>) -> String {
format!("Welcome to {}", state.app_name)
}
async fn settings(State(state): State<AppState>) -> String {
format!("Database: {}", state.database_url)
}
async fn health(State(state): State<AppState>) -> String {
// A health check can confirm the app name is loaded
format!("{} is healthy", state.app_name)
}
async fn limits(State(state): State<AppState>) -> String {
format!("Max upload size: {} MB", state.max_upload_size_mb)
}
Each handler accesses the same original data but reads different fields. There is no code that manually passes the state from one function to another. Axum handles the distribution entirely through the router.
When you run this and hit each route, you get:
GET / → Welcome to File Vault
GET /settings → Database: postgres://localhost/files
GET /health → File Vault is healthy
GET /limits → Max upload size: 100 MB
State Is Cloned for Every Request
The mechanism that makes the State extractor work is cloning. When Axum receives an HTTP request, it looks at the handler's parameters. If it sees State<T>, it clones the stored state value and hands that clone to the handler. The original state remains stored in the router for future requests.
For small structs, cloning is fast and you do not need to think about it. The AppState from the previous example contains three fields (two Strings and one u64). Cloning two strings means copying some heap-allocated bytes. That is an acceptably small cost for most applications.
For larger state, the cost becomes noticeable. Suppose your state includes a large Vec of user records or a heavyweight client for an external service. Cloning the entire thing for every request would be wasteful. This is where Arc comes in.
Arc stands for "Atomic Reference Counted pointer". It is a pointer that can be safely shared between threads. When you clone an Arc<T>, you are not cloning the data inside. You are cloning the pointer and incrementing a counter. Both the original and the clone point to the same underlying data. This makes cloning extremely cheap, regardless of how large the data is.
Here is the same application as before, but with the state wrapped in Arc:
// src/main.rs
use axum::{extract::State, routing::get, Router};
use std::sync::Arc;
struct AppState {
app_name: String,
database_url: String,
max_upload_size_mb: u64,
}
#[tokio::main]
async fn main() {
// Wrap the state in Arc so clones are cheap
let state = Arc::new(AppState {
app_name: String::from("File Vault"),
database_url: String::from("postgres://localhost/files"),
max_upload_size_mb: 100,
});
let app = Router::new()
.route("/", get(index))
.route("/settings", get(settings))
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
async fn index(State(state): State<Arc<AppState>>) -> String {
format!("Welcome to {}", state.app_name)
}
async fn settings(State(state): State<Arc<AppState>>) -> String {
format!("Database: {}", state.database_url)
}
Notice two changes from the previous version. First, the #[derive(Clone)] is gone, because Arc<AppState> already implements Clone regardless of whether AppState does. Second, the handler parameter type changed from State<AppState> to State<Arc<AppState>>. The type you pass to with_state must exactly match the type you extract.
The choice between deriving Clone on your struct and wrapping it in Arc depends on the size of the state and how it is used. For small configuration values, deriving Clone is simpler and requires no extra imports. For large data, connection pools, or values that must not be duplicated, Arc is the better choice.
Match the State Type Exactly:
The type passed to .with_state() must be exactly the same as the type inside State<...> in your handler. If you pass String to with_state but extract State<&str>, or pass Arc<AppState> but extract State<AppState>, the compiler will reject the code. Rust's type system catches this mismatch before the program ever runs.
What Happens When State Is Missing
The State extractor only works when you have called .with_state() on the router. If you declare a handler that uses State<T> but never provide the state to the router, your code will not compile. Axum enforces this at the type level, which is a deliberate design choice.
Consider this broken example:
use axum::{extract::State, routing::get, Router};
#[derive(Clone)]
struct AppState {
app_name: String,
}
#[tokio::main]
async fn main() {
// BUG: We forgot to call with_state
let app = Router::new()
.route("/", get(index));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn index(State(state): State<AppState>) -> String {
format!("Welcome to {}", state.app_name)
}
This code will not compile. The router is inferred to have type Router<()>, meaning it has no state. The handler expects State<AppState>, so the router and the handler disagree. Axum reports this mismatch as a compile-time error, not a runtime error.
This compile-time checking is one of the main advantages of the State extractor over some other sharing patterns. You cannot accidentally run a server that has handlers expecting state but no state registered. The compiler catches the mistake before your server starts.
Forgetting with_state Is a Compile Error:
If you declare a handler with State<T> but do not call .with_state() on the router, the program will not compile. This is intentional. Axum wants you to discover missing state at build time, not at runtime when a user hits your endpoint and gets a cryptic 500 error.
State with Collection Types
State is not limited to strings and structs. You can share any Rust type that implements Clone (or is wrapped in Arc). Collections like Vec and HashMap are common choices for storing shared data.
Here is an example that shares a list of allowed usernames:
// src/main.rs
use axum::{extract::State, routing::get, Router};
use std::sync::Arc;
#[tokio::main]
async fn main() {
let allowed_users = Arc::new(vec![
"alice".to_string(),
"bob".to_string(),
"carol".to_string(),
]);
let app = Router::new()
.route("/users", get(list_users))
.route("/check/bob", get(check_bob))
.with_state(allowed_users);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
async fn list_users(State(users): State<Arc<Vec<String>>>) -> String {
let joined = users.join(", ");
format!("Allowed users: {}", joined)
}
async fn check_bob(State(users): State<Arc<Vec<String>>>) -> String {
if users.iter().any(|u| u == "bob") {
"Bob is allowed".to_string()
} else {
"Bob is not allowed".to_string()
}
}
When you hit GET /users, the output is:
Allowed users: alice, bob, carol
When you hit GET /check/bob, the output is:
Bob is allowed
The state is wrapped in Arc<Vec<String>> because cloning a Vec of strings for every request would be unnecessarily expensive. Cloning the Arc only copies the pointer and increments the reference count.
Passing State to Nested Routers
Real applications often split routes into multiple routers using .nest() or .merge(). The State extractor works seamlessly across these boundaries. You attach the state once, at the outermost router level, and every nested handler can access it.
// src/main.rs
use axum::{extract::State, routing::get, Router};
use std::sync::Arc;
struct AppState {
app_name: String,
}
#[tokio::main]
async fn main() {
let state = Arc::new(AppState {
app_name: String::from("Multi-Service App"),
});
let user_routes = Router::new()
.route("/profile", get(user_profile));
let admin_routes = Router::new()
.route("/dashboard", get(admin_dashboard));
let app = Router::new()
.nest("/users", user_routes)
.nest("/admin", admin_routes)
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
async fn user_profile(State(state): State<Arc<AppState>>) -> String {
format!("{} - User Profile", state.app_name)
}
async fn admin_dashboard(State(state): State<Arc<AppState>>) -> String {
format!("{} - Admin Dashboard", state.app_name)
}
When you hit GET /users/profile, the output is:
Multi-Service App - User Profile
When you hit GET /admin/dashboard, the output is:
Multi-Service App - Admin Dashboard
The state flows through the nested routers automatically. You do not need to call .with_state() on each individual router. Attaching it once at the top level is sufficient, and Axum propagates it down the route tree.
Combining State with Other Extractors
Handlers can use multiple extractors at the same time. The State extractor can be combined with Path, Query, Json, Form, and any other extractor that reads from the request.
// src/main.rs
use axum::{extract::{Path, State}, routing::get, Router};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
api_prefix: String,
}
#[tokio::main]
async fn main() {
let state = AppState {
api_prefix: String::from("v2"),
};
let app = Router::new()
.route("/users/{id}", get(get_user))
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
println!("Listening on http://localhost:3000");
axum::serve(listener, app).await.unwrap();
}
async fn get_user(
State(state): State<AppState>,
Path(user_id): Path<u64>,
) -> String {
format!("API {} - Fetching user {}", state.api_prefix, user_id)
}
The handler declares two extractors. State<AppState> pulls the shared state. Path<u64> pulls the {id} value from the URL path. Axum resolves both before calling the handler. The order of extractor parameters does not matter for State and Path since neither consumes the request body.
When you hit GET /users/42, the output is:
API v2 - Fetching user 42
Your State Extractor Is Working:
If you can run any of the examples above and see the expected output when you visit the routes, your State extractor is configured correctly. The state is flowing from the router into the handler, and the handler is using it to build a response.
Where State Does Not Apply
The State extractor is designed for data that is the same across many requests. It is the right choice for configuration values, database connection pools, shared clients, and similar long-lived resources.
It is not the right choice for data that is unique to each request. If you need to share values that change from request to request, or data that is specific to a particular user session, other mechanisms like request extensions or task-local variables are more appropriate.
It is also not the right tool for mutable state that needs to be updated from multiple handlers simultaneously. If you store a plain integer or string in State and try to mutate it, you will run into Rust's borrowing rules. Handling mutable shared state requires synchronization primitives like Arc<Mutex<T>> or Arc<RwLock<T>>.
The State extractor shines when you have immutable or internally synchronized data that many handlers need to read. For those cases, it is the simplest, most type-safe, and most idiomatic option Axum provides.
Summary
The State extractor is Axum's recommended way to share application-wide data between handlers. You create a value, attach it to the router with .with_state(), and declare State<T> as a handler parameter to receive a clone of that value. The type system ensures that the state type matches between the router and the handler, catching configuration mistakes at compile time.
State is cloned for every request. For small structs, deriving Clone is sufficient. For larger data or resources that must not be duplicated, wrapping the state in Arc makes cloning cheap by only copying a pointer.
This page covered the fundamentals of extracting state in handlers. The concepts that follow in this chapter build on this foundation. Once you understand how to attach and extract state, you can explore more specialized patterns: sharing mutable state with synchronization primitives, extracting only a subset of your state using FromRef, and choosing between Arc, Mutex, and RwLock for different sharing scenarios.