The axum macros feature
Learn what the axum macros feature flag enables, how to turn it on in Cargo.toml, and how to use debug_handler, debug_middleware, and the derive macros for better Rust web development.
What the axum macros feature actually unlocks
The macros feature in the axum crate is a Cargo feature flag that pulls in a companion crate called axum-macros. That companion crate provides procedural macros - small programs that run during compilation and generate Rust code for you. When you enable the macros feature, you get access to attribute macros like debug_handler and debug_middleware, along with derive macros such as FromRef, FromRequest, and FromRequestParts.
These macros do not change how your server runs. They exist to make your life easier while you write and debug code. The most important one for a beginner is debug_handler, which dramatically improves the compiler error messages you see when a handler function has a type mismatch. Without this feature, axum's error messages can be extremely long and difficult to understand. With it, the compiler points you directly at the problem.
The macros feature is strictly a developer-experience tool. You can build a fully working axum server without ever enabling it. Many production applications include it anyway because the time it saves during development - especially when you're learning - is significant.
Macros run at compile time:
A macro in Rust is not like a function. A function runs when your program runs. A macro runs when your program is being compiled. It reads the code you wrote, generates additional Rust code, and inserts that generated code before the compiler finishes. The end user of your server never runs the macro code. They only run the result of what the macro produced.
Why axum puts macros in a separate crate
The axum project is split across multiple Rust crates for a practical reason. The main axum crate contains the router, handlers, extractors, and everything you need at runtime. The axum-macros crate contains only the procedural macros. You never need to add axum-macros to your own Cargo.toml directly - the macros feature on the axum crate handles that automatically.
This separation keeps the main crate lighter and ensures that projects which don't need the macros don't pay for them with longer compile times. Procedural macros require additional compilation machinery, so isolating them in a companion crate means you opt in only when you want the improved error messages and derive helpers.
The axum-macros crate contains no unsafe code. Its minimum supported Rust version is 1.80, the same as the main axum crate, so this is rarely a practical concern for beginners.
Enabling the macros feature in Cargo.toml
Before you can use debug_handler or any of the derive macros, you need to tell Cargo that your project depends on axum with the macros feature turned on. You can do this in two ways: with the cargo add command or by editing Cargo.toml directly.
Method 1: Using cargo add
Open a terminal in your project directory and run:
cargo add axum --features macros
This updates your Cargo.toml automatically. If you already had axum as a dependency, it appends the macros feature to the existing entry. If you didn't have axum yet, it creates the entry with the feature included.
After running that command, your Cargo.toml will contain something like this:
[dependencies]
axum = { version = "0.8", features = ["macros"] }
tokio = { version = "1", features = ["full"] }
Method 2: Editing Cargo.toml manually
Open your Cargo.toml file and find the [dependencies] section. Change the axum line to include the macros feature:
[dependencies]
axum = { version = "0.8", features = ["macros"] }
tokio = { version = "1", features = ["full"] }
If axum already has other features listed - for example, you may already have json or ws enabled - you list them all together inside the same array:
[dependencies]
axum = { version = "0.8", features = ["macros", "json"] }
tokio = { version = "1", features = ["full"] }
That's the entire setup. Once the feature is in your Cargo.toml and you run cargo build or cargo run, the axum-macros crate gets compiled along with everything else, and the macros become available in your code through the axum namespace.
Forgetting the feature causes confusing errors:
If you write #[axum::debug_handler] above a handler function but you forgot to add macros to your axum dependency, the compiler will report that it cannot find debug_handler in the axum crate. The error message will mention the missing macro but won't necessarily tell you it's a feature flag issue. If you see "cannot find attribute debug_handler in crate axum", check your Cargo.toml first.
Your first debug_handler example
Let's build a minimal axum application that uses debug_handler so you can see exactly where the attribute goes and what it looks like in context.
Here's a complete main.rs file for a tiny axum server that serves two endpoints:
// src/main.rs
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(home))
.route("/greet", get(greet));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
async fn home() -> &'static str {
"Welcome to the macros feature demo"
}
async fn greet() -> &'static str {
"Hello from the greet endpoint"
}
This works fine. Now let's add the debug_handler attribute to both handlers:
// src/main.rs
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(home))
.route("/greet", get(greet));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
#[axum::debug_handler]
async fn home() -> &'static str {
"Welcome to the macros feature demo"
}
#[axum::debug_handler]
async fn greet() -> &'static str {
"Hello from the greet endpoint"
}
The only change is that each handler now has #[axum::debug_handler] directly above its async fn definition. When you run cargo run, nothing about the server's behavior changes. You get the same responses, the same routes, the same runtime performance. The difference only appears when something in your handler is wrong.
To understand why that attribute is valuable, you need to see what an axum error looks like without it.
Before and after: compiler errors with and without debug_handler
Axum's handler system is built on Rust's trait system. A handler must implement several traits - Send, Sync, Future, and a specific handler trait that axum defines. When a handler function fails to satisfy one of these requirements, Rust's compiler reports the problem as a trait bound failure. In a large framework like axum, those trait bound failures cascade, producing error messages that can stretch to hundreds of lines.
Consider a handler that accidentally returns a type which doesn't implement the traits axum requires. Here's a slightly incorrect handler:
// Without debug_handler - this will produce a huge error
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(problem_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn problem_handler() -> std::rc::Rc<String> {
// Rc is not Send or Sync, so it cannot be used as an axum response
std::rc::Rc::new("hello".to_string())
}
When you compile this without the macros feature, you'll get an error message that includes deep dives into trait implementations, internal axum types, and various type aliases. The relevant line - the one that tells you what's actually wrong - is buried inside the noise. A beginner reading this error will likely feel lost.
Now add the macros feature to Cargo.toml, then add #[axum::debug_handler] to the same handler:
// With debug_handler - the error becomes readable
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(problem_handler));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
#[axum::debug_handler]
async fn problem_handler() -> std::rc::Rc<String> {
std::rc::Rc::new("hello".to_string())
}
Now when you compile, the error message changes dramatically. The debug_handler macro generates additional code that guides the compiler toward a clearer description of what's wrong. Instead of a trait bound failure nested five levels deep, you get a message that tells you something like: the return type of this handler is Rc<String>, but axum requires the return type to implement IntoResponse, and Rc<String> does not do so.
debug_handler changes error messages, not runtime behavior:
Some beginners think debug_handler is a debugging tool that logs information at runtime. It is not. The word "debug" here refers to debugging your code during compilation. The attribute has zero effect on what your server does when it's running. If you add #[axum::debug_handler] and run your server, you will not see any extra output in the terminal. Its only job is to make compile-time errors more understandable.
How debug_handler works under the hood
When you apply #[axum::debug_handler] to a handler function, the macro inspects the function's signature. It looks at the argument types and the return type. Then it generates a hidden helper function or a type-checking block that forces the Rust compiler to verify each axum-specific trait bound one at a time, rather than all at once.
By checking each requirement separately - "is the return type IntoResponse?", "are all extractor arguments valid?", "is the future Send?" - the macro makes the compiler report the first failing constraint with a targeted message. Without the macro, axum relies on a blanket trait implementation that bundles all requirements together, which is why the error output becomes so large.
This is a useful mental model: debug_handler is not doing anything magical. It's just restructuring the compiler's work so that when something fails, the failure is reported in a human-readable way instead of as a wall of generated type names.
The debug_middleware attribute
Axum's middleware system uses the tower crate's Service trait. A middleware function must implement a specific set of traits to be usable as a layer in your router. The error messages for middleware type mismatches are just as complex as handler errors - sometimes worse, because middleware involves closures and trait objects.
The debug_middleware attribute works the same way as debug_handler, but it applies to middleware functions. Here's a complete example:
// src/main.rs
use axum::{extract::Request, middleware::Next, response::Response, routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(home))
.layer(axum::middleware::from_fn(log_path));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn home() -> &'static str {
"Hello from home"
}
// A middleware function that logs the path of every request
#[axum::debug_middleware]
async fn log_path(
request: Request,
next: Next,
) -> Response {
let path = request.uri().path().to_string();
println!("Request to: {}", path);
let response = next.run(request).await;
response
}
This middleware extracts the path from the incoming request, prints it to the terminal, then passes the request to the next layer in the chain. Note that in axum 0.8 the middleware function is not generic: it takes a concrete Request and a concrete Next, not Request<B> and Next<B>. If the types don't line up - for example, if you return the wrong response type - debug_middleware produces a targeted error that tells you which part of the signature is wrong.
The example above also shows how the middleware is actually used: it is wrapped with axum::middleware::from_fn and applied with .layer(). But for this page, the point is the attribute itself: it sits above the middleware function and improves the compiler output when the middleware signature is incorrect.
debug_middleware requires the macros feature too:
Both debug_handler and debug_middleware are gated behind the same macros feature. There is no separate feature flag for middleware debugging. If debug_handler works in your project, debug_middleware will also be available.
The derive macros bundled with the macros feature
Beyond the two attribute macros, enabling the macros feature also makes three derive macros available: FromRef, FromRequest, and FromRequestParts. These are procedural macros that implement traits for your custom types. They are used far less often than debug_handler in beginner projects, but understanding what they do gives you a complete picture of what the feature flag unlocks.
FromRef derive
The FromRef trait is used when you build axum's application state from a larger struct. In axum, state is any object you want to share with all your handlers - a database connection pool, a configuration struct, a cache. You pass state to the router with .with_state(...), and handlers access it with the State extractor.
The FromRef derive macro lets you automatically implement FromRef for a struct so that each field can be extracted individually from the larger state object. Here's a minimal example:
// src/main.rs
use axum::{extract::State, routing::get, Router};
#[derive(Clone)]
struct DatabaseConnection {
url: String,
}
#[derive(Clone)]
struct RedisCache {
address: String,
}
#[derive(Clone, axum::extract::FromRef)]
struct AppState {
db: DatabaseConnection,
cache: RedisCache,
}
#[tokio::main]
async fn main() {
let state = AppState {
db: DatabaseConnection { url: "postgres://localhost".to_string() },
cache: RedisCache { address: "redis://localhost:6379".to_string() },
};
let app = Router::new()
.route("/", get(home))
.route("/db", get(get_from_db))
.with_state(state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn home() -> &'static str {
"Home route"
}
// This handler only needs the database connection, not the whole AppState
async fn get_from_db(State(db): State<DatabaseConnection>) -> String {
format!("Connected to {}", db.url)
}
The #[derive(axum::extract::FromRef)] on AppState is what makes State<DatabaseConnection> work as an extractor, even though you only passed AppState to .with_state(). The derive generates the code that tells axum "you can get a DatabaseConnection out of an AppState by taking the db field." Without this derive, you'd have to write the FromRef implementation manually. Run the server and visit http://127.0.0.1:3000/db - you will see Connected to postgres://localhost, which proves the handler received just the database connection out of the larger state object.
FromRequest and FromRequestParts derives
FromRequest and FromRequestParts are traits that define custom extractors - objects that pull data out of an incoming HTTP request. Axum implements these traits for built-in extractors like Json, Path, Query, and State. The derive macros let you implement the same traits for your own types with much less boilerplate.
FromRequestParts is used when your extractor only needs to read the request's metadata - headers, method, URI, and so on. FromRequest is used when your extractor needs the entire request body. Here's a small example of a custom parts-based extractor, written as an ordinary manual impl block:
// src/main.rs
use axum::{extract::FromRequestParts, http::request::Parts, routing::get, Router};
// A custom extractor that reads the X-User-Id header
struct UserId(String);
impl FromRequestParts<()> for UserId {
type Rejection = (axum::http::StatusCode, &'static str);
async fn from_request_parts(
parts: &mut Parts,
_state: &(),
) -> Result<Self, Self::Rejection> {
let user_id = parts
.headers
.get("x-user-id")
.and_then(|value| value.to_str().ok())
.map(|value| value.to_string())
.ok_or((
axum::http::StatusCode::BAD_REQUEST,
"Missing x-user-id header",
))?;
Ok(UserId(user_id))
}
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(show_user_id));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn show_user_id(UserId(id): UserId) -> String {
format!("Your user ID is: {}", id)
}
This is a plain manual implementation of the trait: you write the from_request_parts method body yourself, and there is no macro involved. The derive macros are a separate, shorter route for a different shape of extractor: you put #[derive(FromRequestParts)] on a struct whose fields are themselves extractors, and the macro generates the impl for you. For example, a struct with a Query<HashMap<String, String>> field and a typed-header field can derive the trait instead of implementing it by hand. The manual impl above is what you write when the extraction logic is custom, like reading a single header.
Without the derive macro, you would write the same impl block by hand, including several lines of type definitions and trait bounds. The macro eliminates that boilerplate.
Custom extractors are an advanced topic:
If this section felt dense, that's expected. Custom extractors are a bigger topic of their own. For this page, the key point is that the macros feature is what gives you access to these derive macros. You don't need to use FromRequest or FromRequestParts to get value from the macros feature - most beginners use debug_handler far more often.
When to enable the macros feature and when to skip it
The macros feature is not mandatory for any axum application. Whether you include it depends on what you're building and where you are in the learning process.
For a beginner, enabling macros is almost always the right choice. The improved error messages alone are worth the slightly longer compile times. When you're learning axum, you will make handler signature mistakes - that's normal and expected. debug_handler turns those mistakes from a confusing experience into a teachable moment.
For a production application, the calculus is similar. The runtime cost of the macros is zero, and the compile-time cost is modest. Most teams consider the better error messages worth it during development. Some teams strip the macros feature from production builds to minimize binary size and compilation time, but this is an optimization that matters only when you're building very large projects.
The one case where you might reasonably skip macros is when you're writing a small, single-file example that you know works correctly and you want the fastest possible compile times. For a quick prototype with two routes and no custom extractors, the macros add overhead without providing much benefit. In practice, though, the overhead is small enough that enabling macros by default is a sensible habit.
A good default choice:
If you're not sure, enable the macros feature. It costs you a small amount of compile time and gives you significantly better error messages. For a beginner, this trade-off is always worth it. You can remove the feature later if you find you're not using it.
Common mistakes and misconceptions
Several specific errors come up repeatedly when beginners start using the macros feature. Being aware of them in advance will save you time.
Mistake 1: Forgetting to add the feature before using the macros. This is the most common error. The compiler will tell you that debug_handler cannot be found in axum. The fix is to add macros to the features array in your Cargo.toml.
Mistake 2: Expecting debug_handler to print logs at runtime. The name "debug" is misleading if you come from languages where debug means runtime logging. This attribute only affects compiler output. If you want runtime logging, you need a separate logging setup (like the tracing crate).
Mistake 3: Thinking macros changes how axum works internally. It doesn't. The router, handlers, extractors, and the rest of axum behave identically whether or not the macros feature is enabled. The only difference is what happens during compilation.
Mistake 4: Adding axum-macros as a direct dependency. You don't need to. The macros feature on the axum crate already pulls in axum-macros at the right version. Adding it separately can create version conflicts.
Mistake 5: Using debug_handler on a function that isn't an axum handler. The attribute is designed for handler functions. Applying it to arbitrary async functions will produce compiler errors because the macro expects a specific signature.
The most consequential mistake:
The error that will cost you the most time is forgetting to enable the feature in Cargo.toml. When this happens, the compiler error message says something like "cannot find attribute debug_handler in crate axum", which doesn't immediately suggest a feature flag problem. If you see this error, check your Cargo.toml first before changing any code.
Working with multiple feature flags together
In a real project, you'll often want several axum feature flags at once. The macros feature can be combined with any other feature in the same array. Here's what a typical Cargo.toml looks like for a small API server:
[dependencies]
axum = { version = "0.8", features = ["macros", "json", "query"] }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
In this setup, you have macros for debug_handler, json for JSON body extraction, and query for query string extraction. Each feature is independent. Turning on macros doesn't automatically enable json, and vice versa.
Here's the same application using both debug_handler and JSON extraction:
// src/main.rs
use axum::{routing::post, Json, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct CreateUser {
username: String,
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/users", post(create_user));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
#[axum::debug_handler]
async fn create_user(Json(payload): Json<CreateUser>) -> String {
format!("Created user: {}", payload.username)
}
The debug_handler attribute applies cleanly on top of handlers that use extractors. If you make a mistake in the handler signature - for instance, if you forget the Json wrapper or use a type that doesn't implement the right trait - the improved error messages will point you to the exact issue.
The TypedPath macro from axum-extra
You may see TypedPath mentioned in discussions about axum macros. This derive macro actually lives in the axum-extra crate, not in axum-macros directly. It's sometimes grouped with the axum macros because both are procedural macros used in axum projects.
TypedPath provides a way to define routes where the path parameters have a known Rust type, enabling compile-time checking of route paths. Since it requires adding axum-extra as a separate dependency, it's outside the scope of the macros feature itself. Just know that if you encounter TypedPath, it's a related but distinct tool.
Summary
The macros feature is the simplest yet most valuable feature flag you can add to an axum project. It pulls in the axum-macros crate, which provides debug_handler, debug_middleware, and derive macros for FromRef, FromRequest, and FromRequestParts. For a beginner, debug_handler alone justifies enabling the feature - it transforms confusing compiler errors into readable ones.
The key insight is that this feature is entirely about developer experience. Your server behaves identically with or without it. What changes is how much pain you experience when something is wrong with your handler or middleware signature.
If you're building your first axum application, add macros to your Cargo.toml now and put #[axum::debug_handler] above every handler function you write. When you make a mistake - and you will, because that's how learning works - you'll get an error message that helps you understand what went wrong instead of one that buries the answer in a wall of generated type names.