Compose Small Well-Typed Pieces in Axum
Learn how Axum encourages building web applications from small, type-safe components like handlers, extractors, and middleware, and how to combine them effectively.
Compose Small Well-Typed Pieces in Axum
Axum is designed around a simple idea: build your web application from many small, well-typed pieces and let the Rust compiler check that they fit together correctly. This page explains what that means in practice, why it matters, and how you can start composing your own Axum applications from reusable parts.
What "Small Well-Typed Pieces" Means
In Axum, every building block has a clear type. A handler is a function that takes zero or more extractor types and returns a type that can become an HTTP response. An extractor is a type that can be created from an incoming request. Middleware is a type that wraps a service. A router is a type that maps paths to handlers.
The "well-typed" part means each piece declares exactly what it needs and what it produces. When you connect them, the compiler verifies that the types line up. If you add middleware that needs state you haven't supplied, or write a handler whose extractor types don't fit together, the code will not compile. What the compiler does not check is the data a route actually provides at runtime: a handler that expects a JSON body compiles fine even on a route that never receives one - the failure shows up when a request arrives and the extractor rejects it. This is a feature, not a limitation: you get immediate feedback about composition mistakes before your server ever starts, and the runtime checks that remain are the ones only a real request can answer.
Why Compose Small Pieces
Imagine building a large API as one giant function that handles every possible request. It would be impossible to read, test, or modify. Instead, you break the API into small, focused units. Each unit does one thing well. You then combine these units into a full application. This approach gives you several advantages:
- Reusability: a handler that validates a user ID can be used in many endpoints.
- Testability: you can test each handler in isolation.
- Maintainability: changes to one part don't ripple through the entire codebase.
- Type safety: the compiler checks that each handler's argument types are valid extractors, that its return type can become a response, and that the state types line up. (It does not check route strings against handlers.)
- Clarity: the structure of your code reflects the structure of your API.
Axum's design pushes you toward this style naturally. There are no macros that hide the wiring; everything is explicit Rust code, and the types guide you.
The Building Blocks
Before we compose them, let's look at the individual pieces. Each is a Rust type or function with a well‑defined signature.
Handler Functions
A handler is any async function that returns a type implementing IntoResponse. The simplest handler takes no arguments and returns a string:
async fn hello() -> &'static str {
"Hello, world!"
}
Handlers can also take extractors as arguments. For example, a handler that reads a path parameter:
use axum::extract::Path;
async fn get_user(Path(id): Path<u64>) -> String {
format!("User ID: {id}")
}
The Path type is an extractor; it tells Axum "take the id segment from the URL and parse it as a u64". Note what the compiler does not do here: it does not verify that the route where you use this handler actually has a {id} segment. Path<u64> deserializes the captured value positionally (via serde), so the parameter's name in your handler is irrelevant to the compiler - a name mismatch only shows up at runtime, as the example below shows.
Extractors
Extractors are types that implement FromRequest or FromRequestParts. They pull data out of the request - path parameters, query strings, headers, JSON bodies, application state, etc. Because they are types, you can create your own custom extractors that combine several pieces of data, or reuse existing ones.
The key point for composition: a handler's parameter list declares exactly what it needs. The compiler ensures every extractor in the parameter list can be produced from the request. There's no hidden global state or runtime guessing.
Responses
Any type that implements IntoResponse can be returned from a handler. Axum provides implementations for common types: String, &str, StatusCode, Json<T>, Html<T>, tuples, and more. You can also implement IntoResponse for your own custom types. This means you can write handlers that return domain‑specific error types or result types, and Axum will convert them to HTTP responses in one place.
Middleware
Middleware is code that runs before or after your handler. In Axum, middleware is built on Tower's Layer and Service traits. A layer wraps a service and can modify the request, the response, or both. You can apply middleware to an entire router, a single route, or even a single handler. The type system ensures that the middleware's requirements (e.g., needing access to application state) are satisfied when you attach it.
Routers
A Router is the container that connects paths to handlers and applies middleware. It is itself a type that can be composed: you can nest routers, merge routers, and apply layers to a router or a sub‑router. The router's type tracks the state it still needs, so the compiler can check that state is supplied before serving - but it does not check route strings against handlers.
How Composition Works
Composition in Axum is not magic - it's the result of Rust's trait system and careful design of the framework's APIs. Let's walk through a few examples to see how pieces fit together.
Basic Starter Example
The simplest possible Axum application composes one handler with one route. Create a new Rust project and add axum and tokio to Cargo.toml:
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
Then in src/main.rs:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(hello));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn hello() -> &'static str {
"Hello, world!"
}
Here we have one small piece - the hello handler - and we connect it to the path / using the route method and the get function. The get function converts the handler into a MethodRouter, which is a type that only accepts GET requests. The Router now has a routing table with one entry.
If you run this and visit http://localhost:3000, you'll see the text. The compiler has already confirmed that hello returns a type that implements IntoResponse (&'static str does) and that the route is valid.
Adding More Handlers and Routes
Now let's add a second handler that takes a path parameter:
use axum::{extract::Path, routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello))
.route("/users/{id}", get(get_user));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn hello() -> &'static str {
"Hello, world!"
}
async fn get_user(Path(id): Path<u64>) -> String {
format!("User ID: {id}")
}
We added a route /users/{id} and a handler get_user that uses the Path extractor to get the id as a u64. What the types check here is that Path<u64> is a valid extractor for this handler - the segment value can be parsed into a u64.
Important detail for beginners: a single Path<u64> (or Path(id): Path<u64>) does not check the path parameter's name at compile time. The route could be /users/{id} or /users/{user_id} and the code would still compile. Axum takes the path segment value and tries to parse it as u64. If the URL is not a number, the request is rejected at runtime, not by the compiler.
If you want named fields that must match the route template, use a struct with serde (for example Path<UserId> where UserId has an id field). Then a mismatch between field names and {...} segments shows up as a rejection when the request arrives - still not as a compile error for the route string itself.
#[derive(serde::Deserialize)]
struct UserId {
id: u64,
}
async fn get_user(Path(UserId { id }): Path<UserId>) -> String {
format!("User ID: {id}")
}
With that pattern, /users/{id} matches the id field. A route like /users/{user_id} would not fill id correctly and the extractor would reject the request at runtime.
Compilation Proves Extractor Wiring:
When your Axum application compiles without errors, you have a strong guarantee that the handler's extractor types are wired correctly (for example, that Path, Query, and Json appear in a valid order). Many configuration mistakes that would only appear at runtime in other frameworks are caught before you even start the server. Path parameter names versus route templates are a separate check - often runtime - so still test your routes.
Composing Handlers with Different Response Types
Handlers can return different types as long as each implements IntoResponse. This lets you mix and match responses without any extra ceremony:
use axum::{http::StatusCode, Json, Router, routing::get};
use serde_json::json;
async fn plain_text() -> &'static str {
"Just text"
}
async fn not_found() -> StatusCode {
StatusCode::NOT_FOUND
}
async fn json_response() -> Json<serde_json::Value> {
Json(json!({"message": "Hello from JSON"}))
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/text", get(plain_text))
.route("/missing", get(not_found))
.route("/json", get(json_response));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Here, plain_text returns &'static str, not_found returns StatusCode, and json_response returns Json<Value>. All three are valid because Axum implements IntoResponse for each of those types. The router doesn't care about the concrete return type; it only cares that the handler satisfies the Handler trait, which requires the return type to implement IntoResponse.
Nesting Routers for Modular Composition
As your application grows, you'll want to group related routes together. Axum's Router::nest method lets you mount an entire router under a path prefix:
use axum::{extract::Path, routing::get, Router};
// A router for user-related routes
fn user_routes() -> Router {
Router::new()
.route("/", get(list_users))
.route("/{id}", get(get_user))
}
async fn home() -> &'static str {
"Home page"
}
async fn list_users() -> &'static str {
"List of users"
}
async fn get_user(Path(id): Path<u64>) -> String {
format!("User {id}")
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(home))
.nest("/api/users", user_routes());
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The user_routes function returns a complete Router with its own routes. We then mount it under /api/users. The resulting application serves:
GET /→homeGET /api/users→list_usersGET /api/users/{id}→get_user
This is composition in action: small routers are built independently and then combined. The type of the nested router must be compatible with the parent router. Conflicting route definitions are not a compile error, though - registering two routes for the same path and method panics when the router is built at startup.
Merging Routers
Sometimes you have routers that define absolute paths and you just want to combine them side‑by‑side. Use Router::merge:
use axum::{routing::get, Router};
fn user_routes() -> Router {
Router::new().route("/users", get(list_users))
}
fn health_routes() -> Router {
Router::new().route("/health", get(health_check))
}
async fn list_users() -> &'static str {
"List of users"
}
async fn health_check() -> &'static str {
"OK"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.merge(user_routes())
.merge(health_routes());
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
merge takes another router and combines their routes without any prefix. This is useful when each router is responsible for a top‑level path like /users and /health.
Applying Middleware as Layers
Middleware is added with the layer method. You can apply it to an entire router, a nested router, a specific route, or even a single handler. This flexibility means you can compose cross‑cutting concerns like logging, authentication, and compression exactly where they are needed.
For example, to add request tracing to the whole application:
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;
async fn hello() -> &'static str {
"Hello, world!"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello))
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The layer method wraps the existing router (and all its routes) with the given layer. The resulting router has a different type that includes the middleware. If you later try to add a route that doesn't satisfy the middleware's requirements (e.g., a layer that requires application state), the compiler will complain.
Layers Compose Like an Onion:
With Router::layer, each new layer wraps the previous ones, so the last added layer runs first when a request arrives. For predictable top‑to‑bottom execution order, use tower::ServiceBuilder to combine layers.
Using ServiceBuilder for Multiple Middleware
tower::ServiceBuilder is a convenient way to compose several layers together. It ensures they run in a clear top‑to‑bottom order and keeps your code readable:
use axum::{routing::get, Router};
use tower::ServiceBuilder;
use tower_http::{compression::CompressionLayer, trace::TraceLayer};
async fn hello() -> &'static str {
"Hello, world!"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello))
.layer(
ServiceBuilder::new()
.layer(TraceLayer::new_for_http())
.layer(CompressionLayer::new()),
);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Here TraceLayer runs first, then CompressionLayer, then the handler. Using ServiceBuilder prevents confusion about ordering when you have many layers.
Type-Driven Composition in Depth
The real power of Axum's composition model is that the Rust compiler is your safety net. Let's examine what happens when you get the types wrong.
Example: Missing Path Parameter
Suppose you write:
use axum::{extract::Path, routing::get, Router};
async fn get_user(Path(id): Path<u64>) -> String {
format!("User {id}")
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users/{user_id}", get(get_user));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
This compiles fine - which surprises most beginners. The compiler does not check path-parameter names against the route string, and the router's type does not know the set of path parameters the handler requires. Path<u64> deserializes the single captured value positionally (via serde), so the handler's variable name id versus the route's {user_id} does not matter here: a request to /users/42 runs the handler with id = 42.
The mismatch only bites when the handler extracts path parameters by name, for example with a struct:
use axum::{extract::Path, routing::get, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct Params {
id: u64, // the route calls this segment `{user_id}`, not `{id}`
}
async fn get_user(Path(params): Path<Params>) -> String {
format!("User {}", params.id)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users/{user_id}", get(get_user));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
This also compiles - and then fails at runtime: deserializing the captured {user_id} into a struct that expects a field named id fails, so Axum rejects the request with a 400 Bad Request and the handler never runs. The lesson is that the compiler checks extractor types, not route strings. Route strings still deserve a careful look, and a test that actually sends a request to the route is what catches a name mismatch.
Example: Wrong Extractor Order
When a handler takes multiple extractors, the order matters only for body‑consuming extractors. The rule is simple: at most one extractor may consume the request body, and it must be the last parameter. For example:
use axum::{extract::{Path, Query, State}, Json};
use serde::Deserialize;
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
app_name: String,
}
#[derive(Deserialize)]
struct Pagination {
page: u32,
}
#[derive(Deserialize)]
struct UpdateItem {
name: String,
}
async fn update_item(
State(state): State<Arc<AppState>>,
Path(id): Path<u64>,
Query(pagination): Query<Pagination>,
Json(body): Json<UpdateItem>,
) -> String {
format!(
"{}: updating item {} to {} (page {})",
state.app_name, id, body.name, pagination.page
)
}
Here Json consumes the body and is last. That order matters because of Axum's extractor rule: only the last extractor may implement FromRequest (and therefore may consume the body). Query implements FromRequestParts - it reads query string data from the request parts, not from the body. If you put Json before Query, the compiler rejects the handler signature because a body-consuming extractor (Json) appeared before another extractor. The failure is about extractor ordering, not because Query needs the body.
Body-Consuming Extractor Must Be Last:
Axum enforces that only one extractor can consume the request body (like Json, Form, Bytes, String), and it must be the final parameter in the handler's argument list. If you violate this, you get a compile error. This rule prevents hard‑to‑debug runtime issues where the body is read twice or not at all.
Example: Incompatible State Type
Many applications use shared state via the State extractor. You must provide that state to the router using with_state. The state type must match exactly the type the handler expects.
use axum::{extract::State, routing::get, Router};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
db: String,
}
async fn get_config(State(state): State<Arc<AppState>>) -> String {
format!("DB: {}", state.db)
}
#[tokio::main]
async fn main() {
let state = Arc::new(AppState { db: "postgres".into() });
let app = Router::new()
.route("/config", get(get_config))
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
If you forget with_state or provide a different state type, compilation fails. The handler's State extractor requires a specific type, and the router must be constructed with that exact state.
Common Misconceptions and Mistakes
Misconception: "Composition Means Writing Everything as One Big Router"
Beginners sometimes think they must define all routes in a single Router::new() chain. In fact, breaking routes into smaller routers and composing them with nest or merge is encouraged. It improves organization and reusability.
Mistake: Assuming Router::layer Applies Only to Future Routes
The layer method (and route_layer) applies to all routes that have already been added to the router at that point. If you add routes after calling layer, those routes will not be wrapped by that layer. The order of building your router matters.
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;
async fn hello() -> &'static str {
"Hello, world!"
}
#[tokio::main]
async fn main() {
// This does NOT work as expected:
let app = Router::new()
.layer(TraceLayer::new_for_http()) // applied to nothing yet
.route("/", get(hello)); // not traced
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
To trace all routes, add the layer after all routes are defined:
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;
async fn hello() -> &'static str {
"Hello, world!"
}
async fn list_users() -> &'static str {
"List of users"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello))
.route("/users", get(list_users))
.layer(TraceLayer::new_for_http());
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Layer Order vs Route Order:
If you call layer before adding routes, the layer will not apply to those later routes. Always place layer calls after the routes you want to be covered, or use route_layer for finer control. This is a common source of confusion when middleware appears to be missing.
Mistake: Forgetting That Handlers Must Be Send
Axum handlers are async and run on the Tokio runtime. The future returned by a handler must be Send (safe to move between threads). This usually means your handler's arguments and captured variables must be Send + Sync. If you try to hold a non‑Send type across an .await, compilation will fail. This is Rust's way of keeping your async code safe.
Mistake: Not Deriving Clone for State
The State extractor requires the state type to be Clone. If you pass Arc<AppState>, Arc is Clone, but if you pass the raw struct, it might not be. Axum will tell you to implement Clone.
Practical Real-World Usage
In a real project, you would organize your Axum code into modules. Each feature (users, posts, auth) gets its own module with its own router, handlers, extractors, and middleware. Then you compose them all in main.rs:
mod users;
mod posts;
mod auth;
use axum::Router;
#[tokio::main]
async fn main() {
let app = Router::new()
.nest("/api/users", users::router())
.nest("/api/posts", posts::router())
.nest("/api/auth", auth::router());
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
Each module's router() function returns a Router with its own routes and maybe its own state or middleware. This keeps each piece small, well‑typed, and independently testable.
You can also define custom extractors or response types in a module and reuse them across handlers. For example, a custom AuthUser extractor might read a token from headers and return a User object. Then any handler can just add auth_user: AuthUser to its parameters, and the compiler ensures the token was validated.
Summary
Composing small, well‑typed pieces is the heart of Axum's design. Handlers, extractors, responses, middleware, and routers are all types with clear contracts. You connect them with ordinary Rust method calls (route, nest, merge, layer), and the compiler verifies that each connection is valid. This leads to code that is modular, reusable, testable, and free of an entire class of runtime configuration errors.
The most important insight is that Axum doesn't hide the wiring in macros or magic - it makes the wiring visible and checked. When your application compiles, you know the pieces fit. When it doesn't compile, the error messages point you exactly to the mismatch. As you continue learning Axum, you'll see this pattern everywhere: small pieces, explicit composition, compile‑time safety. That's what makes Axum both pleasant to use and reliable in production.