The pub fn app Function in Axum

Learn how to define the public app function that builds and returns your Axum Router from lib.rs, keeping your entry point clean and testable.

A single public function is what turns a split entry point from an idea into a working pattern. That function builds the whole application, every route and handler, and hands back one Router value. This page explains what the function looks like, where it lives, what its signature means, and the mistakes that stop it from compiling.

What pub fn app Is

A Rust function named app that is pub (publicly visible) and returns an Axum Router. The function's only job is to build the application - every route, every nested router, every piece of middleware - and hand back a complete Router value.

Before this function existed, the Router::new() call and all the .route() calls sat directly inside main. That worked for a small program, but it mixed two very different responsibilities into one place: deciding what the application does, and deciding how the server starts. The pub fn app function is the clean split between those two things.

Why Move the Router Into a Function

When the router lives inside main, you cannot use it anywhere else. Tests would have to start a real server just to check whether a route exists. Other parts of the codebase would have no way to inspect the router without booting the whole program.

Moving the router into a function changes that. Now the router is a value you can create on demand. A test can call app() and check what routes are registered without ever binding to a port. main can call app() and hand the result to the server. The function becomes a single, reusable entry point for building the application.

There is another benefit that shows up as projects grow. When all route definitions live in one function, you can see the entire shape of the application in one place. You know exactly where to look when you need to add a route or change middleware.

Synchronous by Design:

The app function is not async. Building a Router is pure configuration work - you are assembling a data structure, not waiting for input or performing I/O. Adding async here would only complicate the signature without providing any benefit.

The Basic Starter Example

Start with the smallest possible version of the function. It imports what it needs, builds a Router, adds one route, and returns the router.

// src/lib.rs
use axum::{routing::get, Router};
pub fn app() -> Router {
    Router::new()
        .route("/", get(|| async { "Hello, world!" }))
}

This function does three things in order. It creates an empty router with Router::new(). It adds a route for the path / using the get method and an inline async closure as the handler. It returns the resulting router as the function's return value.

The closure || async { "Hello, world!" } is a handler that takes no arguments and returns a string. Axum knows how to turn that string into an HTTP response automatically. The important part for this page is not the closure itself - it is that the function builds the router and returns it.

Where the Function Lives

In a split entry point setup, this function belongs in lib.rs. The library root is the natural home for code that defines the application, because a library can be imported by binaries and tests alike. The binary in main.rs will use this function, but it does not own it. The function goes directly inside that file, exactly as shown in the starter example above. No extra module declaration is required - lib.rs is automatically the crate's library root.

Understanding the Function Signature

The full signature is:

pub fn app() -> Router

pub makes the function visible outside the current module. Since the function sits in lib.rs, the crate root of the library, pub means other parts of the crate and external consumers can call it. If you wrote just fn app(), it would be private to the current module, and main.rs would not be able to use it.

fn app names the function. The name is a convention, not a requirement - you could call it build_router or create_app. Most Axum projects stick with app because it reads naturally: "the app function builds the app."

-> Router says the function returns an Axum Router. The type does not require any annotations or generic parameters at this stage. You simply build a router and return it.

On the Right Track:

If your function compiles and returns the router without errors, the split entry point is working. You have successfully separated the application definition from the server startup code.

Building the Router Inside app

Inside the function, you have the full power of the Router builder API. The most common pattern is to start with Router::new() and chain .route() calls. Each .route() call returns a new Router, so the chain works because every method hands back a value you can keep calling methods on.

// src/lib.rs
use axum::{routing::get, Router};
pub fn app() -> Router {
    Router::new()
        .route("/", get(|| async { "Home" }))
        .route("/health", get(|| async { "OK" }))
}

The first .route() attaches the / path. The second .route() attaches /health. Both paths respond to GET requests. The entire chain evaluates to a single Router value, which becomes the function's return value because it is the last expression in the function body.

Returning the Router

Rust functions return the value of their final expression when you omit the return keyword and the semicolon. The chained router call is that final expression.

pub fn app() -> Router {
    Router::new()
        .route("/", get(|| async { "Home" }))
        // no semicolon here, so the router is returned
}

If you accidentally add a semicolon after the last .route() call, the expression becomes a statement and the function returns nothing. The compiler will reject this because the function promises to return a Router but the body does not deliver one.

// This will not compile
pub fn app() -> Router {
    Router::new()
        .route("/", get(|| async { "Home" })); // semicolon turns this into a statement
}

Semicolon Changes Everything:

