Fit for SPA backends

Learn why Axum is a strong choice for building the backend of a single-page application, including static file serving, JSON APIs, client-side routing fallback, and CORS setup.

A single-page application (SPA) is a type of web app that runs almost entirely in the browser. Instead of asking the server for a new full HTML page every time you click a link, the SPA loads one initial HTML page, then uses JavaScript to change what you see on screen. Think of Gmail, Google Maps, or a modern dashboard: you click around, data loads in the background, but the page never fully refreshes.

The backend for an SPA has different responsibilities than a traditional server-rendered web app. This page explains what those responsibilities are and shows why Axum handles them especially well.

What a SPA Needs From a Backend

A SPA needs three main things from its backend:

  1. The initial HTML file. This is usually a small index.html that loads the JavaScript bundle. The backend only needs to serve this file for most routes, not generate unique HTML per page.
  2. Data endpoints. Since the SPA updates the view with JavaScript, it fetches data from the backend over HTTP. These are usually JSON APIs. For example, when you open a chat app, the browser asks GET /api/messages and receives a JSON array of messages.
  3. Support for client-side routing. SPAs often use client-side routers (like React Router or Vue Router). When a user navigates to /settings inside the SPA, the browser changes the URL, but no request goes to the server. However, if the user reloads the page or opens that URL directly, the server must still return the same index.html, not a 404 error. So the backend needs a fallback route: any non-API path that is not a real file should serve index.html.

Additionally, during development you might run the frontend on one port (like localhost:5173) and the backend on another (like localhost:3000). In that case, the browser will block API requests unless the backend explicitly allows them. That's called Cross-Origin Resource Sharing (CORS), and the backend must send the right headers.

SPAs in a Nutshell:

A SPA separates the user interface (in the browser) from the data and business logic (on the server). The backend's job is to be a reliable, fast provider of data and static files.

Why Axum Is a Good Fit for SPA Backends

Axum is built on top of the Tokio async runtime and the Hyper HTTP library. It gives you fine-grained control over routing, request parsing, and response building without forcing a particular project structure. For SPA backends, several Axum features stand out:

  • Simple static file serving through the tower-http crate, which integrates directly with Axum's router.
  • Easy JSON handling with the Json extractor and response type, powered by Serde.
  • Flexible routing with a fallback that can serve index.html for unknown paths.
  • Straightforward middleware for CORS, compression, logging, and more through Tower layers.
  • Performance and low resource usage, which matters when your backend serves both static assets and API endpoints for many users.

Unlike some frameworks that assume server-side rendering, Axum does not force you into a template engine or a specific frontend integration. You stay in control of how the frontend and backend communicate.

A Minimal SPA Backend with Axum

Before adding static files and fallback logic, start with the absolute smallest backend that can serve an SPA's initial HTML page. You don't need any frontend build tools yet - just a plain HTML file with a bit of JavaScript.

Create a new Rust project and add the dependencies. In your Cargo.toml:

[package]
name = "spa-backend"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower-http = { version = "0.7", features = ["fs"] }

The tower-http crate is a collection of Tower middleware built specifically for HTTP servers. We enable the fs feature to get static file serving capabilities.

Now write the main server. This first version only returns a hardcoded HTML string for the root path.

