# Alloy Quickstart

Scaffold a server-rendered Ferrite Alloy app with ferrite new alloy, run it locally, deploy it, and optionally add a generated TypeScript contract and a React front end.

Start from the built-in `alloy` template, run the app locally, and deploy it to
Ferrite Cloud. The final section is optional and adds a generated TypeScript
contract and a Vite React front end (which requires Node.js and npm).

## 1. Scaffold the app

```bash
ferrite new alloy my-app --with-tests
cd my-app
```

This creates a complete application with the Alloy runtime already vendored.
`--with-tests` adds the smoke test and the local test SDK.

```text
my-app/
├── Cargo.toml             # one dependency, ferrite-app
├── ferrite.json           # four services, each with a small workload, and three public routes
├── ferrite-packages.json  # records the alloy and sha256-hmac mounts
├── ferrite.local.toml     # local [secrets]; owner-only, gitignored, never deployed
├── README.md
├── AGENTS.md              # the brief for a coding agent, with the template's API card
├── CLAUDE.md              # points at AGENTS.md
├── rust-toolchain.toml
├── .gitignore             # /target, /.ferrite and /ferrite.local.toml
├── src/
│   ├── lib.rs             # the shell, route table, loader, action and seed
│   ├── main.rs            # the process harness
│   ├── alloy/             # the Alloy runtime, vendored
│   └── crypto/            # sha256-hmac, which alloy depends on
├── tests/smoke.rs         # written by --with-tests: the app boots and GET / is HTML
└── vendor/                # the SDK the local loop compiles against
```

`src/alloy/` and `src/crypto/` match what `ferrite add alloy` installs, and
every file carries a `@generated by ferrite-pkg` header. Leave them unmodified;
run `ferrite add --force alloy` to refresh them from the published version.
`vendor/` is used only on your machine because the platform compiles deployments
against its own `ferrite-app`. `ferrite.local.toml` holds local secrets, is
created owner-readable only, is gitignored, and is never uploaded on deploy.

## 2. Run it locally

```bash
ferrite check    # the source gate, the manifest statics and cargo check
ferrite dev      # http://localhost:8787, rebuilt on every save
ferrite test     # the smoke test, the unit tests in src/lib.rs and, with --with-tests, the demo tests there
```

`ferrite dev` serves the app at `http://localhost:8787` against local planes
persisted under `.ferrite/state`. Submit a note through the form and reload the
page to exercise the 303 redirect and cache invalidation. Local check verdicts
are advisory; the platform's build and gate decide what deploys.

## 3. Read the application

All application code lives in `src/lib.rs`. Your app type implements `AlloyApp`,
and `alloy::app::serve` runs the request loop, reply-before-acknowledge
ordering, and outbox drain:

```rust filename="src/lib.rs"
impl AlloyApp for App {
    const BUILD: &'static str = BUILD;
    const SHELL: &'static str = SHELL;

    async fn answer(ctx: &AppContext, req: &IngressRequest) -> Result<IngressReply, AlloyError> {
        dispatch(ctx, req).await
    }

    async fn seed(ctx: &AppContext) -> Result<(), AlloyError> {
        seed(ctx).await
    }
}
```

The template writes `Result<T, AlloyError>` explicitly; `alloy::error::Result<T>`
is an alias for the same type.

The starter `impl` also overrides `admit`, which decides whether a caller holds
the authority mounted on an action. Because the template has no sessions, it
admits only public actions.

`SHELL` is the HTML document every page renders into. It requires two exact
markers in this order: `<!--__alloy_head-->`, where Alloy writes `<title>`,
description, and canonical tags, followed by an empty
`<script id="__alloy_data" type="application/json"></script>`, where Alloy
embeds the loader payload. `Shell::parse` rejects any shell missing either
marker, and visitors receive 500 on every page.

The route table uses App Router syntax, so dynamic segments use `[id]`. Writing
`:id` parses as a literal path segment and never matches:

