Fit for Desktop App Backends
Learn why Axum is a strong choice for building backends that serve desktop applications, with examples for local servers and remote APIs.
Desktop applications sometimes need a backend. That may sound strange at first - after all, a desktop app runs directly on the user's machine, so why would it need a server? The answer is that many modern desktop apps use a split architecture: the user interface is built with a desktop framework, while certain tasks - reading files, managing a local database, talking to hardware, or syncing with a remote service - are handled by a separate process that exposes an HTTP API. That separate process is the backend, and Axum is an excellent tool for building it.
In this lesson you will learn what a desktop app backend actually is, why Axum fits this role so well, and how to build one step by step. We will start with the simplest possible example, then gradually add realistic features like file access, settings, and embedding the server inside a desktop application.
What Is a Desktop App Backend?
A desktop app backend is a program that runs on the same computer as a desktop application (or on a remote server) and provides services to that application over HTTP. The desktop app acts as a client. It sends requests like GET /settings or POST /save, and the backend responds with data or performs an action.
This pattern solves a real problem. Desktop frameworks such as Tauri, Electron, or native GUI libraries often run with restricted permissions or lack direct access to certain system resources. For example, a Tauri app's frontend (HTML/JavaScript) cannot freely read arbitrary files or use low-level hardware APIs. Instead, the Tauri app can launch a local Rust process that exposes these capabilities as HTTP endpoints. The frontend then talks to that local server using ordinary fetch calls.
Axum is a natural choice for this local server because it is written in Rust, integrates seamlessly with the same async runtime (Tokio) that many desktop apps already use, and produces very small, fast binaries.
Backend does not always mean remote:
A backend does not have to live on the internet. It can be a local process on the user's machine. This is common in desktop apps that need to bridge the gap between a sandboxed UI and the operating system.
Why Axum Fits Desktop App Backends
Axum brings several qualities that make it particularly well-suited for serving desktop applications:
- Lightweight and minimal: Axum adds very little overhead. A local backend built with Axum starts in milliseconds and consumes a tiny amount of memory - important when it runs alongside a desktop app.
- Rust's safety and performance: Desktop backends often touch the file system, handle binary data, or parse structured input. Rust's memory safety prevents crashes that could otherwise bring down the whole app.
- Async by default: Desktop apps need to stay responsive. Axum uses Tokio's async runtime, so a slow file read or database query never blocks other requests.
- No macro magic: Routes are plain Rust functions. That makes the backend easy to read, test, and maintain.
- Tower ecosystem: You can add middleware for logging, CORS, compression, and timeouts without writing your own implementation.
- Cross-platform: Axum works on Windows, macOS, and Linux, so the same backend code can ship on all desktop platforms.
A desktop app backend can be either local (runs on the same machine as the UI) or remote (runs on a server, and the desktop app connects over the internet). Axum fits both, but the local case is especially popular because Rust and Axum are already often part of a Tauri or native Rust desktop stack.
A Basic Local Axum Server for a Desktop App
Let's start with the smallest possible backend. Imagine a desktop app that needs to ask the backend for the current version number. We will create an Axum server that listens on 127.0.0.1:3000 and responds to a GET /version request.
Create a new Rust binary project:
cargo new desktop_backend
cd desktop_backend
cargo add axum@0.8
cargo add tokio@1 --features full
Now replace src/main.rs with this complete code:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
// Build our router with a single route.
let app = Router::new()
.route("/version", get(version));
// Bind to localhost only. This backend is meant for the local desktop app.
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Desktop backend listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
async fn version() -> &'static str {
"1.0.0"
}
Let's understand each part:
Router::new()creates an empty routing table..route("/version", get(version))tells Axum: when an HTTPGETrequest arrives at the path/version, call theversionhandler.- The
versionhandler is an async function that returns a string. Axum automatically converts that string into an HTTP response with status code200 OKandContent-Type: text/plain; charset=utf-8. TcpListener::bind("127.0.0.1:3000")tells the server to listen only on the loopback interface. This is crucial for a local backend: it ensures that no other machine on the network can reach your server. A desktop app backend should almost always bind to127.0.0.1unless you deliberately want remote access.axum::serve(listener, app)runs the server until it is shut down.
You can run this with cargo run, and then test it from a second terminal with curl:
curl http://127.0.0.1:3000/version
You should see 1.0.0. That is the entire backend. A desktop app's frontend would fetch this same URL and display the version to the user.
You have a working local backend:
If you ran the code and got 1.0.0 from the curl command, you have just built and served a real desktop app backend. Everything else in this lesson adds features on top of this foundation.
Serving JSON Data to a Desktop App
Version strings are fine, but real desktop backends usually exchange structured data. For example, a photo manager desktop app might ask the backend for a list of albums. JSON is the most common format for this.
We need to add serde and serde_json, the serialization crates Axum's Json extractor is built on, to our project:
cargo add serde --features derive
cargo add serde_json
Now let's extend the server to include a GET /albums endpoint that returns a JSON array of album names. Replace src/main.rs:
use axum::{routing::get, Json, Router};
use serde::Serialize;
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/version", get(version))
.route("/albums", get(albums));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Desktop backend listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
async fn version() -> &'static str {
"1.0.0"
}
#[derive(Serialize)]
struct Album {
id: u32,
name: String,
photo_count: u32,
}
async fn albums() -> Json<Vec<Album>> {
// In a real app, this data would come from a database or the file system.
let data = vec![
Album { id: 1, name: "Vacation".into(), photo_count: 24 },
Album { id: 2, name: "Family".into(), photo_count: 87 },
Album { id: 3, name: "Work".into(), photo_count: 12 },
];
Json(data)
}
What changed?
- We imported
JsonfromaxumandSerializefromserde. - The
Albumstruct derivesSerialize, meaning Rust can automatically convert it to JSON. - The
albumshandler returnsJson<Vec<Album>>. Axum serializes the vector to a JSON array and sets the responseContent-Typetoapplication/json.
If you run the server and call curl http://127.0.0.1:3000/albums, you will see:
[{"id":1,"name":"Vacation","photo_count":24},{"id":2,"name":"Family","photo_count":87},{"id":3,"name":"Work","photo_count":12}]
A desktop app would parse this JSON and render the albums in its UI. This is a very common pattern: the backend provides data, and the frontend (Tauri webview, Electron renderer, etc.) displays it.
Handling File System Operations Safely
One of the main reasons to build a local backend is to safely access the file system. A desktop app's frontend might be written in JavaScript (Tauri, Electron) or a GUI framework with no direct file access. The backend can expose endpoints that read and write files.
Let's add two endpoints: GET /files to list files in a specific directory, and POST /save to write a small text file. We'll need tokio::fs for async file operations.
Update Cargo.toml (or just use cargo add for any new dependencies) and modify src/main.rs:
use axum::{
http::StatusCode,
routing::{get, post},
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use tokio::fs;
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/version", get(version))
.route("/albums", get(albums))
.route("/files", get(list_files))
.route("/save", post(save_file));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Desktop backend listening on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
async fn version() -> &'static str {
"1.0.0"
}
#[derive(Serialize)]
struct Album {
id: u32,
name: String,
photo_count: u32,
}
async fn albums() -> Json<Vec<Album>> {
let data = vec![
Album { id: 1, name: "Vacation".into(), photo_count: 24 },
Album { id: 2, name: "Family".into(), photo_count: 87 },
Album { id: 3, name: "Work".into(), photo_count: 12 },
];
Json(data)
}
#[derive(Serialize)]
struct FileEntry {
name: String,
size: u64,
}
async fn list_files() -> Result<Json<Vec<FileEntry>>, (StatusCode, String)> {
// For this example, we list the current directory.
let mut entries = fs::read_dir(".").await.map_err(|e| {
(StatusCode::INTERNAL_SERVER_ERROR, format!("Failed to read directory: {e}"))
})?;
let mut files = Vec::new();
while let Some(entry) = entries.next_entry().await.map_err(|e| {
(StatusCode::INTERNAL_SERVER_ERROR, format!("Failed to read entry: {e}"))
})? {
let metadata = entry.metadata().await.map_err(|e| {
(StatusCode::INTERNAL_SERVER_ERROR, format!("Failed to get metadata: {e}"))
})?;
files.push(FileEntry {
name: entry.file_name().to_string_lossy().into_owned(),
size: metadata.len(),
});
}
Ok(Json(files))
}
#[derive(Deserialize)]
struct SaveRequest {
filename: String,
content: String,
}
async fn save_file(Json(payload): Json<SaveRequest>) -> Result<StatusCode, (StatusCode, String)> {
// Basic validation: prevent path traversal.
if payload.filename.contains('/') || payload.filename.contains('\\') || payload.filename.contains("..") {
return Err((StatusCode::BAD_REQUEST, "Invalid filename".to_string()));
}
fs::write(&payload.filename, &payload.content)
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Failed to write file: {e}")))?;
Ok(StatusCode::CREATED)
}
There are several important ideas here:
- The
list_fileshandler reads the current directory usingtokio::fs::read_dir, which does not block the async runtime. - It returns a
Result. If everything works, it returnsOk(Json(files)). If something fails, it returnsErr((StatusCode, String)), which Axum turns into a proper HTTP error response. - The
save_filehandler accepts a JSON body viaJson<SaveRequest>. Axum automatically deserializes the incoming JSON into aSaveRequeststruct. - Before writing the file, we check the filename for
/,\, and... This is a simple guard against path traversal attacks, where a malicious client could try to write outside the intended directory. In a real desktop app, you would want more robust validation and a fixed base directory.
To test these endpoints, you can use curl. First, list files:
curl http://127.0.0.1:3000/files
Then save a file:
curl -X POST http://127.0.0.1:3000/save \
-H "Content-Type: application/json" \
-d '{"filename":"test.txt","content":"Hello from desktop app"}'
After that, a new file test.txt will appear in the backend's working directory.
Never expose a file-writing endpoint to the internet without authentication:
The example above has no authentication and only binds to 127.0.0.1, so it is relatively safe for local use. However, if you ever change the bind address to 0.0.0.0 or deploy this to a remote server, anyone could write files to your machine. Always add authentication and strict path validation before exposing such endpoints beyond localhost.
Running Axum Inside a Tauri Desktop App
A very popular way to build desktop apps with Rust is Tauri. Tauri uses a webview for the UI and a Rust binary for the backend logic. But sometimes you want a clean separation between the UI process and a dedicated HTTP server process, or you want to reuse an existing Axum backend as a local service.
Tauri does not use Axum internally:
Do not confuse the two directions. Tauri does not use Axum for its own dev server or its own internals - Tauri v1's dev server was built on actix-web, and Tauri's normal way for the frontend to talk to Rust code is its own invoke command system, not HTTP at all. Axum enters the picture only when you choose to add an HTTP server of your own: embedded in the Tauri process (below) or shipped as a sidecar binary (next section). It is a popular choice for that job, because it is the same Tokio stack Tauri already runs on - but it is your server, not Tauri's.
You can embed an Axum server directly inside your Tauri app's Rust code. The server runs in the same process as the Tauri app, but it listens on a local port and can be accessed by the webview or by other processes.
Here is a simplified example of what the Tauri main.rs might look like when it starts an Axum server alongside the Tauri app. This is not a full Tauri tutorial, but it shows the integration concept.
First, create a new Tauri project (using create-tauri-app) and add the same dependencies. Then in src-tauri/src/main.rs (or src-tauri/src/lib.rs if using the Tauri v2 structure), you would start the Axum server as a Tokio task before running the Tauri app:
// This is a condensed example. A real Tauri app has more setup.
use axum::{routing::get, Router};
use tauri::Builder;
#[tokio::main]
async fn main() {
// Start the Axum server in a background task.
tokio::spawn(async {
let app = Router::new()
.route("/health", get(|| async { "ok" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
});
// Run the Tauri application.
Builder::default()
.run(tauri::generate_context!())
.expect("error while running Tauri application");
}
In this setup, the Axum server runs inside the same process as the Tauri app. The Tauri webview (or any other local process) can send HTTP requests to 127.0.0.1:3000. This gives you a very convenient way to expose Rust functionality to the frontend without going through Tauri's own command system.
Why use HTTP inside the same process?:
Even though the server and the client are in the same process, HTTP provides a clean, language-agnostic interface. If you later decide to move the backend to a separate process or a remote server, the frontend code does not need to change - it still talks to the same endpoints.
Alternative: Running Axum as a Sidecar Process
Sometimes you don't want to embed Axum inside the UI process. Instead, you ship two separate executables: the desktop app and the backend. The app launches the backend as a child process when it starts, and the backend serves requests on a known port.
This approach has advantages:
- You can update the backend independently of the frontend.
- If the backend crashes, it won't take down the UI.
- You can write the backend in Rust and the frontend in any language (C#, Swift, JavaScript, etc.).
The code for the backend is exactly the same as what we wrote earlier. The only difference is how you package and launch it. For example, in Tauri you can configure a sidecar binary in tauri.conf.json and then spawn it from the Rust code. The frontend then communicates with it over HTTP.
Here is a minimal example of spawning a backend sidecar from a Tauri setup hook (using Tauri v2 commands):
use std::process::Command;
#[tauri::command]
fn start_backend() {
// In a real app, the path would be resolved from the app bundle.
let _child = Command::new("./my_axum_backend")
.spawn()
.expect("Failed to start backend");
// Optionally store the child process handle to kill it later.
// For this example, we just let it run.
}
pub fn run() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![start_backend])
.setup(|app| {
// Start the backend when the app is ready.
start_backend();
Ok(())
})
.run(tauri::generate_context!())
.expect("error while running Tauri application");
}
The frontend can then call the start_backend command (if needed) or simply expect that the backend is already running on 127.0.0.1:3000.
Axum as a Remote Backend for Desktop Clients
While local backends are common, Axum is also excellent as a remote backend that desktop apps connect to over the internet. This is the same kind of backend you would build for a mobile app or a single-page application. The desktop app becomes just another HTTP client.
For a remote backend, you would typically:
- Bind to
0.0.0.0or a reverse proxy. - Add authentication (e.g., API keys, OAuth).
- Use HTTPS.
- Possibly add CORS if the desktop client is a webview (though native clients usually don't need CORS).
The Axum code itself doesn't change dramatically. The main difference is deployment and security. Here's a small example of a remote API with a simple API key check using a middleware-like pattern (though we won't build full auth here, just a simple header check). This shows how you might protect endpoints for remote clients.
use axum::{
extract::Request,
http::{header, StatusCode},
middleware::{self, Next},
response::{IntoResponse, Response},
routing::get,
Router,
};
async fn require_api_key(req: Request, next: Next) -> Result<Response, StatusCode> {
let auth_header = req
.headers()
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok());
if auth_header == Some("Bearer secret-api-key") {
Ok(next.run(req).await)
} else {
Err(StatusCode::UNAUTHORIZED)
}
}
async fn public_data() -> &'static str {
"This endpoint is public"
}
async fn private_data() -> &'static str {
"This endpoint requires an API key"
}
#[tokio::main]
async fn main() {
// `MethodRouter::layer` protects exactly one route. A `route_layer`
// here would have protected BOTH routes added before it, because
// `route_layer` applies to all routes added before the call.
let app = Router::new()
.route("/public", get(public_data))
.route(
"/private",
get(private_data).layer(middleware::from_fn(require_api_key)),
);
// Bind to all interfaces for remote access (use a reverse proxy in production).
let listener = tokio::net::TcpListener::bind("0.0.0.0:8080")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
Notice the choice of layer call. Router::layer would protect every route in the router, and route_layer would protect every route added before the call - both are too broad when only /private needs the key. MethodRouter::layer (.layer(...) on the single get(...) route) protects exactly that one route, which is the per-route tool for this job.
Remote backends need TLS and proper auth:
If your desktop app talks to your Axum server over the internet, you must use HTTPS and a real authentication mechanism. Sending API keys in plain HTTP is insecure. For production, consider using a reverse proxy like Nginx or Caddy to handle TLS, and use tokens or OAuth for authentication.
Common Desktop Backend Patterns and Considerations
Beyond the basic examples, there are several patterns that repeatedly appear when building desktop app backends with Axum:
1. Serving dynamic content from a local database
Many desktop apps maintain a local SQLite database. The backend can expose REST endpoints that query this database. Since Axum handlers are async, you can use an async database crate like sqlx to avoid blocking the UI.
2. Handling long-running tasks
Desktop apps often need to perform tasks that take time: exporting a large file, processing images, or syncing data. The backend can accept a request, start a background task, and return a task ID. The frontend can then poll another endpoint for status. Axum's async nature and integration with Tokio make this straightforward.
3. Streaming large files
If a desktop app needs to download or upload large files, Axum can stream request and response bodies without loading everything into memory. This is important for keeping the app responsive.
4. Using WebSockets for real-time updates
Axum supports WebSockets natively. A desktop app backend can push notifications to the frontend when data changes, avoiding constant polling.
5. Graceful shutdown
When the desktop app closes, the backend should shut down cleanly. Axum's serve can be combined with a shutdown signal, such as listening for a Ctrl+C or a signal from the parent process.
A Complete Example: Settings Manager Backend
Let's build a slightly more complete backend that a desktop app might use to manage user settings. The backend stores settings in a JSON file on disk, exposes GET /settings and PUT /settings, and persists changes.
The first setup already enabled Tokio's full features, which include fs (async file I/O) and sync (the async Mutex). Only serde_json is new here - add it for reading and writing the settings JSON file.
Create a new file src/main.rs:
use axum::{
extract::State,
http::StatusCode,
routing::{get, put},
Json, Router,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tokio::sync::Mutex;
use tokio::fs;
#[derive(Clone, Serialize, Deserialize)]
struct Settings {
theme: String,
language: String,
auto_save: bool,
}
type SharedSettings = Arc<Mutex<Settings>>;
async fn load_settings() -> Settings {
// In a real app, handle file not found gracefully.
let content = fs::read_to_string("settings.json").await.unwrap_or_else(|_| "{}".to_string());
serde_json::from_str(&content).unwrap_or(Settings {
theme: "light".to_string(),
language: "en".to_string(),
auto_save: true,
})
}
async fn save_settings_to_disk(settings: &Settings) -> Result<(), std::io::Error> {
let json = serde_json::to_string_pretty(settings)?;
fs::write("settings.json", json).await
}
async fn get_settings(State(state): State<SharedSettings>) -> Json<Settings> {
let settings = state.lock().await;
Json(settings.clone())
}
async fn update_settings(
State(state): State<SharedSettings>,
Json(new_settings): Json<Settings>,
) -> Result<StatusCode, (StatusCode, String)> {
let mut settings = state.lock().await;
*settings = new_settings.clone();
drop(settings); // Release the lock before the slow file write below.
save_settings_to_disk(&new_settings)
.await
.map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("Failed to save settings: {e}")))?;
Ok(StatusCode::OK)
}
#[tokio::main]
async fn main() {
let initial_settings = load_settings().await;
let shared_state = Arc::new(Mutex::new(initial_settings));
let app = Router::new()
.route("/settings", get(get_settings).put(update_settings))
.with_state(shared_state);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Settings backend running on http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
What's happening here:
- We define a
Settingsstruct that derivesClone,Serialize, andDeserialize. - We use
Arc<Mutex<Settings>>as shared state.Arcallows multiple handlers to access the same data, andMutexensures only one handler modifies it at a time. Since Axum handlers are async, we usetokio::sync::Mutexwhich works with async code. - The
mainfunction loads initial settings from disk, wraps them inArc<Mutex<...>>, and passes that to the router with.with_state(...). - The
get_settingshandler locks the mutex, clones the settings, and returns them as JSON. - The
update_settingshandler receives new settings, replaces the stored value, and saves to disk. If saving fails, it returns a 500 error.
You can test this by fetching and updating settings:
curl http://127.0.0.1:3000/settings
# Output: {"theme":"light","language":"en","auto_save":true}
curl -X PUT http://127.0.0.1:3000/settings \
-H "Content-Type: application/json" \
-d '{"theme":"dark","language":"de","auto_save":false}'
Then fetch again to see the updated values.
Drop the lock before slow I/O:
In the update_settings handler, the mutex is locked only to replace the stored value, then explicitly dropped with drop(settings) before the save_settings_to_disk await. That ordering matters: if the lock were still held during the file write, no other handler could read or write settings for the whole write. Clone what you need, drop the lock, then do the slow I/O.
Handling Errors Gracefully
Desktop apps expect consistent error responses. Axum's error handling model lets you define a uniform error type and convert it into HTTP responses. This is especially important for desktop clients, because they need to parse errors and show meaningful messages to users.
Let's modify the settings backend to use a custom error type and implement IntoResponse for it. This will replace the (StatusCode, String) tuple approach.
Add this to the previous example (or create a new file):
// ... previous imports ...
use axum::response::{IntoResponse, Response};
#[derive(Debug)]
enum AppError {
Io(std::io::Error),
Json(serde_json::Error),
NotFound,
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match self {
AppError::Io(e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("IO error: {e}")),
AppError::Json(e) => (StatusCode::BAD_REQUEST, format!("JSON error: {e}")),
AppError::NotFound => (StatusCode::NOT_FOUND, "Not found".to_string()),
};
(status, message).into_response()
}
}
impl From<std::io::Error> for AppError {
fn from(e: std::io::Error) -> Self {
AppError::Io(e)
}
}
impl From<serde_json::Error> for AppError {
fn from(e: serde_json::Error) -> Self {
AppError::Json(e)
}
}
// Now handlers can return Result<T, AppError>.
async fn get_settings(State(state): State<SharedSettings>) -> Result<Json<Settings>, AppError> {
let settings = state.lock().await;
Ok(Json(settings.clone()))
}
async fn update_settings(
State(state): State<SharedSettings>,
Json(new_settings): Json<Settings>,
) -> Result<StatusCode, AppError> {
let mut settings = state.lock().await;
*settings = new_settings.clone();
// Release the lock before the slow file write below.
drop(settings);
// Save to disk, using ? to convert errors automatically.
let json = serde_json::to_string_pretty(&new_settings)?;
tokio::fs::write("settings.json", json).await?;
Ok(StatusCode::OK)
}
This approach reduces boilerplate and gives consistent error handling across all endpoints. The frontend can rely on receiving a structured error message.
Error handling consistency matters for desktop clients:
When a desktop app makes an HTTP request, it must parse both success and error responses. If your backend returns different error formats for different endpoints, the client code becomes messy. Using a uniform error type like AppError makes the client's job much easier.
Secure Local Backend Communication
Even though a local backend is not exposed to the internet, you should still consider security. Another process on the same machine could potentially connect to your local server. Here are a few best practices:
- Always bind to
127.0.0.1(or::1for IPv6) instead of0.0.0.0. - If possible, use a random port instead of a fixed one, and communicate it to the frontend via environment variable or command line argument. This reduces the chance of port conflicts and makes it slightly harder for other processes to guess the port.
- Add a simple authentication token in a custom header if the backend handles sensitive operations. The frontend can include this token in every request.
- Never expose file write or delete endpoints without proper path validation.
Using a Random Port
Some desktop apps prefer to bind to an ephemeral port (port 0) and let the OS choose a free port. The backend then needs to tell the frontend which port it chose. One way is to write the port number to a file or stdout.
Here's a small example of binding to port 0 and printing the assigned port:
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new().route("/ping", get(|| async { "pong" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.unwrap();
let port = listener.local_addr().unwrap().port();
println!("Backend running on http://127.0.0.1:{port}");
axum::serve(listener, app).await.unwrap();
}
When you run this, it will print a different port each time. In a real desktop app, you would read this output or use an IPC mechanism to inform the UI process of the port.
Graceful Shutdown
When the desktop app closes, you want the backend to stop accepting new requests and shut down cleanly. Axum's serve function accepts an optional shutdown signal. You can use tokio::signal::ctrl_c() to listen for Ctrl+C, or you can create a custom channel that the UI process signals when it's time to exit.
Here is an example that uses a oneshot channel for shutdown:
use axum::{routing::get, Router};
use tokio::sync::oneshot;
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(|| async { "hello" }));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
let (tx, rx) = oneshot::channel::<()>();
// Spawn a task that waits for a signal (e.g., from the UI).
tokio::spawn(async move {
// Simulate a shutdown signal after 5 seconds.
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
let _ = tx.send(());
});
println!("Server running. Will shut down in 5 seconds...");
axum::serve(listener, app)
.with_graceful_shutdown(async {
rx.await.ok();
})
.await
.unwrap();
println!("Server shut down gracefully.");
}
The with_graceful_shutdown method tells Axum to stop accepting new connections once the provided future completes. In a real application, the UI process would send the shutdown signal through an IPC channel when the user closes the app.
The Localhost-Only Security Model, Port Selection, and the Sidecar Pattern
The examples above all bind to 127.0.0.1 for a reason, and it is worth stating the model explicitly rather than treating it as a habit:
- Binding to
127.0.0.1(or::1) means only processes on the same machine can connect. Nothing on the local network, and nothing on the internet, can reach the server. Binding to0.0.0.0removes that protection entirely - do it only for a remote backend behind a reverse proxy with TLS and real authentication, never for a local desktop backend. - Localhost is not the same as private. Any other process running on the user's machine - another app, a browser tab, a script - can connect to
127.0.0.1:3000just as easily as your frontend can. If the backend can read or write files, treat that as a real attack surface: add a per-install secret token (generated at first run, passed to the frontend through an environment variable or a command-line argument, checked in middleware on every request), validate every path against a fixed base directory, and never expose a file-write or delete endpoint without both. - Pick the port deliberately. A fixed port such as
3000is easy to document but can collide with another app on the user's machine, and a fixed, well-known port is the easiest thing for another local process to guess. The safer pattern is to bind to port0and let the OS pick a free ephemeral port, then read it back withlistener.local_addr().unwrap().port()and pass it to the frontend (see the "Using a Random Port" section above) - or, if the port must be fixed, let the user override it with an environment variable such asDESKTOP_BACKEND_PORTand fail loudly, with a clear message, if the bind fails instead of silently picking another port.
The Tauri sidecar pattern is the packaged form of the same idea. Instead of embedding the Axum server in the Tauri process, you ship the backend as a separate executable alongside the app (in Tauri, sidecar binaries live under src-tauri/binaries/ with a target-triple suffix, for example my_axum_backend-x86_64-pc-windows-msvc.exe), and the Tauri app spawns it at startup and kills it on exit:
// Spawned from a Tauri setup hook; the backend listens on 127.0.0.1
// on a port chosen at runtime and passed as an argument.
use std::process::{Child, Command};
fn start_backend(port: u16) -> Child {
Command::new("./my_axum_backend")
.arg("--port")
.arg(port.to_string())
.spawn()
.expect("Failed to start backend")
}
The backend itself is unchanged - it is the same Axum server from the first section, binding to 127.0.0.1 on the port it was given. The sidecar form is worth it when you want to update the backend independently of the UI, when a backend crash must not take the UI down with it, or when the same backend binary also runs standalone or on a server. The embedded form (a tokio::spawn inside the Tauri process, as in the previous section) is simpler and is the right default when none of those apply. Either way, the frontend talks to the backend over plain HTTP on localhost, and the security model above - loopback only, a per-install token for sensitive operations, strict path validation - is what keeps that safe.
Summary
Axum is a strong fit for desktop app backends because it is lightweight, async, safe, and composes well with the Rust ecosystem already used in desktop development. Whether you are building a local HTTP server that gives a Tauri or Electron frontend access to the file system, or a remote API that desktop clients call over the internet, Axum provides the tools you need without unnecessary complexity.
The key takeaways from this lesson:
- A desktop app backend can be local (same machine) or remote (over the network). Local backends are especially common with Tauri and other Rust desktop frameworks.
- Axum's minimal API and Tokio integration make it easy to embed or run alongside a desktop UI.
- Common backend responsibilities include file operations, settings management, database access, and running long tasks.
- Always bind local backends to
127.0.0.1and consider random ports, authentication, and path validation for security. - Use Axum's state management, error handling, and graceful shutdown to build a robust backend that the frontend can rely on.