Rocket vs Axum Attribute Macros
Learn how Rocket uses attribute macros for routing and handlers while Axum avoids them in favor of a macro-free API, with side-by-side examples and beginner explanations.
When you first look at Rust web frameworks, one of the most visible differences is how you define routes. Rocket decorates functions with special #[...] attributes like #[get("/")] and #[post("/submit")]. Axum takes a different path: you write ordinary Rust functions and then connect them to paths using a Router builder. This page explains exactly what attribute macros are, how Rocket relies on them, and what Axum does instead.
What Attribute Macros Are
In Rust, a macro is code that writes other code. An attribute macro is a particular kind of macro that you place above an item - like a function, struct, or module - and it transforms that item at compile time. You've probably seen #[derive(Debug)] before; that's a derive macro, which is a special case of attribute macro. Attribute macros are more general: they can add code, remove code, or completely rewrite the item they are attached to.
Rocket uses attribute macros to turn a normal function into a route handler. When you write:
#[get("/hello")]
fn hello() -> &'static str {
"Hello!"
}
Rocket's get attribute macro runs during compilation. It reads the function hello, wraps it with the necessary plumbing so Rocket knows this function should answer HTTP GET requests to the path /hello, and generates extra code that registers the route. Without the macro, that function is just a regular Rust function that returns a string; the macro is what connects it to the web framework.
Axum does not use attribute macros for routing. Instead, you define a plain async function and then pass it to a Router:
use axum::{routing::get, Router};
async fn hello() -> &'static str {
"Hello!"
}
let app = Router::new().route("/hello", get(hello));
Here, hello is still an ordinary function. The get(hello) call is a normal function that wraps hello into a service, and the route method registers that service at the path. No macro transforms hello; it stays exactly as you wrote it.
How Rocket Uses Attribute Macros
Rocket's entire routing model is built around attribute macros. For every HTTP method you want to handle, there is a corresponding attribute: #[get], #[post], #[put], #[delete], #[patch], #[head], #[options]. You place one of these attributes on a function, and the function becomes a route handler. The attribute also specifies the path pattern, which may contain dynamic segments.
A minimal Rocket application looks like this:
// main.rs
#[macro_use]
extern crate rocket;
#[get("/")]
fn index() -> &'static str {
"Welcome to Rocket!"
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index])
}
Several macros are at work here:
#[macro_use] extern crate rocket;imports Rocket's macros globally so you can use#[get],#[launch], androutes!without writingrocket::geteach time. You can also use explicit paths like#[rocket::get("/")]if you prefer.#[get("/")]attaches thegetattribute macro to theindexfunction. The macro generates code that informs Rocket about this route: its HTTP method, its path, and which function to call.#[launch]is an attribute macro on themainfunction. It sets up the asynchronous runtime (Rocket uses Tokio under the hood) and starts the server. You do not write#[tokio::main]; Rocket's#[launch]does that for you.routes![index]is a function-like macro (written with!after the name) that collects the route metadata generated by the attribute macros and bundles it together. You pass that bundle to.mount().
Rocket's macros do a lot of work behind the scenes. When you write #[get("/users/<id>")], the macro parses the path string at compile time, extracts the parameter name id, and generates code that extracts that segment from the URL and passes it to your function as an argument. It also ensures the function's parameter list matches the path's dynamic segments. If they don't match, you get a compile error.
A Slightly Larger Rocket Example
Here is a Rocket handler for creating a user from JSON:
// main.rs
#[macro_use]
extern crate rocket;
use rocket::serde::{Deserialize, json::Json};
#[derive(Deserialize)]
#[serde(crate = "rocket::serde")]
struct NewUser {
name: String,
email: String,
}
#[post("/users", data = "<user>")]
fn create_user(user: Json<NewUser>) -> String {
format!("Creating user {} with email {}", user.name, user.email)
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![create_user])
}
The #[post("/users", data = "<user>")] attribute macro does three things: it registers a POST route at /users, it indicates that the request body should be parsed as JSON into the user parameter, and it wires the Json<NewUser> extractor into the handler. If the request body is not valid JSON or does not match NewUser, Rocket automatically returns an error response - you don't have to write any error handling.
How Axum Avoids Attribute Macros
Axum's core philosophy is to use ordinary Rust functions and the type system instead of macros for routing. You write handlers as plain async functions; you combine them into a Router using builder methods. There is no special attribute that turns a function into a route.
The equivalent Axum application to the Rocket one above is:
// main.rs
use axum::{extract::Json, routing::post, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct NewUser {
name: String,
email: String,
}
async fn create_user(Json(user): Json<NewUser>) -> String {
format!("Creating user {} with email {}", user.name, user.email)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users", post(create_user));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Notice what is missing: no #[macro_use], no #[launch], no routes!. Axum does not require any attribute macro for routing. The create_user function is completely normal - it could be called from anywhere else in your code. The post(create_user) call wraps the function in a MethodRouter that only responds to POST requests. The route method ties that to the path /users.
Axum does use #[tokio::main], but that's not part of Axum; it's a macro from the Tokio runtime, which you use with any Tokio-based application. The routing itself is macro‑free.
Where Axum Does Use Macros
It would be misleading to say Axum never uses macros. Axum provides a few derive macros for convenience, like #[derive(FromRef)] for sharing application state and #[derive(FromRequestParts)] for custom extractors. However, these macros are not used for routing or turning functions into handlers. They are optional and unrelated to how you define routes. The core routing API remains plain Rust function calls.
Versions to know: Rocket 0.5.2 and Axum 0.8.9
The current Rocket line is 0.5.2, released 23 October 2026 (a security-and-maintenance release after 0.5.1 from May 2024). It requires Rust 1.89+ - check the version in your Cargo.toml before copying examples, because Rocket 0.5.0/0.5.1-era posts predate the 0.5.2 release. The current Axum line is 0.8.9 (April 2026, MSRV Rust 1.80).
Rocket's #[launch] and managed state
Two Rocket pieces deserve a closer look, because they have no direct Axum equivalent.
#[launch] is the attribute macro on the function that returns your Rocket instance. It generates the main function, sets up Rocket's Tokio runtime, and starts the server - it replaces #[tokio::main] entirely. You write the rocket-building function; #[launch] writes the entry point.
Managed state is how Rocket shares data with handlers. You register a value with .manage(...), and handlers receive it as a &State<T> parameter:
#[macro_use] extern crate rocket;
use rocket::State;
struct AppState {
message: String,
}
#[get("/")]
fn index(state: &State<AppState>) -> String {
format!("Server says: {}", state.message)
}
#[launch]
fn rocket() -> _ {
rocket::build()
.manage(AppState { message: "Hello from shared state".to_string() })
.mount("/", routes![index])
}
Rocket checks managed state at runtime, not at compile time: if a handler asks for a &State<T> that was never .manage()d, Rocket refuses to launch the application (and in edge cases where its sentinel checks cannot see the problem, the request fails with a 500). Axum's State<T> is the opposite - the state type is part of the Router<S> type, so a missing or mismatched state is a compile-time error.
Side-by-Side Comparison
To see the difference clearly, let's build the same simple API - a health check, a path parameter, and a JSON body - in both frameworks. Each example is shown in Rocket first, then in Axum, so you can read the two versions side by side.
Hello World
Rocket:
// main.rs
#[macro_use]
extern crate rocket;
#[get("/")]
fn hello() -> &'static str {
"Hello, world!"
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![hello])
}
Axum:
// main.rs
use axum::{routing::get, Router};
async fn hello() -> &'static str {
"Hello, world!"
}
#[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();
}
In Rocket, the route is attached directly to the function through the #[get] attribute. The function does not know it's a route until the macro runs. In Axum, the function is an ordinary async function; the routing connection happens later in the Router::new().route(...) call.
Path Parameters
Rocket:
// main.rs
#[macro_use]
extern crate rocket;
#[get("/users/<id>")]
fn get_user(id: u32) -> String {
format!("User ID: {}", id)
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![get_user])
}
Axum:
// main.rs
use axum::{extract::Path, routing::get, Router};
async fn get_user(Path(id): Path<u32>) -> String {
format!("User ID: {}", id)
}
#[tokio::main]
async fn main() {
let app = Router::new().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();
}
The syntax for dynamic path segments is different. Rocket uses <id> inside the attribute string, and the function parameter must be named id. Axum uses {id} in the route string and requires an extractor Path<u32> in the handler. (Axum used :id before version 0.8; in Axum 0.8 that old form panics at registration when the router is built, so always write {id}.) In Rocket, the macro connects the segment name to the parameter name automatically. In Axum, you explicitly write the extractor.
JSON Body
Rocket:
// main.rs
#[macro_use]
extern crate rocket;
use rocket::serde::{Deserialize, json::Json};
#[derive(Deserialize)]
#[serde(crate = "rocket::serde")]
struct NewUser {
name: String,
email: String,
}
#[post("/users", data = "<user>")]
fn create_user(user: Json<NewUser>) -> String {
format!("Creating {} ({})", user.name, user.email)
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![create_user])
}
Axum:
// main.rs
use axum::{extract::Json, routing::post, Router};
use serde::Deserialize;
#[derive(Deserialize)]
struct NewUser {
name: String,
email: String,
}
async fn create_user(Json(user): Json<NewUser>) -> String {
format!("Creating {} ({})", user.name, user.email)
}
#[tokio::main]
async fn main() {
let app = Router::new().route("/users", post(create_user));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
In Rocket, the data = "<user>" attribute tells the macro that the body should be parsed into the user parameter. The macro also performs validation at compile time to ensure the parameter type implements the right traits. In Axum, the Json<NewUser> extractor does the work, and Axum's type system checks that NewUser implements Deserialize. Both approaches are type-safe, but Rocket's is driven by the macro, while Axum's is driven by the extractor trait system.
Why the serde crate attribute?:
Rocket re-exports Serde, so if you derive Deserialize from serde directly, you may need to tell the derive macro which crate to use. The #[serde(crate = "rocket::serde")] attribute ensures the generated code uses Rocket's re-export, avoiding a common beginner error where Serde's derive macro cannot find the crate.
What the Macros Do Behind the Scenes
When Rocket's attribute macro processes #[get("/users/<id>")], it performs several compile-time tasks:
- Parses the path and extracts static segments, dynamic segments, and any query parameters.
- Generates a route metadata structure that includes the HTTP method, the path pattern, and a pointer to the handler function.
- Checks the function signature to make sure it can accept the extracted parameters. For example, if the path has
<id>and the function parameter isid: u32, the macro verifies thatu32implements theFromParamtrait so it can be parsed from a string. - Wraps the function so it conforms to Rocket's internal handler trait, allowing the framework to call it when a request matches.
This is convenient but it means the macro is doing a lot of work that you cannot see. When something goes wrong, the compiler error message may point to the macro-generated code rather than your source, which can be confusing for beginners.
Axum's approach is different. When you write get(handler), the get function is a normal function that returns a MethodRouter. The route method stores the path and the service. There is no code generation beyond what Rust's type system already does. The compiler checks that handler is a valid handler function (i.e., its return type implements IntoResponse and its arguments implement FromRequestParts or FromRequest). Errors are reported directly against your function, which often makes them easier to understand.
Trade-offs: Attribute Macros vs Macro-Free
Both approaches have strengths. Rocket's attribute macros reduce boilerplate and make the connection between a route and its handler visually obvious - you see #[get("/users/<id>")] right above the function. Axum's macro-free approach makes the routing layer explicit and easier to reason about; nothing is hidden, and you can pass handlers around like any other value.
Readability for beginners: Rocket's attribute macros can feel magical. You write a function and add an attribute, and suddenly it's a web endpoint. That's fantastic for quick demos, but it can obscure how the framework works internally. Axum shows you exactly how routes are constructed, which helps you understand the underlying mechanics.
Flexibility: Because Axum handlers are plain functions, you can reuse them easily. You can call a handler from another function, test it in isolation, or wrap it in a closure. Rocket handlers are also functions, but they are tightly coupled to the route macro; extracting the handler for direct testing is possible but requires going through Rocket's testing utilities.
Compile-time checking: Both frameworks catch many errors at compile time. Rocket's macros parse route strings and validate parameter types; Axum's type system validates extractors and responses. However, some errors in Rocket, like a typo in the path string, may only surface when the macro expands, producing less intuitive error messages. Axum's errors tend to be more direct because they originate from normal Rust type mismatches.
IDE support: Attribute macros can sometimes confuse IDE tools like rust-analyzer because the macro expansion is not always fully understood. Axum's macro-free style tends to work better with autocomplete and inline documentation, since the code is exactly what the IDE sees.
Common Mistakes and Misconceptions
Forgetting #[macro_use] extern crate rocket;:
If you try to use #[get] or #[launch] without importing Rocket's macros, you will get a compile error saying those attributes are not found. You can either add #[macro_use] extern crate rocket; at the top of your main.rs, or use the fully qualified forms like #[rocket::get("/")] and #[rocket::launch]. The latter is more modern and avoids polluting the global namespace.
A common misconception is that Axum is "macro-free" in the absolute sense. Axum does use macros from the Tokio ecosystem, like #[tokio::main], and it provides some derive macros for extractors and state. The correct statement is that Axum does not use attribute macros for routing and handler registration. That is a key difference from Rocket.
Rocket's default port is 8000, not 3000:
Rocket's #[launch] starts the server on port 8000 by default. If you try to connect to http://localhost:3000 like you would with Axum, you'll get a connection refused error. The port is configurable in Rocket.toml or through environment variables, but it's a frequent beginner surprise when switching between frameworks.
Another mistake is assuming that because Rocket uses macros, it is slower or less safe. The macros run at compile time and do not introduce runtime overhead. They generate the same kind of code that Axum's builder methods create. Performance differences come from other factors, not from the use of macros.
Both approaches are production-ready:
Rocket and Axum are both used in real projects. The choice between attribute macros and macro-free routing is largely a matter of style and team preference. If you value concise route definitions and a batteries-included feel, Rocket's macros are excellent. If you prefer explicit, composable building blocks and deep integration with the Tower ecosystem, Axum's approach will feel more natural.
When to Prefer One Over the Other
The decision often comes down to your team's background and the project's complexity.
Choose Rocket's attribute macros when:
- You are building a small to medium service and want to move quickly.
- You like having routes declared right next to their handlers.
- You don't need deep integration with Tower middleware or the broader Tokio ecosystem beyond what Rocket provides.
- You are teaching Rust web development and want a gentle, ergonomic introduction.
Choose Axum's macro-free style when:
- You are building a larger service that will grow over time and need explicit control.
- You plan to use Tower middleware, tonic for gRPC, or other Tokio-based libraries.
- You want your routing logic to be testable and composable like ordinary Rust code.
- Your team is already familiar with Tokio and prefers minimal magic.
Neither approach is objectively better; they optimize for different developer experiences.
Summary
Rocket uses attribute macros to turn functions into route handlers, reducing boilerplate but hiding some of the machinery. Axum rejects attribute macros for routing and instead uses a Router builder with plain async functions, making the wiring explicit and composable. The trade-off is between magic and transparency. A beginner can learn both, but the choice comes down to this: pick Rocket's macros if you want the route and the handler written together in one place, and pick Axum's builder if you want the wiring visible and the compiler checking every parameter for you.