Rocket vs Axum Macro-Free Routes

Compare how Rocket uses attribute macros for route definitions while Axum registers routes with plain function calls and no macros

Every web framework needs a way to turn "when a request comes in for /users, run this function" into something the server understands. Axum and Rocket solve that problem with two completely different styles. Rocket decorates ordinary functions with annotation-like macros. Axum does not use any macros at all for routing. Instead, you register routes by calling methods on a Router object, passing your function as a value.

What "macro-free" actually means

A macro in Rust is a piece of code that writes other code before compilation happens. The compiler runs the macro, the macro produces ordinary Rust code, and then that generated code gets compiled. Macros are not hidden runtime magic - they are a compile-time code generation tool.

Rocket relies heavily on macros to turn plain functions into HTTP handlers. You write a normal function, put #[get("/hello")] above it, and Rocket generates the plumbing that connects that function to HTTP routing. You never see the generated code. It just works. Attribute macros are the normal way to define Rocket routes, but they are not the only way: you can also build a route by hand with Route::new(Method::Get, "/hello", handler) and mount it with Rocket::mount - the macros are the convenient path, not the only path.

Axum takes the opposite path. There is no attribute macro that transforms your function. A handler is just an async fn with no decoration whatsoever. You register that function with a Router by passing it as an argument to a method call. The router stores your function and later invokes it when the path and method match.

No hidden code generation in Axum:

When you look at an Axum handler, the entire function you see is the entire function that runs. There is no generated wrapper, no hidden parameter injection, no rewritten signature. What you read is what executes.

This difference matters because it changes how you search for problems, how the compiler reports errors, and how much you need to trust invisible framework machinery.

The smallest Axum route, fully explained

Start with a complete Axum server that has exactly one route. This is the foundation every other Axum example builds on.

// src/main.rs
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/", get(root));
    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();
}
async fn root() -> &'static str {
    "Hello from Axum!"
}

There are three pieces here, and none of them involve a macro. First, Router::new() creates an empty router - a container that maps paths and HTTP methods to handler functions. Second, .route("/", get(root)) adds one entry to that container. The first argument is the path, the second is a MethodRouter built by the get function, which says "this route responds to HTTP GET requests." Third, root is an ordinary async function that returns a static string. It has no attributes above it.

When a request arrives for GET /, Axum looks up the entry, calls root, takes the returned string, and sends it back as the response body with a 200 OK status. When a request arrives for any other path, Axum falls through to a built-in not-found handler and returns 404.

The #[tokio::main] attribute above main is not a routing macro. It sets up the Tokio async runtime, which Axum needs to accept network connections. Rocket uses #[launch] for the same job, but Axum asks you to write the server startup explicitly.

Your first route is working when...:

Run cargo run, then open http://localhost:3000 in a browser or run curl http://localhost:3000. If you see Hello from Axum! in the response body, the router is registered, the handler is connected, and the server is serving requests.

The same route in Rocket for comparison

Here is the equivalent Rocket server. The handler has a macro above it, and the startup also uses a macro.

// src/main.rs
#[macro_use] extern crate rocket;
#[get("/")]
fn root() -> &'static str {
    "Hello from Rocket!"
}
#[launch]
fn rocket() -> _ {
    rocket::build()
        .mount("/", routes![root])
}

The #[get("/")] attribute is doing real work here. It tells Rocket to generate code that parses the path string, sets up the routing metadata, and registers the function. The routes![root] macro collects all the route handlers into a list. The #[launch] macro generates the main function and starts the server. All three pieces are invisible code generation.

In Axum, you can trace every step because every step is a normal function call. In Rocket, you trust that the macros generate correct code, and you never inspect it unless something fails.

Side by side: one route in both frameworks

Look at the core difference with two handlers that do exactly the same thing.

Axum:

use axum::{routing::get, Router};
async fn hello() -> &'static str {
    "Hello there"
}
let app = Router::new()
    .route("/hello", get(hello));

Rocket:

#[get("/hello")]
fn hello() -> &'static str {
    "Hello there"
}
let app = rocket::build()
    .mount("/", routes![hello]);

In the Axum version, the connection between the path /hello and the function hello lives in the .route() call - a normal expression you can read, modify, or inspect with a debugger. In the Rocket version, that connection lives in the attribute above the function, plus the mount call at startup. The routing metadata is split across two locations, and one of them only exists after macro expansion.

