# Build TanStack Start apps on Ferrite

Compile an unmodified TanStack Start build into a single constrained Ferrite application with prerendered pages, an SPA shell, nitro route rules, and bounded QuickJS server functions.

You can run a [TanStack Start](https://tanstack.com/start/latest) application inside a single constrained Ferrite app. Keep your Start routes, pages, and server functions untouched; `tools/ferrite-start` post-processes the unmodified `vite build` output into Rust modules that compile into your app, and the `nitro` source package serves them. Pages prerender at build time or render in the browser, so React never runs on the server per request. Server functions execute inside a bounded QuickJS sandbox with no network or environment access.

The `ferrite-start` tooling lives in Ferrite's repository and is not shipped with the CLI. Following this guide requires a repository checkout because the scaffolder runs from `tools/ferrite-start` with Node, `npm run emit` invokes that tool, and the generated `Cargo.toml` loads `ferrite-app` and `ferrite-app-test` by relative path from `tools/ferrite-cli/crates/`. If you have only the released `ferrite` CLI, build with [Rsx](/developers/rsx/) or [Alloy](/developers/alloy/) instead; Alloy can also generate a typed contract for a React front end.

## Before you start

Adapt an existing Start application before moving it onto this route if it relies on any of the following:

- Request-time React SSR for HTML responses.
- Server-function `.middleware(...)` chains.
- Outbound HTTP requests, storage calls, or environment reads inside server functions (move I/O into Rust handlers).
- `FormData` or `application/x-www-form-urlencoded` request bodies sent to server functions.
- Streaming or promise-bearing return values from server functions.
- A Node runtime process in production.

## Tutorial: scaffold to green tests

Run these commands from the root of a Ferrite repository checkout:

```bash
node tools/ferrite-start/src/cli.mjs new my-app        # writes apps/my-app
cd apps/my-app
ferrite add nitro --registry https://packages.ferrite.cloud/registry.json   # vendor the runtime package
cd web
npm install
npm run build      # vite build: client + ssr + prerender + SPA shell
npm run emit       # ferrite-start: emit ../src/start_*.rs
cd ..
cargo test         # compiles the app; a fresh scaffold has no tests yet
```

`ferrite-start new` copies the starter template into `apps/<app-name>`:

- A `web/` Start project with the `tanstackStart()` and `nitro()` Vite plugins, prerendering, and the SPA shell enabled.
- A Rust crate containing the serving and server-function wiring, plus placeholder `start_*.rs` files so the crate compiles before your first Vite build.
- A `ferrite.json` deployment manifest.
- A package manifest that mounts `nitro`.

`ferrite add nitro` vendors `nitro` and its `sha256-hmac` dependency under `src/`, where the scaffold's `src/lib.rs` already declares both modules.

Server functions are opt-in so static and API-only apps carry no JavaScript runtime. To enable them, pass `--server-fns` when scaffolding and vendor the QuickJS engine as well:

```bash
node tools/ferrite-start/src/cli.mjs new my-app --server-fns
cd apps/my-app
ferrite add nitro --registry https://packages.ferrite.cloud/registry.json
ferrite add qjs-engine --registry https://packages.ferrite.cloud/registry.json
```

`ferrite add qjs-engine` vendors `qjs-engine` under `src/qjs/` together with `serde-codec` (`src/codec/`) and `wasm-runtime` (`src/wasm/`), all three already declared in the `--server-fns` scaffold's `src/lib.rs`. On an engine-less scaffold, `npm run emit` refuses any build that contains a server function.

Pass `--dir <path>` to override `apps/<app-name>`; `new` refuses an existing directory to avoid overwriting work. Keep the target two directories below the checkout root (like `apps/<name>`) or update the relative paths in the generated `Cargo.toml` and `web/package.json`.

A fresh scaffold ships with no application tests, so `cargo test` compiles the crate and reports 0 passed (with four doc examples from vendored packages ignored). Add your own integration tests against `ferrite-app-test`, which is already listed under `[dev-dependencies]`.

After the first build, one Rust process serves prerendered pages with strong ETags and `304` responses, fingerprinted assets marked `immutable`, an SPA shell for unclaimed HTML navigations, and your API routes and server functions on the `api` routes. The scaffolded `ferrite.json` requests 128 MiB of memory and half a CPU, and needs two edits before it deploys; see [Before you deploy: the scaffolded spec](#before-you-deploy-the-scaffolded-spec).

## How-to: add an API route

API routes pair a row in `manifest.server_routes` with a named handler in the registry. Edit `src/serve.rs`: import `ferrite_app::serde_json`, make `manifest` mutable, and register both inside `build_app`:

```rust filename="src/serve.rs"
use ferrite_app::serde_json;

// in build_app():
let mut manifest = BuildManifest::from_json(crate::start_manifest::MANIFEST_JSON)?;
manifest.server_routes.push(crate::nitro::artifacts::ServerRouteEntry {
    pattern: "/api/hello/:name".to_string(),
    methods: vec!["GET".to_string()],
    handler: "hello".to_string(),
});

// after `let mut registry = Registry::new();`:
registry.handler("hello", |_ctx, ev| {
    Box::pin(async move {
        let name = ev.params.get("name").cloned().unwrap_or_default();
        crate::nitro::event::send_json(
            &mut ev.res,
            200,
            &serde_json::json!({ "hello": name }),
        );
        Ok(())
    })
});
```

Qualify the macro as `serde_json::json!` (or import it explicitly) because Ferrite's code gate refuses unresolved macro paths.

Route patterns use rou3 semantics: static segments, `:param`, `*`, `**`, and `**:name`. Hand-declared API routes and generated routes share one table and one dispatch pipeline.

## How-to: add a server function

Scaffold with `node tools/ferrite-start/src/cli.mjs new my-app --server-fns` and vendor both `nitro` and `qjs-engine` (`ferrite add qjs-engine --registry https://packages.ferrite.cloud/registry.json`). Without the QuickJS mount, `npm run emit` refuses any build containing a server function (`… has no src/qjs engine mount`) and writes nothing.

Write the function in your Start routes using either `.validator(...)` or `.inputValidator(...)`, matching your Start version:

```tsx filename="web/src/routes/fortune.tsx"
import { createServerFn } from '@tanstack/react-start'

export const getFortune = createServerFn({ method: 'POST' })
  .validator((input: { seed: number }) => input)
  .handler(async ({ data }) => ({ fortune: pick(data.seed) }))
```

`npm run build && npm run emit` extracts the compiled provider modules from the SSR bundle, packages them with `seroval` and a driver via esbuild, and writes `src/start_server_fns.rs`. At request time, `/_serverFn/:id` executes that bundle inside QuickJS and Rust maps the verdict onto HTTP. Because both the browser and the embedded driver serialize with the same `seroval` package, wire compatibility is enforced at build time.

The v1 sandbox enforces strict input, output, and authority bounds:

| Surface | Contract |
|---|---|
| Payloads and limits | Accepts seroval-JSON payloads, synchronous serializable results, `notFound()` (`404`), and `redirect()` (serialized-redirect JSON). POST bodies follow the 256 KiB platform limit (`413`; see [Limits](/developers/limits/)). GET `?payload=` rides in the request head, which the gateway caps at 16 KiB (`431`), so send larger payloads by POST. Output caps at 512 KiB and wall time at 10 seconds per call. |
| Status codes | Returns `400` when the input validator throws, `404` for an unknown server-function id, `405` with an `Allow` header on a method mismatch, and `500` when the handler throws. |
| Build-time refusals | Rejects `.middleware(...)` chains and any provider importing symbols from the SSR bundle beyond `createServerFn` and `TSS_SERVER_FUNCTION`. Each refusal names the offending file. |
| Request-time refusals | Returns `501` for multipart `FormData` and `application/x-www-form-urlencoded` bodies, and `500` naming the limitation for streaming or promise-bearing results. |
| Capabilities | Deny-all by default. Calling `fetch` or reading `env` fails with `capability_denied`. Scoped capabilities are granted per app through the engine's dispatch-closure seam, never as a default. |

## How-to: add route rules

Put nitro-style rules in `web/ferrite-start.config.json`:

```json filename="web/ferrite-start.config.json"
{
  "appName": "my-app",
  "routeRules": {
    "/api/**":  { "cors": true },
    "/blog/**": { "isr": 300 },
    "/feed/**": { "swr": 60 },
    "/old/**":  { "redirect": { "to": "/", "status": 307 } }
  }
}
```

The supported rule keys are `cors`, `headers`, `redirect`, `proxy`, `cache`, `swr` (shorthand for `cache: { swr: true, max_age: n }`), and `isr`. Setting a rule to `false` resets an inherited rule, matching upstream merge semantics. On Ferrite Cloud, `api` routes answer `OPTIONS` with `405` at the gateway and strip `access-control-allow-origin` from application replies, so `cors` rules apply only in local tests; serve browser pages and API routes from the same app origin instead (see [Headers & Cookies](/developers/headers-cookies/)).

With `isr: 300`, the runtime stores the full rendered response with a 300-second soft expiry. Within the window, stored responses serve without invoking the handler. Past expiry, stale content serves while one designated request refreshes inline; stored renders stay available and retain their ETag and `304` handling. Setting `isr: true` holds a render until it is overwritten; when both `isr` and `cache` appear on the same route, `isr` subsumes `cache`. Both `redirect` and `proxy` also accept a bare target string (a string redirect answers `307`).

`ferrite-start` rejects unsupported options at build time by name: unknown rule keys; unknown `redirect`, `proxy`, or `cors` options; `cache` options `stream` and `maxResolveTime` (replies are buffered); redirect statuses outside `300..399`; proxy targets that are neither `/`-prefixed internal paths nor absolute `http(s)` URLs; `cors.credentials: true` without an explicit origin list or combined with `*`; and rule patterns other than `/path` or `<METHOD> /path`.

## How-to: regenerate after changes

After editing routes, pages, server functions, or route rules in `web/`, regenerate the Rust modules and re-run tests:

```bash
cd web && npm run build && npm run emit && cd .. && cargo test
```

Never edit `src/start_site.rs`, `src/start_manifest.rs`, or `src/start_server_fns.rs` by hand; the next `npm run emit` replaces all three.

## Before you deploy: the scaffolded spec

`ferrite-start new` writes `ferrite.json` once and hands ownership to your application; `npm run emit` creates one only when no manifest exists. The scaffold declares request, reply, stream-request, and frame queues, cache and data stores, the site blob, `api` routes for `/assets/` and `/`, and a `stream` route for `/stream/`.

Two declarations in the scaffolded manifest prevent a direct deploy to Ferrite Cloud:

1. The `/stream/` route includes `stream_mode` and `forward_headers`. Ferrite restricts forwarded caller headers to `api` and `grpc` routes and rejects both keys on stream routes. `ferrite deploy` strips `forward_headers` from stream routes automatically, and stops on `stream_mode` unless you pass `--drop-stream-mode`. Delete both keys from the stream route before deploying.
2. Both `api` routes include `"rate_limit_per_min": 1200` (as does a manifest generated by `emit` when none exists). Gateway enforcement of `rate_limit_per_min` is not established on Ferrite Cloud, so `ferrite deploy` and `ferrite cost` hold any manifest carrying that key and explain why. Keep the key if you declared it, and never submit through raw `deploy_source` to bypass the hold. See [Rate limits](/developers/rate-limits/) for details on the hold and how to bound routes inside the application with the `http-route-budget` package. A manifest that omits the key is not held; the reference app at `apps/fe-start-demo/ferrite.json` omits both `stream_mode` and `rate_limit_per_min`.

On an unheld manifest, run `ferrite cost` to check projected charges before deploying.

## Explanation: the architecture

Nitro, the server toolkit beneath TanStack Start, already separates a build phase that compiles configuration into static data (a rou3 route table, an h3 rule table, and an asset manifest) from a runtime phase that evaluates that data. Ferrite keeps the JavaScript build phase on your machine and ports the runtime to constrained Rust with zero `unsafe` code as the `nitro` source package:

1. `vite build` runs TanStack Start unmodified to produce client assets, the SSR bundle, prerendered pages, and the SPA shell.
2. `ferrite-start` emits three Rust files: packed client assets (`start_site.rs`), the `BuildManifest` JSON with route rules, asset ETags, and the SPA shell (`start_manifest.rs`), and the QuickJS server-function bundle (`start_server_fns.rs`).
3. The Rust runtime serves everything inside your app's authority boundary: rou3-semantics routing, the h3 rule chain (`cors → headers → redirect → proxy → cache`), SWR caching over Store, ISR stored renders, blob-seeded assets, and bounded server functions.

No request-time React SSR runs on the server. Pages use prerendered HTML, the SPA shell, or selective `ssr: false`, and dynamic per-request HTML is assembled in Rust. Server functions are the only server-side JavaScript, executed in a fueled, output-capped, deny-all QuickJS sandbox.

A `kind: "stream"` route on Ferrite is GET-only server-sent events: every response is `200 text/event-stream` and no request headers reach your app. The `nitro` pipeline answers a stream request with one buffered terminal frame. For a live multi-frame feed, run your own loop over the stream queue, as `fe-start-ticker` does in `src/live.rs`.

## Reference: generated files

| File | Contents |
|---|---|
| `src/start_site.rs` | Packed client assets: `pub fn files() -> Vec<(&'static str, &'static str)>`, URL path → base64 payload |
| `src/start_manifest.rs` | `pub const MANIFEST_JSON: &str`, the schema v1 `BuildManifest`: assets with SHA-256 ETags, MIME types, and cache buckets; route rules; SPA shell; runtime config |
| `src/start_server_fns.rs` | QuickJS server-function bundle and its `(id, name)` table; an empty placeholder when the build carries none |
| `ferrite.json` | Deploy spec (queues, stores, site blob, and `api` routes for the asset base and `/`), written only when the app has none; once scaffolded, your app owns it |

## Reference: ferrite-start.config.json

| Key | Meaning |
|---|---|
| `appName` | Lowercase slug naming the services in a `ferrite.json` generated by `emit` when the app has none |
| `baseUrl` | Application base URL (default `/`) |
| `assetBase` | Client public base path for fingerprinted assets (default `/_build/`) |
| `routeRules` | h3-style `{ "/pattern": { cors \| headers \| redirect \| proxy \| cache \| swr \| isr } }`; camelCase keys are accepted and normalized to snake_case |
| `runtimeConfig` | Embedded runtime config values (`{{VAR}}` expansion at run time) |
| `spaShell` | SPA shell path override (auto-detected when omitted) |
| `serverFnResolveDir` | Directory where esbuild and seroval resolve from (default: the `web/` app root) |

## Reference: the sample apps

Six sample applications under `apps/fe-start-*` in Ferrite's repository exercise one runtime surface each (they live in the repository and are not distributed separately):

| App | Surface |
|---|---|
| `fe-start-launch` | SSG marketing site, zero server code |
| `fe-start-guestbook` | Server-function CRUD |
| `fe-start-ticker` | Streaming ticker: live multi-frame feed from an app-owned loop on the stream route |
| `fe-start-journal` | ISR content |
| `fe-start-metrics` | SPA dashboard with API routes and SWR |
| `fe-start-lockbox` | Cookie-session auth in Rust middleware |

`apps/fe-start-demo` is the reference app. Its end-to-end suite (`tests/e2e.rs`, run with `cargo test`) drives the application in process on the local runtime using the same request envelopes the gateway sends. It verifies immutable fingerprinted assets, parameterized API routes, CORS preflight, `404` responses for unknown API paths, server-function seroval round trips and the `FormData` refusal, ISR storage with `304` conditional requests and post-expiry refresh, and the one-terminal-frame stream response. It is a local test suite, separate from a live Ferrite Cloud deployment.

For agent-oriented build instructions, see [TanStack Start on Ferrite for agents](/developers/tanstack-start-agents/). See also [Routing](/developers/routing/), [Packages](/developers/packages/), and [Deployments](/developers/deployments/).
