lib.rs module in Axum projects

Learn what lib.rs is, why Axum projects use it, and how to move your application code from main.rs into a library module so main.rs becomes a thin startup file.

When you first create a Rust project with Cargo, you get a src/main.rs file. That file is the entry point for a binary program. For small examples, putting everything there works fine. But as your Axum application grows, you will often add a second entry file named src/lib.rs. That file turns part of your project into a library, and it is the natural home for your application's setup logic. This page explains exactly what lib.rs is, why Axum projects use it, and how to move your code into it without breaking anything.

The two kinds of entry points in a Rust project

A Rust project is organized into one or more crates. A crate is a compilation unit; it can be a binary that produces an executable file, or a library that produces reusable code. Cargo decides which kind a crate is by looking at the source files:

  • src/main.rs makes the crate a binary. When you run cargo run, Rust compiles this file and its dependencies into an executable.
  • src/lib.rs makes the crate a library. Library code is not run directly. Instead, other parts of the same project or other projects can import and use it.

A single Cargo project can have both src/main.rs and src/lib.rs. In that case, Cargo treats them as two separate crates that belong to the same package. The binary crate can use the library crate by referring to the package name.

In an Axum project, the library crate is where you put the router, handlers, state, and any other application pieces that do not need to be inside main. The binary crate then becomes a thin startup script.

Why move code out of main.rs

Imagine your Axum app starts as one file with a route and a server:

// 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("0.0.0.0:3000")
        .await
        .unwrap();
    axum::serve(listener, app).await.unwrap();
}

This works. But as you add more routes, handlers, database pools, and configuration, main.rs becomes a long file that mixes two very different jobs:

  1. Building the application (routes, state, middleware).
  2. Running the application (binding a port, starting the server).

Separating those jobs makes the code easier to read, easier to test, and easier to reuse. The application-building part naturally belongs in a library because it is just a value (a Router) that can be inspected or passed around. The server-starting part belongs in main because that is the only place where you actually run the process.

Putting application setup in lib.rs also lets you write unit tests that call your router without starting a real HTTP server. That is much faster and more reliable than always testing through a live connection.

Creating a lib.rs file

Adding a library crate to an existing Cargo project takes one step: create a file named src/lib.rs. Cargo automatically detects it. You do not need to change Cargo.toml for this basic setup.

Start with the simplest possible library file so you can see the effect. Create src/lib.rs with this content:

// src/lib.rs
pub fn greeting() -> &'static str {
    "Hello from the library!"
}

Now change src/main.rs to call that function. The important detail is the use line at the top, which brings the library function into scope under the crate name, which is the same as your package name. There is no mod declaration for lib.rs itself - Cargo already knows about the library crate. For a project created with cargo new my_axum_app, the package name is my_axum_app:

// src/main.rs
use my_axum_app::greeting;
fn main() {
    println!("{}", greeting());
}

Run cargo run. You should see Hello from the library! printed.

It works if you see the output:

If cargo run prints the greeting without any errors, your binary crate is successfully using code from your new library crate. The library file is being compiled and linked.

The pub keyword on the function is important. Library items are private by default. Without pub, main.rs cannot access greeting. Rust will produce a compile error saying the function is private.

How Rust connects main.rs and lib.rs

When Cargo sees both src/main.rs and src/lib.rs, it builds two crates internally:

  • The library crate, named after your package (for example my_axum_app), containing everything you put in lib.rs and its modules.
  • The binary crate, also named after your package but with a main function, containing main.rs.

The use my_axum_app::greeting; line in main.rs is how the binary crate imports an item from the library crate. The mod keyword in main.rs is not required to use lib.rs. That might seem surprising if you have seen Rust modules before. Normally you write mod some_module; to load a file like src/some_module.rs. But lib.rs is special because Cargo already knows about it. The library crate is automatically available to the binary crate under the package name. You only need use to bring items into scope.

This is different from splitting your library into additional modules like routes or handlers. Those need mod declarations inside lib.rs. But the first lib.rs file itself is picked up automatically.