A beginner reading the Axum code can see the entire picture: path, HTTP method, handler function, all on one line. A beginner reading the Rocket code needs to know that #[get("/hello")] is not just a comment - it actively changes how the function behaves when passed to routes![].

Why Axum chose the macro-free path

Macros are powerful, but they create three practical problems for a framework.

First, error messages become harder to understand. When a macro generates code and that generated code fails to compile, the compiler often points at the generated code, not at your original function. You might see an error that references types you never wrote. Axum's maintainers deliberately avoid this by keeping the surface area plain Rust, so compiler errors point at your actual function signature.

Second, macros hide the contract between you and the framework. In Rocket, the function signature requirements are inferred from the attribute macro. You have to know what #[get("/<id>")] expects your function parameters to look like. In Axum, the handler is just an async function that returns something Axum can turn into a response. The contract is expressed through ordinary Rust traits, which the compiler checks directly.

Third, macros make it harder to treat handlers as values. In Axum, a handler is a first-class value you can pass around, store, or compose. You can put a handler in a variable and register it in two different routers. The function is not "owned" by the framework - it is just a function.

Handlers as ordinary values:

Because Axum handlers are just functions, you can write let handler = get(hello); and pass handler to any number of routes. There is no macro that binds the function to a single path. The same function can serve /hello, /hi, and /greeting all at once by registering it three times.

This value-based approach also means Axum can use Rust's standard abstraction tools - functions, closures, and types - instead of inventing framework-specific macro syntax. If you already know Rust, you already understand how Axum routes are built.

How Axum registers routes without macros

The Router is a data structure, not a magical registry. You build it step by step, and each .route() call returns a new Router with one more entry. This is a normal builder pattern, the same idea used by dozens of Rust libraries.

Here is a router with several routes, each registered individually:

use axum::{routing::{get, post}, Router};
async fn index() -> &'static str { "Home" }
async fn about() -> &'static str { "About" }
async fn list_users() -> &'static str { "List users" }
async fn create_user() -> &'static str { "Create user" }
let app = Router::new()
    .route("/", get(index))
    .route("/about", get(about))
    .route("/users", get(list_users).post(create_user));

The last line is worth close attention. get(list_users).post(create_user) chains two method handlers onto the same path. That produces a route that responds to GET /users with list_users and to POST /users with create_user. In Rocket, you would write two separate functions with #[get("/users")] and #[post("/users")] attributes and then include both in the routes![] macro.

With Axum you can also chain all five common HTTP methods on one path if the API calls for it:

use axum::routing::{delete, get, patch, post, put};
let app = Router::new()
    .route("/items/{id}",
        get(get_item)
            .put(update_item)
            .patch(patch_item)
            .delete(delete_item)
    );

There is no macro in sight. The path string /items/{id} uses curly braces for a path parameter, which Axum 0.8 introduced to replace the older :id syntax.

Axum 0.8 changed path parameter syntax:

If you are following a tutorial written for Axum 0.7 or earlier, you will see routes like /users/:id. In Axum 0.8, that syntax is no longer valid. You must write /users/{id} instead. The old form does not compile-but-not-match - it panics at registration when the Router is built, so the server crashes at startup with "Path segments must not start with :". That loud failure is deliberate: Axum would rather crash at startup than silently treat :id as a literal string.

Nested and merged routers stay macro-free

Larger applications need to split routes across files and features. Axum handles this with two ordinary methods: nest and merge. Both take routers as values and combine them. No macro coordinates the pieces.

use axum::{routing::{get, post}, Router};
async fn list_users() -> &'static str { "List all users" }
async fn create_user() -> &'static str { "Create a user" }
async fn get_user() -> &'static str { "Get one user" }
async fn delete_user() -> &'static str { "Delete one user" }
fn user_routes() -> Router {
    Router::new()
        .route("/", get(list_users).post(create_user))
        .route("/{id}", get(get_user).delete(delete_user))
}
fn health_routes() -> Router {
    Router::new().route("/health", get(|| async { "OK" }))
}
let app = Router::new()
    .nest("/api/users", user_routes())
    .merge(health_routes());

The nest call prefixes every route inside user_routes with /api/users. The merge call combines two routers at the same level, so /health works alongside /api/users routes. Both methods are plain function calls that take one router and return a new one.