Adding a semicolon after the final router expression is a frequent cause of compile errors. The error message will say something like "mismatched types, expected Router, found ()". Remove the semicolon and the function returns the router correctly.

Multiple Routes in One app Function

As your application grows, the function will hold more routes. Handlers are defined as separate async functions above app, then referenced by name inside the route calls.

// src/lib.rs
use axum::{routing::get, Router};
async fn home() -> &'static str {
    "Welcome to the home page"
}
async fn about() -> &'static str {
    "About this site"
}
pub fn app() -> Router {
    Router::new()
        .route("/", get(home))
        .route("/about", get(about))
}

The handlers home and about are plain async functions returning string slices. They live in the same file for now, close to the router that references them. The app function stays small and readable even as the number of handlers grows, because each route is a single line.

When a route needs to support multiple HTTP methods, you chain the method handlers on the same path.

// src/lib.rs
use axum::{
    routing::{get, post},
    Router,
};
async fn list_users() -> &'static str {
    "List all users"
}
async fn create_user() -> &'static str {
    "Create a new user"
}
pub fn app() -> Router {
    Router::new()
        .route("/users", get(list_users).post(create_user))
}

The path /users now responds to both GET and POST requests, each with its own handler. The function still returns a single Router, but that router now contains more routing information.

Another Way to Build the Router Inside app

The builder chain is convenient, but you can also build the router step by step with a mutable variable. This is useful when you want to add routes conditionally or insert some logic between route definitions.

// src/lib.rs
use axum::{routing::get, Router};
async fn home() -> &'static str {
    "Home"
}
pub fn app() -> Router {
    let mut router = Router::new();
    router = router.route("/", get(home));
    router = router.route("/health", get(|| async { "OK" }));
    router
}

Here the variable router is declared mutable because each .route() call returns a new router that must replace the old binding. The final line returns the router explicitly by writing its name without a semicolon.

Router Methods Return a New Value:

Router::route does not modify the router in place. It takes the router by value and returns a new Router. If you write router.route("/", get(home)); without assigning the result back to router, the old router value is moved away and gone. Always capture the return value with router = router.route(...).

Common Mistakes When Writing pub fn app

Several specific mistakes trip up beginners at this stage.

Forgetting pub is the most direct one. A private app function cannot be called from main.rs, which lives in a separate binary crate. The compiler error will say the function is private or not found.

Adding async unnecessarily is another. Since building a router does not require awaiting anything, an async fn app() would force callers to .await the result for no reason. Keep the function synchronous.

Adding a semicolon after the final expression causes the function to return () instead of Router. The fix is to remove the semicolon.

Shadowing the function name with a variable can also happen. If you write let app = Router::new(); inside the function and then try to return app, the code still compiles, because the variable shadows the function name inside the function body. It works, but it confuses anyone reading the code, since app then means two different things in the same file. Use a different variable name like router or app_router.

Check the Return Value Capture:

The most consequential beginner error is forgetting to assign the result of .route() back to the variable. Router::route takes the router by value and returns a new one, so writing router.route("/", get(home)); without an assignment moves router away. If you then use router again, the compiler stops you with error[E0382]: use of moved value. The only shape where this slips past the compiler is when the router is fully typed and never used again afterwards, and then you get only a warning, unused Router that must be used, while the route is silently lost. When you use the step-by-step mutable pattern, always write router = router.route(...).

How Beginners Should Think About This Function

Imagine the app function as a factory. A factory takes raw materials and produces a finished product. In this case, the raw materials are the route definitions and the handlers, and the finished product is the Router. The factory does not start the machine or ship the product - it only builds it.

That separation is the entire point. The function knows nothing about ports, network addresses, or the runtime that will eventually serve the router. It only knows what routes exist and what they do. That makes the router testable in isolation and keeps the startup code in main free from routing details.

When you look at an Axum project and want to know what endpoints the application exposes, the app function is the first place to check. Every route should be registered there, directly or through nested routers that the function calls.

Summary

The pub fn app function is the seam between application definition and server startup. It lives in lib.rs, is public so other parts of the crate can use it, and returns the fully assembled Router. It is synchronous because building a router is configuration work, not I/O work.

The most important insight from this page is that a function can be valuable for its separation rather than its logic. The app function does not perform any complicated computation - it just organizes routing information. But by extracting that organization out of main and into a reusable function, you make the codebase easier to test, easier to read, and easier to extend. That small structural change is what enables larger projects to stay maintainable as the number of routes, handlers, and modules grows.