```rust filename="src/lib.rs"
fn routes() -> Result<RouteTable, AlloyError> {
    let mut table = RouteTable::new();
    for (id, pattern) in [("index", "/"), ("note", "/notes/[id]")] {
        table.push(Route::page(id, pattern).map_err(AlloyError::internal)?);
    }
    Ok(table)
}
```

Both pages read notes through the tag-epoch cache, so the loader runs once per
epoch of the `notes` tag across visitors:

```rust filename="src/lib.rs"
let cached = cache
    .get::<Vec<Note>, _, _>(
        "notes",
        b"",
        &[NOTES_TAG.to_string()],
        CacheLife::Minutes,
        ctx.now_ms(),
        || async move { /* scan the data store */ },
    )
    .await?;
```

The index form posts to `/__alloy/action/add-note`. `ActionRunner` records each
admission under the request's idempotency key so a duplicate delivery with the
same key adds no second note, and commits the replay marker together with the
`notes` tag advance in one guarded APE write:

```rust filename="src/lib.rs"
let mut runner = ActionRunner::new(ctx.ape("tags")?);
if runner.recorded(ADD_NOTE, &key).await?.is_none() {
    // write the row, then:
    runner
        .commit(ADD_NOTE, &key, &Effects::new().tag(NOTES_TAG), serde_json::json!({ "id": id }), ctx.now_ms())
        .await?;
}
```

Queue redeliveries always reuse the same idempotency key. Plain HTML forms send
no `idempotency-key` header, so each submission of the starter form gets a new
key and submitting twice adds two notes. See
[The idempotency key and the marker](/developers/alloy-actions/#the-idempotency-key-and-the-marker)
for how keys are derived.

The action answers 303 with `Location: /`, so reloading the page repeats the
`GET` instead of reposting the form.

## 4. Read the manifest

The starter `ferrite.json` declares four services with small starting
`workload` reservations (raise them only when traffic requires more) and three
public routes. `/__alloy/` handles actions and forwards `sec-fetch-site` for
origin verification, `/assets/` forwards `accept-encoding` and `if-none-match`
so front-end files serve compressed with ETag revalidation, and both `/__alloy/`
and `/` forward the headers needed if you add sign-in later:

```json filename="ferrite.json"
{
  "services": [
    { "name": "requests", "primitive": "queue",
      "workload": { "read_qps": 20, "write_qps": 10, "record_size_kb": 0, "keying": "PerKey", "hot_set_gib": 0 } },
    { "name": "cache", "primitive": "store",
      "workload": { "read_qps": 50, "write_qps": 5, "record_size_kb": 1, "keying": "PerKey", "hot_set_gib": 0 } },
    { "name": "data", "primitive": "store",
      "workload": { "read_qps": 50, "write_qps": 5, "record_size_kb": 1, "keying": "PerKey", "hot_set_gib": 0 } },
    { "name": "tags", "primitive": "ape",
      "workload": { "read_qps": 50, "write_qps": 5, "record_size_kb": 0, "keying": "PerKey", "hot_set_gib": 0 } }
  ],
  "applications": [{
    "name": "my-app",
    "artifact_key": "apps/my-app@v1",
    "artifact_sha256": "0000000000000000000000000000000000000000000000000000000000000000",
    "bindings": [
      { "handle": "requests", "kind": "queue", "service": "requests" },
      { "handle": "cache", "kind": "store", "service": "cache" },
      { "handle": "data", "kind": "store", "service": "data" },
      { "handle": "tags", "kind": "ape", "service": "tags" }
    ],
    "routes": [
      { "prefix": "/__alloy/", "binding": "requests", "kind": "api", "public": true, "forward_headers": ["accept", "idempotency-key", "origin", "sec-fetch-site", "cookie", "content-type", "x-csrf-token"] },
      { "prefix": "/assets/", "binding": "requests", "kind": "api", "public": true, "forward_headers": ["accept-encoding", "if-none-match"] },
      { "prefix": "/", "binding": "requests", "kind": "api", "public": true, "forward_headers": ["accept", "cookie", "origin", "sec-fetch-site", "content-type", "x-csrf-token"] }
    ],
    "compute": { "memory_mb": 256, "cpu_percent": 50 }
  }]
}
```

The handle names match Alloy's defaults (`AlloyApp::REQUESTS` = `"requests"`,
`TAGS` = `"tags"`, `LEASES` = `"cache"`); override both the constant and the
binding if you rename one. `requests` is required: `serve` binds it at startup
and fails without it. `tags` and `cache` hold tag epochs, replay markers, and
outbox leases; if either is missing, the outbox drain logs one error and
performs no cross-plane effects for the lifetime of the process. `data` is your
application's own store and can be renamed freely.

