Forms and validation
A form
A form is a plain <form>. It posts to an action, which validates the input and answers, usually with a redirect
back:
// app/routes/contacts/new.tsx
import { back, defineHandler, flash } from 'fondu'
import type { Errors } from 'fondu/client'
import { contactSchema } from '#/modules/contacts/schemas.ts'
// POST /contacts/new
export const action = defineHandler.withValidator({ body: contactSchema })(async (c, { body }) => {
await addContact(body)
flash(c, { message: 'Contact added' })
return back(c)
})
export default function NewContact({ errors }: { errors: Errors }) {
return (
<form method="post">
<input name="email" aria-invalid={!!errors.email} />
{errors.email && <p>{errors.email}</p>}
<button>Add</button>
</form>
)
}A form without an action posts to its page's URL. A page with several forms gives each its own:
actions = { add, remove } in the route file, <form method="post" action="?remove"> in the page.
With JavaScript, Fondu's client sends it without a page load: back at the same URL, the page is updated where it is. Without, it is an ordinary form post, with the same result.
After an action
An action answers with a redirect, so that a reload doesn't send the form again:
back(c): back to the page the form was on. With JavaScript, that page is updated in place.c.redirect(url, 303): to another page, a file or another site. A URL with the schemejavascript:,data:orvbscript:is refused: the request gets a 500,fondu: a redirect to "javascript:" is refused, and the error is logged.flash(c, { message: 'Saved' })before either: data for the next page only, inusePage().flash, for a "Saved" message say.
Flash data and errors travel in a short cookie. The cookie comes back from the client, so what a page reads from
usePage().flash is not trusted: anyone can write it. Fondu ignores a cookie whose flash is not an object or whose errors are not strings, and shows
the flash once. Keep the values short: a cookie over about 4 KB is dropped by the browser, so Fondu leaves
out the flash data first, then the errors that don't fit, and logs a warning.
Invalid input
When the body or the query doesn't fit its schema, the handler doesn't run:
- a page's form (a POST, PUT, PATCH or DELETE) gets a redirect back to the page it came from, and that page gets the errors in its
errorsprop, one message per field ({ email: 'Invalid email' }). What was typed stays in the form. - a GET (or HEAD) with an invalid query has no form to go back to, and a redirect could loop: a visitor gets the error page with status 422.
- an API client gets 422 and
{ errors }.
Params that don't fit are a 404: the URL names nothing.
A check the schema can't make, such as an address already taken, throws ValidationError from the handler, with the
same result:
import { ValidationError } from 'fondu'
if (await emailTaken(body.email)) throw new ValidationError({ email: 'This address is taken' })The errors are one object for the page: two forms on a page keep theirs apart by their fields' names.
The same schema in the browser
A schema is plain code: a page can import it, from any module that isn't server code, and check the form before it is sent. It is still a plain form: when the check passes, Fondu's client sends it; when it doesn't, the submit is stopped and the errors shown. The server checks again, and what only it can (an address already taken).
useForm(schema) from fondu/client does it. It reads the fields as the server does (tags[], user[name]), so
the browser's check and the server's agree:
import { useForm } from 'fondu/client'
import { contactSchema } from '#/modules/contacts/schemas.ts'
export default function NewContact() {
const { form, field, errors, submitting } = useForm(contactSchema)
return (
<form method="post" {...form}>
<input {...field('email')} />
{errors.email && <p>{errors.email}</p>}
<button disabled={submitting}>Add</button>
</form>
)
}| Field | Is |
|---|---|
form | for the <form>: checks it on submit; an invalid one isn't sent, its first field to fix focused |
field(name) | for a field: its name, aria-invalid, and its checks as it is left and changed |
errors | the server's (the page's errors prop), and the browser's: errors.email, errors['user.name'] |
submitting | this form is being sent |
failed | this form could not be sent (offline…): it stays, to send again |
- A field is checked as it is left for another with something typed, and again as it changes while it is wrong, so a fixed field loses its message. Not as it is left for the submit button: the message would move the button from under the pointer.
- A server's error stays until its field is checked again. Back with the server's errors, the first field to fix gets the focus.
- Any Standard Schema works in the browser if it checks synchronously. Without a schema,
useForm()gives the server's errors,submittingandfailedonly. - A schema that returns a promise (an async rule, such as a taken email) gives no verdict in the browser: the form is
sent as it is, and the server's errors come back as any other. In development, one warning per schema says so
(
fondu: this schema has an async rule, so useForm leaves it to the server). The server keeps async schemas: put that rule in the action's schema, and the browser still checks the rest. errorshas the server's keys: a field's path, joined with dots (user[name]isuser.name).- With a schema,
formsetsnoValidateon the<form>: the schema's messages replace the browser's own (required,type="email"). Without JavaScript the browser's checks stay. - Your own handlers go next to it:
onChange={(e) => { field('email').onChange(e); … }}. - Without JavaScript, the form is sent as it is, and the server's check answers.
While it is sent
The form being sent has aria-busy="true" until the answer is on the screen, however it was sent (a click, Enter,
requestSubmit()): its buttons can show it with CSS alone, and assistive technology says it.
form[aria-busy='true'] button[type='submit'] {
opacity: 0.6;
cursor: progress;
}In a component, useForm().submitting says it, or useNavigation().form, the form being sent:
import { useNavigation } from 'fondu/client'
export function SubmitButton(props: ComponentProps<'button'>) {
const ref = useRef<HTMLButtonElement>(null)
const { form, state } = useNavigation()
const sending = state !== 'failed' && form !== null && form === ref.current?.form
return <button ref={ref} type="submit" disabled={sending} {...props} />
}A form that could not be sent (offline, the connection lost) stays as it was, and useForm().failed says so until the
next navigation starts:
{failed && <p role="alert">Not sent. Check your connection and try again.</p>}The progress bar shows for submissions too; fondu({ progress: { forms: false } }) leaves it to the buttons.
Files and nested fields
The body is one object whether it comes as JSON (application/json or any application/*+json, such as
application/merge-patch+json) or as form fields. Form fields named like user[name] or tags[]
become nested objects and arrays, files are File objects, and empty file inputs are left out. A body that can't be
one object is a 400: JSON that doesn't parse, a name that is both a value and an object (a and a[b]), names nested
deeper than 32, and more than 10,000 entries (files and empty file inputs count).
A body of any other type (text/plain, or none) is a 415 Unsupported Media Type; a request with no body is {}.
withValidator({ query }) reads the query the same way: ?tag=a&tag=b and ?tag[]=a are lists, ?user[name]=Ada is an
object, and ?a=1&a[b]=2 is a 400. A query carries text, so a schema that wants a number or a boolean parses it
(z.coerce.number()), and a list field is written tag[]=a (href() does), as ?tag=a is a string. A useForm that
sends a GET form reads its fields this way too.
Only a multipart/form-data form sends its files (enctype, or a submitter's formenctype, which comes first). In any
other form (URL-encoded is the default) a file input sends its file name, empty when no file is chosen. useForm
checks the form as it is sent: your schema sees a File, or that string.
The body limit
The body is read whole, in memory, files too, and it takes about twice its size while it is parsed. A body over 10 MB
is answered 413 by default, with the error page. The limit is in the chain of each route that takes a body (POST, PUT,
PATCH, DELETE), after the _middleware.ts of its directories and before its action or handler. The error page has the
shared props they set, and a request they refuse is never read; for that, a middleware must not read the body. A GET and
a URL that is no route are never read. A client that disconnects mid-upload is not logged as an error. createApp({ bodyLimit: 25 * 1024 * 1024 })
in app/server.ts changes the limit for the app, and false removes it. Raise it for the whole app only a little: every request can use
it. On Cloudflare Workers an isolate has 128 MB of memory, shared by the requests it serves
(limits). Served by Node or Bun directly over HTTP/1.1,
Firefox and Safari may show a failed request rather than the 413 page when a large body is refused unread; behind
Cloudflare, every browser gets the page.
A route that should take less adds Hono's bodyLimit in its _middleware.ts; a directory's middleware cannot raise
the app's limit.
// app/routes/avatars/_middleware.ts
import { bodyLimit } from 'hono/body-limit'
export default bodyLimit({ maxSize: 1024 * 1024 }) // 1 MB, then 413A route that should take more has no way to raise the app's limit, so the app has none, and the root middleware sets
one for each path. The 413 must be an HTTPException (Hono's default onError throws one that carries its own plain-text response), so
that it gets the error page, with the props the root middleware shared above it.
// app/server.ts
export default createApp({ bodyLimit: false })// app/routes/_middleware.ts
import { defineMiddleware, share } from 'fondu'
import { bodyLimit } from 'hono/body-limit'
import { HTTPException } from 'hono/http-exception'
const limit = (maxSize: number) =>
bodyLimit({
maxSize,
onError: () => {
throw new HTTPException(413)
},
})
const photos = limit(50 * 1024 * 1024)
const rest = limit(1024 * 1024)
export default [
defineMiddleware(async (c, next) => {
share(c, { site: 'Acme' }) // what every page needs, the error page too
await next()
}),
defineMiddleware((c, next) => (c.req.path.startsWith('/photos') ? photos : rest)(c, next)),
]Large files
Cloudflare refuses a request over its own limit with a 413 before your app has a say: 100 MB on the Free and Pro plans, 200 MB on Business, more on Enterprise (limits). Under it, a large file is better not sent through the app at all. The browser sends it straight to storage, and the form sends only where it went.
With R2, the app gives the browser a presigned URL to PUT the file to. The Workers binding can't make one: sign it
with the S3 API (presigned URLs), in a .ts route.
// app/routes/api/upload-url.ts
import { defineHandler } from 'fondu'
export const POST = defineHandler(async (c) => {
const key = crypto.randomUUID()
const url = await presign(key, 'image/jpeg') // yours, with aws4fetch or the AWS SDK: a signed PUT URL
return c.json({ key, url })
})In the browser, request() from fondu/client gets the URL (typed), then the file goes to R2 with the platform's
fetch(). The form's action receives only the key.
import { request } from 'fondu/client'
async function upload(file: File) {
const { key, url } = await request('/api/upload-url', { method: 'POST' })
const res = await fetch(url, {
method: 'PUT',
headers: { 'Content-Type': 'image/jpeg' }, // the type that was signed
body: file,
})
if (!res.ok) throw new Error('Upload failed')
return key // a hidden input of the form: the action stores the key
}The bucket needs a CORS rule, or the browser refuses the request, valid URL or not
(CORS): the app's origin, the PUT method, and the headers the
browser sends.
[
{
"AllowedOrigins": ["https://example.com"],
"AllowedMethods": ["PUT"],
"AllowedHeaders": ["Content-Type"]
}
]CSRF
createApp() turns on Hono's CSRF protection: a request that changes something (a POST, a form) must come from the
app's own origin. The app's own forms do; nothing else is needed.