Axum macros feature
How to enable the macros feature flag in Axum and use the FromRef derive for cleaner application state management
When you first try to use #[derive(FromRef)] in an Axum project, you might hit a confusing compile error. The macro simply does not exist. This page explains why that happens, what the macros feature flag actually is, how to enable it, and how to use it properly with application state.
Feature flags in Rust
Before diving into Axum specifically, it helps to understand what a Cargo feature flag is in Rust. A feature flag is a way to turn parts of a library on or off when you add it to your project. The authors of a crate can group code behind named switches, and you decide which switches to flip in your Cargo.toml file.
The main reason libraries do this is compile time. Every feature you enable means more code for the compiler to process, and more dependencies to download. If a library is split into a core part and several optional extras, you can save significant build time by only enabling what you actually use.
Axum follows this pattern. The core routing, handlers, and extractors work without any special features. But some convenience tools - especially derive macros - are packaged separately and only compile when you ask for them. The macros feature is the switch that pulls in those derive macros.
What the macros feature unlocks
In Axum, the macros feature connects the main axum crate to a separate companion crate called axum-macros. That companion crate is a procedural macro crate, which means it contains code that runs at compile time to generate other code for you. It is not included by default: in axum 0.8, the default feature set is form, http1, json, matched-path, original-uri, query, tokio, tower-log, and tracing, and macros is not among them.
The most relevant macro for application state work is FromRef. When you write #[derive(FromRef)] on a struct, the compiler needs that derive macro to exist. The macro lives in axum-macros, and the macros feature on the axum crate re-exports it so you can use it with a simple use axum::extract::FromRef; import.
But FromRef is not the only macro hidden behind this feature. The same feature also gives you access to FromRequest, FromRequestParts, debug_handler, and debug_middleware. These are separate tools with separate purposes, but they all live in the same optional crate and are all unlocked by the same feature flag.
Why a separate crate:
Axum splits its derive macros into a separate proc-macro crate because proc-macro code must compile completely before any of your own code can be type-checked. Keeping the macros separate from the main runtime code allows the core library to compile faster and lets you skip the proc-macro dependency entirely if you never use these derives.
Enabling the macros feature
You have two ways to add the feature to your project. Both produce the same result, so pick whichever fits your workflow.
From your project root, run this command:
cargo add axum --features macros
This modifies your Cargo.toml automatically and pulls in the latest compatible version. If you already have axum in your dependencies, it simply adds the feature to the existing entry.
After adding the feature, run cargo build once. Cargo will download axum-macros and its proc-macro dependencies. This may take a moment the first time.
Checkpoint:
If cargo build completes without errors after adding the feature, you have successfully enabled the macros feature. You can now use #[derive(FromRef)] in your code.
A complete working example
Here is a full example that uses the macros feature to derive FromRef on a substate struct. The derive replaces the manual FromRef implementations with a single line.
[package]
name = "axum-macros-demo"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = { version = "0.8", features = ["macros"] }
tokio = { version = "1", features = ["full"] }
use axum::{
extract::{FromRef, State},
routing::get,
Router,
};
#[derive(Clone, FromRef)]
struct AppState {
api_state: ApiState,
db_state: DbState,
}
#[derive(Clone)]
struct ApiState {
base_url: String,
}
#[derive(Clone)]
struct DbState {
connection_string: String,
}
async fn api_handler(State(api_state): State<ApiState>) -> String {
format!("API base URL: {}", api_state.base_url)
}
async fn db_handler(State(db_state): State<DbState>) -> String {
format!("DB connection: {}", db_state.connection_string)
}
#[tokio::main]
async fn main() {
let app_state = AppState {
api_state: ApiState {
base_url: "https://api.example.com".to_string(),
},
db_state: DbState {
connection_string: "postgres://localhost/mydb".to_string(),
},
};
let app = Router::new()
.route("/api", get(api_handler))
.route("/db", get(db_handler))
.with_state(app_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();
}
The #[derive(FromRef)] attribute on AppState tells the compiler to generate those implementations automatically, one for each field in the struct. This only works because the macros feature is enabled in Cargo.toml and the FromRef trait is imported at the top.
What the derive replaces
Without the feature, you would have to write those two implementations by hand:
impl FromRef<AppState> for ApiState {
fn from_ref(app_state: &AppState) -> ApiState {
app_state.api_state.clone()
}
}
impl FromRef<AppState> for DbState {
fn from_ref(app_state: &AppState) -> DbState {
app_state.db_state.clone()
}
}
Each block clones one field out of the state and hands it to the handler. The trait itself is always available, so these manual implementations never need the macros feature. The feature only buys you the derive that writes them for you. When your state grows to five or ten fields, that is five or ten blocks you no longer write by hand, and one less place for a copy-paste mistake.
Run cargo run and visit http://localhost:3000/api to see API base URL: https://api.example.com. Visit http://localhost:3000/db to see DB connection: postgres://localhost/mydb. Both handlers receive their own substate, extracted from the full AppState behind the scenes.
Derive needs the trait in scope:
Even though #[derive(FromRef)] generates the implementation code, Rust still requires the FromRef trait to be in scope for the derive to work. The use axum::extract::FromRef; import at the top is not optional.
What happens without the macros feature
If you remove features = ["macros"] from Cargo.toml and try to compile the code with #[derive(FromRef)], here is the kind of error you will see:
error: cannot find derive macro `FromRef` in this scope
--> src/main.rs:6:17
|
6 | #[derive(Clone, FromRef)]
| ^^^^^^^
|
= note: `FromRef` is a trait, not a derive macro
The error message points at the problem: the macro is not in scope because the feature is not enabled. The fix is simple: add "macros" to the features list for axum in Cargo.toml and rebuild.
Missing feature causes immediate compile failure:
This is not a runtime error that only shows up when a request hits a handler. The compiler fails before your program can even run. That is actually good news - you find out about the missing feature at build time, not in production.
A different kind of error appears if you try to use the derive but forget the use axum::extract::FromRef; import entirely:
error: cannot find derive macro `FromRef` in this scope
The message is nearly identical, but the cause is different. The feature is enabled, but the trait path is not imported. Adding use axum::extract::FromRef; fixes it. If you get this error, check both the feature flag and the import before digging deeper.
All macros shipped with the feature
The macros feature unlocks more than just FromRef. Here is a quick survey of what else becomes available.
FromRequest and FromRequestParts derives
Just as FromRef generates the code to pull a substate from the full app state, these two derive macros generate implementations of the FromRequest and FromRequestParts traits. These traits are the foundation of Axum's extractor system. Writing a custom extractor normally requires implementing one of these traits by hand, but the derive macros can do the repetitive part for you when your extractor is a struct with extractable fields.
debug_handler attribute
The debug_handler attribute is placed on a handler function. When Axum's type checking fails, for example when you use an extractor in the wrong position or return an invalid response type, the compiler error can be long and cryptic. #[debug_handler] rewrites the error into a much more human-readable message that tells you exactly which argument or return type is causing the problem.
use axum::{debug_handler, extract::State, routing::get, Router};
#[debug_handler]
async fn show_count(State(count): State<u32>) -> String {
format!("Count: {count}")
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/count", get(show_count))
.with_state(42u32);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
This handler is valid, so it compiles normally and visiting /count returns Count: 42. The attribute earns its keep when something is wrong: change the return type to something Axum cannot turn into a response, and the compiler points at the return type and names the missing trait, instead of only printing the long Handler trait-bound failure. Put #[debug_handler] on a handler while you are building it, and remove it or keep it once the handler works, it costs nothing at runtime.
debug_middleware attribute
debug_middleware does the same thing for middleware functions. It produces clearer compiler errors when your middleware has type signature problems.
All of these macros are optional conveniences. None of them are required to build a working Axum application. They exist to reduce boilerplate and make debugging easier, which is why they are grouped under a single feature that you can turn on when you want those conveniences.
Common mistakes and misconceptions
Several specific misunderstandings come up repeatedly with this feature.
Thinking the derive is always available. Many beginners assume that because FromRef appears in the Axum documentation, it should work out of the box. The reality is that the derive macro is gated behind a feature. The trait itself is always available, you can always implement FromRef manually. But the derive macro that writes the implementation for you requires the feature.
Adding the feature but not rebuilding. Adding features = ["macros"] to Cargo.toml does not immediately make the macro available in your editor or compiler. You must run cargo build or cargo check first so Cargo downloads and compiles the axum-macros crate. If your editor shows an error even after adding the feature, try a rebuild.
Enabling the feature but forgetting the import. The feature makes the derive macro exist, but Rust still needs to know where to find it. Without use axum::extract::FromRef; at the top of your file, the derive fails with a "not in scope" error. This feels like the feature is missing, but the feature is fine, the import is the missing piece.
Assuming macros is always on. In axum 0.8, the macros feature is not part of the default feature set. Check your Cargo.toml and your cargo tree -e features output to see whether the feature is actually active in your specific setup.
Using the feature when you do not need it. If you only use manual FromRef implementations, the macros feature is not required. The trait itself is part of the core crate. You only need the feature when you want the #[derive(FromRef)] convenience, or any of the other derive and attribute macros in axum-macros.
Summary
The macros feature in Axum is a single switch in Cargo.toml that connects your project to the axum-macros proc-macro crate. That crate contains the derive macro for FromRef, along with derives for FromRequest and FromRequestParts, and attribute macros for better compiler errors.
The key insight is separation. The core Axum library works without any proc-macro code, which keeps minimal builds fast. When you want the convenience of derived implementations, you opt in with one line in your dependency declaration. When the derive fails to compile, the cause is almost always one of three things: the feature is not enabled, the trait is not imported, or the code has not been rebuilt after adding the feature.
Once the feature is active and the import is in place, #[derive(FromRef)] eliminates entire blocks of boilerplate. You can then focus on the actual structure of your application state rather than the repetitive task of writing from_ref methods for every field.