Build modern single-page apps with React, Vue or Svelte, routed and rendered by your Rust server. No client-side router, no API to build and maintain: handlers return a page component and its props, and Inertia.js does the rest.
async fn show(inertia: Inertia, Path(id): Path<u64>, State(db): State<Db>) -> inertia::Response {
let user = db.find_user(id).await;
inertia.render("Users/Show", props! {
user,
activity => inertia::defer(async move || db.activity_for(id).await),
})
}This crate implements the server side of the Inertia v3 protocol, ported from the official Laravel adapter. Its core is framework-agnostic; an adapter for Axum ships with it.
- Installation
- Quick start
- Responses
- Props
- Shared data
- Forms, validation and flash data
- Redirects
- History encryption
- The root view and Vite
- Server-side rendering
- Testing
- Architecture and writing an adapter
- Feature flags
- Coming from Laravel
[dependencies]
inertia-laravel-rust = { path = "../inertia-laravel-rust" }The crate's library name is inertia, so Rust imports use inertia::…. The sibling path above assumes the current workspace layout.
The default features include the Axum adapter, tower-sessions support and server-side rendering. For the framework-agnostic core alone, use default-features = false.
On the client, follow the Inertia client-side setup for React, Vue or Svelte. The demo app is a complete example with React, TypeScript, Tailwind, Vite and SSR.
use axum::{Router, routing::get};
use inertia::axum::InertiaLayer;
use inertia::{Config, Inertia, props};
use tower_sessions::{MemoryStore, SessionManagerLayer};
async fn home(inertia: Inertia) -> inertia::Response {
inertia.render("Home", props! { greeting => "Hello from Rust" })
}
#[tokio::main]
async fn main() {
let config = Config::new()
.version("1")
.root_view(|view: &inertia::View<'_>| {
format!(
r#"<!DOCTYPE html>
<html>
<head>
<script type="module" src="/build/app.js"></script>
{head}
</head>
<body>{body}</body>
</html>"#,
head = view.head.join("\n"),
body = view.body,
)
});
let app = Router::new()
.route("/", get(home))
.layer(InertiaLayer::new(config))
// The session layer goes outside of the Inertia layer.
.layer(SessionManagerLayer::new(MemoryStore::default()).with_secure(false));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}This example assumes your frontend bundle is served at /build/app.js. It shows the server wiring; see the demo app for asset serving and frontend setup. .with_secure(false) allows session cookies on local HTTP; use secure cookies in HTTPS deployments.
The Inertia extractor is the handle for the current request. render returns an inertia::Response right away, so handlers don't .await it. Once the handler returns, the layer resolves the props and responds with an HTML document on a first visit, or the page as JSON on an Inertia visit, much like a Laravel Responsable.
render takes a component name and its props: either Props, usually built with the props! macro, or any Serialize struct.
#[derive(Serialize)]
struct ShowProps {
user: User,
can_edit: bool,
}
async fn show(inertia: Inertia) -> inertia::Response {
inertia
.render("Users/Show", ShowProps { user, can_edit: true })
.with("title", "Profile") // add a prop
.with_view_data("meta", "...") // data for the root view only
.with_header("cache-control", "no-store") // sent with the page, as JSON or HTML
}Status codes and headers set around a render are kept, so an error page is just a tuple:
async fn not_found(inertia: Inertia) -> impl IntoResponse {
(StatusCode::NOT_FOUND, inertia.render("Error", props! { status => 404 }))
}Any Serialize value is a prop. props! takes variables by name and name => value pairs. Quote a key that isn't a Rust identifier, such as a dot notation path for nested props. props! nests as well:
props! {
user, // the `user` variable, a struct
can_edit => true,
"auth.user.permissions" => ["edit"], // nested with dot notation
settings => props! { // nested props, with behavior of their own
theme => "dark",
billing => inertia::optional(async || load_billing().await),
},
}A key is the name as you write it, so can_edit stays can_edit. When a page expects camelCase, write canEdit => can_edit.
props! borrows a variable named on its own and serializes it straight away, so you can keep using the variable afterward. A name => value pair takes the value as written. Pass &value to keep the value, and move a lazy prop with stats => stats.
An if block adds its props only when its condition holds, and else if, else and if let work as they do in Rust:
props! {
user,
if user.is_admin {
stats => inertia::defer(async || load_stats().await),
} else {
upgrade_url => "/billing",
}
if let Some(team) = user.team {
team,
}
}A prop in a block whose condition doesn't hold isn't sent at all, unlike an Option prop, which is sent as null.
Partial reloads (router.reload({ only: ['user.name'] })) only resolve the props they ask for, matching nested paths in both directions.
The functions at the crate root create props with special behavior, which builder methods refine further:
| Prop | Behavior |
|---|---|
inertia::lazy(async || { .. }) |
Computed only when the prop is part of the response. |
inertia::optional(..) |
Only sent when a partial reload asks for it. |
inertia::defer(..) |
Left out of the first render; the client fetches it right after. .group("name") loads deferred props in parallel groups. |
inertia::always(value) |
Sent with every response, even partial reloads that didn't ask for it. |
inertia::merge(value) |
Appended to its client-side value. .prepend(), .append_at("data"), .prepend_at("data"), .match_on("id"). |
inertia::deep_merge(value) |
Deep merged with its client-side value. |
inertia::once(..) |
Resolved once and remembered by the client. .once_as("key"), .until(1.hour()), .fresh(). |
inertia::live(value, listeners) |
Reloaded when the client receives a broadcast event. .live(listeners) makes any other prop live, and .throttle(5.seconds()) limits how often it reloads. |
inertia::scroll(paginator) |
An infinite scroll page, for <InfiniteScroll>. inertia::scroll_with(async || { .. }) loads it lazily. |
inertia::try_lazy(..) |
Like lazy, for a callback whose Result has an error type that is itself Serialize, such as String. |
The behaviors compose:
props! {
posts => inertia::defer(async || load_posts().await).group("feed").merge().match_on("id"),
plans => inertia::once(async || load_plans().await).until(1.hour()),
stats => inertia::defer(async || stats_api().await).rescue(),
}until and throttle take a length of time, such as 1.hour() with jiff::ToSpan in scope, or a std::time::Duration. Calendar units, such as 1.month(), count from now in UTC.
A callback may return a Result. Its error fails the response, unless the prop is .rescue()d, which tells the client that the prop failed. A callback runs after the handler returns, so it owns what it uses: move values into it with async move, such as a database pool or an ID. Sibling callbacks run concurrently, so independent lookups can overlap rather than run one after another.
For infinite scroll, pass a page of results that keeps its items under data and implements ProvidesScrollMetadata. Laravel's paginators implement it. For a paginated type of your own, return its ScrollMetadata:
#[derive(Serialize)]
struct UserPage {
data: Vec<User>,
#[serde(skip)]
page: u64,
#[serde(skip)]
last_page: u64,
}
impl ProvidesScrollMetadata for UserPage {
fn scroll_metadata(&self) -> ScrollMetadata {
ScrollMetadata::pages("page", self.page, self.last_page)
}
}
users => inertia::scroll_with(async move || db.user_page(page).await),Like a lazy prop's callback, a scroll_with callback may return a Result. Its error fails the response, unless the prop is .rescue()d.
A live prop reloads when the client receives one of its broadcast events. Each LiveListener names a channel and the events broadcast on it:
use inertia::{LiveChannel, LiveListener};
let listeners = vec![LiveListener::new(LiveChannel::private("orders.1"), ["OrderUpdated"])];
props! {
order => inertia::lazy(async move || load_order(id).await).live(listeners),
metrics => inertia::defer(async || load_metrics().await)
.live([LiveListener::new(LiveChannel::public("metrics"), ["MetricsUpdated"])])
.throttle(5.seconds()),
}A channel is public, private, presence or encrypted_private. Give its name without the private- or presence- prefix. The page lists a prop's listeners even when it leaves the prop out, as with deferred props, so the client knows what to listen for. A live prop can't merge, and it must listen for at least one event. Otherwise the response fails.
An event can carry new prop values, so the client applies them without a reload. inertia::broadcast_props adds them to the event's payload:
let payload = inertia::broadcast_props(json!({ "order_id": order.id }), json!({ "order": order }))?;Share data with every page from the config. The callback runs on each render, so make anything expensive lazy:
Config::new().share(|_request| props! {
appName => "Acme",
announcement => inertia::lazy(async || latest_announcement().await),
})For data that depends on the request, such as the signed-in user, share it from a middleware. The Inertia handle is shared by everything that handles the request:
use axum::extract::Request;
async fn share_user(inertia: Inertia, user: CurrentUser, request: Request, next: Next) -> Response {
inertia.share("auth.user", user);
next.run(request).await
}
let app = Router::new()
.route("/", get(home))
.layer(middleware::from_fn(share_user)) // inside of the Inertia layer
.layer(InertiaLayer::new(config));Validation errors are shared automatically as errors. Shared prop keys are listed in the page's sharedProps.
The Inertia client sends form data as JSON, or multipart data for uploads. Validate it, and on failure redirect back with the errors. They're shared with the next page in its errors prop:
async fn store(inertia: Inertia, Json(form): Json<NewUser>) -> HttpResponse {
let mut errors = ValidationErrors::new();
if form.name.trim().is_empty() {
errors.add("name", "The name field is required.");
}
if !errors.is_empty() {
return inertia.back_with_errors(errors);
}
create_user(form).await;
inertia.flash("toast", "User created!");
inertia::redirect("/users")
}- Error bags. Forms with an
errorBagget their errors scoped under it (errors.createUser.name).Config::all_errors(true)shares every message per field instead of the first. - Validation crates. With the
validatororgardefeatures, their errors convert intoValidationErrorswith.into(). - Flash data is delivered in the page's
flashfield, not its props, so it isn't kept in the browser history.
Like Laravel's session, flash, with_errors, clear_history and preserve_fragment are queued during the request, written to the session when it ends, and delivered to the next page render. That can be a render in the same request.
Flash data queued by prop callbacks also reaches the page being rendered. Values set with inertia::Response::flash take precedence over the request's flash data.
| Call | Response |
|---|---|
inertia::redirect("/users") |
302. After PUT, PATCH, DELETE and QUERY the layer makes it a 303, so the browser follows it with a GET. |
inertia.back() |
A redirect to the Referer. |
inertia.location("https://..") |
A full page visit: 409 with X-Inertia-Location for Inertia visits. Use it for external URLs. |
The layer also handles the protocol's edge cases:
- A redirect to a URL with a
#fragmentbecomes a409withX-Inertia-Redirect, sincefetchdrops fragments. - An empty
200response to an Inertia visit becomes a redirect back. - A client running outdated assets (a different
version) gets a409that makes it reload the page.
inertia.render("Billing", props).encrypt_history(true) // or Config::encrypt_history(true) for every page
inertia.clear_history(); // e.g. on logout: encrypted pages can't be restoredThe root view renders the HTML document of a first visit. It is any Fn(&View) -> String, or a type implementing RootView. A View holds:
head: the SSR<head>elements, one string per element,body: the page data<script>and the app element,page: the page object,data: view data,ssr: whether the page was server-side rendered.
The laravel-vite-rust crate's Vite renders asset tags like Laravel's @vite. It's a separate dependency, laravel-vite-rust = { path = "../laravel-vite-rust" }, used as vite::Vite:
- In development the Vite dev server writes its URL to a hot file (
public/hot), and tags point at the dev server, withVite::react_refresh()providing React Fast Refresh's preamble. - In production tags come from the build manifest, and its hash makes a good asset version.
The manifest is parsed once and cached. Each render checks for the hot file and the manifest's modified time, so starting the dev server or a new build is picked up without a restart. In production, where neither changes without a deploy, Vite::new().watch(false) checks each once instead, and so does HttpGateway::watch(false) for its hot file and bundle.
let vite = Vite::new();
Config::new()
.version_with({
let vite = vite.clone();
move || vite.manifest_hash().unwrap_or_default()
})
.root_view(move |view: &View<'_>| format!(
"<!DOCTYPE html><html><head>{refresh}{assets}{head}</head><body>{body}</body></html>",
refresh = vite.react_refresh(),
assets = vite.tags(["resources/js/app.tsx", &format!("resources/js/pages/{}.tsx", view.page.component)]),
head = view.head.join("\n"),
body = view.body,
))Vite has no hot file of its own. The demo app's vite.config.ts adds a ten-line plugin that writes one, like laravel-vite-plugin does.
use inertia::ssr::HttpGateway;
Config::new().ssr(
HttpGateway::new()
.hot_file("public/hot") // dev: render through Vite's /__inertia_ssr endpoint
.bundle("bootstrap/ssr/app.js") // prod: use :13714/render once the bundle is built
.except(["admin/*"]),
)On first visits the page is rendered by the SSR server, and the client hydrates it. If the server is down or rendering fails, the page is rendered on the client instead. A slow SSR server can still delay the response until its timeout. Implement ssr::Gateway to render pages another way.
The gateway speaks plain HTTP, which suits an SSR server on the same machine. Enable the ssr-tls feature to reach https:// URLs, including a Vite dev server that serves over HTTPS.
AssertablePage reads a page from a response body (an HTML document or JSON), with assertions modeled on Laravel's assertInertia:
use inertia::testing::AssertablePage;
AssertablePage::from_body(&body)
.component("Users/Index")
.has_count("users", 3)
.equals("users.0.name", "Taylor")
.missing("users.0.password")
.deferred("default", &["stats"])
.flash("toast", "Saved!");To assert on a nested object or list, scope into it with scope, first, or each. A scope fails if its closure doesn't assert on every prop in the scoped value, unless the closure calls etc():
page.has_count("users", 3)
.first("users", |user| {
user.equals("name", "Taylor")
.satisfies("id", |id: u64| id > 0)
.missing("password")
.etc()
})
.contains("tags", "rust")
.has_count_in("tags", 1..=5)
.has_flash("toast.message");With pages_in("resources/js/pages"), component also asserts that the component has a page file, such as Users/Index.tsx.
A page can reload itself as the Inertia client does. The reload is an Inertia visit to the page's URL, and it sends the page's component and asset version. Awaiting reload, reload_only, reload_except, or load_deferred_props returns the reloaded page. Before it returns, each one asserts that the reloaded page has the same component, URL, and asset version. reload_only also asserts that the page has the props it asked for, and reload_except asserts that the page lacks the props it excluded:
page.reload_only(&["reviews"]).await.has_count("reviews", 3).missing("post");
page.reload_except(&["head"]).await.has("post");
page.load_deferred_props().await.has("stats");A page from from_body can't send requests on its own. Give it a function with reloads_with that sends a ReloadRequest to your application and reads the page from the response, as reloadable in tests/axum.rs does for an Axum Router.
The core can also be tested without a web framework. Build an Inertia handle from a Request and an ArraySession, then resolve a render with Response::into_page. See tests/core.rs.
src/
├── config.rs Config: version, root view, shared props, SSR
├── inertia.rs Inertia: the per-request handle (render, share, flash, errors, redirects)
├── request.rs Request: the protocol headers, parsed once
├── props/ Props, Prop and its behaviors, and the props resolver
├── response.rs Response: a pending render, resolved into an HTTP response
├── page.rs Page: the typed page object
├── protocol.rs The rules applied around each handler: before() and after()
├── session/ The Session trait, ArraySession, and tower-sessions support
├── ssr.rs The Gateway trait and HttpGateway
├── view.rs The RootView trait
├── testing.rs AssertablePage
└── axum/ The Axum adapter: InertiaLayer, the extractor, IntoResponse
The core depends on http, serde and utility crates. Optional features add HTTP SSR, session stores and framework or validation integrations. An adapter for another framework is a thin translation layer:
// 1. Parse the request.
let request = inertia::Request::new(method, &uri, headers);
// 2. Outdated clients reload the page instead of running the handler.
if let Some(response) = inertia::protocol::before(&request, &config) {
return response;
}
// 3. Make the handle available to handlers, with the framework's session.
let inertia = Inertia::with_session(config.clone(), request, session);
// 4. Run the handler. If it returned an inertia::Response, resolve it.
// `try_into_http` returns a prop's failure instead of a plain `500`,
// for the framework to render as it renders any error.
let response = page.into_http().await;
// 5. Write queued flash data and errors to the session, and drop what
// earlier requests left for a page this one didn't render.
inertia.commit(response.status()).await;
// 6. Apply the redirect rules, which may replace the response.
let (mut parts, body) = response.into_parts();
if let Some(replacement) = inertia::protocol::after(inertia.request(), &mut parts, body.is_empty()) {
return replacement;
}Implement the Session trait (get, put, pull, forget) for the framework's session. See src/axum for the complete Axum adapter.
| Feature | Default | |
|---|---|---|
axum |
✓ | The Axum adapter |
tower-sessions |
✓ | Session for tower_sessions::Session |
ssr |
✓ | HttpGateway, which uses reqwest |
ssr-tls |
HTTPS for HttpGateway |
|
validator |
From<validator::ValidationErrors> for ValidationErrors |
|
garde |
From<garde::Report> for ValidationErrors |
| Laravel | Rust |
|---|---|
Inertia::render('Users/Index', [...]) |
inertia.render("Users/Index", props! { .. }) |
Inertia::optional(fn () => ..) |
inertia::optional(async || { .. }) |
Inertia::defer(fn () => ..)->group('x') |
inertia::defer(async || { .. }).group("x") |
Inertia::merge(..)->matchOn('id') |
inertia::merge(..).match_on("id") |
Inertia::deepMerge(..) / Inertia::always(..) |
inertia::deep_merge(..) / inertia::always(..) |
Inertia::once(fn () => ..)->until(..) |
inertia::once(async || { .. }).until(..) |
Inertia::live(fn () => .., on: new OrderUpdated($order)) |
inertia::live(inertia::lazy(..), [LiveListener::new(LiveChannel::private("orders.1"), ["OrderUpdated"])]) |
Inertia::broadcastProps([...]) |
inertia::broadcast_props(payload, props) |
Inertia::scroll(User::paginate()) |
inertia::scroll(User::query().paginate(15).await?) |
HandleInertiaRequests::share() |
Config::share or inertia.share(..) in a middleware |
HandleInertiaRequests::version() |
Config::version / Config::version_with |
back()->withErrors($errors) |
inertia.back_with_errors(errors) |
Inertia::flash('key', $value) |
inertia.flash("key", value) |
Inertia::location($url) |
inertia.location(url) |
Inertia::clearHistory() / encryptHistory() |
inertia.clear_history() / .encrypt_history(true) |
$response->assertInertia(fn ($page) => ..) |
AssertablePage::from_body(&body).. |
$page->reloadOnly('reviews', fn ($page) => ..) |
page.reload_only(&["reviews"]).await.. |
$page->loadDeferredProps(fn ($page) => ..) |
page.load_deferred_props().await.. |
$page->has('user', fn ($user) => $user->where(..)->etc()) |
page.scope("user", |user| user.equals(..).etc()) |
$page->where('views', fn ($views) => $views > 10) |
page.satisfies("views", |views: u64| views > 10) |
Not ported yet: Inertia DevTools, ProvidesInertiaProperties, component name transformers, the render-time pages.ensure_pages_exist check, and Precognition.
The props resolver and protocol rules are ports of inertiajs/inertia-laravel. The framework-agnostic core with adapters, and handlers that return a render without awaiting it, were inspired by Veer.
cargo test --all-features