Skip to main content

Crate axum_frontend

Crate axum_frontend 

Source
Expand description

§Axum Frontend

Build Status Coverage Status Crate Docs

Serve a Vite (or any) frontend from axum: embed the built SPA in your binary, serve it from a directory on disk, or spawn and reverse-proxy the dev server.

§Installation

As a dependency of a Rust project:

cargo add axum-frontend

Dev mode (spawn the dev server and reverse-proxy to it) is behind the dev feature:

cargo add axum-frontend --features dev

§Library Usage

axum-frontend is provided as a crate that you can use in your own code.

Cargo.toml:

[dependencies]
axum = "0.8"
tokio = {version = "1", features = ["full"]}
axum-frontend = "0.2"
rust-embed = "8"

§Embed the built SPA in the binary

RustEmbed expands to paths in the rust-embed crate, so your crate needs it as a direct dependency.

ⓘ
use axum::{routing::get, Router};
use axum_frontend::{embed_router, RustEmbed};

#[derive(RustEmbed)]
#[folder = "dist/"]
struct Assets;

let app = Router::new()
  .route("/api/health", get(|| async { "ok" }))
  // Your routes win; everything else is served from the embedded assets,
  // falling back to index.html for client-side routes.
  .merge(embed_router::<Assets>());

§Serve the built SPA from a directory

use axum::{routing::get, Router};
use axum_frontend::static_router;

let app = Router::new()
  .route("/api/health", get(|| async { "ok" }))
  .merge(static_router("dist"));

A missing path with a dot in it, such as /missing.js, is a 404 in both modes. Any other path with no file behind it gets the index document, for client-side routing.

Directory paths are client-side routes too. /assets gets the index document instead of a redirect to /assets/, and docs/index.html is not served at /docs/, so link to /docs/index.html if you ship pages in subdirectories.

Under .nest("/app", ...), axum itself answers /app/ with a 404 before the request reaches these routers. Link to /app, or add a redirect in your app.

§Routes and caching

Both routers answer only GET and HEAD: any other method is a 405. Successful responses get Cache-Control: no-cache, so browsers check for a new version before reusing a file, and an unchanged file answers 304. A policy the serving mode already set is kept.

SpaOptions adds two settings:

use axum::{routing::get, Router};
use axum_frontend::{static_router_with, SpaOptions};

let opts = SpaOptions::new()
  // Every method is a 404 under these paths, so an API miss never becomes HTML.
  .exclude(["/api"])
  // Browsers keep these for a year without asking. Name only content-hashed files.
  .immutable(["/assets/"]);

let app = Router::new()
  .route("/api/health", get(|| async { "ok" }))
  .merge(static_router_with("dist", opts));

SpaOptions::apply puts the same policy in front of any Router, which is how dev mode gets it, and how it goes on the far side of a layer such as authentication. dev_router on its own forwards every method.

exclude matches the decoded path, so /%61pi, //api, and /api\users count as /api. It is case-sensitive, though: on a case-insensitive filesystem, folder mode and debug embedded builds can still serve /ASSETS/app.js with /assets excluded, so use it to shape responses, not to keep files private.

§Dev mode: spawn the dev server and reverse-proxy to it

Requires the dev feature.

ⓘ
use axum::{routing::get, Router};
use axum_frontend::{shutdown_requested, DevConfig};

// Inside an async context:
// Spawns `pnpm dev` in ./frontend with --host/--port pinned, and waits until
// it accepts connections. The returned DevServer kills the dev server (and, on
// Unix, its whole process group) on drop.
let dev = DevConfig::vite()
  .cwd("frontend")
  .port(5173)
  .spawn()
  .await?;

let app = Router::new()
  .route("/api/health", get(|| async { "ok" }))
  // Proxy everything else to the dev server.
  .merge(dev.router(["/"]));

let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await?;

// Racing the server against the shutdown signal is what makes `dev`'s cleanup
// reachable: a process killed by SIGINT or SIGTERM runs no destructors, so
// without this the guard never drops and the dev server is orphaned onto init,
// still holding port 5173.
//
// A race rather than `.with_graceful_shutdown(shutdown_requested())`: graceful
// shutdown drains open connections first, and Vite's HMR WebSocket stays open
// for as long as a browser tab has the page on screen, so draining turns Ctrl-C
// into a hang for exactly the workflow this exists to serve.
tokio::select! {
  result = axum::serve(listener, app) => result?,
  () = shutdown_requested() => {}
}

// The guard has to outlive the server: dropping it is the only thing that kills
// the dev server, so keep it in scope until serving is over.
drop(dev);

Use DevConfig::new(["npm", "run", "dev"]) for a tool-neutral command, or dev_router(prefixes, target) directly if you manage the dev server yourself. Wrap the proxy with SpaOptions::apply for the policy above: SpaOptions::new().exclude(["/api"]).apply(dev.router(["/"])).

§Shutdown

DevServer kills the dev server and its process group when it is dropped, so the host process has to live long enough to drop it. A process killed by a signal runs no destructors, which means handling SIGINT and SIGTERM is on you: shutdown_requested() resolves on either (Ctrl-C on non-Unix) so you can race it as above. Ctrl-C alone won’t do it. On Unix the dev server runs in its own process group, deliberately, so the group kill can reap the real Vite server under pnpm dev without touching your shell and cargo, and that group is not the terminal’s foreground one, so the terminal’s Ctrl-C never reaches it.

kill -9 on the host is the one case nothing covers: it runs no cleanup at all and the dev server is orphaned. If a later run fails with the port already in use, that orphan is the likely holder.

§Inspiration

I wanted a single, ergonomic way to serve a Vite frontend from an axum backend: one dev front door with hot-module reloading while developing, and a self-contained binary (or a directory of assets) in production, without wiring up the same proxy, embed, and SPA-fallback logic by hand in every project.

Structs§

SpaOptions
Options shared by the SPA routers, and the policy SpaOptions::apply puts in front of any of them.

Traits§

Embed
A directory of binary assets.
RustEmbed
A directory of binary assets.

Functions§

embed_router
A Router whose fallback serves the embedded assets of E, using index.html as the SPA entry document.
embed_router_with
Like embed_router, with configurable SpaOptions (e.g. the index file).
static_router
A Router whose fallback serves dir, falling back to dir/index.html for client-side routes.
static_router_with
Like static_router, with configurable SpaOptions (e.g. the index file served for / and unmatched client-side routes).

Derive Macros§

Embed
RustEmbed