Smeltery
Get started

Alloy

v0.1

Alloy: React and Vue

On this page

Alloy (smeltery::alloy) is the server side of the Inertia protocol, version 3. A controller returns a page, a component name with its props, instead of a Mold view, and Inertia's client packages (@inertiajs/react, @inertiajs/vue3) render it in the browser. The first visit gets HTML from a Mold root template with the page inside; every later visit (a link, a form, a reload) gets the page as JSON, and the client swaps the component without reloading the browser page. smeltery new --frontend react and --frontend vue create apps set up this way (see The React and Vue starter kits). Node.js builds the JavaScript only: the server runs the Rust binary and serves the build from public/build/.

Setup#

rust
use smeltery::alloy::{Alloy, AlloyExt as _, Props, SharedCtx};

/// The HTML of a first visit: resources/views/app.mold.html.
#[derive(smeltery::Mold, Default)]
#[mold("app")]
pub struct Root {}

/// Props every page gets.
async fn shared(ctx: SharedCtx) -> smeltery::Result<Props> {
    Ok(Props::new().with("app", smeltery::json!({ "name": ctx.app().settings().name })))
}

pub fn build(app: smeltery::AppBuilder) -> smeltery::AppBuilder {
    app.alloy(
        Alloy::new()
            .root::<Root>()
            .entries(["resources/js/app.tsx"]) // what a bare @vite loads
            .share(shared),
    )
}

The root template loads the assets with @vite and places the page with @alloy:

html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>My App</title>
    @vite
    @alloyHead
  </head>
  <body>
    @alloy
  </body>
</html>

@alloy renders <script data-page="app" type="application/json">…</script><div id="app"></div> (the page's JSON escaped, so no prop can close the script element); @alloy("root") uses another id, which the client's createInertiaApp({ id }) must name too. @alloyHead renders an empty string. @vite renders the configured entries and @vite("resources/js/admin.ts", …) the named ones (see Vite). In an app without .alloy(…), @alloy and @vite are template errors.

Alloy also has .version(f) (the asset version, below), .all_errors() (every message per field), .encrypt_history() (see Redirects and history), .build_dir("build") (the folder under public/ and the URL prefix of the build: letters, digits and _ . / @ -, no ..; anything else stops the app at boot) and .hot_file(path) (the dev-server marker, storage/framework/vite.hot). .alloy(…) adds a middleware to every web route (inside the session and CSRF stack), sets the XSRF-TOKEN cookie that Inertia's client sends back as the X-XSRF-TOKEN header, and names X-Inertia in the Vary header of every web response. API routes are not touched.

↑↓ moveEnter openEsc close