The headers forwarded on `/__alloy/` enforce Alloy's CSRF origin check. Before
any action handler runs, the dispatcher rejects browser POSTs it cannot verify
as coming from your own pages. Because the platform gateway never forwards
`Host`, a browser POST is admitted only when `Sec-Fetch-Site` is `same-origin`
or when `Origin` is listed in `ALLOWED_ACTION_ORIGINS`. Browsers set
`Sec-Fetch-Site` automatically and page scripts cannot spoof it. Requests
marked `cross-site` or `same-site` (including sibling subdomains) return 403
unless their origin is explicitly listed. Non-browser requests with no `Origin`
and no cross-site mark pass because they carry no browser cookies.

Forward both `origin` and `sec-fetch-site` on the action route. Forwarding
`origin` without `sec-fetch-site` returns 403 to every browser form post from
an unlisted origin while `curl` without `Origin` still succeeds; forwarding
neither causes the gate to treat every request as non-browser and admit
cross-site forms. Where a local test harness supplies `Host`, the dispatcher
also admits an `Origin` matching `Host` as long as `Sec-Fetch-Site` is neither
`cross-site` nor `same-site`. See
[CSRF origin checks](/developers/alloy-actions/#csrf-origin-checks) for the
full matrix.

## 5. Deploy

```bash
ferrite account              # confirm which account the CLI uses
ferrite cost --instances 1   # the deploy fee and the projected monthly cost, without deploying
ferrite deploy
```

`ferrite cost` (MCP: `estimate_cost`) prints your account balance, deploy fee,
and projected monthly cost at current rates without charging or deploying.
Share that estimate with the account owner before deploying.

The starter's `compute` block (`256` MiB memory, `50`% CPU, one instance)
matches what a trial account supports. Trial accounts last 48 hours and start
with $5 of credit, enough to run an app or a few. If you do not have an account yet, follow
[Quickstart](/developers/quickstart/#deploy-the-app) to create a trial account
and keep the app running after the trial ends.

Each deploy is one charged build that compiles your checked source on the
platform and typically takes three to eight minutes. Submit it once; if your
shell disconnects before completion, run `ferrite deploy resume` to reattach to
the same attempt.

The hosted repository uploads `Cargo.toml`, `ferrite.json`, `src/`, and
`tests/`. The platform uses `[dev-dependencies]` for `test_ref` and omits them
from the deployed binary. See [Deployments](/developers/deployments/) for
account details, build stages, and failure recovery.

## Add a typed contract and a React front end

You can declare routes and actions under `app/` and serve a Vite React front
end from `web/`. No template creates this layout, so these steps layer it onto
the scaffolded app. Make sure `node` and `npm` are on your `PATH`, because
`ferrite dev` runs your front end's npm scripts.

### Declare routes and actions

Files under `app/` are read by the contract generator and are not compiled as
part of the Rust crate. A route declares its path, loader name, return type,
and render mode. Wire types carry `#[derive(Contract)]`, which the generator
parses and `rustc` never sees:

```rust filename="app/page.rs"
alloy::route! {
    id: index,
    path: "/",
    loader: get_notes,
    output: NotesView,
    render: Hybrid,
}

/// Every note, newest first.
#[derive(Contract)]
pub struct NotesView {
    pub items: Vec<NoteRow>,
}

#[derive(Contract)]
pub struct NoteRow {
    pub id: String,
    pub text: String,
}
```

An action declares its input and output types plus the tag families it may
advance:

```rust filename="app/notes/actions.rs"
alloy::action! {
    name: add_note,
    input: AddNote,
    output: NoteRow,
    tags: ["notes"],
}

#[derive(Contract)]
pub struct AddNote {
    pub text: String,
}
```

### Add the front end

Create `web/` as a standard Vite and React project whose `package.json` defines
a `build` script (`prebuild` and `postbuild` are optional). Install
`@tanstack/react-query` alongside `react` and `react-dom` because the generated
hooks import it. Configure Vite to emit content-hashed filenames for every
output (including the entry) and to write a manifest: the asset packer reads
those hashed names from the manifest, caches them for a year, and hands the
entry paths to the Rust shell. Leave source maps disabled; the packer skips
`.map` files regardless:

```ts filename="web/vite.config.ts"
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plugins: [react()],
  build: {
    manifest: true,
    sourcemap: false,
    // Emit real files rather than data URIs, so every asset is served from
    // the packed archive and cached by its own name.
    assetsInlineLimit: 0,
    rollupOptions: {
      output: {
        entryFileNames: "assets/entry-[hash].js",
        chunkFileNames: "assets/[name]-[hash].js",
        assetFileNames: "assets/[name]-[hash][extname]",
      },
    },
  },
});
```

### Run the generator through `ferrite dev`

Once `app/`, `web/package.json`, and `src/alloy/mod.rs` all exist, every
`ferrite dev` build runs five steps in order before compiling the crate:

1. `npm run prebuild` in `web/`, if defined.
2. The contract generator built into `ferrite`, which reads `app/` and writes
   `src/generated/` (`mod.rs`, `routes.rs`, `contract.rs`),
   `web/src/generated/` (`types.ts`, `routes.ts`, `client.ts`, `hooks.ts`), and
   `contract/` (`openapi.json`, `llms.txt`).
3. `npm run build` in `web/`.
4. `npm run postbuild` in `web/`, if defined.
5. The asset packer, which compresses `web/dist/assets/` into
   `src/site_assets.rs` as Rust string constants.

Invalid declarations (such as a loader with no `output` type or a redirect that
substitutes an uncaptured parameter) stop the build with the file path and
reason. Commit the `@generated` files and edit `app/` instead of changing
generated output by hand.

### Wire the generated code into the Rust half

Declare the generated modules in `src/lib.rs` and pass the packed asset archive
to `AlloyApp`:

```rust filename="src/lib.rs"
pub mod generated;
pub mod site_assets;

impl AlloyApp for App {
    const BUILD: &'static str = BUILD;
    const SHELL: &'static str = SHELL;
    const ASSETS_B64: &'static [&'static str] = site_assets::ARCHIVE_B64;
    const ASSETS_LEN: usize = site_assets::ARCHIVE_SIZE;
    // answer, seed and admit as before
}
```

With `ASSETS_B64` set, the runtime serves `GET /assets/*` from the packed
archive before `answer` runs, so the existing `/assets/` route handles static
files and `/` serves documents with no separate content route. Keep
`accept-encoding` and `if-none-match` in the `/assets/` route's
`forward_headers`. If you bind a `blob` handle named `site`, the runtime also
seeds assets into object storage at startup; without it, the runtime logs one
warning and serves assets from memory.

Complete the Rust-to-React seam with six changes:

- Build the route table from `generated::route_table()` so Rust resolves the
  exact routes and redirects declared under `app/`.
- Return generated contract types from every loader.
  `src/generated/contract.rs` defines a `Serialize`/`Deserialize` struct for
  each `#[derive(Contract)]` type. Because the compiler does not verify that a
  loader's JSON matches `app/`'s declared `output`, leaving the template's bare
  `Vec<Note>` causes `useIndex()` to type `data` as `NotesView` while
  `data.items` is `undefined` at runtime. Return
  `loader_value(&generated::contract::NotesView { items })?` instead.
- Handle `GET /__alloy/loader?path=<path>` in `dispatch` using
  `alloy::app::loader_reply_for::<App>`, which renders the payload together
  with the route's declared headers.
- Render documents with
  `alloy::app::document_for::<App>(req, &route, &params, data, &metadata, None)`
  (or copy `route.headers()` manually). The starter's `render` helper builds a
  fixed `cache-control: private, no-cache` reply, so declared route headers
  reach loader JSON responses while missing HTML documents until you switch;
  see [Per-route response headers](/developers/alloy-routing/#per-route-response-headers).
- Mount actions under their exact declared names. The generator forbids hyphens
  in action names, so `alloy::action!` declares `add_note` and the generated
  client posts to `/__alloy/action/add_note`, whereas the starter mounts
  `add-note` (a mismatch returns 400 `no action named 'add_note' is declared`).
  Set `ADD_NOTE` to `"add_note"` and update any form action URL or test that
  still references `add-note`.
- Decode action inputs as JSON and reply with JSON. The generated client sends
  a JSON body with an `idempotency-key` header (unlike the starter's
  `application/x-www-form-urlencoded` form) and expects
  `{ "result": ..., "advanced": [[tag, epoch]] }`. If you keep the starter's
  303 redirect, `fetch` follows `/` and fails when it tries to parse HTML as
  JSON. Decode with `alloy::actions::decode_input` (which returns 400 on
  malformed JSON) and reply through `commit_reply` and `replay_reply`:

```rust filename="src/lib.rs"
async fn add_note(ctx: &AppContext, req: &IngressRequest) -> Result<IngressReply, AlloyError> {
    let input: generated::contract::AddNote = alloy::actions::decode_input(req)?;
    let text = input.text.trim();
    // validate `text` as before
    let key = idempotency(req);
    let mut runner = ActionRunner::new(ctx.ape("tags")?);
    if let Some(record) = runner.recorded(ADD_NOTE, &key).await? {
        return Ok(alloy::actions::replay_reply(req, &record.result, &record.advanced));
    }
    let id = invocation_digest(ADD_NOTE, &key)[..12].to_string();
    // write the note as before, then:
    let row = generated::contract::NoteRow { id, text: text.to_string() };
    runner
        .commit_reply(req, ADD_NOTE, &key, &Effects::new().tag(NOTES_TAG), &row, ctx.now_ms())
        .await
}
```

Update `SHELL` to include a React mount point (`<div id="root"></div>`),
`<script type="module" src="/assets/entry.js"></script>` before `</body>`, and
`<link rel="stylesheet" href="/assets/entry.css">` in `<head>` if your entry
imports CSS. At startup, the runtime rewrites those stable URLs to the
content-hashed names recorded by the asset packer.

### Seed the first paint

The server document already embeds the loader payload inside `__alloy_data`, so
first paint needs no network request. Seed the TanStack Query cache under
`["alloy", "loader", path]` before rendering:

```tsx filename="web/src/main.tsx"
import { QueryClient } from "@tanstack/react-query";
import type { AlloyPayload } from "./generated/types";

const queryClient = new QueryClient({
  defaultOptions: {
    queries: { networkMode: "always" },
    mutations: { networkMode: "always" },
  },
});
const embedded = document.getElementById("__alloy_data")?.textContent;
if (embedded) {
  const payload = JSON.parse(embedded) as AlloyPayload<unknown>;
  queryClient.setQueryData(["alloy", "loader", window.location.pathname], payload);
}
```

Set `networkMode: "always"` on both `queries` and `mutations` so a browser that
misreports offline status does not pause queries and generated action hooks
indefinitely. From there, components call the generated hooks typed from
`app/`; renaming a field under `app/` fails both TypeScript and Rust builds
wherever the old field name remains.

### Deploy a contract app

`ferrite deploy` submits `src/` and omits `app/`, `web/`, and `contract/`, so
deployments run the generated Rust and packed assets produced by your last
`ferrite dev` build. Run `ferrite dev` after changing `app/` or `web/` so
`src/generated/` and `src/site_assets.rs` are up to date before you deploy.

Next: [Routing](/developers/alloy-routing/),
[Data & Caching](/developers/alloy-data/), and
[Actions & Effects](/developers/alloy-actions/).
