cargo-watch for Axum Development
Learn how to use cargo-watch to automatically restart your Rust application whenever you change your code, with a focus on Axum development.
cargo-watch for Axum Development
When you build a Rust application with Axum, you will spend a lot of time editing code, saving files, and then restarting your server to see the changes. Doing this manually - stopping the process, running cargo run again, waiting for compilation - quickly becomes tedious. cargo-watch automates that loop. It watches your source files for changes and runs a command (like cargo run or cargo test) automatically every time you save.
This page explains what cargo-watch is, why it is useful for Axum development, how to install it, and how to use it effectively. You will learn the basic commands, common options, and real-world patterns that keep your development flow smooth.
What is cargo-watch?
cargo-watch is a command-line tool that monitors your Rust project's files. When it detects a change - like you editing a .rs file or a Cargo.toml file - it executes a command that you specify. The most common command is cargo run, which rebuilds and runs your application. But you can also use it with cargo test, cargo check, cargo clippy, or any other command.
Think of cargo-watch as an assistant that watches over your project directory. You start it once, and then you can focus on writing code. Each time you hit save, the assistant runs the command for you and shows the output.
The tool is written in Rust and distributed through cargo install, so it fits naturally into your existing Rust toolchain. It works on Linux, macOS, and Windows.
Why do you need cargo-watch?
Without cargo-watch, a typical Axum development session looks like this:
- Edit a handler in
main.rs. - Save the file.
- Go to your terminal.
- Stop the running server (usually with Ctrl+C).
- Run
cargo runagain. - Wait for the compilation to finish.
- Test the change in your browser or API client.
- Repeat.
That is a lot of context switching. With cargo-watch, you only do step 1 and 2. The tool detects the save, restarts the server, and you see the result immediately. You never leave your editor.
Why this matters for Axum:
Axum servers are long-running processes. They do not re-read their code while running. Once compiled and started, the binary stays the same until you stop it and start a new one. cargo-watch handles that stop‑start cycle for you automatically.
Installing cargo-watch
cargo-watch is distributed as a Rust crate. To install it, you use Cargo itself. Make sure you have Rust and Cargo installed on your machine. If you have completed earlier environment setup pages, you already have them.
Open a terminal and run:
cargo install cargo-watch
This command downloads the source code for cargo-watch, compiles it locally, and places the binary in your Cargo bin directory (~/.cargo/bin on Linux and macOS, %USERPROFILE%\.cargo\bin on Windows). After installation completes, the cargo watch command becomes available.
For a reproducible install, the cargo-watch README recommends adding the --locked flag: cargo install cargo-watch --locked. That flag pins every dependency to the exact versions the project was tested with. Without it, Cargo picks the newest compatible versions, which can occasionally change the build. Either command gives you the same cargo watch binary.
Step 1: Verify Cargo is installed
Run cargo --version in a terminal. You should see a version number. If not, install Rust via rustup before proceeding.
Step 2: Install cargo-watch
Run the installation command:
cargo install cargo-watch
This may take a minute or two because Cargo compiles the tool from source.
Step 3: Confirm the installation
After it finishes, check that the command works:
cargo watch --version
You should see a version number, for example cargo-watch 8.5.3.
Installation successful:
If cargo watch --version prints a version, you are ready to use the tool. You can now start watching your project.
Your First cargo-watch Command
Let's start with the simplest possible use of cargo-watch - restarting a basic Rust program when you change its code.
Create a small project if you don't have one already. For this example, we'll create a new binary project named watch-demo:
cargo new watch-demo
cd watch-demo
Open src/main.rs in your editor and replace the default content with:
fn main() {
println!("Hello, cargo-watch!");
}
Now, instead of running cargo run, run:
cargo watch -x run
The -x flag tells cargo-watch to execute the command cargo run each time a change is detected. The tool will start by compiling and running your program once, then stay in the foreground watching for file changes.
You should see output like:
[Running 'cargo run']
Hello, cargo-watch!
Now edit src/main.rs again. Change the message to something else, for example println!("Hello again!");, and save the file. Immediately, cargo-watch detects the change, stops the old running program, recompiles, and runs again:
[Running 'cargo run']
Hello again!
That is the core behavior. You never manually stop and start the program.
cargo-watch stops the current process before restarting:
When cargo-watch triggers a new run, it kills the previous running instance. For Axum servers, this means any in‑flight requests are dropped. For local development this is fine; you are the only user.
Common cargo-watch Options
The cargo watch command accepts many options. Here are the ones you will use most often:
| Option | Description |
|---|---|
-x <command> | Execute the given command (can be repeated for multiple commands). Example: -x run or -x test |
-c / --clear | Clear the terminal screen before each run. Useful to keep output clean. |
-d <delay> | Debounce delay in seconds before triggering a command. Default is 0.5 seconds. |
-i <pattern> | Ignore files matching the pattern (can be repeated). Use -i '*.md' to ignore Markdown files. |
-w <path> | Watch only the given path (instead of the whole project). |
-s <command> | Execute the given shell command (can be repeated). To run a command with a different shell, use --use-shell <shell>, for example --use-shell=bash |
--why | Print a message explaining why a command was triggered (which file changed). |
--no-restart | Do not restart the command while it is still running - if a file changes while the command is still running, cargo-watch waits instead of killing it and starting it again. |
Running Multiple Commands
You can chain multiple -x options. For example, to run cargo check and then cargo run on every change:
cargo watch -x check -x run
Cargo-watch will run cargo check first. If it succeeds (exit code 0), it then runs cargo run. If cargo check fails, cargo run will not run. This is a great way to catch compile errors quickly without fully building the binary.
Clearing the Screen Between Runs
When the output scrolls up, it can be hard to see the latest result. Use -c to clear the terminal before each command:
cargo watch -c -x run
Each time you save a file, the terminal clears, and you see only the most recent output.
Slowing Down with a Debounce Delay
Sometimes you save several files in quick succession. Cargo-watch's default debounce of 0.5 seconds is usually fine. But if you want to avoid too many restarts while you are still typing, increase the delay:
cargo watch -d 2 -x run
This waits 2 seconds after the last file change before starting the command.
Using cargo-watch with Axum
Now let's apply cargo-watch to an Axum web server. If you haven't built an Axum project yet, the steps are straightforward.
Create a new project and add Axum and Tokio as dependencies:
cargo new axum-watch-demo
cd axum-watch-demo
cargo add axum
cargo add tokio --features full
Then replace src/main.rs with a minimal Axum server:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(|| async { "Hello from Axum!" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Now, instead of cargo run, start the server with:
cargo watch -x run
Your terminal will compile and start the Axum server. Open a browser and go to http://127.0.0.1:3000. You should see "Hello from Axum!".
Keep the server running. Now edit main.rs and change the response string to "Hello, cargo-watch with Axum!". Save the file.
Cargo-watch detects the change, stops the running server, recompiles, and starts it again. Refresh your browser - you will see the updated message. No manual restart required.
The development loop is now automated:
You can keep your editor and browser side by side. Every time you save a change to any Rust source file, the server restarts and your browser shows the new behavior after a refresh. This is the most common way Axum developers work.
Combining cargo-watch with cargo run and other commands
While cargo watch -x run is the most common pattern, you might want to run additional steps before starting your server. For example, you may want to run cargo fmt to keep your code formatted, then cargo clippy to catch warnings, and only then cargo run.
Cargo-watch supports multiple -x flags in sequence:
cargo watch -x fmt -x clippy -x run
This will:
- Run
cargo fmtevery time you save. - If formatting succeeds, run
cargo clippy. - If clippy passes (no errors), run
cargo run.
If any command fails (non‑zero exit code), the chain stops and the server is not restarted. This ensures you don't accidentally run a server with code that fails static analysis.
Order matters:
Commands are run in the order you specify them. If you put cargo run first, it will start the server and then the subsequent commands will not run until the server stops. So always put commands that should complete before the server before run.
Running Tests with cargo-watch
cargo-watch is not only for running servers. It is also extremely useful for running tests automatically. When you work on a library or a service with unit tests, you can have the test suite run every time you change code.
For an Axum project, you might have tests defined in src/main.rs or in a separate module. For instance, add a test to the project from the previous section:
#[cfg(test)]
mod tests {
use super::*;
use axum::{body::Body, http::Request, http::StatusCode};
use tower::ServiceExt;
#[tokio::test]
async fn test_hello() {
let app = Router::new().route("/", get(|| async { "Hello from Axum!" }));
let response = app
.oneshot(Request::builder().uri("/").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
}
}
(If you don't have tower in your dependencies, add it with cargo add tower --features util.)
Now run:
cargo watch -x test
Every time you change any file, cargo-watch runs cargo test. If the tests pass, you see the success output. If a test fails, you see the failure immediately.
Be careful with long test runs:
If your test suite takes a long time or involves external services, running it on every save may slow you down. In that case, use cargo watch -x check during active development and run tests manually or on a delay.
Ignoring Files and Directories
By default, cargo-watch watches all files in your project directory, including Cargo.toml, Cargo.lock, and files in src/. However, it may also react to changes in irrelevant files like README.md, .gitignore, or log files. Each time those change, it may trigger a restart unnecessarily.
You can tell cargo-watch to ignore certain patterns with the -i flag. The pattern works like a .gitignore glob. For example, to ignore all Markdown files:
cargo watch -x run -i '*.md'
You can use multiple -i flags to ignore multiple patterns:
cargo watch -x run -i '*.md' -i '*.txt' -i 'target/*'
The last one is important: by default, cargo-watch automatically ignores the target/ directory because changes there are generated by the compiler, not by you. But if you want to be explicit, you can add it yourself.
Don't ignore source files you need:
Make sure your ignore patterns are correct. If you accidentally ignore *.rs, cargo-watch will never restart your server when you edit Rust code. Use -i only for files that do not affect the build.
Using cargo-watch with Environment Variables
Sometimes your application needs environment variables set before it runs. For example, an Axum server might read the port from $PORT or database credentials. When using cargo-watch, you can set these variables in the same terminal before starting the watch command.
On Linux or macOS:
PORT=8080 DATABASE_URL=postgres://localhost/mydb cargo watch -x run
On Windows (PowerShell):
$env:PORT=8080
$env:DATABASE_URL="postgres://localhost/mydb"
cargo watch -x run
These environment variables will be passed to each invocation of cargo run (or any command you specify). If you need them to change per run, you can edit them in your terminal and restart cargo-watch.
Alternatively, you can use a .env file and a tool like dotenvy inside your Rust program to load variables at runtime. That is independent of cargo-watch.
Troubleshooting Common Issues
cargo-watch Does Not Detect Changes
If you save a file and nothing happens, check the following:
- Are you editing a file inside the project directory? cargo-watch watches the current directory by default.
- Is the file matched by an ignore pattern? Run
cargo watch --whyto see why a restart was (or wasn't) triggered. - Does your editor use atomic saves? Some editors write to a temporary file and then rename it. cargo-watch should still detect this, but if not, try a different editor, or run with
--ignore-nothingto disable all ignore rules while you debug (cargo-watch normally honours.gitignoreand.ignorefiles, and its built-in ignores fortarget/and.git/).
The Server Restarts Too Often
If cargo-watch triggers on every keystroke, increase the debounce delay with -d 2 or higher. Also check that you aren't editing files inside target/ (those changes are from the compiler and can cause loops). Use -i target to ignore the entire directory if needed.
cargo watch Command Not Found
After installing with cargo install cargo-watch, the binary may not be in your shell's PATH. On Linux and macOS, ensure ~/.cargo/bin is in your PATH. On Windows, ensure %USERPROFILE%\.cargo\bin is in your system PATH. You can also run the binary directly with its full path.
Multiple cargo-watch Instances Conflict
If you accidentally start cargo-watch twice in the same directory, both processes may try to restart the server simultaneously, causing errors. Always stop the previous instance with Ctrl+C before starting a new one.
cargo-watch vs Other Auto-Reload Tools
There are other tools that offer similar functionality, but cargo-watch is the most widely used and simplest for Rust.
cargo runwith a script - You can write a shell script that loops and re-runscargo run, but it won't detect file changes as elegantly.entr- A generic file‑watching command that can run any command when files change. It is not Rust‑specific and requires manual configuration.bacon- A newer tool that also watches Rust projects and shows errors in a friendly way. It is more focused on error reporting and may be worth exploring after you are comfortable withcargo-watch.
cargo-watch maintenance status:
The cargo-watch README says the project is on life support and will not receive further updates, and its maintainer recommends Bacon instead. cargo-watch still works fine for everyday use, but if you want an actively maintained tool, Bacon is the suggested successor.
For most Axum development, cargo-watch is the right choice because it integrates directly with Cargo and requires almost no configuration.
Summary
cargo-watch removes the repetitive stop‑start cycle from Rust development. You install it once, then start it with a command like cargo watch -x run, and from then on, every save triggers a rebuild and restart of your Axum server. You can combine it with cargo fmt, cargo clippy, or cargo test to keep your code clean and verified automatically. The tool's options allow you to ignore unnecessary files, adjust timing, and clear the screen for a tidy output.
Once you incorporate cargo-watch into your workflow, you will spend less time managing processes and more time writing the actual Axum application logic. The next natural step is to use it alongside your API testing tools - when you save a handler change, the server restarts, and your API client can immediately send a test request.