# Build web apps with GizApp

This guide shows how to build a server-rendered web app with GizApp. In about 20 minutes
you walk through a model, its pages, an Action, sign-in and grants, and the tests of one app.

- The guide is for developers who know Next.js, Remix or React.
- The first part builds one app step by step. Each later section does one task. The last part compares the model
  with Next.js.
- Each example ran on the current toolchain. Each response is the real response, from `curl`
  or from a browser. Long output is trimmed (`…`).
- A section with a status badge describes GizApp (`gizapp`). Every other section runs on
  the SDK modules of the released toolchain.
- To install the toolchain, refer to the [installation guide](../quickstart.md). For the
  `giz` command, refer to the [command line guide](command-line.md).

## What GizApp is

GizApp is the `gizapp` library shipped with the toolchain, so a project needs no other
installation. Import the web library as `gizapp`, the data library as `gizdb:NAME` and standard modules as `gizlang:NAME`:

| Module | Use it for |
| --- | --- |
| `gizlang/http` | The HTTP server (`serve`), `Request`, `Response`, headers, streamed replies; routes (`router`, `Route`, `resolve`, `href`), redirects, cookies, static files, URL encoding, gzip |
| `gizlang/html` | The `Html` type that markup compiles to, `each`, `when`, `Shadow` (declarative shadow DOM) |
| `gizapp` | GizApp: pages and the app shell, routes with a context (`Web.route`, `Web.path`, `Web.typed`, `Web.before`, `Web.limited`, `Web.serve`), static pages (`Web.prerender`), forms, actions, live views, content and data views |
| `gizmodel/model` | The record model: annotations, `Shape`, input checks, `Rejection`, DDL and JSON ([Model your data](model.md)) |
| `gizmodel/data` | The app's database: `Data.open` gives a `Db` with every verb; `Engine` ([Data access](data-access.md)) |
| `gizmodel/query` | Typed reads: `Query.from<R>()` gives a `Query<R>` ([Data access](data-access.md#query-what-to-read)) |
| `gizlang/sql/sqlite` | An embedded SQLite database |
| `gizlang/security` | Signed session tokens |
| `gizlang/tls` | HTTPS with your certificate |
| `gizlang/test` | vitest's `test` and `expect` for `X.test.giz` files (also as `vitest`) |

Pages and screens are `.ghtml` files ([GHTML](../reference/ghtml.md)). Markup in a `.giz` expression has the same
syntax as TSX; its descriptive name is GSX. Both compile to the writes of `gizlang/html`.

- A lowercase tag writes HTML.
- A capitalized tag calls a typed component function.
- `{value}` writes escaped text. Strings, integers, floats and `Html` values can be children.
- A markup expression has the type `Html`. Its bytes are in `.markup`.

## Tutorial: build a small web app

:::status{of="gizapp"}
:::

You walk through Atlas, the reference app in [examples/apps/atlas](https://github.com/gizai/gizlang/tree/main/examples/apps/atlas):
a revenue workspace of deals with a live overview, an editable grid, a page for each deal, a Markdown page, an admin
screen, sign-in, per-deal grants, one Action of its own and an agent's tools. One schema gives the table, the forms
and their checks, the admin screens and the tools. The same pages on `gizlang/http` alone, without a model, are
`examples/app/http`.

### Before you start

- Install the toolchain. `giz` must be on your `PATH`.
- Run the commands in `examples/apps/atlas`. The app listens on port 8080 of 127.0.0.1; `PORT=8081` takes another.

### Step 1: write the model

A model is a record type and its schema, in `model.ts`:

```typescript file="examples/apps/atlas/model.ts"
import { schema, key, text, flag, number } from "gizapp";

/** One deal of the revenue workspace. */
export type Deal = {
  id: string;
  account: string;
  contact: string;
  region: string;
  owner: string;
  stage: string;
  amount: number;
  margin: number;
  close_on: string;
  priority: number;
  won: boolean;
};

// The shape is the table, the forms, the admin screens and the tools' input: one declaration, no copies.
export const Deal = schema<Deal>("deals", {
  id: key("ID"),
  account: text({ label: "Account", min: 1, max: 80, trim: true, search: true }),
  contact: text({ label: "Contact", max: 80, search: true }),
  region: text({ label: "Region", max: 24 }),
  owner: text({ label: "Owner", max: 40 }),
  stage: text({ label: "Stage", max: 24 }),
  amount: number({ min: 0, max: 1000000, label: "Amount" }),
  margin: number({ min: 0, max: 100, label: "Margin %" }),
  close_on: text({ label: "Close on", max: 10 }),
  priority: number({ min: 1, max: 5, label: "Priority" }),
  won: flag("Won"),
});
```

- `schema<Deal>("deals", …)` makes `Deal` a table, with `id` as its key.
- The columns give the label, the limits and the trim of each field. They make the server checks, the error that a
  form shows next to its field and the JSON Schema of the tools. The checks run on the server for every caller: a
  browser, an API client and an agent.
- `search: true` gives a field a full-text index, so a page finds a deal as people type.

### Step 2: write the pages

Each `.ghtml` or `.md` file below `pages/` is an address ([GHTML](../reference/ghtml.md)):

- `pages/_layout.ghtml` wraps every page: the rail, whose links mark the page you are on with
  `aria-current={request.path === "/" ? "page" : "false"}`, and a Sign in link while `me` is `"public"`.
- `pages/index.ghtml` is the overview at `/`. `table(Deal, "priority desc")` reads the table, and the page follows
  it: when anyone adds, changes or removes a deal, every open page gets the rows that changed over its one WebSocket.
  `deals.count(…)` and `deals.where(…)` run in the database. `<form create={deals}>` adds a deal from the fields the
  form names, and `{deals.editableGrid()}` is the grid with its ten views.
- `pages/about.md` is Markdown in the same layout, at `/about`.
- `pages/404.ghtml` answers an address that has no page.

`pages/deals/[id].ghtml` is the page of one deal, at `/deals/ID`. Its controls write each change to the deal, and its
form calls the app's own Action:

```html file="examples/apps/atlas/pages/deals/[id].ghtml"
<script>
import {Field, controlId, describedBy} from "gizapp";
import {Deal} from "../../model.ts";
import {share} from "../../share.giz";

const deals = table(Deal, "id");
const id = params.get("id");
</script>

<title>Deal — Atlas</title>
<article each={d of deals.where(d => d.id === id)} key={d.id} class="card deal">
  <p class="eyebrow">{d.region} · {d.owner}</p>
  <h1>{d.account}</h1>
  <Field name="stage" label="Stage" hint="">
    <input id={controlId("stage")} value={d.stage} aria-describedby={describedBy("stage", false)}/>
  </Field>
  <Field name="amount" label="Amount" hint="">
    <input id={controlId("amount")} type="number" value={d.amount} aria-describedby={describedBy("amount", false)}/>
  </Field>
  <form action={share()} class="share">
    <input type="hidden" name="deal" value={`${d.id}`}/>
    <input type="hidden" name="role" value="viewer"/>
    <Field name="email" label="Share with" hint="A person of this app; they see this deal and no other.">
      <input id={controlId("email")} name="email" type="email" aria-describedby={describedBy("email", true)}/>
    </Field>
    <button class="ui-button">Share</button>
  </form>
  <div class="end"><button class="ui-button danger" onclick={deals.remove(d)}>Remove</button></div>
</article>
<p if={deals.count(d => d.id === id) === 0} class="ui-empty">No such deal. <a href="/">Back to the overview</a></p>

<style>
  .deal { display: grid; gap: 14px; max-width: 40rem; padding: 24px; }
  .deal h1 { margin: 0; font-size: 26px; letter-spacing: -.02em; }
  .eyebrow { margin: 0; color: var(--color-muted); font-size: 12px; font-weight: 600; text-transform: uppercase; }
  .share { display: flex; align-items: flex-end; gap: 8px; }
  .end { display: flex; justify-content: flex-end; }
</style>
```

- `params.get("id")` reads the part of the address that `[id]` names.
- `value={d.stage}` writes the field to its row when it changes, and `onclick={deals.remove(d)}` removes the row.
- `<form action={share()}>` calls the Action `share()` with the form's controls as its input. The compiler checks each
  control's name and kind against the input record, so a control that the Action does not take is an error of the
  page. Without script it is a plain form post; with script the page changes in place.

### Step 3: write an Action

An Action is the one way to make a change that is more than a table write. Its input is a record, it runs as the
person of the request, and a page's form, an agent's tool and the JSON API reach the same Action:

```gizlang file="examples/apps/atlas/share.giz"
import * as Model from "gizmodel/model";
import * as Gate from "gizmodel/gate";
import * as Policy from "gizmodel/policy";
import * as Security from "gizlang/security";
import {Auth, Data, Pages} from "gizapp";
import {Deal} from "./model.ts";

/** Who gets a deal, and as what: a "viewer" reads it, an "editor" also changes it. */
export type Share = { deal: string; email: string; role: string; };

/** The share action: a manager of a deal (its owner) grants one person of the app a role on that deal. That person then
 * sees and changes only the deals shared with them, on every page, tool and admin screen: the Gate judges each read and
 * write by the grants. */
export function share(): Model.Action<Pages.Context, Share, Share> {
    return Model.action<Pages.Context, Share, Share>(
    "share_deal", "Share one deal with a person of this app as a viewer or an editor.", (
        context: Pages.Context, input: Share
    ): Share throws Model.Rejection => {
        const s = context.scoped;
        if (s === undefined) { throw Model.unauthenticated(); }
        const row = s.row(Deal, [{ kind: "text", v: input.deal }]);
        const deal = Gate.record(s.scope!, Deal, row);
        const held = Gate.access(s.source, s.scope!, Deal, deal).role;
        if (Security.rank(held) < Security.rank(Security.Role.manager())) {
            throw Model.forbidden("Only a manager of this deal may share it.");
        }
        // The people and the grant are written and read without the actor's Gate, as they were before.
        const trusted: Data.Db = s.trusted();
        const person = Auth.personByEmail(trusted.inSchema("auth"), input.email);
        if (person === undefined) { throw Model.invalid("email", "No person of this app has that address."); }
        const role = input.role === "editor" ? Security.Role.editor() : Security.Role.viewer();
        const to: Security.Principal = { kind: "person", id: person.id };
        let grant: Policy.Write;
        try { grant = Policy.grant(to, deal, role, 0, s.scope!.now, s.scope!.actor); } catch (e) { throw e.rejection(); }
        trusted.write([grant], "");
        return input;
    }
    );
}
```

- `Gate.access` gives the person's role on this deal; only a manager (the owner) may share it.
- `Policy.grant` gives one person a role on one deal. The Gate then judges each read and write by the grants, so that
  person sees and changes this deal and no other, on every page, tool and admin screen.

### Step 4: serve the app

`main.giz` makes the app. The CLI generates `./pages/.routes` from the pages folder:

```gizlang file="examples/apps/atlas/main.giz"
import * as Path from "gizlang/path";
import * as Local from "gizdb/app";
import {Pages} from "gizapp";
import {site} from "./pages/.routes";
import {Deal} from "./model.ts";
import {share} from "./share.giz";

/** Atlas over the data in FOLDER. With an owner's PASSWORD (12 or more characters) and a SECRET for the sessions (32 or
 * more), people sign in at /auth/sign-in: the owner (owner@example.com) sees every deal, another person only the deals
 * shared with them. */
export function atlas(folder: string, password: string, secret: string): Pages.Application throws string {
    const app = Local.app(site, [Deal], folder).admin("/admin").actions(() => [share().any]);
    if (password === "") { return app; }
    const owner = app.account("owner@example.com", "Owner", password);
    const origin = sys.environment("APP_ORIGIN") ?? "http://127.0.0.1:8080";
    return app.signIn(Pages.People("Atlas", origin, true, utf8(secret), owner, (served: Pages.Served): Pages.Mailing => {
        return { send: (to: string, link: string): bool => { return false; } };
    }));
}
export function main(): i64 {
    // The data stays beside this app, whichever folder `giz` runs it from.
    const source = sys.source();
    const folder = source === "" ? "data" : `${Path.dirname(source)}/data`;
    const password = sys.environment("APP_PASSWORD") ?? "";
    const app = atlas(folder, password, sys.environment("APP_SESSION_SECRET") ?? "")!;
    // The grid's Chart view draws with giz-chart when app/components/dist is built beside this checkout.
    return app.components(["chart"])!.listen(8080);
}
```

- `.admin("/admin")` adds the list, detail and create screens of every table, and `.actions(() => [share().any])` lists the
  Action beside the five tools of each table.
- With a password, `signIn` signs people in at `/auth/sign-in` (gizapp Auth, its tables in the schema `auth`).
  Without one, every request acts as the one owner: right for an app on your own machine.
- `listen` serves with the design system, compression, ETags and security headers.

```sh
giz run main.giz
APP_PASSWORD='choose-a-local-password' APP_SESSION_SECRET='a-stable-secret-of-at-least-32-characters' giz run main.giz
```

The same app in TypeScript, without its own Action, runs on giz, Node, Bun and Deno:

```typescript file="examples/apps/atlas/app.ts"
// With APP_PASSWORD (12+ characters) and APP_SESSION_SECRET (32+ characters) set, the owner signs in at /auth/sign-in
// as owner@example.com. The share action is the Gizlang entry's (main.giz).
import { app } from "gizapp";
import type { Owner } from "gizapp";
import { Deal } from "./model.ts";

const password = process.env.APP_PASSWORD ?? "";
const owner: Owner | undefined = password === "" ? undefined : {
  email: "owner@example.com", name: "Owner", password, secret: process.env.APP_SESSION_SECRET ?? "", title: "Atlas",
  origin: process.env.APP_ORIGIN ?? "http://127.0.0.1:8080",
};
app({ tables: [Deal], admin: "/admin", owner, chart: true }).listen(8080);
```

Open <http://127.0.0.1:8080/> in two tabs. Change a deal in one: the other shows it at once. Stop the server and
start it again: the deals are still there, in the folder `data`. An agent finds the tables and the Action as tools,
with the rules that the schema gave:

```sh
curl http://127.0.0.1:8080/_tools
```

### Step 5: test the app

`main.test.giz` tests a rule of the model alone, then runs the app's handler against a database in a temporary
directory, with no server:

```gizlang file="examples/apps/atlas/main.test.giz"
import * as Model from "gizmodel/model";
import * as Http from "gizlang/http";
import {expect, test} from "gizlang/test";
import {Auth} from "gizapp";
import {Deal as DealModel} from "./model.ts";
import {atlas} from "./main.giz";

test("a deal needs an account", () => {
    try {
        Model.read(DealModel, Model.formFields("id=a&account=+&contact=&region=EMEA&owner=x&stage=Discovery&amount=1&margin=2&close_on=2026-12-01&priority=1&won=0")!);
        expect(false).toBe(true);
    } catch (r) {
        expect(r.status).toBe(422);
        expect(r.message).toContain("Account");
    }
});

function call(method: string, path: string, cookie: string, body: string): Http.Request {
    let headers = [Http.Header("content-type", "application/json")];
    if (cookie !== "") { headers.push(Http.Header("cookie", cookie)); }
    return { method, path, headers, body: utf8(body) };
}
function get(path: string, cookie: string = ""): Http.Request { return call("GET", path, cookie, ""); }
const NORTHWIND = "{\"account\":\"Northwind Labs\",\"contact\":\"Ada Lin\",\"region\":\"EMEA\",\"owner\":\"Maya Chen\",\"stage\":\"Proposal\",\"amount\":120000,\"margin\":32,\"close_on\":\"2026-12-12\",\"priority\":5,\"won\":false}";
/** The id that an add_deals answer gives. */
function idOf(answer: Http.Response): string {
    const text = string(answer.body);
    const at = text.indexOf("\"id\":\"") + 6;
    return text.slice(at, text.indexOf("\"", at));
}

test("the revenue workspace serves and manages deals", () => {
    const dir = sys.temporaryDir()!;
    const handle = Http.whole(atlas(`${dir.temporaryPath()!}/data`, "", "")!.hosted().answer);
    const added = handle(call("POST", "/_a/add_deals", "", NORTHWIND));
    expect(added.status).toBe(200);
    const home = string(handle(get("/")).body);
    for (const part of ["Northwind Labs", "Open pipeline", "Pipeline by stage", "<giz-chart", "class=\"ui-stats", "giz-grid", "id=\"deals\"", "type=\"search\""]) {
        expect(home).toContain(part);
    }
    // The overview's nav marks the page it is on; the record of one deal is its own address.
    expect(home).toContain("href=\"/\" aria-current=\"page\"");
    expect(string(handle(get(`/deals/${idOf(added)}`)).body)).toContain("Northwind Labs</h1>");
    expect(string(handle(get("/deals/none")).body)).toContain("No such deal.");
    const about = string(handle(get("/about")).body);
    expect(about).toContain("<code>pages/about.md</code>");
    expect(about).toContain("href=\"/about\" aria-current=\"page\"");
    expect(string(handle(get("/admin/deals")).body)).toContain("Northwind Labs");
    // An agent's tool is refused by the same rules as a form.
    const refused = handle(call("POST", "/_a/add_deals", "", NORTHWIND.replace("Northwind Labs", " ")));
    expect(refused.status).toBe(422);
    expect(string(refused.body)).toContain("Account");
    const missing = handle(get("/nope"));
    expect(missing.status).toBe(404);
    expect(string(missing.body)).toContain("This page left the pipeline");
    dir.dispose();
});

/** The quoted value after the last WHAT before AT in PAGE (a button's event id, the page's revision). */
function valueOf(page: string, at: string, what: string): string {
    const end = page.indexOf(at);
    const before = page.slice(0, end + at.byteLength + 200);
    const from = at.startsWith("name=") ? end + at.byteLength : before.slice(0, end).lastIndexOf(what);
    const start = page.indexOf(what, from) + what.byteLength;
    return page.slice(start, page.indexOf("\"", start));
}
/** The session cookie of a password sign-in. */
function signIn(handle: (request: Http.Request) => Http.Response, email: string, password: string): string {
    const form = [Http.Header("content-type", "application/x-www-form-urlencoded")];
    const body = utf8(`email=${Http.encode(email)}&password=${Http.encode(password)}`);
    const cookie = Http.header(handle({ method: "POST", path: "/auth/sign-in", headers: form, body }).headers, "set-cookie")!;
    return cookie.byteSlice(0, cookie.byteIndexOf(";"));
}

test("a person sees only the deals shared with them", () => {
    const dir = sys.temporaryDir()!;
    const app = atlas(`${dir.temporaryPath()!}/data`, "owner password", "a session secret of 32 characters")!;
    Auth.signUp(app.db.inSchema("auth")!, "lee@example.com", "Lee", "lee's password", sys.time())!;
    const handle = Http.whole(app.hosted().answer);
    const owner = signIn(handle, "owner@example.com", "owner password");
    const lee = signIn(handle, "lee@example.com", "lee's password");
    const shared = idOf(handle(call("POST", "/_a/add_deals", owner, NORTHWIND)));
    handle(call("POST", "/_a/add_deals", owner, NORTHWIND.replace("Northwind Labs", "Contoso")));
    expect(string(handle(get("/", lee)).body).includes("Northwind Labs")).toBe(false);
    // Only a manager of the deal shares it: Lee may not share it with Lee.
    const share = `{"deal":"${shared}","email":"lee@example.com","role":"viewer"}`;
    expect(handle(call("POST", "/_a/share_deal", lee, share)).status).toBe(404);
    // The deal's page shares it with its form, a plain post without script: the same action as the tool.
    const page = string(handle(get(`/deals/${shared}`, owner)).body);
    const event = valueOf(page, "Share</button>", "value=\"");
    const form = event.split(":")[0];
    const fields = `_a=${event}&${form}.deal=${shared}&${form}.role=viewer&${form}.email=lee%40example.com`;
    const posted = handle({ method: "POST", path: `/deals/${shared}`, headers: [
        Http.Header("content-type", "application/x-www-form-urlencoded"), Http.Header("cookie", owner)
    ], body: utf8(`${fields}&_revision=${valueOf(page, "name=\"_revision\"", "value=\"")}`) });
    expect(posted.status).toBe(200);
    const seen = string(handle(get("/", lee)).body);
    expect(seen).toContain("Northwind Labs");
    expect(seen.includes("Contoso")).toBe(false);
    expect(string(handle(get(`/deals/${shared}`, lee)).body)).toContain("Northwind Labs</h1>");
    dir.dispose();
});
```

```sh
giz test main.test.giz
```

```text
✓ main.test.giz  3 passed
```

You now have a live app with a model, pages, an Action, an admin, agent tools, sign-in, grants and tests. The next
sections each do one task. [Access application data](data-access.md) shows the queries and verbs
below the model.

## How-to guides

### Organize pages with file-system routing

GizApp organizes applications into a `pages/` directory where the file structure directly defines the application routes ([GHTML reference](../reference/ghtml.md#7-pages-a-folder-of-files-is-a-site)):

| Pattern | Route address | Description |
| --- | --- | --- |
| `pages/index.ghtml` | `/` | The root page of the directory |
| `pages/blog/[slug].ghtml` | `/blog/{slug}` | Dynamic single parameter; read via `params.get("slug")` |
| `pages/docs/[...path].ghtml` | `/docs/{path...}` | Catch-all segment; `docs/[...path].ghtml` matches `/docs/a/b/c` |
| `pages/(admin)/settings.ghtml` | `/settings` | Route group; scopes `_layout.ghtml` without adding to the URL |
| `pages/_layout.ghtml` | (none) | Nested layout wrapping descendant pages at `<slot/>` |
| `pages/_middleware.giz` | (none) | Route middleware; exports `before(props): Option<Http.Response>` |
| `pages/api/[id].giz` | `/api/{id}` | Endpoint handling any method: `export function handle(props)` |
| `pages/404.ghtml` | (none) | Custom not-found error page (status 404) |
| `pages/about.md` | `/about` | Markdown document rendered inside layouts |
| `components/Card.ghtml` | (none) | Capitalized component; auto-imported without explicit `import` |

Every page automatically accesses ambient bindings in its script and markup:
- `me`: The authenticated identity (`Option<Security.Identity>`), or `"public"`.
- `params`: Dynamic route parameters (`Http.Params`).
- `request`: The incoming `Http.Request`.
- `form`: Form-posted parameters (`Http.Params`).
- `locale` and `languages`: Current language and site language list.
- `error`: Form validation refusal message, displayed in `<output role="alert">{error}</output>`.

In `.ghtml`, `table(Todo, "id desc")` and `url("all")` are declarative compiler statements that register reactive tables and URL query synchronization. In standalone `.giz` files, access the table through `props.context.table<Todo>("id desc")`.

### Declare routes and read parameters

A route is `Http.Route(METHOD, PATTERN, TARGET)`. `TARGET` is any value. Usually it is a union
of endpoints.

| Pattern part | Meaning |
| --- | --- |
| `/users` | A literal segment |
| `/users/{id}` | `{id}` captures one segment |
| `/files/*path` | `*path` captures the rest of the path, with its slashes |

- A literal segment has priority over a capture. A capture has priority over a rest capture.
  The order of the declarations has no effect.
- Two equal routes are refused when you call `Http.router`.
- Each captured value is decoded one time. A bad escape such as `%ZZ` gets `400`.
- `found.params.get(name)` gives the text. `found.params.integer(name)` gives an `Option<i64>`.
- `route.href(Http.Params(names, values))` makes a URL from a declaration. It escapes
  each segment. A missing parameter is an error.
- `Http.query(request)` decodes the query one time to `Params`. `get(name)` gives the first value,
  or `""`. A malformed query is an error with status 400 ([Serve HTTPS](#serve-https) has an example).

The how-to examples are in a folder `howto`, next to the app. Run them from the same folder as
the tutorial.

`howto/routes.giz`:

```typescript gizlang
import * as Http from "gizlang/http";

type Endpoint = | { kind: "readme"; } | { kind: "file"; } | { kind: "user"; };
function fileRoute(): Http.Route<Endpoint> { return Http.Route("GET", "/files/*path", Endpoint.file()); }
function main(): i64 {
    const routes = Http.router([
        Http.Route("GET", "/files/readme", Endpoint.readme()),   // a literal segment wins over a capture
        fileRoute(),                                             // *path captures the rest of the path
        Http.Route("GET", "/users/{id}", Endpoint.user()),       // {id} captures one segment
    ])!;
    console.log(fileRoute().href(Http.Params(["path"], ["docs/a b.txt"]))!);
    const listener = sys.listen("127.0.0.1", 61102)!;
    Http.serve(listener, (request: Http.Request): Http.Response => {
        try {
            const found = routes.resolve(request);
            match (found.target) {
                Endpoint.readme() => { return Http.text(200, "the readme"); }
                Endpoint.file() => { return Http.text(200, "file " + found.params.get("path")); }
                Endpoint.user() => { return Http.text(200, "user " + found.params.get("id")); }
            }
        } catch (response) {
            return response;   // 404, 405 with Allow, or 400 for a bad escape
        }
    })!;
    return 0;
}
```

```sh
giz howto/routes.giz
```

It prints the URL that `href` made, and then serves requests:

```text
/files/docs/a%20b.txt
```

```sh
curl http://127.0.0.1:61102/files/readme
curl http://127.0.0.1:61102/files/docs/a%20b.txt
curl http://127.0.0.1:61102/users/kim%2Fx
curl -i http://127.0.0.1:61102/users/%ZZ
curl -i -X DELETE http://127.0.0.1:61102/users/1
```

```text
the readme
file docs/a b.txt
user kim/x

HTTP/1.1 400 Bad Request
content-type: text/plain; charset=utf-8
date: Wed, 14 Oct 2026 02:01:14 GMT
content-length: 28

Invalid path escape or UTF-8

HTTP/1.1 405 Method Not Allowed
content-type: text/plain; charset=utf-8
allow: GET, HEAD
date: Wed, 14 Oct 2026 02:01:14 GMT
content-length: 18

method not allowed
```

`%2F` in `{id}` stays in the one segment: the value is `kim/x`.

Parameters are text. Convert them with `params.integer` or your own check. With GizApp, a route
target is a typed record, so `{id}` is an `i64` that the compiler checks.

### Name the parameters of a route in a record

A parameter named in a pattern is text that a handler reads by name, and a misspelled name is found when the route runs.
`Web.path<P>(method, pattern)` takes the parameters from a record `P` instead. The names in the pattern are
exactly the field names of `P`. The program stops at start-up, not at the first request, when they differ:

```typescript gizlang
import * as Http from "gizlang/http";
import * as Web from "gizapp";

type Site = { name: string; };
type Thread = { target: string; page: i64; };

/** The route of a page of a thread. */
export function threadRoute(): Http.Route<Web.Handle<Site>> {
    const thread = Web.path<Thread>("GET", "/t/{target}/{page}");
    console.log(Web.link(thread, { target: "abc", page: 3 })!);   // /t/abc/3
    return Web.typed(thread, (site: Site, request: Http.Request, p: Thread): Http.Response => {
        return Http.text(Http.STATUS_OK, p.target + " " + string(p.page));
    });
}
```

- A field type is checked and converted like a form field: `page` is a number, and `/t/abc/x` answers
  `400` with the field that is wrong.
- `Web.link(path, params)` makes the URL and escapes each segment. A misspelled field is a compile error
  (`E_FIELD`), and a link cannot name a parameter the route does not have.
- Use the same `path` value for the route and for its links.

### Make layouts and components

A component is a function. It takes a props record, and, if it has children, an `Html` value.
It returns `Html`.

```typescript gizlang
import {Html} from "gizlang/html";

type LayoutProps = { title: string; };
export function Layout(p: LayoutProps, children: Html): Html {
    return <html lang="en">
        <head><meta charset="utf-8"/><meta name="viewport" content="width=device-width,initial-scale=1"/><title>{p.title}</title></head>
        <body><header><a href="/">Notes</a></header><main>{children}</main></body>
    </html>;
}
```

- Call it as `<Layout title="Notes">…</Layout>`. A props value in braces is a typed expression:
  `<Counter start={3}/>`.
- A nested layout is a component that calls another component.
- Lists: `<li each={n of items}>{n.title}</li>`.
- Conditions: `<p if={condition}>…</p>`, then `else-if` and `else` on the next elements.
- A component has no state and no lifecycle. It runs on the server for each request.
- Text that you trust as HTML goes in with `raw(text)` from `gizlang/html`. Do not use it for
  user input.

### Use Web Components

Use a Web Component when a part of the page needs browser behavior. The `Shadow` component of
`gizlang/html` writes a declarative shadow root. The browser makes the shadow DOM from the HTML,
before scripts run. Keep the meaningful content in light DOM, and show it through a `<slot>`.

`howto/components.giz`:

```typescript gizlang
import * as Http from "gizlang/http";
import {Html, Shadow} from "gizlang/html";

type CounterProps = { start: i64; };
/** A Web Component rendered on the server: the shadow root is in the HTML. */
function Counter(p: CounterProps, children: Html): Html {
    return <note-counter>
        <Shadow delegatesFocus={false}><button type="button">+1</button> <output>{p.start}</output> <slot/></Shadow>
        {children}
    </note-counter>;
}
type Endpoint = | { kind: "home"; } | { kind: "asset"; };
function main(): i64 {
    const routes = Http.router([Http.Route("GET", "/", Endpoint.home()), Http.Route("GET", "/static/*path", Endpoint.asset())])!;
    const listener = sys.listen("127.0.0.1", 61104)!;
    Http.serve(listener, (request: Http.Request): Http.Response => {
        try {
            const found = routes.resolve(request);
            match (found.target) {
                Endpoint.home() => {
                    const view = <html lang="en"><head><meta charset="utf-8"/><title>Counter</title>
                        <script type="module" src="/static/counter.js"></script></head>
                        <body><Counter start={3}><span>clicks</span></Counter></body></html>;
                    return Http.Response(200, [Http.Header("content-type", "text/html; charset=utf-8")], b"<!doctype html>" + view.markup);
                }
                Endpoint.asset() => {
                    const dir = sys.directory("howto/public")!;
                    const response = Http.file(dir, request, found.params.get("path"), sys.time());
                    dir.dispose();
                    return response;
                }
            }
        } catch (refusal) {
            return refusal;
        }
    })!;
    return 0;
}
```

`howto/public/counter.js` is a plain JavaScript module in a static folder:

```js
// Upgrades the server-rendered <note-counter>. The shadow root already exists.
customElements.define("note-counter", class extends HTMLElement {
  connectedCallback() {
    const output = this.shadowRoot.querySelector("output");
    this.shadowRoot.querySelector("button").addEventListener("click", () => { output.value = String(Number(output.value) + 1); });
  }
});
```

Run `giz howto/components.giz`, and open <http://127.0.0.1:61104/>. The server sends:

```text
<!doctype html><html lang="en"><head><meta charset="utf-8"><title>Counter</title><script type="module" src="/static/counter.js"></script></head><body><note-counter><template shadowrootmode="open" shadowrootclonable><button type="button">+1</button> <output>3</output> <slot></slot></template><span>clicks</span></note-counter></body></html>
```

In a Chromium browser, the element had its shadow root from the HTML. After two clicks, the output showed
`5`, and the light DOM `<span>` still said `clicks`.

- The script does not make the DOM again. It only adds behavior to the DOM that the server sent.
- With GizApp, browser code can also be Gizlang: `client` compiles it to WebAssembly, and a live
  update replaces it in place.

### Handle forms and validate input

GizApp derives the whole pattern from one record type ([Step 2](#step-2-write-the-pages)):
the form, its parser and its validation. Without a model, the pattern is:

1. A native `<form method="post" action={…}>`, with its URL from a route declaration.
2. A `POST` route. Its handler reads the fields from `request.body`.
3. Validation on the server. On failure, `422` and the same form, with the typed values and an
   error message. On success, `303` to the result page.

`examples/app/http` is a complete app of this kind.

- `Http.decode(text, true)` decodes one form value (`+` is a space). It gives none for a bad
  escape.
- `gizlang/http` limits a request body to `Http.MOST_BODY` bytes (16 MiB).
- A body may come compressed (`Content-Encoding: gzip`, `deflate` or `zstd`). `Http.content(request)` undoes it
  and `Http.contentText(request)` gives its UTF-8 text; every GizApp reader of a form, JSON or file body
  (`Web.inputs`, `Web.fields`, the tools, views and sign-in) reads through them. An unknown coding is 415.
  A streamed body takes `Http.decoding(headers)`: `feed` each piece, then `finish`. A handler that stores the
  bytes as sent (S3, a relay) does not call them and keeps the header.
- `Forms.form(shape, fields)` writes the form of a Shape, and `Web.inputs(request, shape)` reads and
  checks it. A file field (`@File`) makes the form multipart ([Take files in a form](#take-files-in-a-form)).

For a form that changes data, also check that the request comes from your site. A browser sends
`Sec-Fetch-Site` and `Origin` headers. Read them with `Http.header(request.headers, name)`.
Cookies from `Http.setCookie` are `SameSite=Lax`, so other sites do not send them with a cross-site
`POST`.

### Take files in a form

Mark a text field with `@File(accept, maxBytes, multiple)`. Its form control is then a file input, and the form is
`multipart/form-data`. The field holds the file name (a JSON list of names with `multiple`), so a Shape checks that a
file was chosen like any other value.

```typescript gizlang
import {Option} from "gizlang/core";
import {Submit, File} from "gizmodel/model";

@Submit("Send")
export type Attach = {
    note: string;
    @File("image/*,.pdf", 5000000, false)
    picture: string;
    @File("", 0, true)
    more: Option<string>;
};
```

- `Web.validatedInputs(request, shape)` reads the body once and returns `values` and `uploads`. It checks text
  values and each file against the Shape, including `accept` and `maxBytes`. A file in a field
  that takes none, or two files in a single-file field, is a `422` for that field.
- Each upload is `Upload { field, name, mediaType, size, bytes }`. Use `validatedInputs` when a handler needs both
  values and files. `Web.inputs` returns only values; `Web.uploads` checks and returns only files. Each call parses
  the body, so calling both separately repeats the parse.
- The kernel sends a form with a file input as `FormData`. A file dropped or pasted on the form fills its input. A form
  posted without script works the same.
- The body is read whole (`Http.MOST_BODY`). A larger upload is streamed through a mount's `upload` (or the listener's chooser); store the bytes
  with Storage.

### Keep styles and scripts in files

Write CSS and JavaScript as files and import them as text. `Assets.minifyStyle` and `Assets.minifyScript` make the
served form.

`site.css`:

```css title="site.css"
body { margin: 0; font-family: system-ui, sans-serif; }
```

`style.giz`:

```typescript gizlang
import {text as siteStyle} from "./site.css";
import {Assets} from "gizapp";

export function style(): string { return Assets.minifyStyle(siteStyle); }
```

For an app with many files, `Assets.build(sources, roots, minify, maps)` reads the whole graph:

- a script imports another by its logical name (`import {a} from "app/a.js"`); `import()` makes a lazy module;
- a style sheet may `@import` another (inlined) or `layer()` it; its classes are global (a `.ghtml` file scopes its
  own `<style>`);
- `var(--x)` with no fallback and no declaration, an import cycle, an import of a file that is no source, and a source
  that no root reaches are problems, not silent output;
- `graph.audit(forbidden)` reads every served file for texts that must not leave the server (a secret, `/home/`).

`Web.sources(shell, graph, entries)` links the sheets, the import map, `modulepreload` and the entry scripts into every
page.

### See an edit at once

Under `giz live` on this machine, the host tells an open page at once when a new generation serves. It updates the
page in place, as a link does (the stylesheets sync, the form values stay); a changed kernel reloads it. If the new
generation cannot start, or an edit does not compile, its reason or the compiler's error covers the page until an
edit fixes it, while the generation before keeps serving. The terminal that runs `live` shows the same error.

`Web.doctor(shell, graph, forbidden)` lists what is wrong with the setup (an empty language or name, a graph problem, a
served file over `Web.HEAVY_BYTES`), `Web.doctorReport(found)` prints it, and `Web.weights(graph)` sizes each file.
Run them in a test so a regression fails the suite.

### Answer slow or broken calls

A handler call that runs longer than `Serving.limitMs` is cancelled and answers `504`; a fault answers `500`. A
browser gets a page and a program gets the JSON error that every refusal uses.

### Update a page before the server answers

Put attributes on a form (`data-a`):

- `data-optimistic="KEY=FIELD KEY@ATTRIBUTE=FIELD"` shows the form's `FIELD` in the element keyed `KEY` (as its text, or
  as `ATTRIBUTE`) at once. If the action fails, the old value comes back; the server's patches replace it when it
  succeeds.
- A network failure never retries a mutation implicitly: its response may have been lost after the server committed.
- A `data-cancel` control in a busy form stops its request.
- `data-state` on the form is `busy`, `ok`, `error` or `cancelled`, for CSS.
- A rejected field gets `aria-invalid`, its message is in an `aria-live` slot that the control names with
  `aria-describedby`, and the first bad control takes the focus.

### Use the form and interaction components

The parts, tokens and themes of every screen are in [Design screens](design.md).

GizApp includes accessible components in `gizapp` that render standard HTML controls with proper ARIA attributes:

```html
<script>
import {Field, Check, Chip, Dialog, controlId, describedBy} from "gizapp";

let openDialog: bool = false;
</script>

<!-- Integrated field with label, hint, and error reporting -->
<Field name="title" label="Note title" hint="Keep it brief">
  <input id={controlId("title")} name="title" placeholder="Meeting notes" autocomplete="off" aria-describedby={describedBy("title", false)}/>
</Field>

<!-- Accessible checkbox bound to a table row field -->
<Check label={t.text}><input type="checkbox" checked={t.done}/></Check>

<!-- Status chips (tone: "ok", "warn", "bad", "neutral") -->
<Chip if={t.done} label="Done" tone="ok"/>

<!-- Native HTML dialog with backdrop and accessibility controls -->
<Dialog open={openDialog} title="Confirm delete" onclose={() => { openDialog = false; }}>
  <p>Are you sure you want to delete this note?</p>
  <button class="ui-button pri" onclick={doDelete}>Confirm</button>
</Dialog>
```

`DateField`, `Combobox`, `Menu` and `Chart` use the native elements (`input`, `datalist`,
`dialog`, `popover`, `svg` with a table for assistive technology), so they work without script, and the browser
supplies the keyboard, the language and right-to-left layout. `Combobox` adds the `giz-combobox` element
(`Web.comboboxScript()`, register it with `Web.enhancement`): the arrow keys move, Enter chooses, Escape closes, and an
IME composition is left alone. `Web.uiStyle()` covers dark mode, `prefers-contrast`, `forced-colors`,
`prefers-reduced-motion`, right-to-left and print.

### Add search to a page

A search box, its results and the marks on them use one engine: the typeahead `match` of GizDB. It finds a prefix of
the last word, words with a typo, Hangul by its initial jamo consonants (`U+314E U+3147 U+3139` matches `U+D68C U+C758 U+B85D`) and words typed in the other keyboard
layout. The marks come from the same engine, so a result never marks words that the search did not find.

1. Mark the fields to search with `search: true`. Each gets a full-text index:

   ```ts
   export type Note = { id: string; title: string; body: string };
   export const Note = schema<Note>("notes", { id: key(), title: text({ search: true }), body: text({ search: true }) });
   ```

2. Keep the query in the address and select with `matches` in the page:

   ```html
   <script>
   import {Marked} from "gizapp";
   const notes = table<Note>("id desc");
   let q = "" @url;
   const sought = q.trim();
   const found = sought === "" ? notes.rows() : notes.where(n => n.title.matches(sought) || n.body.matches(sought));
   </script>

   <input type="search" value={q} aria-label="Search notes" autocomplete="off"/>
   <ul id="notes">
     <li each={n of found} key={n.id} data-filter-item>
       <a href={"/notes/" + n.id}><Marked text={n.title} query={sought}/></a>
       <small if={sought !== ""}><Marked text={n.body} query={sought} most={120}/></small>
     </li>
   </ul>
   <p if={sought !== "" && found.length === 0}>No note holds “{sought}”.</p>
   ```

   - `value={q}` binds the field to the state. Each change asks the server, and the page shows the new rows.
   - `/notes?q=plan` opens with the search done. Typing replaces the history entry, so Back leaves the search.
   - The results are best first, unless the `where` has an `order`. The person sees only rows that the grants allow.
   - `Marked` marks the whole `text`. With `most`, it shows at most that many characters around the first match.
   - Add `data-filter="notes"` to the field so that Enter opens the first result.

3. For a ⌘K search, give `Palette` a binding (`value`, and `name` and `form` when the state is not the page's own). Put
   the results in its children:

   ```html
   <Palette id="cmd" links={commands} value={ask} placeholder="Search or type a command">
     <li each={n of asked} key={n.id} data-filter-item>
       <a role="menuitem" href={"/notes/" + n.id}><Marked text={n.title} query={ask}/><small>Note</small></a>
     </li>
   </Palette>
   ```

   Here `asked` is `notes.where(n => n.title.matches(ask)).slice(0, 6)`. Without a binding, the palette narrows its
   `links` in the browser. With one, the server lists what the search found.

In SQL, the same search is `match(column, query, 'typeahead')`, and `highlight` marks what it found
([Search text and vectors](data.md#search-text-and-vectors)).

### Give an agent the contract

`Web.contractRoute(shell, handlers, routes)` serves `/_contract`: the version, the routes, the actions (the same
list as the agent tools at `/_tools`), the subscription path and the served files. It is made from the declarations,
so it cannot disagree with them.

A site of pages (`gizapp/pages`) answers `/_contract` from its router: each page and each endpoint with the methods
that the endpoint exports. A page event (`onclick`, a bound field) is not in the contract. It is a form action of a
rendered page and needs that page's revision. Give an agent an endpoint or an action for each operation it must do.

### Serve HTML without hydration

Each page in this guide is complete HTML from the server. The pages in the tutorial have no
`<script>` element. There is no client component tree, no serialized props and no hydration
step.

- A link is a normal `<a href>`. A form is a normal `<form>`. The tutorial pages contain no
  script, thus they work the same with JavaScript disabled.
- Add browser behavior only where it is necessary, as a Web Component
  ([Use Web Components](#use-web-components)).
- Static content is static bytes. A component does not go to the browser.

### Stream a response

A handler can return `Http.progressive(render, release)` in place of a `Response`. The server sends the
head and each piece when you write it. Use it to send the start of a page before slow work ends.

`howto/server.giz` (this file is also used for static files and sessions below):

```typescript gizlang
import {Option} from "gizlang/core";
import * as Http from "gizlang/http";
import * as Task from "gizlang/task";
import * as Security from "gizlang/security";

type Endpoint = | { kind: "asset"; } | { kind: "login"; } | { kind: "me"; } | { kind: "clock"; };
type Site = { routes: Http.Router<Endpoint>; secret: bytes; };

function handle(site: Site, request: Http.Request): Http.ReplyPlan {
    try {
        return serve(site, request, site.routes.resolve(request));
    } catch (response) {
        return response.plan();
    }
}
function serve(site: Site, request: Http.Request, found: Http.Routed<Endpoint>): Http.ReplyPlan {
    match (found.target) {
        // Static files: ETag, Last-Modified, ranges and HEAD come from Http.file.
        Endpoint.asset() => {
            const dir = sys.directory("howto/public")!;
            const response = Http.file(dir, request, found.params.get("path"), sys.time());
            dir.dispose();
            return Http.withHeader(response, "cache-control", "public, max-age=3600").plan();
        }
        // Sessions: a signed token in an HttpOnly cookie.
        Endpoint.login() => {
            const token = Security.token(site.secret, "kim", sys.time());
            return Http.withHeader(Http.redirect(Http.STATUS_SEE_OTHER, "/me"), "set-cookie", Http.setCookie("session", token, Option.none<i64>(), false)!).plan();
        }
        Endpoint.me() => {
            match (Security.verified(site.secret, Http.cookie(request, "session") ?? "", sys.time())) {
                Option.some(signed) => { return Http.text(200, "Signed in as " + signed.who).plan(); }
                Option.none() => { return Http.text(401, "Sign in first").plan(); }
            }
        }
        // Streaming: the head and each piece go to the client when they are written.
        Endpoint.clock() => {
            return Http.progressive((exchange: mut Http.Exchange): bool throws Http.HttpError => {
                try exchange.respond(200, [Http.Header("content-type", "text/html; charset=utf-8")], Http.UNKNOWN_LENGTH);
                try exchange.write(<p>Loading…</p>.markup);
                for (const n of range(1, 4)) {
                    Task.sleep(500);
                    try exchange.write(<p>Tick {n}</p>.markup);
                }
                return exchange.finish();
            });
        }
    }
}
function main(): i64 {
    const routes = Http.router([Http.Route("GET", "/static/*path", Endpoint.asset()), Http.Route("POST", "/login", Endpoint.login()),
        Http.Route("GET", "/me", Endpoint.me()), Http.Route("GET", "/clock", Endpoint.clock())])!;
    const site: Site = { routes: routes, secret: sys.randomBytes(32)! };
    const listener = sys.listen("127.0.0.1", 61103)!;
    Http.serve(listener, (request: Http.Request): Http.ReplyPlan => { return handle(site, request); })!;
    return 0;
}
```

Run `giz howto/server.giz`. `Http.serve` accepts a handler that returns `Response` or `ReplyPlan`. A
buffered response becomes a plan with `.plan()`.

```sh
curl -N --trace-time --trace-ascii - -o /dev/null http://127.0.0.1:61103/clock
```

```text
0000: HTTP/1.1 200 OK
0000: content-type: text/html; charset=utf-8
0000: date: Wed, 14 Oct 2026 02:01:14 GMT
0000: transfer-encoding: chunked
20:43:38.793436 <= Recv data, 17 bytes (0x11)
0000: <p>Loading...</p>
20:43:39.294065 <= Recv data, 13 bytes (0xd)
0000: <p>Tick 1</p>
20:43:39.794659 <= Recv data, 13 bytes (0xd)
0000: <p>Tick 2</p>
20:43:40.295156 <= Recv data, 13 bytes (0xd)
0000: <p>Tick 3</p>
```

The pieces arrive 500 ms apart. (`curl --trace-ascii` shows the non-ASCII `…` as `...`.)

- Make all decisions that change the status or the headers before `respond`. After `respond`,
  the status is sent.
- Call `exchange.finish()` to end the response.
- With GizApp, `stream` places pieces into the page out of order, by key, through the
  page kernel.

### Live updates

:::status{of="gizapp"}
:::

A GizApp page follows the rows that it shows. When a row commits, the server sends keyed DOM
patches for the changed elements only, and the page keeps typed text and focus.

A Pages app does this for each table read of a page: it follows the rows before it reads them, and the page kernel
takes the patches of the changed rows at `/_s`.

See [Data access live changes](data-access.md#live-changes)
for native GizDB watches versus Relay-backed external SQL stores and their limitations.
With `gizlang/http` alone, use a streamed response ([Stream a response](#stream-a-response)) for a page
that changes while it is open.

### Serve static files

`Http.file(dir, request, path, nowMs)` serves a file below a directory, as nginx serves `root`.
In `howto/server.giz` above, the route `GET /static/*path` serves the folder `howto/public`. For
this example, `howto/public/site.css` contains `body { font-family: system-ui; }`.

```sh
curl -i http://127.0.0.1:61103/static/site.css
curl -i -H 'If-None-Match: "6accc7c7-21"' http://127.0.0.1:61103/static/site.css
curl -i http://127.0.0.1:61103/static/%2e%2e/routes.giz
```

```text
HTTP/1.1 200 OK
content-type: text/css; charset=utf-8
last-modified: Mon, 12 Oct 2026 11:43:03 GMT
etag: "6accc7c7-21"
accept-ranges: bytes
cache-control: public, max-age=3600
date: Wed, 14 Oct 2026 02:01:14 GMT
content-length: 33

body { font-family: system-ui; }

HTTP/1.1 304 Not Modified
content-type: text/css; charset=utf-8
last-modified: Mon, 12 Oct 2026 11:43:03 GMT
etag: "6accc7c7-21"
accept-ranges: bytes
cache-control: public, max-age=3600
date: Wed, 14 Oct 2026 02:01:14 GMT

HTTP/1.1 400 Bad Request
content-type: text/plain; charset=utf-8
date: Wed, 14 Oct 2026 02:01:14 GMT
content-length: 22

Forbidden path segment
```

- `Http.file` sets the media type, `ETag` and `Last-Modified`. It answers conditional requests,
  `HEAD` and one byte range.
- A path cannot leave the directory or follow a link.
- `Http.withHeader` adds a header, for example `cache-control`.
- `Http.asset` gives a file a content-hashed name, so it can be cached for a year.

### Pictures and fonts

A picture or a font is a file of the program: `import {bytes as heroBytes} from "./hero.jpg";`.
`Web.Assets.picture` makes its variants once, at start: a WebP for each width you list that is
no wider than the picture (a PNG when it is transparent). `Web.Assets.font` takes a WOFF2 face.
`Web.media` serves them under their content's names, for a year.
Every page then preloads the fonts and links their faces, with `font-display: swap`.

```giz
const hero = Web.Assets.picture(heroBytes, [480, 960, 1600])!;
const inter = Web.Assets.font("Inter", "100 900", "normal", interBytes)!;
const shell = Web.media(Web.shell("en", handlers, style), [hero], [inter]);
// In a page (`import {Picture} from "gizapp"`): the browser takes the file that `sizes` and the screen need.
<Picture picture={hero} alt="The dashboard" sizes="(min-width: 60rem) 50vw, 100vw" eager={true}/>
```

The `<img>` has the picture's width and height, so the page does not move as it loads.
It loads when it nears the view; `eager` loads the first picture a person sees at once.

### Build static pages

`Web.prerender(answer, paths, dir)` asks `answer` for each path with a `GET`, as a browser does,
and writes the answers to `dir`. The same routes and the same HTML writer make the pages. Run it when you deploy:

```typescript gizlang
import * as Http from "gizlang/http";
import * as Web from "gizapp";

/** The function that your server passes to `Http.serve`. */
function handle(request: Http.Request): Http.Response { return Http.text(Http.STATUS_OK, "a page"); }

function main(): void {
    sys.files()!.makeDirectories("public")!;
    const written = Web.prerender(handle, ["/", "/about", "/blog/first", "/feed.xml"], sys.directory("public")!)!;
    console.log(`${written.length} files`);
}
```

- `/about` becomes `about/index.html` and `/` becomes `index.html`. A path with a file extension keeps its name.
- A path that does not answer `200` stops the build with the path and the status in the error. A page that is
  missing never goes to production by chance.
- The result is the list of the names written.
- Serve the folder with `Http.fileReply` ([Serve static files](#serve-static-files)). No route handler runs and
  no context is needed. The pages have the bytes of the live pages.
- Only static pages belong here. A page that depends on the person who asks (the session, the query) is
  served by its route.
- GizStack does this for the content pages of its own site: it writes `Content.staticPaths` after each deploy and
  answers those paths from the files with `public, no-cache`.

### Sessions and sign-in

For accounts, teams, API tokens and sign-in with a provider, use [Accounts and sign-in](auth.md). The `Auth`
module keeps sessions as rows, and it still reads the signed token below until that token is 30 days old.

`gizlang/http` reads and writes cookies. `gizlang/security` signs a session token with HMAC-SHA256.
In `howto/server.giz` above:

- `POST /login` makes a token for `kim` with `Security.token(secret, principal, issuedMs)`. It
  sets it with `Http.setCookie`. The cookie has `Path=/`, `HttpOnly` and
  `SameSite=Lax`, and `Secure` when you pass `secure`; `giz doc Http.setCookie` gives the rules.
- `GET /me` reads the cookie with `Http.cookie`, and checks it with `Security.verified`. A token
  is valid for 30 days (`Security.SESSION_LIFE`).

```sh
curl -i http://127.0.0.1:61103/me
curl -i -c jar.txt -X POST http://127.0.0.1:61103/login
curl -b jar.txt http://127.0.0.1:61103/me
curl -b 'session=kim.1.00' http://127.0.0.1:61103/me
```

```text
HTTP/1.1 401 Unauthorized
content-type: text/plain; charset=utf-8
date: Wed, 14 Oct 2026 02:01:14 GMT
content-length: 13

Sign in first

HTTP/1.1 303 See Other
location: /me
content-type: text/plain; charset=utf-8
set-cookie: session=kim.1791805408905.8eb182c76ef99f65fc43c57dc879fc23f6c509eca36cead8ed57ce9b2d33a1f1; Path=/; HttpOnly; SameSite=Lax
date: Wed, 14 Oct 2026 02:01:14 GMT
content-length: 3

/me

Signed in as kim

Sign in first
```

- The example makes a new random secret at each start. Thus a restart signs out all users. In a
  real app, keep the secret in your database or in a protected file.
- The example signs in without a password, to show the cookie flow only. Use
  `Crypto.argon2id` from `gizlang/crypto` if you store passwords (or the `gizapp` auth module, which
  does it for you), or deploy to GizStack and use its sign-in.
- Add the `Secure` attribute to the cookie when you serve HTTPS.

### Protect routes with one policy

:::status{of="gizapp"}
:::

A rule that holds for many routes is written once. `Web.before(routes, check)` runs `check` ahead of
the handler of each route in the table. `check` gets the context, the request and the parameters.
It answers in the handler's place, or gives `Option.none()` to let the route run:

```typescript gizlang
import {Option} from "gizlang/core";
import * as Http from "gizlang/http";
import * as Web from "gizapp";

type Site = { secret: bytes; };

function page(path: string, text: string): Http.Route<Web.Handle<Site>> {
    return Http.Route("GET", path, Web.Handle((site: Site, request: Http.Request, p: Http.Params): Http.Response => {
        return Http.text(Http.STATUS_OK, text);
    }));
}
function signedIn(site: Site, request: Http.Request, p: Http.Params): Option<Http.Response> {
    match (Web.principal(site.secret, request, sys.time())) {
        Option.some(name) => { return Option.none(); }
        Option.none() => { return Option.some(Http.redirect(Http.STATUS_SEE_OTHER, "/login")); }
    }
}
export function routes(): Http.Router<Web.Handle<Site>> {
    let all = [page("/", "home"), page("/login", "sign in")];
    for (const r of Web.before([page("/account", "account"), page("/settings", "settings")], signedIn)) { all.push(r); }
    return Http.router(all)!;
}
```

A GET handler that throws a `Model.Rejection` with status 401 sends a browser to `/login` through `Web.respond`.
A feature flag and a maintenance page are written the same way. For a rate limit see [Limit requests from one client](#limit-requests-from-one-client).

### Limit requests from one client

`Web.limited(routes, limit, windowMs, proxies)` answers `429 Too Many Requests` with `Retry-After` to a client
that makes more than `limit` requests within `windowMs` milliseconds. Other clients are not affected:

```typescript gizlang
import * as Http from "gizlang/http";
import * as Web from "gizapp";

type Site = { name: string; };

function page(path: string, text: string): Http.Route<Web.Handle<Site>> {
    return Http.Route("GET", path, Web.Handle((site: Site, request: Http.Request, p: Http.Params): Http.Response => {
        return Http.text(Http.STATUS_OK, text);
    }));
}
export function routes(): Vec<Http.Route<Web.Handle<Site>>> {
    return Web.limited([page("/", "home"), page("/search", "results")], 600, 60000, ["203.0.113.1"]);
}
```

To limit a whole server, make a limiter once with `Web.limiter(limit, windowMs, proxies)` and call
`limiter.admits(request)` at the start of the handler. It gives `Option.some(response)` for a client over its limit.
The counts live in memory. To keep them over a restart, save `limiter.counted(wallMs, atLeast)` (the clients with at least `atLeast` requests in the window) and give them back with `limiter.restore(counts, wallMs)` at start. giz saves them every 15 s for the clients with at least 60 requests, in the `request_counts` table.

- The client is the address of the socket. The server puts it in the request header
  `x-peer-address` (`Http.PEER_HEADER`) and removes a header with that name that the client sent.
- Behind a reverse proxy, every request comes from the proxy. List its address in `proxies`. For a connection
  from a listed proxy, the client is the last value of `X-Forwarded-For`: the proxy added it. The values before it
  are what the client wrote, and they can be forged. A client that is not a listed proxy cannot choose
  its address with this header.
- A refused request is not counted. A client that is quiet for one window is forgotten.
- The counts are in the memory of the process. A restart resets them.
- GizStack reads the proxy addresses of its own site from `STACK_PROXIES` (see `stack/README.md`).

### Test a web app

A handler is a function from `Request` to `Response`. Call it in a test. No server, port or
browser is necessary. There are two kinds of test:

- A test file `X.test.giz` has functions that start with `test`. It checks what needs no
  `System`: a Shape (the checks of a form), a route table, a component. The compiler certifies a
  pure test, and a test that passed is not run again while its inputs are unchanged.
- A program with `main()` checks what needs a database or a clock. It makes a GizDB
  folder in a temporary directory, builds the handler of one thread (`app(engine)` in the
  tutorial) and calls it with requests. Step 4 of the tutorial shows both.

The router can be tested alone:

```typescript gizlang title="router.test.giz"
import {expect, test} from "gizlang/test";
import * as Http from "gizlang/http";

test("equal routes are refused", () => {
    expect(() => Http.router([Http.Route("GET", "/users/{id}", 1), Http.Route("GET", "/users/{name}", 2)]))
        .toThrow("Ambiguous route");
});
test("href escapes each segment", () => {
    const route = Http.Route("GET", "/users/{id}", 1);
    expect(route.href(Http.Params(["id"], ["a/b c"]))!).toBe("/users/a%2Fb%20c");
    expect(() => route.href(Http.Params([], []))).toThrow("id");
});
test("an invalid pattern is refused", () => {
    expect(() => Http.router([Http.Route("GET", "/users/{id", 1)])).toThrow("Captures must occupy a complete segment");
});
```

The first run gives `✓ router.test.giz  3 passed`. A second run gives:

```text
✓ router.test.giz  3 cached
```

A test that passed before is not run again (`cached`) while its meaning and the inputs its run observed are unchanged.
A failed assertion shows the test, the values and the line.

For browser journeys, use a browser automation tool against the running server.

### Deploy a web app

Build a native executable, and run it on a server:

```sh
giz build notes/app.ts -o notes-server
./notes-server
```

```text
listening on http://127.0.0.1:61100
```

- The executable runs on any x86-64 Linux server, with no system C library: no build is for the CPU
  of the build computer.
- The data folder (`data` in the tutorial) is relative to the working directory. Run the executable
  from the folder that holds the data, and back up that folder.
- To deploy to GizStack instead, refer to [Deploy to GizStack](https://gizstack.com/docs/platform/deploy).

#### Serve HTTPS

`gizlang/tls` serves the same handler over TLS with your certificate. `Tls.credentials` reads the
PEM chain and the PEM private key from their paths.

For a local test, make a self-signed certificate in `tls/`:

```sh
mkdir -p tls
openssl req -x509 -newkey rsa:2048 -nodes -keyout tls/key.pem -out tls/cert.pem -days 1 -subj "/CN=localhost"
```

`howto/https.giz`:

```typescript gizlang
import * as Http from "gizlang/http";
import * as Tls from "gizlang/tls";

// giz howto/https.giz /absolute/cert.pem /absolute/key.pem
function main(): i64 {
    const args = sys.arguments();
    const credentials = Tls.credentials(args[0], args[1])!;   // PEM chain (own certificate first), PEM key
    const listener = sys.listen("127.0.0.1", 61105)!;
    Tls.serve(listener, credentials, (request: Http.Request): Http.Response => {
        try {
            const q = Http.query(request);
            return Http.text(200, "Hello over TLS. q=" + q.get("q"));
        } catch (e) {
            return Http.text(e.status, e.message);   // 400: a malformed query
        }
    })!;
    return 0;
}
```

```sh
giz howto/https.giz "$PWD/tls/cert.pem" "$PWD/tls/key.pem"
curl -k -i 'https://127.0.0.1:61105/?q=two+words'
```

```text
HTTP/1.1 200 OK
content-type: text/plain; charset=utf-8
date: Wed, 14 Oct 2026 02:01:14 GMT
content-length: 27

Hello over TLS. q=two words
```

- The test used a self-signed certificate, thus `curl -k`. Use a certificate from a certificate
  authority on a public server.
- The server speaks HTTP/1.1, and HTTP/2 when the browser asks for it in the TLS handshake (ALPN). With
  `TLS_DOMAINS` set, `Web.listen` also serves HTTP/3 (QUIC, UDP on the same port number) to a browser that has seen the
  `alt-svc` header. A handler does not change. Several requests of a browser share one connection and do not wait for each other.
  `gizlang/acme` gets certificates from an ACME authority such as Let's Encrypt.
### Share requests among servers

`Http.proxy(pool, upstream, request)` forwards a request to one server. `Http.balancer(pool, upstreams, holdMs)`
shares requests among several. `balancer.send(request)` answers like `Http.proxy`:

```typescript gizlang
import * as Http from "gizlang/http";

function main(): void {
    const pool = Http.pool(Http.poolDefaults());
    const servers = [Http.Origin(false, "10.0.0.2", 8080), Http.Origin(false, "10.0.0.3", 8080)];
    const balancer = Http.balancer(pool, servers, 5000);
    const listener = sys.listen("127.0.0.1", 61106)!;
    Http.serve(listener, (request: Http.Request): Http.Response => { return balancer.send(request); })!;
}
```

- The servers get requests in turn.
- A server that cannot be reached is not asked again for `holdMs` milliseconds. A request that is safe to
  repeat (`GET`, `HEAD`, `OPTIONS`, `PUT`, `DELETE`) goes to the next server.
- A `POST` is never sent twice. The client gets `502`. `502` is also the answer when no server can be reached.
- An answer of the server with a status such as `500` is passed to the client as it is. It does not
  count as a server that cannot be reached.


### Publish content

:::status{of="gizapp"}
:::

GizApp has a CMS: Markdown collections checked by a model, menus from one `nav.md`, blocks such as
`:::cards` and `:::steps`, values bound from code, drafts and review, and `/llms.txt`,
`/llms-full.txt` and `sitemap.xml` for free. This site runs on it.

```typescript gizlang
import {Dir} from "gizlang/system";
import {Html} from "gizlang/html";
import * as Model from "gizmodel/model";
import * as Web from "gizapp";
import {Content} from "gizapp";

/** The pages under docs/ of ROOT, with the nav in nav.md: SHAPE types their frontmatter. */
export function docs(root: Dir, shape: Model.Shape, layout: (view: Content.View) => Html, labels: Web.Labels): Content.Loaded {
    const site = Content.Site("Docs", "https://example.com", "nav.md", "/play",
        [Content.Collection("docs", "/docs", shape, Content.Source.files("docs"))], [], [], layout, labels);
    return Content.load(root, site);
}
```

### Speak more than one language

A site of `.ghtml` pages is written in English. Each run of text a person reads is one message, together with its holes
and inline elements (`Hello <b>{name}</b>!`). A catalog `locales/TAG.json` beside the pages translates the messages:

```sh
giz i18n . --add ko      # create locales/ko.json with every message, untranslated
giz i18n .               # add new messages, remove the ones no page shows any more
giz i18n . --check       # in CI: fail when a catalog is incomplete or a translation does not fit
```

- A catalog maps each message, written in Unicode MessageFormat 2 (`Hello {#b}{$name}{/b}!`), to its translation. An
  untranslated message shows in English. The build fails on a translation whose holes or elements do not fit.
- `<template plural={count}>` with a `<template case="one">` for each case (and `case="=0"` for an exact count) is one
  message. Each translation uses its own language's plural cases: Korean has one, Arabic six.
- Each language has its own address: `/ko/pricing` is Korean, and `/pricing` English. Links in a page keep the
  language. The language picker's links add `?hl=ko`, and a cookie keeps the choice for a year. A browser that opens an
  English address while its languages say otherwise is sent to its own language's address (307); a crawler is not. Each
  page carries its `hreflang` alternates.
- An application behind a sign-in keeps one address for every language with `byCookie(site)` (`gizapp/pages`):
  the person's choice, then the browser's `Accept-Language`, picks the language.

## Explanation: how GizApp differs from Next.js

### Server HTML is the state

In Next.js, the server renders React components to HTML. Then the browser downloads the
component code and the serialized props, and hydrates the page: React builds its tree again
and attaches the event handlers.

In GizApp, a component is a function that writes escaped HTML bytes on the server. Nothing
goes to the browser except the HTML, and the scripts that you add yourself. There is no hydration
step, because there is no client tree to build. A page works before any script loads, and it
works with JavaScript disabled. Interaction is added at small boundaries, with native controls
and Web Components that use the DOM that the server sent.

The cost is that a page does not change in the browser without a new request, a stream or your
own script. GizApp keeps the authoritative state on the server, and the browser keeps only
local interaction state.

### Routes are data, and their targets are typed

A Next.js route is a file path. A Remix route is a module in a route config. A GizApp route
is a value: method, pattern and a typed target. The router compiles all declarations one time,
and refuses ambiguity. Thus:

- With `Http.Router<Endpoint>`, the compiler checks that `match (found.target)` handles each endpoint. With
  `Web.route`, the target is the handler, and `Web.serve` calls it with the context of the app.
- Links come from the same declaration (`route.href(params)`), so a changed pattern changes each link.
- One policy runs ahead of many routes (`Web.before`).
- 404, 405 with `Allow`, and `HEAD` come from the router, not from each handler.

### Actions are ordinary typed functions

A Next.js Server Action is a function that the framework calls through a generated endpoint. In
GizApp, the form posts to a declared route, and the handler is an ordinary function with
typed inputs and a typed `Response`. The form works without JavaScript. Validation stays on the
server, and the answer follows Post/Redirect/Get: `303` on success, `422` with the form on
failure.

GizApp goes one step further: an Action is derived from one record type, with its validation, its
form, its JSON answer and its agent tool description ([GizApp](https://gizstack.com/gizapp)).

### One process, native code

A GizApp app compiles to one native executable. The HTTP server, the router, the HTML
writer and the database driver are in the same program. There is no Node.js runtime and no
separate bundler.

## Where to go next

- [Design screens](design.md): the parts, tokens and themes that every screen is made of.
- [Command line guide](command-line.md): `check`, `test`, `build`, `live` and packages.
- [Start with Gizlang](../quickstart.md): the Playground and the markup example.
- [Packages](packages.md): split an app into modules with a pinned manifest.
- [GizApp](https://gizstack.com/gizapp): models, Actions, live views and the CMS.
- [Model your data](model.md): record declarations, validation, migrations and access policy.
- [Data access](data-access.md): the DAL, typed queries, external databases, transactions and live feeds.
- The official examples ([the examples index](https://github.com/gizai/gizlang/blob/main/examples/README.md)): `examples/apps/atlas` is the complete app of this guide.
- [Deploy to GizStack](https://gizstack.com/docs/platform/deploy): your app at its own address.