In Rocket, splitting routes across files means collecting all #[get]-decorated functions into routes![] macros and mounting them. The connection between a handler and its path is baked into the attribute, so you cannot reuse the same function at a different path without changing the macro or reaching for more advanced Rocket features. With Axum, the same Router returned by user_routes() can be nested under any prefix you choose, because the path is attached at registration time, not at function definition time.

What beginners usually misunderstand

The most common misunderstanding is believing that Axum's lack of routing macros means Axum is lower-level or harder to use. The opposite is true for many learners: every route is explicit, so there is no need to learn what a particular attribute macro does before you can read the code. A route definition in Axum reads like a statement of fact, not an incantation.

Another misconception is that macros are bad and macro-free is automatically better. Rocket's macros are well designed, and they save typing. The real tradeoff is about visibility and control. Rocket trades some visibility for concise syntax. Axum trades some conciseness for total explicitness. Neither choice is wrong - they serve different preferences.

A third confusion arises when beginners expect Axum to use a macro because they saw #[tokio::main] or #[derive(Deserialize)] elsewhere. Those macros are not routing macros. Axum does use macros in a few optional places, but route registration is not one of them. The routing API is entirely function calls.

Do not mix Rocket syntax into Axum:

Rocket code such as #[get("/")] above an Axum handler will fail to compile, because Axum does not export a get attribute macro. In Axum, get is a function imported from axum::routing, not an attribute you place above a function. If you come from Rocket and write #[get("/")] out of habit, Rust will complain that get is not a valid attribute. Replace it with a .route("/", get(handler)) call.

Another mistake specific to Axum is forgetting that .route() takes a MethodRouter, not a bare function. The code route("/", handler) without wrapping the handler in get(...) or post(...) will not compile. Axum needs to know which HTTP method to associate with the function, because the same path can serve different functions for different methods.

Path parameters in both styles

A route with a dynamic segment shows the contrast clearly. In Axum, the path string and the handler are separate; in Rocket, the path lives in the attribute and the handler signature must match it.

Axum:

use axum::{extract::Path, routing::get, Router};
async fn greet(Path(name): Path<String>) -> String {
    format!("Hello, {name}!")
}
let app = Router::new()
    .route("/hello/{name}", get(greet));

Rocket:

#[get("/hello/<name>")]
fn greet(name: &str) -> String {
    format!("Hello, {name}!")
}
let app = rocket::build()
    .mount("/", routes![greet]);

Both achieve the same result: a request to /hello/world returns Hello, world!. But notice where the path parameter name is declared. In Axum, the placeholder {name} appears in the route string, and separately the handler declares Path(name): Path<String> to extract it. For a single value like Path<String> or Path<u64>, or a tuple like Path<(u32, String)>, the connection is positional, not by name: Axum hands the extractor the captured values in the order they appear in the path, so the variable name in the handler does not have to match the placeholder. Names only matter when the extractor is a struct, where each field is matched to a placeholder of the same name. In Rocket, the placeholder <name> also appears in the attribute, and the function parameter name is matched positionally by Rocket's generated code.

If you rename the path placeholder but forget to update a struct-typed extractor in Axum, the compiler will not catch it - Axum never checks extractor names against route strings at compile time. The code still compiles, and the mismatch only shows up at runtime, when the Path extractor fails to deserialize the captured values and the request is rejected. Rocket, by contrast, does catch this at compile time: its macros compare the <name> in the attribute with the function parameter names.

Two Axum answers to the name-checking gap

Router::without_v07_checks() is the escape hatch for the old syntax. It turns off the startup panic for paths whose segments start with : or *, so a route like /:colon is treated as a literal path (matching a segment that literally starts with a colon) instead of a capture. It does not bring back the old :id capture behavior - it only exists for the rare API that genuinely has literal : or * segments. Do not use it to keep writing :id captures.

TypedPath (from axum-extra) is Axum's real typed-routing answer, and the closest thing to Rocket's compile-time checking. It needs the axum-extra crate with the typed-routing feature:

