# Form details

Every option, rule and error message behind the [Forms and login](/forms-and-login) guide. The shapes per library are in the [adapters reference](/api-reference/adapters#form-formprops).

## A schema without a package

An `input` is any [Standard Schema](https://standardschema.dev) object: Valibot, Zod and ArkType all are. `schema(jsonSchema, check)` below makes one from a check function:

````ts [forms/server/utils/schema.ts]
import type { StandardJSONSchemaV1, StandardSchemaV1 } from "hamur/server"

type Issue = { message: string; path?: PropertyKey[] }
type Check<T> = (value: unknown) => { value: T } | { issues: Issue[] }

export function schema<T>(
  jsonSchema: Record<string, unknown>,
  check: Check<T>,
): StandardSchemaV1<unknown, T> & StandardJSONSchemaV1<unknown, T> {
  return {
    "~standard": {
      version: 1,
      vendor: "docs",
      validate: check,
      jsonSchema: { input: () => jsonSchema, output: () => jsonSchema },
    },
  } as StandardSchemaV1<unknown, T> & StandardJSONSchemaV1<unknown, T>
}

export const idInput = schema<{ id: string }>(
  { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
  (value) => {
    const id = (value as { id?: unknown } | undefined)?.id
    return typeof id === "string" && id
      ? { value: { id } }
      : { issues: [{ message: "An id is required", path: ["id"] }] }
  },
)
````

## The `Form` component

- Every adapter exports `Form`.
- With a handler as `action` it renders `<form method="post" action="<this page>?_fn=<id>" data-hamur-form>`, so it works with and without JavaScript.
- With a path or a route location as `action`, or none, it renders a `GET` form that navigates with the fields as the query.
- A POST form to anything else is not a `Form`: write a plain `<form>`.

| Prop             | Default            |                                                                                                                                     |
| ---------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------- |
| `action`         | the page on screen | a handler, which must not be `method: "GET"`, or an app path or route location for a `GET` form                                     |
| `encType`        | urlencoded         | `"multipart/form-data"` for files                                                                                                   |
| `instance`       |                    | a key for the store of this form's runs: `useAction(fn, { instance })` is the same store, so one handler can sit in a list of forms |
| `replace`        | `false`            | replace the history entry (a `GET` form)                                                                                            |
| `reset`          | `false`            | reset the form after a success                                                                                                      |
| `reloadDocument` | `false`            | leave the form to the browser                                                                                                       |
| `refresh`        | `true`             | `false` leaves the page's data alone after a success                                                                                |
| `restore`        | `true`             | `false` keeps typed values out of a no-JavaScript failure page                                                                      |
| `onSubmit`       |                    | called before the request, with the `FormData`; `cancel()` stops it                                                                 |

The [`Form` reference](/api-reference/adapters#form-formprops) has the per-library shapes. A plain `<form>` in a page script or an html page gets the same behaviour from `enhance(form, options)` of `hamur/app`.

A form is left to the browser when it has `data-hamur-reload`, a `target` other than `_self`, `method="dialog"`, `enctype="text/plain"`, a `GET` with `multipart/form-data`, or another origin as its `action`.

## What a handler returns to a form

| Return                             | The page gets                                                                                                                                        |
| ---------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
| `redirect(to)`, returned or thrown | a navigation to `to`. Without JavaScript a `303`                                                                                                     |
| `fail(status, data)`               | `useAction(fn).failure` holds `{ status, data }`; the status must be 400 to 499 (else `RangeError`). A failure is not an error and refreshes nothing |
| any other value, or nothing        | the value in `useAction(fn).state`                                                                                                                   |
| a failed `input` check             | status 400 and `useAction(fn).error` with `data: { issues, values }`; `useForm(fn).fields` reads it                                                  |
| a thrown error                     | the error with the error's status, masked as every error ([Errors](/errors)); `useAction(fn).error` holds it                                         |

- `redirect` is the usual answer to a change the visitor must not repeat (post, redirect, get), so `redirect("/todos")` from a post on `/todos` is the normal pattern.
- A target on another origin needs `redirect(to, { external: true })`.

## Reading the result

- `useAction(fn)` returns `{ run, state, failure, pending, error, reset }`: the last value, the last `fail()`, whether a call is running (the refresh after it included), the last error, and `run(input)` to call the handler from code.
- A `Form action={fn}` and a `useAction(fn)` call share one store, so the form's result is readable anywhere in the app.
- `useForm(fn)` returns `{ fields, pending, result, for(key) }`.

This page shows a failure message, the pending state and the field helpers:

````ts [forms/server/todos.ts]
import { defineHandler, fail } from "hamur/server"
import { db } from "./utils/todos.ts"
import { idInput, schema } from "./utils/schema.ts"

const newTodo = schema<{ title: string }>(
  { type: "object", properties: { title: { type: "string", minLength: 1 } }, required: ["title"] },
  (value) => {
    const title = (value as { title?: unknown } | undefined)?.title
    return typeof title === "string" && title
      ? { value: { title } }
      : { issues: [{ message: "A todo needs a title", path: ["title"] }] }
  },
)

export const listTodos = defineHandler({
  method: "GET",
  handler: () => db.all(),
})

export const addTodo = defineHandler({
  input: newTodo,
  handler: ({ title }) => db.add(title),
})

export const removeTodo = defineHandler({
  input: idInput,
  handler({ id }) {
    if (!db.remove(Number(id))) return fail(404, { message: "That todo is already gone" })
    return { removed: Number(id) }
  },
})
````

````tsx [forms/app/pages/todos.tsx]
import { Form, useAction, useData, useForm } from "@hamur/adapter-react"
import { addTodo, removeTodo } from "#server"

export default function Todos() {
  const { todos } = useData<{ todos: Array<{ id: number; title: string }> }>()
  const form = useForm(addTodo)
  const removal = useAction(removeTodo)
  return (
    <main>
      <ul>
        {todos.map((todo) => (
          <li key={todo.id}>
            {todo.title}
            <Form action={removeTodo} instance={todo.id}>
              <input type="hidden" name="id" value={todo.id} />
              <button>Remove</button>
            </Form>
          </li>
        ))}
      </ul>
      <Form action={addTodo} reset>
        <input {...form.fields.title.as("text")} />
        {form.fields.title.issues().map((issue) => (
          <p role="alert" key={issue.message}>
            {issue.message}
          </p>
        ))}
        <button disabled={form.pending}>Add</button>
      </Form>
      {form.pending ? <p>Saving…</p> : null}
      {removal.failure ? <p role="alert">{(removal.failure.data as { message: string }).message}</p> : null}
    </main>
  )
}
````

- The `load` that gives the page its list is in `todos.load.ts`; after a success the page's `load` files and live `useAsyncData` entries are fetched again, so the list shows the new todo.

````ts [forms/app/pages/todos.load.ts]
import type { Load } from "hamur/app"
import { listTodos } from "#server"

export const load = (async () => ({ todos: await listTodos() })) satisfies Load
````

## Validation

- With `input`, the body is decoded, validated with the schema's `~standard.validate`, and the handler is called only when it passes.
- A form body goes through `formToObject`; a JSON body (a call from code) is used as it is. On issues the call fails with status 400 and this `data`:

```ts
{
  issues: Array<{ path: Array<string | number>; message: string }>,
  values: Record<string, unknown>,
}
```

- `values` is the decoded body, minus every field whose name (after its `n:` or `b:` prefix) starts with `_`, every top-level JSON key that starts with `_`, and every `File`.
- A password sent as `_password` therefore never comes back.
- A validator that throws gives one issue with an empty path: the message of a `TypeError` or `RangeError`, else `Validation failed` outside dev; a thrown `HamurError` is not turned into an issue, it is the handler's error.
- An `input` that is not a Standard Schema throws `TypeError` when the handler is defined.

## The form codec

A form body is flat; `formToObject` makes it an object in one pass:

| Input                                      | Output                                                                           |
| ------------------------------------------ | -------------------------------------------------------------------------------- |
| `a.b=1`                                    | `{ a: { b: "1" } }`                                                              |
| `a[0]=x&a[1]=y`, `a[0].b=1`                | `{ a: ["x", "y"] }`, `{ a: [{ b: "1" }] }`                                       |
| `tag=a&tag=b`                              | `{ tag: ["a", "b"] }` (one occurrence stays a string)                            |
| `n:qty=2`                                  | `{ qty: 2 }` (a value that is not a number gives `NaN` for the schema to refuse) |
| `b:agree=on`, `b:agree=true`, `b:agree=no` | `{ agree: true }`, `{ agree: true }`, `{ agree: false }`                         |
| `title=`                                   | `{ title: undefined }`                                                           |
| a file part                                | the `File`                                                                       |
| `a[1000]=x`                                | 400 `Form field index too large in "a[1000]"`                                    |

- Use `formToObject` yourself in a route without a schema, and `readValidatedForm(event, schema)` from `hamur/server` in a handler that reads the event: it reads the form, decodes it, validates it, and throws a 400 `Validation failed` with `data: { issues }` as `readValidatedBody` does.

## Field helpers

- `fields.title.as("text")` returns `name`, `type`, `value` and `aria-invalid="true"` while there are issues, as a plain object to spread in JSX, a Vue `v-bind` or a Svelte `{...}`. In React it returns `defaultValue` and `defaultChecked`, because React treats a `value` without `onChange` as read-only. `as` takes any input type, `"select"` and `"textarea"` included; `checkbox` and `radio` take the value as a second argument.
- `fields.title.issues()` lists the issues whose path is this field's; `allIssues()` also those below it. `fields.info.height` and `fields.tags[0]` follow the path.
- `fields.title.value()` and `set(value)` read and write the value that `as()` shows.
- The names carry the codec prefix. `as("number")` and `as("range")` post as numbers (`n:`), and a `checkbox` without a value as a boolean (`b:`). The build runs no user code for a form and cannot read the schema, so `as("text")` over a numeric field posts text: use `z.coerce.number()` or the like in the schema.
- `form.pending` is true while a run of this handler is in flight. A page with several forms of one handler gives each form a key with `instance` and reads `form.for(key).pending`, `.result` and `.fields`. `for("")` throws.
- A schema field named `as`, `issues`, `allIssues`, `value` or `set` is not reachable through `fields`; rename it.

## Keeping values and focus

- After a failure with `values`, the typed values come back into the form.
- With JavaScript the form is not replaced, so nothing is lost; the first field with `aria-invalid="true"` takes the focus once the issues are shown, unless the visitor moved the focus.
- Without JavaScript the server rewrites the page: inside each form with `data-hamur-form` that posted this handler and has no `data-hamur-restore="false"`, a text input gets `value`, a checkbox or radio `checked`, a textarea its content, a select the matching `selected`. It never writes into `password`, `file` or `hidden` inputs, and it leaves a control that already has a value alone, so a field made with `as()` is not written twice.
- `restore={false}` on `Form` turns this off.

## Login and logout

- `logIn` keeps the visitor's `next` target, which the page sends in a hidden field, but only when it is an app path: a value like `//example.com` would otherwise send the visitor to another site, and `redirect` refuses it with a 500.
- `logOut` is a second handler, so there is no action name to pick.
- `whoami` is a `GET` handler the plugin below calls.
- Login and logout change what every page shows, so the forms use `reloadDocument`.
- The browser posts the form itself and follows the `303`, and the next page is rendered on the server with the new session. That also re-runs the app plugin below.
- The plugin runs on the server only. It does not run after a client navigation, which is why the login and logout forms load the next page in full.
- A reload of `/account` renders on the server again, where the plugin finds the session cookie.

- A dev host on plain `http` other than `localhost` also needs `cookie: { secure: false }` in the session options ([Sessions and security](/sessions-and-security)).

## Without JavaScript

- A form that `Form` renders is a native form, so a visitor with JavaScript off, a script that failed to load, or a form submitted before hydration all use the same handler.
- The browser posts to `<page>?_fn=<id>`, the handler runs with the decoded fields as its input, and the answer is the page itself, rendered with the result in `useAction(fn)` and `useForm(fn)`.
-

The order of a `POST` to a page path:

1. The origin check and server middleware run as for any request.
2. A `POST` without `_fn` answers 405 with `Allow: GET, HEAD`; an unknown id answers 404; the id of a `GET` handler answers 405.
3. The content type must be a form (`application/x-www-form-urlencoded` or `multipart/form-data`); any other answers 415.
4. The body is read within the handler's `form` limits, `formToObject` decodes it, and the handler runs with `middleware` and `input`.
5. The result is answered as in the table above: a redirect as 303, a `fail()` as the page with the failure's status, a failed `input` as the page with 400, a value as the page with 200, a thrown error as the page with the error's status.
6. The page renders as for a `GET`: route middleware, then the `load` files, which run after the handler, so the page shows fresh data.

- A success that returns a value (not a redirect) answers the page with status 200.
- A reload posts the form again, as in every framework; return a `redirect` after a change the visitor must not repeat.
- The typed values come back into the fields, except `password`, `file` and `hidden` inputs and every field whose name starts with `_`.
- A handler needs a server: a static site has none, and its forms have nothing to post to.

## Pending state and optimistic UI

- `useFormStatus()` gives `{ pending, data, action }` for the `Form` the component is rendered in; `useForm(fn).pending` and `useAction(fn).pending` give it for a handler, and the navigator sets `data-pending` on a `data-hamur-form` form while it posts, which CSS can use (`form[data-pending] button { opacity: .5 }`) and which is the only status an html page has, since it has no `useFormStatus`.
- `useNavigation()` has `state: "idle" | "loading"` for navigations and `revalidation: "loading"` while `refresh()` runs.

````ts [forms/server/notes.ts]
import { defineHandler } from "hamur/server"
import { auth } from "./guards/auth.ts"
import { schema } from "./utils/schema.ts"

const newNote = schema<{ text: string }>(
  { type: "object", properties: { text: { type: "string", minLength: 1 } }, required: ["text"] },
  (value) => {
    const text = (value as { text?: unknown } | undefined)?.text
    return typeof text === "string" && text
      ? { value: { text } }
      : { issues: [{ message: "A note needs text", path: ["text"] }] }
  },
)

export const addNote = defineHandler({
  input: newNote,
  middleware: [auth],
  handler({ text }, { context, clientContext }) {
    return { author: context.user, locale: String(clientContext.locale ?? "?"), text }
  },
})
````

- `useOptimistic(value, reduce)` returns `reduce(value, pending)` while a handler call made from a `Form` or a `useAction` is running, and `value` otherwise.
- `pending` lists the running calls, oldest first, each `{ fn, instance?, input, formData? }`.
- An entry leaves the list when the call has settled and the refreshed data is on screen, so a failed row disappears.
- React runs it over React's own `useOptimistic`; html has no `useOptimistic`, and its page scripts read `pendingRuns(app)` from `hamur/adapter`.

````tsx [forms/app/pages/quick.tsx]
import { Form, useAction, useData, useOptimistic } from "@hamur/adapter-react"
import { addTodo } from "#server"

export default function Quick() {
  const { todos } = useData<{ todos: Array<{ id: number; title: string }> }>()
  const add = useAction(addTodo)
  const shown = useOptimistic(todos, (current, pending) => [
    ...current,
    ...pending.flatMap((run) => {
      const title = run.formData?.get("title") ?? (run.input as { title?: string } | undefined)?.title
      return typeof title === "string" ? [{ id: -1, title: `${title} (saving)` }] : []
    }),
  ])
  return (
    <main>
      <ul>
        {shown.map((todo, at) => (
          <li key={at}>{todo.title}</li>
        ))}
      </ul>
      <Form action={addTodo} reset>
        <input name="title" />
        <button disabled={add.pending}>Add</button>
      </Form>
      {add.error ? <p role="alert">{add.error.message}</p> : null}
      <button type="button" onClick={() => void add.run({ title: "From code" })}>
        Add from code
      </button>
    </main>
  )
}
````

`addTodo` is the handler of the todo list above and `quick.load.ts` returns the same list, so the saving row is replaced by the real one when the refresh ends.

## Uploads

A handler's `form` option sets how a multipart body is read, with Hamur's streaming parser:

| Option         | Default                      |                                                                                                                          |
| -------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `maxBodySize`  | `server.maxBodySize` (1 MiB) | the whole body                                                                                                           |
| `maxFileSize`  | `maxBodySize`                | one file                                                                                                                 |
| `maxFiles`     | `10`                         | files in the form                                                                                                        |
| `onFile(file)` |                              | gets each file as a stream (`field`, `name`, `type`, `stream`); returns a `File`, a string, or nothing to drop the field |

- Without `onFile`, file parts are collected as `File`s. With it, the stream is read from the request as it is pulled, so a large file does not sit in memory; what you leave unread is drained and still counts against the limits.
- A body above `maxBodySize` answers 413 `Request body is too large` before any byte is parsed; a file above `maxFileSize` answers 413 `File "photos" is larger than 5242880 bytes`; more files than `maxFiles` answers 413 `More than 3 files in the form`; more than 1000 text fields answers 413 `More than 1000 fields in the form`.
- A malformed body answers 400 `Invalid multipart body`; the handler does not run. The same parser is `readMultipart(event, options)` for code that reads the event.

- A file can never be larger than the body that carries it. This config sets `server.maxBodySize` to 2 MiB for every other request:

````ts [forms/hamur.config.ts]
import type { HamurConfig } from "hamur"

export default {
  framework: "react",
  server: {
    maxBodySize: 2 * 1024 * 1024,
  },
  build: {
    importProtection: { client: { deny: ["pg", /^@internal\//] } },
  },
} satisfies HamurConfig
````

## Cross-site posts

- A handler is a public endpoint, and a form post to it is a `POST` anyone can send.
- Hamur refuses a cross-site form post before it reaches the handler: the origin check answers 403 to a `POST` with no content type, `application/x-www-form-urlencoded`, `multipart/form-data` or `text/plain` that another site sent, and the 415 rule refuses any content type other than the two form types and `application/json`.
- `csrf()` from [Sessions and security](/sessions-and-security) still works inside a handler when you want a token as well; call it with `event` from the handler's context.

## Things to keep in mind

- A handler runs for anyone who can send a `POST` to its page or to its URL. Check the session inside it or in its `middleware`, not only in a route middleware that guards the page.
- A page whose handler sets a cookie, like the login, must not be cached or prerendered.
- Keep per-user data out of the shared state unless the visitor may read it: the state is part of the page.
- A `POST` route at the page's own path takes the post first, so such a page cannot take `?_fn=`.

## Other libraries

The handlers, the plugin and the middleware are the same in every library. Only the page differs:

- Preact: the same code, with the imports from `@hamur/adapter-preact`.
- Vue: `useForm` returns a reactive object, so templates read `form.fields.email.issues()` directly and spread `v-bind="form.fields.email.as('email')"`; `Form` is a component with a default slot.
- Svelte: `useForm` returns getters, and `Form` takes its content as a `children` snippet.
- Solid: `pending` and `result` of `useForm` are accessors, so `form.pending()`.
- html: pages are strings. `Form({ action: fn }, "<input name='email'>")` returns the form; `useForm` returns an object at render time, and the page builds the attributes from it. A hydrated html page runs no component code, so a handler form there is always a native post that the browser follows.