// src/main.rs
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
    let app = Router::new().route(
        "/",
        get(|| async {
            r#"
            <!DOCTYPE html>
            <html>
            <head><title>SPA</title></head>
            <body>
                <h1>Hello from the SPA</h1>
                <p>This page is served by Axum.</p>
            </body>
            </html>
            "#
        }),
    );
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("SPA backend running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Run this with cargo run, then open http://127.0.0.1:3000 in your browser. You'll see the HTML page. It works, but a real SPA has many static files (JavaScript, CSS, images) and uses client-side routing, so hardcoding HTML strings is not practical.

The example above uses a raw string literal (the r#"..."# syntax) to embed the HTML directly in Rust. That's fine for a tiny demo, but you would never do this for a real frontend.

Serving Static Files for Production Builds

When you build a SPA with a tool like Vite, Create React App, or Vue CLI, the output is a folder (often called dist or build) containing index.html, JavaScript bundles, CSS files, images, and other assets. The backend should serve this folder as-is.

Axum does not include static file serving in the core crate, but the tower-http crate provides a ServeDir service that does exactly that. In axum 0.8 the way to mount it for a whole site is not nest_service - nesting a service at the root panics at startup:

Nesting at the root is no longer supported. Use `fallback_service` instead.

So .nest_service("/", ServeDir::new("dist")) never starts a server in axum 0.8; the process panics while building the router. The correct mount point is Router::fallback_service, which is called only when no route matches. Here is an example that serves files from a ./dist folder. Create a dist folder in your project root and put an index.html inside it.

// src/main.rs
use axum::Router;
use tower_http::services::ServeDir;
#[tokio::main]
async fn main() {
    let app = Router::new()
        .fallback_service(ServeDir::new("dist"));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("Serving static files from ./dist on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Now any request to the root path will look for a file in the dist folder relative to the URL path. For example, GET /assets/main.js serves dist/assets/main.js, and GET /logo.png serves dist/logo.png. If a file does not exist, it returns a 404 response. (ServeDir also appends index.html for directory requests by default, so GET / serves dist/index.html.)

Static Files Working:

If you see your SPA's index page when visiting http://127.0.0.1:3000, static file serving is configured correctly. All other assets referenced by that page will load automatically.

The fallback_service method mounts the ServeDir service as the last resort: every path that isn't matched by another route (we'll add API routes later) falls through to ServeDir. This is a clean way to serve both static files and API endpoints from one server. (nest_service still exists, but only for a non-root prefix such as .nest_service("/assets", ServeDir::new("dist/assets")).)

Handling Client-Side Routing with a Fallback

The ServeDir approach has one gap: client-side routes. Suppose your SPA has a route like /dashboard that the JavaScript router handles. If a user reloads the page while on http://127.0.0.1:3000/dashboard, the browser sends a GET /dashboard request to the server. ServeDir will look for a file named dashboard in the dist folder, not find it, and return a 404.

To fix this, you need a fallback: any request that does not match an API route and does not correspond to a real file should serve index.html. The SPA's JavaScript then reads the URL and displays the correct view.

Axum's Router::fallback_service is what you use when no other route matches. The trap in the old pattern above is that a plain fallback_service(ServeFile::new("dist/index.html")) after a ServeDir can never fire for a client-side route: ServeDir is itself the fallback, and a router has only one fallback - so a request for /dashboard is answered by ServeDir with a 404 before the ServeFile fallback is ever consulted. The fix is to put the SPA fallback inside the ServeDir service, with ServeDir::fallback, and mount that whole service as the router's fallback:

// src/main.rs
use axum::Router;
use tower_http::services::{ServeDir, ServeFile};
#[tokio::main]
async fn main() {
    // Real files are served from dist/; anything else gets dist/index.html.
    let serve_dir = ServeDir::new("dist")
        .fallback(ServeFile::new("dist/index.html"));
    let app = Router::new()
        // API routes go here, before the fallback...
        .fallback_service(serve_dir);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("SPA with fallback running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

ServeFile::new("dist/index.html") creates a service that always responds with that single file. ServeDir::fallback calls it whenever there is no file at the requested path, and - unlike ServeDir::not_found_service, which forces the response status to 404 - it keeps the 200 OK status the SPA shell should have. So a request for /dashboard (which is not a real file) is served dist/index.html, and the SPA's JavaScript reads the URL and displays the correct view.

Route Order Matters:

The fallback is the last thing Axum checks: it only fires when no route matches, so an API route like GET /api/users always wins over the fallback, whichever order you write them in. Still, write your explicit routes first and the fallback last - it reads in the order requests are actually resolved, and it keeps a future reader from having to reason about precedence.

Now reloading /dashboard in the browser will correctly load the SPA, and your JavaScript can take over from there.

Building JSON API Endpoints for Your SPA

Most SPAs communicate with the backend through JSON APIs. Axum makes this extremely ergonomic with the Json extractor (for request bodies) and the Json response type.

Let's add a simple API to the same server. We'll create a handler that returns a list of messages as JSON.

First, add Serde to your Cargo.toml:

serde = { version = "1", features = ["derive"] }
serde_json = "1"

Then define a struct and a handler:

// src/main.rs
use axum::{routing::get, Json, Router};
use serde::Serialize;
use tower_http::services::{ServeDir, ServeFile};
#[derive(Serialize)]
struct Message {
    id: u64,
    author: String,
    body: String,
}
async fn list_messages() -> Json<Vec<Message>> {
    let messages = vec![
        Message {
            id: 1,
            author: "alice".to_string(),
            body: "Hello from Axum!".to_string(),
        },
        Message {
            id: 2,
            author: "bob".to_string(),
            body: "SPA backends are easy.".to_string(),
        },
    ];
    Json(messages)
}
#[tokio::main]
async fn main() {
    let app = Router::new()
        .route("/api/messages", get(list_messages))
        .fallback_service(
            ServeDir::new("dist").fallback(ServeFile::new("dist/index.html")),
        );
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("SPA + API running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

Now when the frontend JavaScript runs fetch('/api/messages'), it receives this JSON:

[
  {
    "id": 1,
    "author": "alice",
    "body": "Hello from Axum!"
  },
  {
    "id": 2,
    "author": "bob",
    "body": "SPA backends are easy."
  }
]

The Json wrapper tells Axum to serialize the struct into a JSON response with the correct Content-Type: application/json header. The frontend can then parse this with response.json() and update the UI.

For POST requests that create data, you would use Json as an extractor, like Json(payload): Json<CreateMessage> - Axum automatically parses the JSON body into your Rust struct.

Allowing Cross-Origin Requests During Development

When you develop a SPA, you often run the frontend on a different port than the backend. For example, Vite's dev server might run on http://localhost:5173, while Axum runs on http://localhost:3000. The browser will see these as two different origins (because the port differs). By default, browsers block fetch requests from one origin to another unless the server sends CORS headers.

To allow this during development, you can add the CorsLayer from tower-http to your Axum router. This is a middleware that adds the appropriate Access-Control-Allow-Origin headers to responses.

Add the cors feature to tower-http in Cargo.toml:

tower-http = { version = "0.7", features = ["fs", "cors"] }

Then modify the router to include the CORS layer:

// src/main.rs
use axum::{routing::get, Json, Router};
use serde::Serialize;
use tower_http::{
    cors::{Any, CorsLayer},
    services::{ServeDir, ServeFile},
};
#[derive(Serialize)]
struct Message {
    id: u64,
    author: String,
    body: String,
}
async fn list_messages() -> Json<Vec<Message>> {
    // ... same as before ...
}
#[tokio::main]
async fn main() {
    // Allow any origin during development. In production, restrict this.
    let cors = CorsLayer::new().allow_origin(Any);
    let app = Router::new()
        .route("/api/messages", get(list_messages))
        .fallback_service(
            ServeDir::new("dist").fallback(ServeFile::new("dist/index.html")),
        )
        // `.layer()` only applies to the routes and fallback added BEFORE
        // this call, so it must come last. Put it before the fallback and
        // the static responses get no CORS headers at all.
        .layer(cors);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    println!("SPA + API with CORS running on http://127.0.0.1:3000");
    axum::serve(listener, app).await.unwrap();
}

The CorsLayer::new().allow_origin(Any) tells the server to send Access-Control-Allow-Origin: * on all responses, which tells the browser "requests from any origin are allowed." That's fine for local development, but for production you should set a specific allowed origin, like allow_origin(["https://your-spa.example.com".parse().unwrap()]).

CORS Misconfiguration Breaks Frontend:

If you forget to add CORS headers during development, your frontend's fetch calls will fail with an error like "blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present." The backend will be running fine, but the browser will not deliver the response to the JavaScript code. Always add the CORS layer when the frontend and backend are on different origins.

Combining Static Files and API Routes in One Server

In the previous sections we built a single Axum server that serves both static files and API endpoints. This is a common production setup for smaller projects or when you want to keep deployment simple. The server acts as both a static file host and an API server.

The key pieces are:

  • Router::new() starts with API routes (e.g., /api/messages).
  • fallback_service(ServeDir::new("dist").fallback(ServeFile::new("dist/index.html"))) serves real static files, and serves the SPA's index.html for any other path.
  • .layer(cors) comes last, after the routes and the fallback, so CORS headers land on API and static responses.

Route matching is precedence-based, not first-registered-first-served: a matched API route always wins over the fallback, and the fallback only fires when nothing else matched. Inside the fallback service, ServeDir tries to find a real file first; only if none exists does its own .fallback(...) serve index.html.

Here is a complete, runnable example that includes everything we've discussed. It assumes you have built your SPA and placed the output in a dist folder at the project root.

// src/main.rs
use axum::{routing::get, Json, Router};
use serde::Serialize;
use tower_http::{
    cors::{Any, CorsLayer},
    services::{ServeDir, ServeFile},
};
#[derive(Serialize)]
struct User {
    id: u64,
    name: String,
    role: String,
}
async fn list_users() -> Json<Vec<User>> {
    Json(vec![
        User { id: 1, name: "Alice".into(), role: "admin".into() },
        User { id: 2, name: "Bob".into(), role: "editor".into() },
    ])
}
async fn health_check() -> &'static str {
    "OK"
}
#[tokio::main]
async fn main() {
    let cors = CorsLayer::new().allow_origin(Any);
    let app = Router::new()
        .route("/api/users", get(list_users))
        .route("/api/health", get(health_check))
        .fallback_service(
            ServeDir::new("dist").fallback(ServeFile::new("dist/index.html")),
        )
        // Last, so it also covers the static-file responses.
        .layer(cors);
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
        .await
        .unwrap();
    println!("Full SPA backend listening on http://localhost:3000");
    axum::serve(listener, app).await.unwrap();
}

Run this and test:

  • GET /api/users returns JSON.
  • GET /api/health returns plain text "OK".
  • GET / serves dist/index.html.
  • GET /dashboard (if no such file) serves dist/index.html as fallback.
  • GET /assets/app.js serves the file if it exists in dist/assets/.

This single server is easy to deploy because you only have one process and one port. You can put it behind a reverse proxy like Nginx for TLS termination, but the Rust process handles everything itself.

Precompressed Files and Cache Headers

Two ServeDir options pay for themselves in production. First, precompressed variants: if your build produces app.js.gz and app.js.br next to app.js, ServeDir can serve the compressed copy to clients that accept it, instead of compressing on the fly:

let serve_dir = ServeDir::new("dist")
    .precompressed_gzip()
    .precompressed_br()
    .precompressed_deflate()
    .precompressed_zstd()
    .fallback(ServeFile::new("dist/index.html"));

Each .precompressed_*() call only takes effect when the matching precompressed file actually exists in dist/; otherwise the uncompressed file is served as normal, so enabling all four is safe.

Second, cache headers. ServeDir sets the Content-Type from the file extension, but it does not invent a caching policy for you - and the right policy differs by file. Hashed asset files (/assets/app-abc123.js) never change content under the same name, so they can be cached for a year; index.html changes on every deploy, so it must not be cached long. The clean way to express that is to nest the hashed assets under their own prefix (nesting at a non-root prefix is allowed) and give that prefix a long Cache-Control, while the SPA fallback keeps the default:

use axum::{http::{header, HeaderValue}, routing::get, Router};
use tower::ServiceBuilder;
use tower_http::{
    services::{ServeDir, ServeFile},
    set_header::SetResponseHeaderLayer,
};

// The long-lived Cache-Control applies ONLY to the hashed assets,
// because the layer wraps just that one ServeDir service.
// (`list_users` is the handler from the full example above.)
let assets = ServiceBuilder::new()
    .layer(SetResponseHeaderLayer::overriding(
        header::CACHE_CONTROL,
        HeaderValue::from_static("public, max-age=31536000, immutable"),
    ))
    .service(
        ServeDir::new("dist/assets")
            .precompressed_gzip()
            .precompressed_br(),
    );

let app = Router::new()
    .route("/api/users", get(list_users))
    .nest_service("/assets", assets)
    .fallback_service(
        ServeDir::new("dist").fallback(ServeFile::new("dist/index.html")),
    );

Do not put that long Cache-Control on the whole router with .layer(...) - it would land on index.html too, and a browser that cached the entry file for a year would never pick up a new deploy. Leave index.html with a short or no-cache policy. The point is that the caching policy is yours to set per service; ServeDir will not choose it for you.

Alternative Architecture - Separate API and Frontend Servers

Some teams prefer to run the frontend and backend as separate services. For example, the frontend might be deployed to a static hosting service like Netlify or Vercel, or served by a dedicated web server like Nginx, while the Axum backend runs elsewhere and only handles API requests.

In this setup, Axum does not serve static files at all. It only exposes JSON endpoints. This separation can be beneficial when:

  • The frontend and backend scale independently.
  • You want to use a CDN for static assets.
  • Different teams manage frontend and backend deployments.
  • The backend is used by multiple frontends (web, mobile, etc.).

The Axum code becomes simpler because you remove ServeDir and the fallback. You only need API routes and CORS.

Here is an example of such a backend:

// src/main.rs
use axum::{routing::get, Json, Router};
use serde::Serialize;
use tower_http::cors::{Any, CorsLayer};
#[derive(Serialize)]
struct Product {
    id: u64,
    name: String,
    price: f64,
}
async fn list_products() -> Json<Vec<Product>> {
    Json(vec![
        Product { id: 1, name: "Laptop".into(), price: 999.99 },
        Product { id: 2, name: "Mouse".into(), price: 29.99 },
    ])
}
#[tokio::main]
async fn main() {
    let cors = CorsLayer::new().allow_origin(Any);
    let app = Router::new()
        .route("/api/products", get(list_products))
        .layer(cors);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
        .await
        .unwrap();
    println!("API-only backend listening on http://127.0.0.1:8080");
    axum::serve(listener, app).await.unwrap();
}

The frontend would be hosted elsewhere and make requests to https://api.yourdomain.com/api/products. You must configure CORS to allow requests from your frontend's domain, not just Any in production.

One server or two?

Single server (static + API). The single-server approach is simpler to deploy and develop because you only manage one process. It works well for small to medium projects, internal tools, and when you don't need a CDN for static assets. However, serving static files through Rust may not be as optimized for high traffic as a dedicated CDN or Nginx, and scaling the API and static serving together can be less flexible.

Separate servers. The separate approach gives you maximum flexibility: you can host static files on a CDN for fast global delivery, scale the API independently, and possibly reuse the API for mobile apps. The downside is more moving parts to configure, deploy, and monitor, plus you must carefully manage CORS and environment variables.

Common Mistakes When Building SPA Backends with Axum

Even with Axum's clean design, beginners often run into a few predictable problems.

1. Placing the fallback before API routes. The fallback only fires when no route matches, so an API route wins over it regardless of the order you write the builder calls - but write the API routes first and the fallback last anyway, so the code reads in the order requests are resolved.

2. Serving index.html with ServeDir without a fallback. ServeDir only serves files that actually exist. If your SPA uses client-side routes like /settings, those URLs do not correspond to files, so ServeDir returns 404. You need the explicit fallback.

3. Forgetting CORS during development. When the frontend runs on a different port, the browser blocks API calls. This often appears as a "network error" in the browser console, while the server logs show successful requests. Adding CorsLayer fixes it.

4. Using allow_origin(Any) in production. While convenient for development, allowing any origin is a security risk for production. Limit it to your actual frontend domain(s).

5. Using nest_service at the root path. nest_service("/", ServeDir::new("dist")) panics at startup in axum 0.8 - nesting at the root is no longer supported. Use fallback_service(ServeDir::new("dist").fallback(ServeFile::new("dist/index.html"))) instead. If you also want a custom handler for exactly /, register route("/", get(handler)) - a matched route wins over the fallback - and let the fallback serve everything else.

Check the Order:

API routes first, then the fallback service. Explicit routes win over the fallback by precedence, and inside the fallback ServeDir serves real files before its own .fallback(...) serves the SPA shell. This ordering ensures that explicit routes win, then real files, then the SPA shell.

Summary

Axum is a natural fit for SPA backends because it combines high-performance HTTP handling with flexible routing, easy JSON support, and seamless integration with Tower middleware for static files and CORS. You can either serve the frontend and API from a single Axum process or run Axum as a pure API server behind a separate frontend host.

The core pattern to remember is:

  • Define your API routes first.
  • Mount the SPA's build output as the fallback service: fallback_service(ServeDir::new("dist").fallback(ServeFile::new("dist/index.html"))) - never nest_service("/", …), which panics in axum 0.8.
  • Add .layer(cors) (and any other layers) last, after the routes and the fallback, so they cover static responses too.
  • Enable CORS when the frontend and backend are on different origins during development.

With these pieces in place, Axum gives you a solid, maintainable backend for any modern single-page application. You can then build on this foundation with database access, authentication, and more advanced features as your SPA grows.