[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
axum-extra = { version = "0.12", features = ["typed-routing"] }
serde = { version = "1", features = ["derive"] }
use axum_extra::routing::{RouterExt, TypedPath};
use serde::Deserialize;
// The path and the struct fields are tied together by the derive.
#[derive(TypedPath, Deserialize)]
#[typed_path("/users/{id}")]
struct UsersMember {
    id: u32,
}
async fn users_show(UsersMember { id }: UsersMember) -> String {
    format!("User {id}")
}
#[tokio::main]
async fn main() {
    let app = axum::Router::new().typed_get(users_show);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

With TypedPath, the path string lives on the struct and typed_get registers it, so a renamed placeholder that no longer matches a struct field fails to compile - the check Rocket's macros give you, without attribute macros on the handler itself.

How the router actually matches requests

When Axum receives a request, it does not run a macro or consult generated metadata. It looks the path up in a tree of path segments and HTTP methods that you built with your .route() calls. A request for GET /api/users/42 gets split into segments api, users, 42, and each segment is compared against the registered paths as the lookup walks down the tree. The method is checked at the leaf node. If no leaf matches, the fallback 404 handler responds.

This is the same kind of matching a hand-written switch statement would do, except Axum organizes the comparisons into a tree so it does not have to check every route for every request. The important point for understanding macro-free routing is that the tree is built at startup from the .route() calls you wrote. There is no expansion step that rewrites your code. The data structure exists in memory exactly as your builder calls describe it.

Rocket does its own matching, but the routing metadata is assembled by macros at compile time. The routes![] macro collects handlers, and the #[get] attributes carry the path and method information. The end result is also a routing tree, but you never see how it is built.

When explicit registration feels better

One practical advantage of Axum's approach appears when you want to inspect or modify routes conditionally. Because the Router is a normal value, you can wrap route registration in if statements, loops, or helper functions.

use axum::{routing::get, Router};
let mut app = Router::new();
if enable_debug_routes {
    app = app.route("/debug", get(debug_handler));
}
app = app.route("/", get(root));

This conditional registration is ordinary Rust control flow applied to a value. With Rocket, routes are declared as attributed functions at compile time, so enabling or disabling a route based on runtime configuration requires a different mechanism. Axum lets you decide at startup which routes to include, because the router is just a data structure you are building.

Teams building services that share route definitions across binaries also benefit from this. A Router can be constructed in a library, exported, and then nested or merged into multiple different applications. The path prefix can be applied by the consuming binary, not hard-coded in the library. This composition is natural when routes are values, and more awkward when routes are attribute-decorated functions.

Handlers must implement the right traits:

Axum validates handlers at compile time through trait bounds. If your handler's return type does not implement IntoResponse, or if an extractor parameter is not valid, the compiler will produce an error pointing at the .route() call. These errors can look long because they reference trait bounds, but they are almost always caused by one of two things: the handler's return type is not a valid response type, or an extractor is in the wrong position. The fix is usually to adjust the function signature, not to add an attribute.

Practical real-world usage

Axum's macro-free routing shows up most clearly in backend teams that value explicit code review. When a route is added, the diff shows exactly one new line in the router builder - the path, the method, and the handler function, all together. Reviewers can immediately see what changed without understanding what a macro expands to.

Rocket's style, by contrast, is appealing when the team wants each handler to carry its own routing metadata inline. A developer can see #[get("/users")] directly above the function and know immediately where that function lives in the URL space, without searching for a separate router file. Both styles have real teams using them productively. The choice usually comes down to whether your team prefers metadata attached to functions or a central, explicit registry.

For a beginner, Axum's approach tends to be easier to debug because every route is written in code you can read directly. There is no moment where you must trust that a macro did the right thing before you can move on.

Summary

The difference between Rocket and Axum routing is not about what they can do - both can register paths, methods, parameters, and nested routes. The difference is where the routing information lives. Rocket bakes it into attributes above functions, relying on macros to generate the plumbing. Axum keeps it in ordinary function calls that build a router value, with no code generation involved.

That single design choice cascades through everything else. Axum handlers are plain functions you can pass around. Route registration is conditional, composable, and visible. Compiler errors point at your code, not at generated code. Rocket handlers are plain functions too, but the attribute macro stands between you and the framework contract.

If you are trying to decide which style feels right, write the same small API in both. Pay attention to where you look when something goes wrong. In Axum, you look at the .route() call. In Rocket, you look at the attribute and the routes![] list. Whichever location feels natural to you is the framework whose mental model fits your way of thinking.