Creating the state.rs Placeholder in Axum Project Structure
Learn what application state is in Axum, why it needs its own file, and how to set up a state.rs placeholder as part of a conventional project layout.
Application state is the shared information that multiple request handlers need to access while your server is running. In a web API, that might be a database connection pool, a small object that keeps a few ready-made database connections on hand so handlers do not open a new one for every request, a configuration object, or a counter that tracks how many requests have arrived. Axum lets you pass this shared data into handlers through a feature called State. An extractor is a piece of Axum that pulls a value out of the request or the shared state and hands it to your handler as a function argument, and State is the extractor that hands a handler the shared application state. Before you can use State, though, your project needs a place to define the type that will hold all that shared information. That place is conventionally a file named state.rs.
Why a Dedicated state.rs File
When an Axum server receives a request, it runs one of your handler functions. That handler might need to read or update data that lives for the entire lifetime of the server, not just for one request. For example, imagine a hit counter that increments every time someone visits the home page. The counter value must survive between requests. You cannot store it in a local variable inside the handler because local variables are destroyed when the handler finishes.
Instead, you create the counter outside the handler, store it somewhere the handler can reach, and give the handler access to it through Axum's State extractor. The type of that shared data is what we call application state. It could be as simple as an integer or as complex as a struct with many fields.
In a small project, you might define this state type directly in main.rs or lib.rs. But as your project grows, that file becomes crowded. A conventional Axum project layout separates concerns into different files:
src/
├── main.rs
├── lib.rs
├── routes/
│ └── mod.rs
├── handlers/
│ └── mod.rs
├── models/
│ └── mod.rs
└── state.rs
Each file has a clear job. state.rs is where you will define the AppState struct and any methods or helper functions related to the shared data. Right now, the file is just a placeholder - it exists so the module structure is ready, and you can fill it with real content later without changing the overall layout.
Creating the Placeholder File
We will create state.rs inside the src directory and then tell the compiler that this file is a module by adding mod state; to the crate root. This process is sequential: you must create the file first, otherwise the compiler will complain that it cannot find the module.
Step 1: Create the state.rs file
Open your code editor and create a new empty file at src/state.rs. You can leave it completely blank for now, or add a comment to remind yourself what it will contain:
// src/state.rs
// This file will define the application state shared by all handlers.
That comment is not required, but it helps future readers understand the purpose of the file.
Step 2: Declare the state module
The Rust compiler only knows about files that are explicitly included as modules. In a project that uses a lib.rs as the library root, you add the module declaration there. If your project still uses only main.rs, add it to main.rs instead.
Since we are following the conventional layout that separates library and binary, we will put the declaration in src/lib.rs. Open that file and add the following line near the top:
// src/lib.rs
pub mod state;
If your lib.rs already contains other module declarations like pub mod routes;, pub mod handlers;, and pub mod models;, just add pub mod state; alongside them. The pub makes the module public so other parts of the crate can use it. The exact ordering does not matter, but keeping modules grouped together makes the file easier to read.
Module declaration added:
After adding pub mod state; and saving both files, your project should still compile. Run cargo check to confirm there are no errors. The placeholder is now part of your crate.
Different Ways to Define the Placeholder
An empty file works, but many developers prefer to put at least a minimal type definition inside state.rs right away. That way, the file's purpose is visible immediately, and the compiler can check that the type name is valid. Below are four common placeholder styles, from the most minimal to slightly more prepared.
Option 1: Just a comment, no actual code
This is the simplest possible placeholder. The file contains only a comment and nothing else.
// src/state.rs
// Application state will go here.
When to use this: When you are not yet sure what fields the state will need, or when you want to keep the file completely empty until the real state is designed. The downside is that there is no type name to reference yet, so other files cannot import anything from state.rs until you add actual code.
Option 2: A unit struct
A unit struct is a struct with no fields. It still has a type name, so you can reference AppState in other modules and pass it around as a value, even though it carries no data.
// src/state.rs
#[derive(Clone)]
pub struct AppState;
The #[derive(Clone)] attribute automatically implements the Clone trait for this type. Many Axum setups require the state type to be cloneable because the router stores it and passes a clone to each handler. A unit struct can be cloned cheaply - it is essentially a zero-sized value.
When to use this: When you want a concrete type that you can wire into the router early, but you know you will add fields later. The router is the part of your application that matches incoming request paths to handler functions. You can start with AppState and gradually turn it into a struct with actual data without changing the code that references the type name.
Option 3: A struct with placeholder fields
If you already have an idea of what kind of data the state will hold, you can create a struct with fields, even if those fields are not yet initialized. For example, you might know that the application will eventually need a shared string for the API version or a number for a counter.
// src/state.rs
#[derive(Clone)]
pub struct AppState {
pub api_version: String,
pub request_count: u64,
}
This struct has two public fields: api_version and request_count. The fields are pub so that handlers can read them directly after extracting the state. You will need to provide values for these fields when you create an instance of AppState, which you would do in the function that builds the router.
When to use this: When you have a clear early design and want to force yourself to initialize all required data from the start. It is less flexible than a unit struct because every time you add a field, you must also update the code that constructs the state.
Option 4: A type alias for a known type
Instead of defining a new struct, you can create a type alias that points to an existing type. This is useful when your state is just a simple wrapper around another type, like a HashMap or a Vec.
// src/state.rs
use std::sync::Arc;
use tokio::sync::Mutex;
pub type AppState = Arc<Mutex<Vec<String>>>;
Here, AppState is not a new type; it is an alias for Arc<Mutex<Vec<String>>>. That means AppState and Arc<Mutex<Vec<String>>> are exactly the same type. This can be convenient when you want to avoid extra struct boilerplate and your state is just one container. However, a type alias does not give you a name that is distinct from the underlying type, and you cannot attach methods to it at all. Writing impl AppState fails with error E0116, because the compiler sees the alias as the foreign type Arc<Mutex<Vec<String>>>, and Rust does not let you define methods for a type from another crate.
When to use this: When your state is a single standard library type that you want to share, and you do not need to extend it with custom behavior. Many small examples use this pattern to keep the code short.
Pick one style and stay consistent:
Whichever placeholder you choose, make sure every part of your project uses the same definition of AppState. If you later change from a type alias to a struct, you will need to update all code that depends on the type's structure. Starting with a simple unit struct is often the easiest path because it gives you a stable name to build around.
Common Mistakes When Adding state.rs
Several small errors can cause your project to stop compiling after you add the placeholder. Here are the most frequent ones and how to avoid them.
Forgetting to add the module declaration:
If you create src/state.rs but do not add mod state; (or pub mod state;) to lib.rs or main.rs, the compiler will not see the file. You will get no error at all until you try to use something from state.rs, and then the compiler reports an unresolved import error (E0432). Always add the module declaration immediately after creating the file.
Making the struct non-public when it needs to be public:
If you define struct AppState without the pub keyword, other modules cannot refer to it. Handlers in a separate handlers/ module will need to use crate::state::AppState. If the struct is not public, the compiler will tell you that AppState is private. Make the struct pub unless you have a specific reason to keep it internal.
Missing Clone implementation:
Axum's State extractor requires the state type to implement Clone because it stores one copy in the router and gives each request its own cloned reference. For types that contain a Mutex or other non-cloneable value, you need to wrap them in Arc to make them cloneable. The simplest placeholders (unit struct, empty struct, or a struct with only cloneable fields) automatically derive Clone correctly if you add #[derive(Clone)].
Verifying the Placeholder Compiles
After creating the file and adding the module declaration, run cargo check in your project directory. You should see output similar to this:
Checking my-axum-project v0.1.0 (/path/to/my-axum-project)
Finished `dev` profile [unoptimized + debuginfo] target(s)
The exact time the check took will be different on your machine, so the second line may end with a timing of its own. What matters is that there are no errors. The project still runs exactly as it did before - no behavior has changed. That is the goal of a placeholder: it prepares the structure without altering functionality.
How This Placeholder Evolves
Right now, state.rs contains only a minimal definition or nothing at all. That is intentional. As you build more features, you will eventually add real data to this file: a database pool, a configuration struct, a connection to an external service, or any other long-lived resource that handlers need. The placeholder gives you a clear, conventional location to put that code, so you never have to hunt through main.rs to find where the shared state lives.
When you are ready to use state in a handler, you will create an instance of AppState in the function that builds your router, pass it to .with_state(...), and then extract it in handlers using State<AppState> as a parameter. Those steps are covered when you work with application state in depth. For now, the file is in place, and the project structure follows the conventional Axum layout.