Router::new revisit
Understand what Router::new does, why every Axum application starts with it, and how to use it correctly when building your HTTP routing table.
Router::new is the function that creates an empty Axum router. It is the starting point for every Axum application because a router holds the mapping between incoming HTTP requests and the functions that handle them. Without Router::new, you have no place to register routes.
What Is Router::new?
In Axum, a Router is a data structure that stores routing rules. Each rule connects an HTTP method and a path to a handler function. For example, a rule might say: when a GET request arrives at /, call the hello handler.
Router::new() is a constructor function. It creates a Router that contains no rules at all. That empty router is not useful on its own, but it gives you a starting point to build on. You add rules with the .route() method, which returns a new Router with that rule included. Because .route() returns a new router, you can chain many .route() calls together in one expression.
The type of the value returned by Router::new() is Router<()>. The () is the Rust unit type, which means "no data". In Axum, the Router type has a generic parameter for application state. We will revisit state much later in this course, but for now the important point is that Router::new() always starts with the unit type because no state has been attached yet.
The Simplest Possible Example
Before building anything larger, start with a minimal main function that uses Router::new and serves exactly one route.
// src/main.rs
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("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
This code does three things. First, it calls Router::new() to create an empty router. Second, it calls .route("/", get(handler)) to register one route. Third, it passes the finished router to axum::serve so that incoming connections can be matched against it.
When you run this program with cargo run, the server starts listening on 127.0.0.1:3000. If you open a browser to http://127.0.0.1:3000, you will see the text Hello, world!.
This Is the Correct Starting Pattern:
A complete Axum application always begins with Router::new(). If you see that exact function call in your code, followed by one or more .route() calls, you are on the right track.
The Builder Pattern Behind Router::new
Router::new() returns a value that behaves like a builder. A builder is an object that starts empty and lets you add pieces to it one method at a time. Each call to a method like .route() does not modify the original router. Instead, it creates a brand-new Router that contains everything the original had plus the new route.
Because the original router is never changed, you can safely chain methods in one long expression:
let app = Router::new()
.route("/", get(home))
.route("/about", get(about))
.route("/contact", get(contact));
Here, Router::new() creates an empty router. The first .route() creates a second router that knows about /. The second .route() creates a third router that knows about / and /about. The third .route() creates the final router that knows all three paths. The variable app gets the final router.
If you prefer, you can keep the intermediate routers in separate variables:
let empty_router = Router::new();
let with_home = empty_router.route("/", get(home));
let with_about = with_home.route("/about", get(about));
let app = with_about.route("/contact", get(contact));
Both versions produce exactly the same final router. The chained style is more common because it is shorter and easier to read.
The Router Is Immutable:
Router::new() does not create a mutable object that you change in place. It creates an immutable value. Every .route() call produces a new immutable value. This design makes it harder to accidentally break a working router.
The State Type Parameter Explained
The return type of Router::new() is Router<()>. The angle brackets after Router indicate that Router is generic over a state type. In Axum, handlers can optionally extract shared application state. The state type is part of the router type so the compiler can check that every handler gets the correct state.
The unit type () is Rust's way of saying "nothing here". When you call Router::new(), you have not attached any state, so the state type parameter is (). Later, if you call .with_state(some_value), the router becomes Router<YourStateType>. But that is a topic for a later page. For now, remember that Router::new() always yields a router with no state.
A handler that does not use state can be registered on a Router<()>. A handler that does use state cannot be registered on a Router<()> because the compiler would see a type mismatch. The error message will point you toward adding .with_state(...).
use axum::{
extract::State,
routing::get,
Router,
};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
message: String,
}
// This handler expects state of type Arc<AppState>
async fn handler(State(state): State<Arc<AppState>>) -> String {
state.message.clone()
}
#[tokio::main]
async fn main() {
// ERROR: cannot register handler that needs Arc<AppState>
// on a Router<()> produced by Router::new().
let app = Router::new()
.route("/", get(handler));
}
If you try to compile that code, you will get a compile-time error. The fix is to provide the state with .with_state(...). You can call it after the .route() calls - that is the usual pattern, and it works because the state type is inferred from the .with_state() call:
let state = Arc::new(AppState {
message: "Hello from state".to_string(),
});
let app = Router::new()
.route("/", get(handler))
.with_state(state);
Forgetting with_state Causes a Compile Error:
A handler that extracts state must be registered on a router whose state type matches. Router::new() always creates Router<()>, so any state-using handler will fail to compile unless you call .with_state() somewhere in the chain. The compiler will catch this mistake before you even run the program.
Building a Router with Multiple Routes and Methods
A realistic Axum application will have more than one route and more than one HTTP method. Router::new() is the base for all of them.
// src/main.rs
use axum::{
routing::{get, post},
Router,
};
async fn home() -> &'static str {
"Welcome to the home page"
}
async fn about() -> &'static str {
"This is the about page"
}
async fn submit() -> &'static str {
"Form submitted!"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(home))
.route("/about", get(about))
.route("/submit", post(submit));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
In this example, GET / goes to home, GET /about goes to about, and POST /submit goes to submit. A request with a method that does not match any route for a given path will produce a 405 Method Not Allowed response. A request to a path that has no routes at all will produce a 404 Not Found response.
An Empty Router Always Returns 404:
If you call Router::new() and then immediately pass it to axum::serve without adding any routes, every request will receive a 404 Not Found response. The router has no rules, so it cannot match anything. Always add at least one route before serving.
Alternative Ways to Build a Router from Router::new
There are several common patterns for using Router::new. They all start the same way, but they differ in how the routes are organized.
Inline Route Handlers
For very small applications, you can write the handler as a closure directly inside the .route() call. The closure must still be async - it has to return an async block, exactly like a named async fn handler. A plain synchronous closure that returns a string does not compile, because it does not implement the Handler trait.
let app = Router::new()
.route("/", get(|| async { "Home" }))
.route("/health", get(|| async { "OK" }));
This avoids separate handler functions and keeps everything in one place. It works well for tiny examples and for health-check endpoints that never change.
Separate Handler Functions
For anything beyond a few routes, you should define handler functions separately. This makes the code easier to read and test.
async fn home() -> &'static str { "Home" }
async fn health() -> &'static str { "OK" }
let app = Router::new()
.route("/", get(home))
.route("/health", get(health));
Using the merge Method
If you have several routers that each define their own full paths, you can merge them into a single router. Router::new() is still the starting point for the final router.
use axum::{routing::get, Router};
async fn list_users() -> &'static str {
"Here is the list of users"
}
async fn get_user() -> &'static str {
"Here is one user"
}
async fn admin_dashboard() -> &'static str {
"Admin dashboard"
}
fn user_routes() -> Router {
Router::new()
.route("/users", get(list_users))
.route("/users/{id}", get(get_user))
}
fn admin_routes() -> Router {
Router::new()
.route("/admin", get(admin_dashboard))
}
let app = Router::new()
.merge(user_routes())
.merge(admin_routes());
Here, Router::new() creates the base router, and .merge() combines the other routers into it. The final app router contains all routes from both user_routes and admin_routes. Each small function builds its own router with Router::new(), so each group of routes stays in one place and the final router is assembled from the pieces.
How Router::new Fits into the Async Runtime
Router::new is a synchronous function. It does not perform any asynchronous work. It simply allocates a new, empty router and returns it. You can call it anywhere, even outside an async context.
The router becomes useful only when you pass it to axum::serve, which is an async function. That function takes a listener and a router, and it runs the server loop. The router is Send (but not Sync), and axum::serve requires the service it is given to be Clone + Send + 'static - a plain Router satisfies that, so in a typical single-main async program you just build it and move it into the serve call.
#[tokio::main]
async fn main() {
// Router::new() runs synchronously here.
let app = Router::new().route("/", get(handler));
// serve is async and runs until the server shuts down.
axum::serve(listener, app).await.unwrap();
}
The router implements the tower::Service trait, which means it can process individual HTTP requests. axum::serve turns incoming TCP connections into requests and feeds them to the router. The router then looks up the matching route and calls the associated handler.
A Step-by-Step Walkthrough of Building a Router
Because beginners often learn best by following a sequential process, here is a concrete example that builds a router for a small task API.
Step 1: Create an empty router
Start with Router::new(). This creates a Router<()> with no routes.
let app = Router::new();
Step 2: Add a GET route for listing tasks
Register a handler for GET /tasks.
let app = app.route("/tasks", get(list_tasks));
Step 3: Add a POST route for creating a task
Register a handler for POST /tasks.
let app = app.route("/tasks", post(create_task));
Step 4: Serve the router
Bind a listener and pass the final router to axum::serve.
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
Each step depends on the previous one. You cannot serve a router before you create it, and you cannot register routes on a router that does not exist. This sequence is exactly how a real Axum application is assembled.
Common Misconceptions About Router::new
Misconception 1: Router::new Starts the Server
Some beginners think that calling Router::new() will start an HTTP server. It does not. It only builds an in-memory routing table. The server starts only when you call axum::serve.
Misconception 2: Router::new Is a Macro
Router::new looks like a function call because it is one. It is not a macro. There is no special syntax or compile-time magic. You can call it like any other function.
Misconception 3: Router::new Returns a Service That Handles All Paths Automatically
The router returned by Router::new() is empty. It has no routes and will respond with 404 Not Found to every request until you add at least one route. There is no default handler for unknown paths.
Misconception 4: Router::new Takes Arguments
Router::new takes no arguments. It always creates a fresh, empty router. If you want to pre-populate a router with routes, you must call .route() afterward.
Router::new Does Not Do Routing by Itself:
Many newcomers assume that an Axum application automatically knows how to handle common paths like / or /health. That is not true. Every path you want to serve must be explicitly registered using .route() after Router::new().
When to Use Router::new vs Other Constructors
Axum provides one main constructor for Router: Router::new(). Router::default() also exists and creates exactly the same empty router as Router::new(), but there is no Router::empty(). For most applications, you will start with Router::new() and then call methods like .route(), .nest(), or .merge().
If you are building a library or a reusable component, you might define a function that returns a Router and call Router::new() inside that function. The caller can then merge or nest that router into a larger application.
A Complete Example with Several Handlers
Here is a full, runnable example that uses Router::new to create an application with three different endpoints. The handlers are defined as separate async functions. This example includes the necessary imports and the Tokio runtime.
// src/main.rs
use axum::{
routing::{get, post},
Router,
};
async fn root() -> &'static str {
"Welcome to the root path"
}
async fn about() -> &'static str {
"About this application"
}
async fn submit() -> &'static str {
"Data received"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(root))
.route("/about", get(about))
.route("/submit", post(submit));
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();
}
When you run this program, you can test it with curl:
curl http://127.0.0.1:3000/
# Output: Welcome to the root path
curl http://127.0.0.1:3000/about
# Output: About this application
curl -X POST http://127.0.0.1:3000/submit
# Output: Data received
If you send a request to a path that does not exist, like /missing, the server responds with a 404 Not Found status and an empty body. Axum sends no error page text by default, so a browser shows a blank page.
Router::new and Ownership
Because Router is an owned value and not a reference, you can move it around freely. In a typical main function, you create the router, then pass it by value to axum::serve. The router is consumed by the serve function, which is fine because you do not need it again after the server starts.
If you need to reuse the same base router for multiple configurations, you can clone it. Router implements Clone, and cloning is cheap because the router stores its routing table behind a shared reference, so a clone copies that reference rather than the whole table.
let base_router = Router::new().route("/", get(root));
let api_router = base_router.clone().route("/api", get(api_handler));
let admin_router = base_router.clone().route("/admin", get(admin_handler));
// base_router still works and has only "/"
In practice, you rarely clone a router. Most applications build one final router and serve it.
How Router::new Compares to Other Web Frameworks
If you have used other web frameworks, you may have seen a similar concept. In Express.js for Node.js, you start with const app = express(). In Flask for Python, you use app = Flask(__name__). In Rust's Axum, Router::new() plays the same role: it creates the central object that holds your route definitions.
The key difference is that Axum's router is type-safe and immutable. Registering the same method and path twice is not caught by the compiler - it panics at runtime when the router is built. Also, the router is not tied to a specific server; you can pass it to axum::serve, use it in tests, or embed it in a larger service.
How the Router Pieces Fit Together
The pieces you have met so far each do one job. Handlers must be async functions, because the runtime can only run futures. Router::new creates the empty routing table those handlers are registered on. The .route() calls fill the table, TcpListener::bind reserves the address and port, and serve runs the loop that matches incoming requests against the table. Router::new is the piece that connects all of them: you create a router, register routes on it, bind a listener, and then serve the router.
Without Router::new, there would be no object to pass to serve. Every Axum application, no matter how large, begins with this single function call.
Summary
Router::new() is the constructor that creates an empty Axum router. It returns a value of type Router<()>, which means no application state is attached. You build a functional router by chaining .route() calls onto the result of Router::new(). The router itself is an immutable, builder-style data structure that implements the tower::Service trait, making it ready to be passed to axum::serve.
The most important insight is that Router::new does not do any routing by itself. It only creates the container. All routing rules come from the .route() calls that follow. If you forget to add any routes, your server will respond 404 Not Found to every request. Keeping that in mind will save you from confusion as you continue building Axum applications.