Ergonomic Modular Design in Axum
Understand how Axum's ergonomic API and modular composition work together to make building web services in Rust clear and maintainable
Ergonomic Modular Design in Axum
Axum describes itself as an HTTP routing and request-handling library that focuses on ergonomics and modularity. Those two words do a lot of work. This page unpacks exactly what they mean, why they matter for you as a beginner, and how they show up in real Axum code. You will see that ergonomic design reduces the amount of typing and mental overhead you need to get a route working, while modular design lets you grow an application from a single file into a clean set of reusable pieces without fighting the framework.
What Ergonomics Means in a Web Framework
Ergonomics is a term borrowed from product design. An ergonomic chair fits your body so you can sit comfortably for hours. An ergonomic API fits the way your brain already thinks about a problem, so you can write code without constantly stopping to look up obscure syntax or satisfy pointless requirements.
For a Rust web framework, ergonomics shows up in several concrete places:
- You do not need to learn a special routing macro or annotation language.
- Handler functions are ordinary
async fnitems, not structs with trait implementations. - Extracting data from a request is as simple as adding a parameter with the right type.
- Returning a response works with plain strings, JSON wrappers, tuples, or custom types that implement one small trait.
The result is that the code you write looks close to what you would sketch on a whiteboard: this path goes to this function, the function takes these inputs, and it returns this output. The framework handles the plumbing behind the scenes.
Example Without Ergonomics (Hypothetical)
To appreciate Axum, consider a pseudo-Rust framework that is not ergonomic. You might have to write something like this:
#[route(GET, "/users/{id}")]
struct GetUserHandler;
impl Handler for GetUserHandler {
type Request = GetUserRequest;
type Response = GetUserResponse;
fn handle(req: GetUserRequest) -> Self::Response {
// manual parsing, manual response building
}
}
That is a lot of boilerplate for what should be one simple function. Axum removes all of that. You write a function, and the framework understands what you mean from its signature.
What Modularity Means in Axum
Modularity is the ability to break a large program into small, independent pieces that you can reason about, test, and reuse. Axum achieves this through a few core building blocks that all fit together because they share common interfaces from the tower and http crates.
The main pieces you compose are:
Router- decides which handler should run for a given path and method.- Handlers - async functions that contain your application logic.
- Extractors - typed request parsers that pull data out of the incoming request.
- Responses - anything that implements
IntoResponse. - Middleware - layers that wrap services to add behavior like logging, timeouts, or authentication.
Each piece does one job well. You build an application by combining them, not by inheriting from a massive base class or filling in a huge config struct.
A First Taste of Ergonomics and Modularity
The canonical Axum hello world is only a few lines, but it already demonstrates both qualities.
use axum::{
routing::get,
Router,
};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "Hello, World!" }));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
This code is ergonomic because the get function accepts a closure or function item directly; you do not wrap it in a special handler type. The Router::new().route(...) chain reads naturally from left to right. The framework figures out that "Hello, World!" can become a valid HTTP response with status 200 OK.
It is modular because the closure that handles the request is a separate piece from the router. You could replace the closure with a named function defined in another module, and the router would not care. That separation of concerns is the seed of modular design.
Everything Compiles:
If you see this code compile and the server starts, you are already using Axum's ergonomic and modular design correctly. The compiler did not ask you to implement any traits or provide any additional context; the framework inferred it all from your function signature.
Ergonomic Routing with Plain Functions
In Axum, a route is just a path string paired with an HTTP method and a handler function. The handler can be defined anywhere - in the same file, in a different module, even in a different crate - as long as it has the right signature.
Separate Handler Functions
use axum::{routing::get, Router};
async fn home() -> &'static str {
"Welcome to the home page"
}
async fn about() -> &'static str {
"This is the about page"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(home))
.route("/about", get(about));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Each handler is an ordinary async fn. You can move home and about into a file named handlers.rs, import them, and the router still works. That is modularity without ceremony.
Handlers with Different Return Types
Because Axum uses the IntoResponse trait, different handlers can return different types. One can return a string, another a Json value, another a status code. The router does not need to know about these types at all.
use axum::{
http::StatusCode,
response::Json,
routing::get,
Router,
};
use serde_json::{json, Value};
async fn plain_text() -> &'static str {
"Just text"
}
async fn json_data() -> Json<Value> {
Json(json!({ "message": "Hello from JSON" }))
}
async fn not_found() -> StatusCode {
StatusCode::NOT_FOUND
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/text", get(plain_text))
.route("/json", get(json_data))
.route("/missing", get(not_found));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The ergonomic benefit here is that you never write code to serialize a string into an HTTP body or to set the Content-Type header for JSON. Returning Json(...) tells Axum to do all of that for you.
Modular Routing with Nested and Merged Routers
As your application grows, you will want to group related routes. Axum gives you two main tools: nest and merge.
Using nest for Path Prefixes
Suppose you have a set of user-related routes: list users, create a user, get one user. You can define them in a separate Router and then nest that under a path prefix like /users.
use axum::{
extract::Path,
routing::{get, post},
Router,
};
fn user_routes() -> Router {
Router::new()
.route("/", get(list_users).post(create_user))
.route("/{id}", get(get_user))
}
async fn list_users() -> &'static str {
"List all users"
}
async fn create_user() -> &'static str {
"Create a new user"
}
async fn get_user(Path(id): Path<u32>) -> String {
format!("Get user {id}")
}
#[tokio::main]
async fn main() {
let app = Router::new()
.nest("/users", user_routes())
.route("/", get(home));
async fn home() -> &'static str {
"Home page"
}
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
With this structure, a request to /users goes to list_users, /users/42 goes to get_user with id = 42, and so on. The user_routes function is a self-contained module that only knows about user routes. You could move it to a separate file without changing main.
Nested Router Paths:
The path prefix you pass to nest is prepended to every route in the nested router. So .route("/", ...) inside user_routes becomes /users after nesting - a nested router at /users matches /users but not /users/, and a nested router at /users/ matches /users/ but not /users. Axum does no trailing-slash redirecting: /users and /users/ are different paths, and the one you did not register returns 404. If both forms must work, register both, or normalise the path before routing with tower-http's NormalizePathLayer::trim_trailing_slash(), wrapped around the whole Router (a Router::layer runs after routing, so it cannot change which route matches).
Wrapping the layer around the whole router looks like this. The key line is NormalizePathLayer::trim_trailing_slash().layer(app): the layer sees the request before the router does, so /users/ is trimmed to /users and matches. into_make_service() turns the wrapped router into the make-service that axum::serve expects.
use axum::{body::Body, extract::Request, routing::get, Router, ServiceExt};
use tower::Layer;
use tower_http::normalize_path::NormalizePathLayer;
async fn list_users() -> &'static str {
"List all users"
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users", get(list_users));
// Wrap the whole router so the path is normalised before routing.
let app = NormalizePathLayer::trim_trailing_slash().layer(app);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
// The layer is generic over the request body type, so the compiler
// needs a hint: `Request<Body>` is Axum's request type.
axum::serve(
listener,
ServiceExt::<Request<Body>>::into_make_service(app),
)
.await
.unwrap();
}
With this in place, both /users and /users/ reach list_users.
Using merge for Composing Independent Routers
nest is useful when routes share a prefix. But sometimes you have two completely independent sets of routes that you want to combine. merge does that without adding any prefix.
use axum::{routing::get, Router};
fn health_routes() -> Router {
Router::new()
.route("/health", get(|| async { "OK" }))
}
fn api_routes() -> Router {
Router::new()
.route("/api/items", get(|| async { "List items" }))
}
#[tokio::main]
async fn main() {
let app = Router::new()
.merge(health_routes())
.merge(api_routes());
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The final router knows about both /health and /api/items. Each subrouter remains independent and can be tested in isolation.
Sharing State Ergonomically with the State Extractor
Most real applications need to share data between handlers - a database pool, a configuration object, or an HTTP client. Axum's State extractor makes this ergonomic and type-safe.
Basic State Sharing
use axum::{
extract::State,
routing::get,
Router,
};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
app_name: String,
}
async fn home(State(state): State<Arc<AppState>>) -> String {
format!("Welcome to {}", state.app_name)
}
#[tokio::main]
async fn main() {
let shared_state = Arc::new(AppState {
app_name: "My Axum App".to_string(),
});
let app = Router::new()
.route("/", get(home))
.with_state(shared_state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The State extractor tells Axum: "This handler needs access to the shared application state of type Arc<AppState>." The router was given that state via with_state. No manual lookup, no global variables. If you forget to call with_state, the router will not satisfy the handler's requirements, and the compiler will tell you.
Cloning State on Every Request:
Axum clones the state for each request. If your state struct is large or contains non-cloneable fields, you should wrap it in Arc (as shown) so that clones are cheap reference-count increments. If your state contains many small cloneable fields, you can also derive Clone directly on the struct and pass it without Arc. The choice depends on what your state holds.
Extracting Substate with FromRef
Sometimes a handler only needs a part of the overall state. Instead of passing the entire AppState, you can use FromRef to extract a substate. This keeps handlers focused and reduces coupling.
use axum::{
extract::{FromRef, State},
routing::get,
Router,
};
#[derive(Clone)]
struct AppState {
database: DatabaseState,
config: ConfigState,
}
#[derive(Clone)]
struct DatabaseState {
pool_size: u32,
}
#[derive(Clone)]
struct ConfigState {
debug: bool,
}
impl FromRef<AppState> for DatabaseState {
fn from_ref(state: &AppState) -> Self {
state.database.clone()
}
}
impl FromRef<AppState> for ConfigState {
fn from_ref(state: &AppState) -> Self {
state.config.clone()
}
}
async fn debug_info(State(config): State<ConfigState>) -> String {
format!("Debug mode is {}", config.debug)
}
async fn pool_info(State(database): State<DatabaseState>) -> String {
format!("Pool size is {}", database.pool_size)
}
#[tokio::main]
async fn main() {
let state = AppState {
database: DatabaseState { pool_size: 10 },
config: ConfigState { debug: true },
};
let app = Router::new()
.route("/debug", get(debug_info))
.route("/pool", get(pool_info))
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
A handler that needs only the ConfigState does not have to know that AppState exists. You provide the FromRef implementation once, and Axum handles the conversion automatically when the handler is called.
Modular Middleware with Tower Layers
Axum does not have its own middleware system. Instead, it uses tower::Service and tower::Layer. This is the single biggest factor that makes Axum modular: every piece of middleware from the tower-http ecosystem works with Axum, and you can even share middleware with other Rust services like Hyper or Tonic.
Applying a Layer to All Routes
use axum::{routing::get, Router};
use tower_http::trace::TraceLayer;
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "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();
}
TraceLayer logs information about every request and response. You did not write any logging code, and you did not modify your handler. You just layered a ready-made middleware on top of your router. If you later want to add compression, you add another .layer(CompressionLayer::new()).
Layer Order Matters:
When you stack multiple layers using successive .layer() calls, they apply in reverse order of appearance (last one added is the outermost layer). This affects the order in which middleware sees requests and responses. If you are unsure, test with logging middleware to observe the order. A common mistake is adding an authentication layer after a logging layer and expecting the auth failure to be logged the same way as a success - the order determines what gets logged.
Building a Modular Application Step by Step
A common beginner question is: "How do I structure a real Axum project so it doesn't turn into a thousand-line main.rs?" The following steps show one natural progression from a single-file app to a modular one. Each step builds on the previous.
Step 1: Start with a Single Router
Begin with everything in main.rs. It works, and that is fine for a tiny prototype.
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "Home" }))
.route("/users", get(|| async { "Users" }))
.route("/health", get(|| async { "OK" }));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
At this stage, you are not worried about modularity; you are just verifying that the server runs.
Step 2: Move Handlers into a Separate Module
Create a handlers.rs file and move the logic there. main.rs becomes smaller.
// handlers.rs
pub async fn home() -> &'static str { "Home" }
pub async fn users() -> &'static str { "Users" }
pub async fn health() -> &'static str { "OK" }
// main.rs
mod handlers;
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(handlers::home))
.route("/users", get(handlers::users))
.route("/health", get(handlers::health));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Now the route definitions are separate from the implementation. You can test the handlers without starting a server.
Step 3: Group Routes with Nested Routers
Create a users.rs module that returns a Router for all user routes.
// users.rs
use axum::{routing::get, Router};
pub fn routes() -> Router {
Router::new()
.route("/", get(list_users))
.route("/{id}", get(get_user))
}
async fn list_users() -> &'static str { "List users" }
async fn get_user() -> &'static str { "Get one user" }
// main.rs
mod users;
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.nest("/users", users::routes())
.route("/", get(|| async { "Home" }))
.route("/health", get(|| async { "OK" }));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
The users module owns everything about user endpoints. If you later add a posts module, you just nest another router.
Step 4: Share State Across Modules
Define an AppState struct in a state.rs file and pass it to the router. Each subrouter can use State extractor to access the parts it needs.
// state.rs
#[derive(Clone)]
pub struct DatabasePool {
size: u32,
}
impl DatabasePool {
pub fn new(size: u32) -> Self {
Self { size }
}
pub fn size(&self) -> u32 {
self.size
}
}
#[derive(Clone)]
pub struct AppConfig {
pub debug: bool,
}
impl AppConfig {
pub fn new() -> Self {
Self { debug: false }
}
}
#[derive(Clone)]
pub struct AppState {
pub db: DatabasePool,
pub config: AppConfig,
}
impl AppState {
pub fn new() -> Self {
Self {
db: DatabasePool::new(10),
config: AppConfig::new(),
}
}
}
// users.rs
use axum::{extract::State, routing::get, Router};
use crate::state::AppState;
use std::sync::Arc;
pub fn routes() -> Router<Arc<AppState>> {
Router::new()
.route("/", get(list_users))
}
async fn list_users(State(state): State<Arc<AppState>>) -> String {
format!("DB pool size: {}", state.db.size())
}
// main.rs
mod state;
mod users;
use axum::{routing::get, Router};
use std::sync::Arc;
#[tokio::main]
async fn main() {
let state = Arc::new(state::AppState::new());
// The outer router must expect the same state type as the nested
// router, so it is created as `Router<Arc<AppState>>` before
// `with_state` turns it back into a plain `Router<()>`.
let app = Router::<Arc<AppState>>::new()
.nest("/users", users::routes())
.route("/", get(|| async { "Home" }))
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Each module now depends only on the state it actually needs, and the composition happens at the top level.
The key insight is that Axum never forces you into a particular project structure. The framework gives you small building blocks, and you decide how to combine them. Start simple, then refactor by moving pieces into modules and functions without changing the underlying logic.
Common Misconceptions and Mistakes
Even experienced developers new to Axum can stumble on a few points related to ergonomics and modularity.
Thinking Ergonomic Means "No Types"
Axum is ergonomic, but it is still Rust. You cannot avoid types entirely. The ergonomics come from the fact that the types are usually inferred or hidden behind small traits like IntoResponse. If you try to return a type that does not implement IntoResponse, the compiler will complain. The fix is not to avoid types but to understand which types Axum already supports and to implement the trait for your own custom types when needed.
Over-modularizing Too Early
It is tempting to split every route into its own file on day one. That often creates more navigation overhead than it saves. The right time to modularize is when a single file gets hard to scan or when you have two clearly independent domains (like users and posts). The steps above show a gradual approach, not an all-at-once rewrite.
Forgetting that Router is Typed
Router has a type parameter representing the state type it expects. A Router<()> is a router with no state. When you call with_state, you get a Router<()> again because the state has been provided. If you see compiler errors involving Router<...> mismatches, it usually means you have a router that requires state but you are trying to nest it into another router without providing that state. The fix is to ensure state is consistently passed at the top level.
Mixing Stateful and Stateless Routers:
If you have a nested router that uses State<AppState> and your top-level router has not yet called with_state, the types will not match and compilation will fail. Always provide state before serving. Axum's type system catches this at compile time, which is a benefit: you cannot accidentally forget state in production.
Summary
Ergonomic modular design in Axum is not a single feature; it is the result of several design choices working together. Plain function handlers, type-driven extractors, the IntoResponse trait, nested routers, and Tower middleware all contribute to an experience where you spend more time writing application logic and less time fighting framework boilerplate.
The most important idea to carry forward is that modularity in Axum comes from composition, not inheritance or configuration files. You build small, focused pieces and combine them with Router, nest, merge, State, and layer. When a piece gets too large, you split it into a new module or function, and the rest of the application does not need to change.
This ergonomic, modular foundation is what makes the rest of this chapter feel natural rather than like separate systems to learn. Each idea reinforces the same pattern: small, well-typed pieces that snap together.