The package name becomes the crate name:

In the use statement, replace my_axum_app with whatever your package is called. You can see the package name in Cargo.toml under [package] name = "...".

Moving the Axum router setup to lib.rs

Now that you understand the basic idea, you can apply it to a real Axum application. The goal is to move the router construction from main.rs into lib.rs, leaving only the server startup in main.rs.

Start with the single-file version of an Axum app that has one route and maybe some application state. Here is a complete example:

// src/main.rs
use axum::{extract::State, routing::get, Router};
use std::sync::Arc;
#[derive(Clone)]
struct AppState {
    app_name: String,
}
async fn root(State(state): State<Arc<AppState>>) -> String {
    format!("Welcome to {}", state.app_name)
}
#[tokio::main]
async fn main() {
    let shared_state = Arc::new(AppState {
        app_name: "My Axum App".to_string(),
    });
    let app = Router::new()
        .route("/", get(root))
        .with_state(shared_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();
}

This is a complete, working app. To move the router setup into lib.rs, follow these steps:

1

Step 1: Create src/lib.rs

Add a new file src/lib.rs. Move the AppState struct, the root handler, and a new function that builds the router into this file. The function should return the Router value.

2

Step 2: Mark everything as public where needed

The function that builds the router and the AppState struct must be pub if main.rs needs to call or construct them. Handlers can remain private because they are only used inside lib.rs.

3

Step 3: Remove the moved code from main.rs

Delete the struct, handler, and router construction from main.rs. Replace them with a call to the new library function.

4

Step 4: Add the use statement in main.rs

Import the router-building function from your library crate at the top of main.rs.

After applying those steps, your files look like this.

src/lib.rs now contains the application setup:

// src/lib.rs
use axum::{extract::State, routing::get, Router};
use std::sync::Arc;
#[derive(Clone)]
pub struct AppState {
    pub app_name: String,
}
async fn root(State(state): State<Arc<AppState>>) -> String {
    format!("Welcome to {}", state.app_name)
}
pub fn create_app() -> Router {
    let shared_state = Arc::new(AppState {
        app_name: "My Axum App".to_string(),
    });
    Router::new()
        .route("/", get(root))
        .with_state(shared_state)
}

src/main.rs is now much shorter:

// src/main.rs
use my_axum_app::create_app;
#[tokio::main]
async fn main() {
    let app = create_app();
    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();
}

Run cargo run. The server starts exactly as before, and visiting http://localhost:3000 shows the same welcome message. The behavior is unchanged, but the code organization is now clearer.

You have successfully split the entry point:

If the server compiles and responds correctly, you have moved your application logic into the library and turned main.rs into a thin startup file. This is the pattern used by many production Axum projects.

What belongs in lib.rs and what stays in main.rs

The division is simple:

lib.rs should contain:

  • Function(s) that build the Router
  • Handler functions and their input/output types
  • Application state structs
  • Configuration loading and parsing
  • Any other application setup logic that does not require a running server

main.rs should contain:

  • The #[tokio::main] entry point
  • Creating a TcpListener
  • Calling axum::serve to start the server
  • Logging or error reporting that happens only at startup

There is no strict rule that everything must live in lib.rs. Many developers keep the main function in main.rs and a function like build_app in lib.rs. That is enough to get the benefits of testability and separation.

A note about function names and visibility

The name create_app is arbitrary. You can call it build_router, make_app, or anything else that clearly says what it does. The important thing is that it is pub and returns a Router.

If your AppState struct needs to be constructed from main.rs (for example, to inject configuration), it must also be pub, along with any fields main.rs needs to access. If main.rs does not need to see the struct, you can keep it private inside lib.rs.

Handlers are almost always private. They are internal details of how the router responds to requests. Only the router-building function needs to be public.

Forgetting pub causes private item errors:

A common beginner mistake is to move the router builder into lib.rs but forget to mark it pub. Rust will reject the code with an error like "function create_app is private". The same happens for structs or fields used from main.rs. Always check what is actually accessed from outside the library.

Using lib.rs with modules

As your application grows, you will likely split lib.rs further. For example, you might create a routes module with its own file and then declare it inside lib.rs:

// src/lib.rs
mod routes;
use axum::Router;
pub fn create_app() -> Router {
    routes::create_router()
}

In that case, routes is a submodule of the library crate, not a separate crate. The mod routes; declaration must be inside lib.rs. This is different from the automatic connection between main.rs and lib.rs. Submodules always need an explicit mod statement.

The mod routes; line tells Rust to load the file src/routes.rs. That file must exist, and it must define the function lib.rs calls:

// src/routes.rs
use axum::{routing::get, Router};
pub fn create_router() -> Router {
    Router::new().route("/", get(|| async { "Hello from the routes module!" }))
}

The function is pub because lib.rs calls it from outside the routes module. The handler stays private inside the module because nothing outside the module needs to name it.

You will see this pattern more as you add more directories to your Axum project. For now, the key point is that lib.rs is the root of your library's module tree, and any files you add later will be connected through it.

Common mistakes and how to fix them

Mistake 1: Creating lib.rs but not using it from main.rs. After creating lib.rs, you must add a use statement in main.rs that refers to the package name. Without it, the library code is compiled but never called, and you will not see any change in behavior.

Mistake 2: Trying to use mod lib; in main.rs. You do not need to write mod lib;. The library crate is already available under the package name. Writing mod lib; does not cause a compile error - it compiles, but Rust warns you with found module declaration for lib.rs and points out that lib.rs is already the root of the library target, so you should refer to it through the library's name instead. It also needlessly compiles the same file a second time as a submodule of the binary crate. Just use the package name with use.

A warning here means a real mistake:

Writing mod lib; does not fail the build, but the warning it produces is not harmless noise. Rust is telling you that you loaded the library file twice, once as the library crate and once as a submodule of the binary crate. Remove the mod lib; line and use the package name with use instead.

Mistake 3: Forgetting pub on the router-building function. As mentioned, this leads to privacy errors. Mark anything that main.rs calls as pub.

Mistake 4: Moving server startup into lib.rs. Some beginners move the entire main function content into lib.rs and then try to call it from main.rs. That defeats the purpose of having a library. The library should not start a server; it should only build the router. Starting the server is a side effect that belongs in main.

Mistake 5: Using a hyphenated package name. Rust crate names use underscores, but Cargo package names often use hyphens. When you import the library crate in code, replace hyphens with underscores. For example, a package named my-axum-app is imported as use my_axum_app::create_app;.

Why Axum examples often use this pattern

If you read official Axum examples or larger community projects, you will frequently see a lib.rs file that exposes a function returning a Router. This pattern has become standard because it makes the application testable without starting a real server. You can write tests that call create_app() and then send fake HTTP requests to it using tools like tower::ServiceExt::oneshot. That is much faster and more reliable than always binding a port.

The pattern also separates configuration and setup from the runtime environment. You can construct the app once and then serve it on different ports in different contexts (development, tests, production) without duplicating the router-building code.

A real-world mental model

Think of your Axum application like a restaurant:

  • The kitchen and recipes are your lib.rs. They define what the restaurant serves and how to make it.
  • The front door and host stand are your main.rs. They open the restaurant, greet customers, and send them to the kitchen.

You would not put the stove in the doorway. Similarly, you should not put your router construction and handlers in the same file that starts the TCP listener. Keeping the kitchen (library) separate from the front door (binary) makes both easier to manage and test.

Summary

Moving your Axum application setup into lib.rs is a small change that makes a big difference in code organization. You add one file, mark the router-building function as pub, and then call it from main.rs. The result is a thin startup file that only handles binding and serving, while all application logic lives in the library crate. This separation makes your code easier to read, easier to test, and ready to grow as you add more routes, state, and modules. The next logical step after this split is to think about what exactly that router-building function should look like and how to structure its return type, but that is a separate topic.