SPA Fallback to Index - Serving index html for Single Page Apps
Learn how ServeDir fallback with ServeFile sends unknown paths to index html so client side routing works in single page apps
A single-page app is a website that ships as one HTML page plus JavaScript, and then changes what the user sees without ever asking the server for a new page. The JavaScript rewrites the address bar itself, so the user can visit /dashboard and /dashboard/settings while the server only ever sent one file. The problem appears when the user refreshes the page or shares the link. The browser asks the server for /dashboard/settings, the server looks for a file with that name, finds nothing, and returns a 404. The app never loads. The fix is a fallback: when no file matches the request, serve index.html anyway, with a 200 status, and let the JavaScript read the URL and show the right screen. In tower-http 0.7.1, that fix is one method on ServeDir called fallback, given a ServeFile pointing at index.html.
Where This Fits
The earlier pages taught ServeDir as a strict file mapping: a request names a file, and a missing file means a 404. That strictness is right for a documentation site, where every URL should name a real page. A single-page app breaks the assumption, because its URLs name screens inside the JavaScript app, not files on disk. The fallback does not change the file mapping. It only changes what happens when the mapping fails: instead of an empty 404, the service answers with the app's entry file. Real files still win. Only unknown paths fall back.
Think of it like a receptionist at a building with one tenant. A visitor who asks for a named office by its exact number is sent to that office. A visitor who asks for anything else is sent to the lobby, where the tenant's own directory tells them where to go. The receptionist does not need to know the tenant's floor plan. The lobby handles it.
The Smallest Working Version
This project is a tiny single-page app: one HTML page, one script, and one stylesheet. The script is deliberately small. It reads the current path and writes a message into the page, which is the whole of client-side routing in miniature.
my-spa/
Cargo.toml
src/main.rs
assets/
index.html
app.js
style.css
[package]
name = "my-spa"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower-http = { version = "0.7", features = ["fs"] }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My App</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<h1>My App</h1>
<p id="screen">Loading...</p>
<script src="/app.js"></script>
</body>
</html>
const screen = document.getElementById("screen");
const path = window.location.pathname;
if (path === "/dashboard") {
screen.textContent = "You are on the dashboard.";
} else if (path === "/dashboard/settings") {
screen.textContent = "You are on the settings screen.";
} else {
screen.textContent = "You are on the home screen.";
}
body {
color: navy;
font-family: sans-serif;
}
The server mounts ServeDir with a fallback. The fallback is a ServeFile pointing at the same index.html. ServeFile is the single-file service from tower-http: it serves exactly one file, at whatever path the request carries.
use axum::Router;
use tower_http::services::{ServeDir, ServeFile};
#[tokio::main]
async fn main() {
let app = Router::new().fallback_service(
ServeDir::new("assets").fallback(ServeFile::new("assets/index.html")),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
Run it with cargo run. Open http://127.0.0.1:3000/dashboard/settings in a browser. The page loads, and the script reads the path and shows "You are on the settings screen." Refresh the page. It still loads, because the server answered the refresh with index.html instead of a 404. The same check works with curl, which shows the fallback directly: an unknown path returns the HTML file with a 200 status.
curl -i http://127.0.0.1:3000/dashboard/settings
HTTP/1.1 200 OK
content-type: text/html
accept-ranges: bytes
last-modified: Sat, 14 Nov 2026 10:06:50 GMT
etag: "6af832ba.1ef0834f-84"
content-length: 132
date: Sat, 14 Nov 2026 10:08:04 GMT
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My App</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<h1>My App</h1>
<p id="screen">Loading...</p>
<script src="/app.js"></script>
</body>
</html>
Working Setup:
If an unknown path such as /dashboard/settings returns the index.html contents with a 200 OK status, the fallback is working. If it returns a 404 instead, the .fallback(...) call is missing or the ServeFile path is wrong.
What fallback Does, Step by Step
The fallback method sets a fallback service on the ServeDir. The official tower-http 0.7.1 documentation describes it plainly: this service will be called if there is no file at the path of the request, and the status code returned by the fallback will not be altered. The flow for each request has three steps.
First, ServeDir tries the normal file lookup. A request for /app.js finds assets/app.js and returns it, with content-type: text/javascript. A request for /style.css finds assets/style.css. The fallback plays no part in these requests at all.
Second, when the lookup fails, the request is passed to the fallback service instead of returning a 404. The fallback in the example is ServeFile::new("assets/index.html"), so it reads that one file and returns it. The response carries the fallback file's content type, text/html, and the fallback file's own status, which for a successful read is 200.
Third, the response goes back to the browser, which receives the HTML page and runs the script. The script reads window.location.pathname, sees /dashboard/settings, and renders the settings screen. The server never knew about the settings screen. It only knew that no file matched and that the fallback file should answer.
The key point is the order: files first, fallback second. A fallback never shadows a real file. If the app has a file named dashboard.html, a request for /dashboard.html serves that file, not the fallback. The fallback only answers for paths with no file behind them.
The Fallback Can Be Any Service:
The fallback does not have to be a ServeFile. Any service works: another ServeDir, a handler wrapped as a service, or a custom error page service. ServeFile is the usual choice because the app entry point is one file, but the method accepts whatever service fits the application.
Why the Browser Needs the Fallback
To understand why the fallback is necessary, follow a single-page app through its two kinds of navigation. The first kind happens inside the app: the user clicks a link, the JavaScript updates the address bar and swaps the screen, and no request reaches the server at all. The second kind happens outside the app: the user refreshes the page, pastes a link into a new tab, or shares the URL with a friend. Then the browser makes a real request for the path in the address bar, and the server must answer it.
Without a fallback, that real request 404s, because no file is named dashboard/settings. The app never loads, the script never runs, and the user sees a blank error page for a screen that worked fine a moment ago. With a fallback, the request returns index.html, the script loads, reads the path, and shows the right screen. The refresh becomes invisible. That is the whole purpose of the technique: make the server agree with the address bar, even though the address bar names a screen, not a file.
A beginner mental model is a theatre with one stage and many plays. The audience enters through one door, the lobby, no matter which play they came to see. Once inside, the programme tells them which play is on. The server is the door. The JavaScript router is the programme. The fallback is the rule that every visitor goes through the lobby door.
Real Files Still Win
The fallback must never break real files, and it does not. The requests below, run against the smallest example, show the split: exact files return themselves, and everything else returns the app.
curl -i http://127.0.0.1:3000/app.js
HTTP/1.1 200 OK
content-type: text/javascript
curl -i http://127.0.0.1:3000/missing.txt
HTTP/1.1 200 OK
content-type: text/html
The script request returned the script with the JavaScript content type. The missing file request returned the HTML page with a 200 status. That second response is the part beginners find strange: a file that does not exist returns success. It returns success because, from the app's point of view, /missing.txt is not a failed file request. It is a client-side route the app has never heard of, and the app's own code will decide what to show for it, usually a "page not found" screen rendered inside the app. The server has handed the decision over.
A Typo Now Returns 200:
With a fallback in place, a mistyped asset URL returns the HTML page with a 200 status instead of a 404. A stylesheet link typed as /stlye.css loads the app HTML as if it were CSS, and the browser silently ignores it, leaving the page unstyled with no error in the network tab beyond a wrong content type. When a page loads unstyled after adding a fallback, check the asset URLs for typos first.
fallback and not_found_service - the Status Difference
ServeDir has a second method that looks almost identical: not_found_service. It takes the same kind of fallback service, but it forces the response status to 404. The official documentation describes the difference exactly: fallback does not alter the status code returned by the fallback, while not_found_service sets the fallback service and overrides the fallback's status code to 404 Not Found.
// Unknown paths return index.html with status 200
let service = ServeDir::new("assets")
.fallback(ServeFile::new("assets/index.html"));
// Unknown paths return index.html with status 404
let service = ServeDir::new("assets")
.not_found_service(ServeFile::new("assets/index.html"));
Run the second version and request the same unknown path. The body is identical: the index.html contents. Only the status line changes.
curl -i http://127.0.0.1:3000/dashboard/settings
HTTP/1.1 404 Not Found
content-type: text/html
The choice between them depends on who reads the status. A browser loading the app needs a 200, because a 404 response body is still rendered by most browsers, but the navigation itself is marked failed, and some app code treats a failed navigation as an error. A search engine reading the site needs a 404 for a genuinely missing page, because a 200 tells it the page exists and it will index a copy of the app under a nonsense URL. The practical rule is simple: use fallback for the single-page app itself, where unknown paths are app routes and must load with 200. Use not_found_service when the file being served is a custom error page for a normal site, where a missing file should stay a 404 in every sense.
The Scoping Problem - the Fallback Swallows Everything
A fallback mounted at the root answers every unmatched request, including requests that were never meant for the app. The example below shows the problem. The server has no API routes at all, so a request for /api/users falls through to the file service, finds no file, and returns the app page with a 200 status.
curl -i http://127.0.0.1:3000/api/users
HTTP/1.1 200 OK
content-type: text/html
An API client asking for /api/users receives an HTML page instead of JSON or a 404. That is wrong in a way that is hard to debug, because the response looks like a success. The fallback cannot tell an app route from an API path. It only knows that no file matched.
The fix is to scope the fallback so it only sees app paths. The cleanest way is to mount the single-page app under its own prefix and keep the API on the main router. The prefix mount uses nest_service, and the fallback travels with the ServeDir inside the mount, so it only answers for paths under that prefix.
use axum::{routing::get, Router};
use tower_http::services::{ServeDir, ServeFile};
async fn api_hello() -> &'static str {
"{\"message\": \"hello from the api\"}"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/api/hello", get(api_hello))
.nest_service(
"/app",
ServeDir::new("assets").fallback(ServeFile::new("assets/index.html")),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
With this router, the same four requests split cleanly along the prefix boundary.
curl -i http://127.0.0.1:3000/app/dashboard
HTTP/1.1 200 OK
content-type: text/html
curl -i http://127.0.0.1:3000/app/app.js
HTTP/1.1 200 OK
content-type: text/javascript
curl -i http://127.0.0.1:3000/api/hello
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
curl -i http://127.0.0.1:3000/api/unknown
HTTP/1.1 404 Not Found
content-length: 0
Unknown paths under /app return the app. Real files under /app return themselves. API routes answer from their handlers. Unknown API paths return the router's plain empty 404, because the fallback never sees them. And a request for /dashboard outside the prefix also returns 404, which is correct: the app lives under /app, and its routes are /app/dashboard and /app/settings.
A Root Fallback Hides API Errors:
A root-mounted fallback turns every API typo into a 200 response carrying HTML. API clients that check only the status code will treat the HTML as a successful answer and fail later in confusing ways. If the application has an API, scope the app under a prefix as shown above, or accept that unknown API paths will return the app page.
How a Request Flows Through the Fallback
The full path of a request through a ServeDir with a fallback, from the browser to the disk and back, looks like this in plain text.
Browser asks for /dashboard/settings
|
v
ServeDir joins the folder path and the request path
assets + /dashboard/settings = assets/dashboard/settings
|
v
No file exists at that path
|
v
The fallback service is called with the same request
ServeFile opens assets/index.html
|
v
Content type is guessed from the fallback file: text/html
|
v
Response sent with 200 OK and the index.html bytes
|
v
Browser runs the script, which reads /dashboard/settings
and renders the settings screen
A request for a real file leaves this flow at the join step and returns the file directly. The fallback only runs on the failure branch, which is why files always win.
Non-GET Requests and the Fallback
By default, the fallback only runs for GET and HEAD requests. A POST to an unknown path returns 405 Method Not Allowed instead of the app page, because ServeDir refuses to serve files for methods that change state, and the fallback inherits that refusal. The setting behind this is call_fallback_on_method_not_allowed, which defaults to false. Turning it on makes the fallback answer POST requests too, but there is rarely a reason to: a single-page app fetches its pages with GET, and a POST to an unknown path is almost always a mistake that deserves a 405. Leave the default alone.
Testing It
The fallback is tested the same way as the file service: build the router, send fake requests with oneshot, and check statuses and content types. The tests below pin down the three behaviours that matter: a real file returns itself, an unknown path returns the app, and the two are distinguishable by content type.
use axum::{body::Body, http::{Request, StatusCode}, Router};
use tower::ServiceExt;
use tower_http::services::{ServeDir, ServeFile};
fn app() -> Router {
Router::new().fallback_service(
ServeDir::new("assets").fallback(ServeFile::new("assets/index.html")),
)
}
#[tokio::test]
async fn unknown_path_serves_index_with_200() {
let response = app()
.oneshot(
Request::builder()
.uri("/dashboard/settings")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["content-type"], "text/html");
}
#[tokio::test]
async fn real_file_still_serves_itself() {
let response = app()
.oneshot(
Request::builder()
.uri("/app.js")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["content-type"], "text/javascript");
}
#[tokio::test]
async fn not_found_service_keeps_404_status() {
let app = Router::new().fallback_service(
ServeDir::new("assets").not_found_service(ServeFile::new("assets/index.html")),
);
let response = app
.oneshot(
Request::builder()
.uri("/dashboard/settings")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
assert_eq!(response.headers()["content-type"], "text/html");
}
The tower crate is needed as a dev dependency with the util feature, as on the earlier pages.
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Run the tests with cargo test. All three pass.
Common Beginner Mistakes
Using fallback on a Normal Website
// Wrong for a documentation site - every typo URL now returns 200
let service = ServeDir::new("assets")
.fallback(ServeFile::new("assets/index.html"));
A documentation site with a fallback returns the home page for every mistyped URL, with a 200 status. Search engines index those nonsense URLs as real pages, and visitors who mistype an address see the home page instead of an error. The fallback belongs on a single-page app, where unknown paths are routes. A normal site wants the plain empty 404, or a custom error page served with not_found_service so the status stays 404.
Pointing the Fallback at a Missing File
// Wrong - assets/index.html must exist, or every unknown path 404s
let service = ServeDir::new("assets")
.fallback(ServeFile::new("assets/app.html"));
If the fallback file does not exist, ServeFile fails to open it, and unknown paths return a 404 instead of the app. The symptom is specific: real files work, and every app route fails with a 404. Check that the fallback path is spelled correctly and that the file is inside the folder.
Putting the Fallback on the Wrong Mount
A fallback set on a ServeDir mounted at /app only answers under /app. A fallback set on a root fallback_service answers everywhere. Mixing the two up produces the scoping problem in reverse: the app loads at /app/dashboard but a refresh of /dashboard 404s, because no fallback covers the root. Decide where the app lives first, then put the fallback on exactly that mount.
Forgetting That the App Must Read the Path
The server side of the fallback is only half the technique. The JavaScript must read window.location.pathname and render the matching screen. A fallback with an app that always shows the home screen will load on every URL and always show the same screen. If every route shows the home screen, the server is fine. The client-side routing is missing.
Expecting the Fallback to Fix API Routes
The fallback serves a file. It cannot manufacture JSON, and it cannot run a handler. An unknown API path that returns the app page is a routing mistake, not a fallback success. Scope the app under a prefix so API paths never reach the fallback, as shown earlier on this page.
Final Complete Example
Here is everything from this page put together: a single-page app mounted under /app with a fallback to its own index.html, an API route beside it, and unknown API paths returning a plain 404. The app's HTML, script, and stylesheet are the same files as the smallest example, with the asset links written for the /app prefix.
use axum::{routing::get, Router};
use tower_http::services::{ServeDir, ServeFile};
async fn api_hello() -> &'static str {
"{\"message\": \"hello from the api\"}"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/api/hello", get(api_hello))
.nest_service(
"/app",
ServeDir::new("assets").fallback(ServeFile::new("assets/index.html")),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("Server running at http://127.0.0.1:3000");
axum::serve(listener, app).await.unwrap();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>My App</title>
<link rel="stylesheet" href="/app/style.css">
</head>
<body>
<h1>My App</h1>
<p id="screen">Loading...</p>
<script src="/app/app.js"></script>
</body>
</html>
const screen = document.getElementById("screen");
const path = window.location.pathname;
if (path === "/app/dashboard") {
screen.textContent = "You are on the dashboard.";
} else if (path === "/app/dashboard/settings") {
screen.textContent = "You are on the settings screen.";
} else {
screen.textContent = "You are on the home screen.";
}
[package]
name = "my-spa"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["full"] }
tower-http = { version = "0.7", features = ["fs"] }
[dev-dependencies]
tower = { version = "0.5", features = ["util"] }
Check the four behaviours in order: /app/dashboard loads the app and shows the dashboard message, /app/app.js returns the script, /api/hello answers from the handler, and /api/unknown returns an empty 404. The app and the API share one server and never answer each other's requests.
Summary
The single-page app fallback is a deal between the server and the JavaScript. The server promises that any path with no file behind it still returns the app's entry page with a 200 status. The JavaScript promises to read the path and render the right screen. ServeDir keeps its half with one method, .fallback(ServeFile::new("assets/index.html")), and the file-first order guarantees real assets are never shadowed.
The decision framework is three questions. Does an unknown path name a screen inside a JavaScript app? If yes, use fallback and a 200 status. Does it name a genuinely missing page on a normal site? If yes, use not_found_service so the status stays 404 while the body shows a friendly page. And does the application also have an API? If yes, scope the app under a prefix, because a root fallback cannot tell an app route from an API path, and the HTML it returns for a mistyped API call is the hardest kind of wrong answer: one that looks like success.