Form details
Every option, rule and error message behind the Forms and login guide. The shapes per library are in the adapters reference.
A schema without a package
An input is any Standard Schema object: Valibot, Zod and ArkType all are. schema(jsonSchema, check) below makes one from a check function:
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
actionit 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 aGETform 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 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); useAction(fn).error holds it |
redirectis the usual answer to a change the visitor must not repeat (post, redirect, get), soredirect("/todos")from a post on/todosis 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 lastfail(), whether a call is running (the refresh after it included), the last error, andrun(input)to call the handler from code.- A
Form action={fn}and auseAction(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:
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) }
},
})
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
loadthat gives the page its list is intodos.load.ts; after a success the page'sloadfiles and liveuseAsyncDataentries are fetched again, so the list shows the new todo.
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 thisdata:
{
issues: Array<{ path: Array<string | number>; message: string }>,
values: Record<string, unknown>,
}
valuesis the decoded body, minus every field whose name (after itsn:orb:prefix) starts with_, every top-level JSON key that starts with_, and everyFile.- A password sent as
_passwordtherefore never comes back. - A validator that throws gives one issue with an empty path: the message of a
TypeErrororRangeError, elseValidation failedoutside dev; a thrownHamurErroris not turned into an issue, it is the handler's error. - An
inputthat is not a Standard Schema throwsTypeErrorwhen 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
formToObjectyourself in a route without a schema, andreadValidatedForm(event, schema)fromhamur/serverin a handler that reads the event: it reads the form, decodes it, validates it, and throws a 400Validation failedwithdata: { issues }asreadValidatedBodydoes.
Field helpers
fields.title.as("text")returnsname,type,valueandaria-invalid="true"while there are issues, as a plain object to spread in JSX, a Vuev-bindor a Svelte{...}. In React it returnsdefaultValueanddefaultChecked, because React treats avaluewithoutonChangeas read-only.astakes any input type,"select"and"textarea"included;checkboxandradiotake 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.heightandfields.tags[0]follow the path.fields.title.value()andset(value)read and write the value thatas()shows.- The names carry the codec prefix.
as("number")andas("range")post as numbers (n:), and acheckboxwithout a value as a boolean (b:). The build runs no user code for a form and cannot read the schema, soas("text")over a numeric field posts text: usez.coerce.number()or the like in the schema. form.pendingis true while a run of this handler is in flight. A page with several forms of one handler gives each form a key withinstanceand readsform.for(key).pending,.resultand.fields.for("")throws.- A schema field named
as,issues,allIssues,valueorsetis not reachable throughfields; 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-formthat posted this handler and has nodata-hamur-restore="false", a text input getsvalue, a checkbox or radiochecked, a textarea its content, a select the matchingselected. It never writes intopassword,fileorhiddeninputs, and it leaves a control that already has a value alone, so a field made withas()is not written twice. restore={false}onFormturns this off.
Login and logout
logInkeeps the visitor'snexttarget, which the page sends in a hidden field, but only when it is an app path: a value like//example.comwould otherwise send the visitor to another site, andredirectrefuses it with a 500.logOutis a second handler, so there is no action name to pick.whoamiis aGEThandler 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
/accountrenders on the server again, where the plugin finds the session cookie.A dev host on plain
httpother thanlocalhostalso needscookie: { secure: false }in the session options (Sessions and security).
Without JavaScript
- A form that
Formrenders 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 inuseAction(fn)anduseForm(fn).
The order of a POST to a page path:
- The origin check and server middleware run as for any request.
- A
POSTwithout_fnanswers 405 withAllow: GET, HEAD; an unknown id answers 404; the id of aGEThandler answers 405. - The content type must be a form (
application/x-www-form-urlencodedormultipart/form-data); any other answers 415. - The body is read within the handler's
formlimits,formToObjectdecodes it, and the handler runs withmiddlewareandinput. - The result is answered as in the table above: a redirect as 303, a
fail()as the page with the failure's status, a failedinputas the page with 400, a value as the page with 200, a thrown error as the page with the error's status. - The page renders as for a
GET: route middleware, then theloadfiles, 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
redirectafter a change the visitor must not repeat. - The typed values come back into the fields, except
password,fileandhiddeninputs 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 theFormthe component is rendered in;useForm(fn).pendinganduseAction(fn).pendinggive it for a handler, and the navigator setsdata-pendingon adata-hamur-formform 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 nouseFormStatus.useNavigation()hasstate: "idle" | "loading"for navigations andrevalidation: "loading"whilerefresh()runs.
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)returnsreduce(value, pending)while a handler call made from aFormor auseActionis running, andvalueotherwise.pendinglists 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 nouseOptimistic, and its page scripts readpendingRuns(app)fromhamur/adapter.
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 asFiles. 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
maxBodySizeanswers 413Request body is too largebefore any byte is parsed; a file abovemaxFileSizeanswers 413File "photos" is larger than 5242880 bytes; more files thanmaxFilesanswers 413More than 3 files in the form; more than 1000 text fields answers 413More than 1000 fields in the form.A malformed body answers 400
Invalid multipart body; the handler does not run. The same parser isreadMultipart(event, options)for code that reads the event.A file can never be larger than the body that carries it. This config sets
server.maxBodySizeto 2 MiB for every other request:
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
POSTanyone can send. - Hamur refuses a cross-site form post before it reaches the handler: the origin check answers 403 to a
POSTwith no content type,application/x-www-form-urlencoded,multipart/form-dataortext/plainthat another site sent, and the 415 rule refuses any content type other than the two form types andapplication/json. csrf()from Sessions and security still works inside a handler when you want a token as well; call it witheventfrom the handler's context.
Things to keep in mind
- A handler runs for anyone who can send a
POSTto its page or to its URL. Check the session inside it or in itsmiddleware, 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
POSTroute 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:
useFormreturns a reactive object, so templates readform.fields.email.issues()directly and spreadv-bind="form.fields.email.as('email')";Formis a component with a default slot. - Svelte:
useFormreturns getters, andFormtakes its content as achildrensnippet. - Solid:
pendingandresultofuseFormare accessors, soform.pending(). - html: pages are strings.
Form({ action: fn }, "<input name='email'>")returns the form;useFormreturns 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.