@rsc-kit/mcp 0.41.0 → 0.42.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/recipes.js +18 -2
  2. package/dist/recipes.js.map +1 -1
  3. package/guides/admin-plugins.md +206 -6
  4. package/guides/api-routes.md +159 -215
  5. package/guides/authorization.md +103 -114
  6. package/guides/backend-answered-pages.md +301 -252
  7. package/guides/bap-vs-inertia.md +67 -25
  8. package/guides/blueprints.md +300 -169
  9. package/guides/bun.md +42 -25
  10. package/guides/caching.md +46 -49
  11. package/guides/coming-from-inertia.md +2 -2
  12. package/guides/commands.md +251 -200
  13. package/guides/connection.md +50 -54
  14. package/guides/content-security-policy.md +133 -84
  15. package/guides/domains.md +190 -149
  16. package/guides/edge-caching.md +242 -268
  17. package/guides/emails.md +96 -45
  18. package/guides/errors.md +116 -137
  19. package/guides/feature-flags.md +100 -30
  20. package/guides/file-uploads.md +101 -26
  21. package/guides/fonts.md +139 -110
  22. package/guides/forms.md +520 -542
  23. package/guides/images.md +87 -28
  24. package/guides/index.json +13 -33
  25. package/guides/instrumentation.md +134 -95
  26. package/guides/isr.md +3 -3
  27. package/guides/live-data-in-production.md +695 -0
  28. package/guides/live-data.md +170 -839
  29. package/guides/mcp.md +83 -59
  30. package/guides/metadata.md +124 -179
  31. package/guides/navigation.md +118 -147
  32. package/guides/no-javascript.md +49 -57
  33. package/guides/offline.md +118 -153
  34. package/guides/openapi.md +100 -35
  35. package/guides/pages.md +160 -50
  36. package/guides/ppr.md +178 -256
  37. package/guides/pwa.md +270 -216
  38. package/guides/queries.md +171 -300
  39. package/guides/react-compiler.md +90 -50
  40. package/guides/redirects.md +141 -177
  41. package/guides/response-headers.md +76 -74
  42. package/guides/route-interception.md +112 -111
  43. package/guides/routing.md +216 -322
  44. package/guides/sections.md +63 -66
  45. package/guides/seo-files.md +127 -65
  46. package/guides/server-actions.md +285 -357
  47. package/guides/static-generation.md +131 -199
  48. package/guides/testing.md +269 -147
  49. package/guides/third-party-scripts.md +94 -47
  50. package/guides/typed-routes.md +115 -113
  51. package/guides/url-validation.md +113 -61
  52. package/guides/validation.md +53 -62
  53. package/guides/view-transitions.md +159 -132
  54. package/guides/where-it-runs.md +226 -162
  55. package/package.json +2 -2
  56. package/guides/admin.md +0 -520
  57. package/guides/deployment.md +0 -598
  58. package/guides/go.md +0 -539
  59. package/guides/laravel.md +0 -787
  60. package/guides/your-own-backend.md +0 -602
package/guides/forms.md CHANGED
@@ -2,29 +2,35 @@
2
2
 
3
3
  > Progressive forms, pending state and validation errors.
4
4
 
5
- `<Form>` submits to a server action: a component
6
- that handles the state for you, and a hook for when you want to hold it
7
- yourself. Both cover validation errors, pending state, optimistic updates and
8
- GET-form navigation.
5
+ `<Form>` submits to a server action and handles the state around it: pending,
6
+ validation errors, success and optimistic updates. It works before the page's
7
+ JavaScript has loaded.
9
8
 
10
- ## The rule: uncontrolled, unless one field needs otherwise
9
+ ```tsx title="NewOrder.tsx"
10
+ "use client";
11
11
 
12
- A form here is **uncontrolled by default**. Inputs keep their own value in
13
- the DOM, an initial value is React's `defaultValue`, and the action reads
14
- `FormData` on submit. No `useState` per field, no `value`/`onChange` pair,
15
- no re-render of the whole form on every keystroke — and after a refused
16
- submit the values are still there, because nothing re-rendered the inputs.
12
+ import { Form } from "@rsc-kit/core/form";
13
+ import * as orders from "../server-actions/orders";
17
14
 
18
- Reach for a controlled field only where the UI has to react *as* the user
19
- types — a character count, a live preview, a dependent select — and bind
20
- that one field with `useField` (below), which scopes the re-render to it.
21
- Coming from react-hook-form this is the same default; coming from TanStack
22
- Form or from `useState`-per-input it is the opposite, and the difference is
23
- most of why these forms stay fast.
15
+ export function NewOrder() {
16
+ return (
17
+ <Form action={orders.create}>
18
+ {({ pending, error }) => (
19
+ <>
20
+ <input name="title" />
21
+ {error('title') && <p>{error('title')}</p>}
22
+ <button disabled={pending}>{pending ? 'Saving…' : 'Save'}</button>
23
+ </>
24
+ )}
25
+ </Form>
26
+ );
27
+ }
28
+ ```
24
29
 
25
- ## The `<Form>` component
30
+ ## Submitting a form
26
31
 
27
- The simplest way to handle forms. Works without any hooks — just pass a server action and use the render-prop for pending state and errors.
32
+ Pass a server action as `action`. The children are a function that receives the
33
+ form's state:
28
34
 
29
35
  ```tsx title="TodoForm.tsx"
30
36
  "use client";
@@ -41,9 +47,7 @@ export default function TodoForm() {
41
47
  <>
42
48
  <input name="title" placeholder="What needs to be done?" />
43
49
  {error('title') && <span className="text-red-500">{error('title')}</span>}
44
- <button disabled={pending}>
45
- {pending ? 'Adding...' : 'Add Todo'}
46
- </button>
50
+ <button disabled={pending}>{pending ? 'Adding...' : 'Add Todo'}</button>
47
51
  </>
48
52
  )}
49
53
  </Form>
@@ -51,50 +55,50 @@ export default function TodoForm() {
51
55
  }
52
56
  ```
53
57
 
54
- The generic type parameter `<FormValues>` gives you autocomplete on `error()` and typed form data throughout the component.
55
-
56
- ### Two words: `error` and `field`
57
-
58
- There is one way to read a form, and it is the same everywhere — in the render
59
- prop, in a component of its own, with shadcn or without:
60
-
61
- - **`error('title')`** — the field's message, or `undefined`. Show it, or test
62
- it: `!!error('title')` is "invalid". Nested fields are paths:
63
- `error('address.city')`, `error('items[0].name')`. When the action says what
64
- it takes, the names are checked: `error('titel')` fails the typecheck instead
65
- of showing nothing, ever. See [Field names](#field-names).
66
- - **`formError`** — the refusal that is not about a field: the action's
67
- `serverError`, such as a payment required or a slot just taken, or a
68
- validation message for the whole form. `{formError && <p role="alert">{formError}</p>}`.
69
- It clears with the field errors. A failure thrown on the way, such as the
70
- network, still goes to `onError`.
71
- - **`field('title')`** — a binding to spread onto a control, for the few fields
72
- whose value this component has to hold. Most fields need nothing: they are
73
- uncontrolled, the DOM holds the value, and it is read back on submit.
74
-
75
- Beside them: `pending`, `dirty`, `succeeded`, `recentlySucceeded`, `reset()` and
76
- `clearErrors()`. A field is checked when it is left and when the form is
77
- submitted, so `error()` never lights up on a field nobody has reached.
78
-
79
- ### Props
80
-
81
- ```text
82
- action — server action function (POST) or URL string (GET)
83
- method — "get" | "post" (defaults to "post" for functions, "get" for strings)
84
- resetOnSuccess — auto-reset form on success (default: true)
85
- optimistic — callback for optimistic updates, called inside the transition
86
- onSuccess — called with the action result on success
87
- onError — called with validation errors on 422
88
- onSubmit — called before submit, return false to cancel
89
- prefetch — "hover" (default) | "mount" | "none" (GET forms only)
90
- replace — replace history state (GET forms)
91
- preserveScroll — keep scroll position (GET forms)
92
- ```
58
+ The inputs are ordinary named inputs. They keep their own value, and the action
59
+ reads them as `FormData` on submit. There's no `useState` per field and no
60
+ `value`/`onChange` pair, and typing doesn't re-render the form. Bind a field
61
+ only when the page has to react as it's typed: see
62
+ [controlling one field](#controlling-one-field).
63
+
64
+ The type parameter, `<FormValues>`, types the names `error()` accepts. With a
65
+ generated action you don't need it: the names come from the action.
66
+
67
+ What the render function receives:
68
+
69
+ | Name | What it is |
70
+ | --- | --- |
71
+ | `error(name)` | The field's message, or `undefined`. |
72
+ | `formError` | A refusal that isn't about one field. |
73
+ | `field(name)` | A binding to spread onto a control you need to hold. |
74
+ | `pending` | `true` while the submit is running. |
75
+ | `dirty` | Whether any value differs from what the form started with. |
76
+ | `succeeded`, `recentlySucceeded` | Whether the last submit succeeded; the second for two seconds only. |
77
+ | `reset()`, `clearErrors()` | Go back to the starting values; clear the errors. |
78
+ | `validate()`, `validating`, `valid(name)` | Ask the server to check fields now. |
79
+
80
+ ### Form props
81
+
82
+ | Prop | What it does |
83
+ | --- | --- |
84
+ | `action` | A server action (POST), or a URL (GET). |
85
+ | `method` | `"get"` or `"post"`. Defaults to `"post"` for an action and `"get"` for a URL. |
86
+ | `schema` | A schema to check the values with in the browser. |
87
+ | `defaultValues` | Starting values for bound fields. |
88
+ | `fields` | Field names, for a form whose values aren't posted fields. |
89
+ | `resetOnSuccess` | Reset the form after a successful submit. Default `true`. |
90
+ | `optimistic` | Called inside the transition, for [optimistic updates](#optimistic-updates). |
91
+ | `onSuccess` | Called with the action's result. |
92
+ | `onError` | Called with the validation errors on a 422. |
93
+ | `onSubmit` | Called before submitting. Return `false` to cancel. |
94
+ | `prefetch` | `"hover"` (default), `"mount"` or `"none"`. GET forms only. |
95
+ | `replace` | Replace the history entry. GET forms only. |
96
+ | `preserveScroll` | Keep the scroll position. GET forms only. |
93
97
 
94
98
  ### In a component of its own
95
99
 
96
- `useForm()` returns exactly what the render prop gets, so a piece of a form
97
- moved into its own component is written the same way it was inline:
100
+ `useForm()` returns what the render function receives, so part of a form can
101
+ move into its own component:
98
102
 
99
103
  ```tsx title="SubmitButton.tsx"
100
104
  "use client";
@@ -112,109 +116,36 @@ export function SubmitButton() {
112
116
  }
113
117
  ```
114
118
 
115
- Not React's `useFormStatus`: that is a different hook with a different answer,
116
- which is why this one is not called that.
117
-
118
- ---
119
-
120
- ### Field names
121
-
122
- `error()` and `clearErrors()` are typed from the action's input, so a typo
123
- fails `tsc` rather than silently never matching:
124
-
125
- ```tsx
126
- <Form action={orders.create}>
127
- {({ error }) => (
128
- <>
129
- {error('name')} {/* ok */}
130
- {error('address.city')} {/* ok: a nested path */}
131
- {error('items.0.sku')} {/* ok: a list's index */}
132
- {error('nmae')} {/* type error */}
133
- </>
134
- )}
135
- </Form>
136
- ```
137
-
138
- Where the names come from: a generated stub's typed parameter (the backend
139
- already lists the fields of the struct or the FormRequest-shaped array it takes
140
- in `rsc-host.json`, so nothing is written for this), or `createActionClient()`'s
141
- `.input(schema)`. Fields the form declares in `defaultValues` count too. When
142
- the action says nothing — a function of a `FormData`, a url, a cast — nothing is
143
- claimed and any name is accepted, as before. A name the backend reports that its
144
- input does not have, such as a key it computes, is a type error you can answer by
145
- declaring it in `defaultValues`.
146
-
147
- **A wrapper you write around a stub** says nothing on its own: a function of a
148
- `FormData` could read anything. Declare the fields on its parameter, where the
149
- code that reads them lives:
150
-
151
- ```tsx
152
- import type { FormFields } from '@rsc-kit/core/form'
153
-
154
- export async function renameApp(form: FormFields<'id' | 'name'>) {
155
- 'use server'
156
- await appsRename(String(form.get('id')), String(form.get('name')))
157
- }
158
- ```
159
-
160
- `<Form action={renameApp}>` then closes `error()` to `id` and `name` — and to
161
- whatever `defaultValues` adds. A `FormFields` is a `FormData`; nothing runs, and
162
- the names are a claim the types keep, not a check the browser makes. It names
163
- what `error()` may be asked for, so a field the backend refuses under that the
164
- form does not post — `redirect`, say — belongs in the same list.
165
-
166
- **A team-scoped action**, `func(ctx, team string, in NewApp)`, is a form's action
167
- once the team is bound. A form fills the struct parameter, the one after
168
- whatever you bound, and the generated stub keeps its field names:
169
-
170
- ```tsx
171
- const create = apps.create.bind(null, team) // once, not inline
172
-
173
- <Form action={create}>{({ error }) => error('name')}</Form>
174
- ```
175
-
176
- Bind into a `const` first. Written inline in the JSX, TypeScript reads `bind`'s
177
- result before the form's render function is known and the names are not
178
- carried: the form still compiles, and is open as it always was. A stub whose
179
- parameters are all plain strings has no struct for a form to fill — wrap it, as
180
- above.
181
-
182
- **A form that posts nothing** — its values live in React state, or it is a
183
- button — has no `FormData` to name the fields on. Name them on the form:
184
-
185
- ```tsx
186
- <Form action={resize} fields={['size', 'copies']}>
187
- {({ error }) => error('size')} {/* error('sise') fails the typecheck */}
188
- </Form>
189
- ```
119
+ This isn't React's `useFormStatus`, which is a different hook with a different
120
+ answer.
190
121
 
191
- `fields` closes the set beside the action's own names — a bound stub's included —
192
- and `defaultValues`. It is types only: nothing is checked in the browser. It is
193
- also how to name a field the backend refuses under that the struct does not
194
- spell the same way, such as an untagged Go field `Host` that the backend reports
195
- as `host`; tagging the struct (`json:"host"`) is the cleaner fix.
122
+ ## Validation errors
196
123
 
197
- A component below the form types its own prop with `FieldNamesOf`:
124
+ When a submit fails validation, `error('title')` returns the field's message.
125
+ There's no `try`/`catch` to write and no state to hold.
198
126
 
199
127
  ```tsx
200
- import type { FieldNamesOf } from '@rsc-kit/core/form'
201
-
202
- type Props = { name: FieldNamesOf<typeof orders.create> }
128
+ {error('title') && <p>{error('title')}</p>}
129
+ {error('address.city')} {/* a nested field */}
130
+ {error('items[0].name')} {/* a field in a list */}
131
+ {formError && <p role="alert">{formError}</p>}
203
132
  ```
204
133
 
205
- ## Validation errors
134
+ - **`error(name)`** shows a field's message. `!!error('title')` tells you
135
+ whether the field is invalid.
136
+ - **`formError`** is a refusal that isn't about one field: the action's
137
+ `serverError`, such as a payment required or a slot just taken, or a message
138
+ for the whole form. It clears with the field errors.
139
+ - A failure on the way, such as the network, goes to `onError` instead.
206
140
 
207
- When a submit fails validation, `error('title')` answers with the field's
208
- message — there is no `try`/`catch` to write, and no state to hold.
141
+ Errors come from the schema in the browser and from the server, and `error()`
142
+ shows both. Where the server's come from depends on your backend: see
143
+ [Validation](/guides/validation).
209
144
 
210
- Where those errors come from depends on the host, and the components do not
211
- care. See [Validation](/guides/validation).
145
+ ### Returning an error from an action
212
146
 
213
- An action can also name a field itself, for a refusal no schema could know
214
- about. Through the [action client](/guides/server-actions#failing-on-something-a-schema-cannot-know)
215
- `fieldErrors` arrives with the handler's arguments, typed to its input. A plain
216
- `"use server"` function has no input type to draw on, so it imports the same
217
- thing untyped:
147
+ An action can refuse a field itself, for something no schema could know.
148
+ Return `fieldErrors()`:
218
149
 
219
150
  ```ts
220
151
  'use server';
@@ -230,221 +161,117 @@ export async function addTodo(formData: FormData) {
230
161
  }
231
162
  ```
232
163
 
233
- Either way, write `return fieldErrors(…)`. The form renders it under the field
234
- you named, exactly as it would a schema failure.
164
+ The form shows it under that field, the same as a schema failure. Through the
165
+ [action client](/guides/server-actions#failing-on-something-a-schema-cannot-know),
166
+ `fieldErrors` arrives with the handler's arguments, typed to its input.
235
167
 
236
- ---
168
+ ## Field names
237
169
 
238
- ## Optimistic updates
170
+ `error()` and `clearErrors()` are typed from the action's input, so a typo fails
171
+ the typecheck instead of never matching:
239
172
 
240
- Optimistic updates go through React's `useOptimistic`. The callback runs inside the transition, so React reverts it automatically on error.
173
+ ```tsx
174
+ <Form action={orders.create}>
175
+ {({ error }) => (
176
+ <>
177
+ {error('name')} {/* ok */}
178
+ {error('address.city')} {/* ok: a nested path */}
179
+ {error('items.0.sku')} {/* ok: a list's index */}
180
+ {error('nmae')} {/* type error */}
181
+ </>
182
+ )}
183
+ </Form>
184
+ ```
241
185
 
242
- ```tsx title="TodoList.tsx"
243
- "use client";
186
+ The names come from:
244
187
 
245
- import { useOptimistic } from "react";
246
- import { Form } from "@rsc-kit/core/form";
247
- import { addTodo } from "./actions";
188
+ - a generated action's parameter. The backend lists the fields of the struct or
189
+ form request it takes in `rsc-host.json`, so you write nothing.
190
+ - `createActionClient()`'s `.input(schema)`.
191
+ - `defaultValues` on the form.
248
192
 
249
- type Todo = { id: number; title: string; done: boolean };
193
+ When the action says nothing about its input - a function of `FormData`, a URL,
194
+ a cast - any name is accepted. A name the backend reports that its input
195
+ doesn't have, such as a key it computes, is a type error: add it to
196
+ `defaultValues`.
250
197
 
251
- export default function TodoList({ todos }: { todos: Todo[] }) {
252
- const [optimisticTodos, addOptimistic] = useOptimistic(
253
- todos,
254
- (state, newTodo: Todo) => [...state, newTodo]
255
- );
198
+ ### Typing a wrapper around an action
256
199
 
257
- return (
258
- <div>
259
- <ul>
260
- {optimisticTodos.map((todo) => (
261
- <li key={todo.id}>{todo.title}</li>
262
- ))}
263
- </ul>
200
+ A function of `FormData` could read anything, so it names no fields. Declare
201
+ them on its parameter with `FormFields`:
264
202
 
265
- <Form
266
- action={addTodo}
267
- optimistic={(data) =>
268
- addOptimistic({ id: Date.now(), title: data.title as string, done: false })
269
- }
270
- >
271
- <input name="title" />
272
- <button>Add</button>
273
- </Form>
274
- </div>
275
- );
276
- }
277
- ```
278
-
279
- ## Search and filter forms
280
-
281
- When `action` is a URL string, the form navigates via RSC instead of doing a full page reload. Form fields are serialized as query parameters. Supports prefetching for instant navigation.
282
-
283
- ```tsx title="SearchForm.tsx"
284
- "use client";
285
-
286
- import { Form } from "@rsc-kit/core/form";
203
+ ```tsx
204
+ import type { FormFields } from '@rsc-kit/core/form'
205
+ import * as apps from './server-actions/apps'
287
206
 
288
- export default function SearchForm() {
289
- return (
290
- <Form action="/search" method="get" prefetch="hover">
291
- <input name="q" placeholder="Search..." />
292
- <select name="sort">
293
- <option value="relevance">Relevance</option>
294
- <option value="date">Date</option>
295
- </select>
296
- <button>Search</button>
297
- </Form>
298
- );
207
+ export async function renameApp(form: FormFields<'id' | 'name'>) {
208
+ 'use server'
209
+ await apps.rename(String(form.get('id')), String(form.get('name')))
299
210
  }
300
211
  ```
301
212
 
302
- This navigates to `/search?q=hello&sort=date` via SPA navigation. The nearest Suspense boundary streams in the results. With `prefetch="hover"`, hovering the submit button pre-warms the base URL for instant feedback.
303
-
304
- ### A search on the page it is on
213
+ `<Form action={renameApp}>` then accepts `error('id')` and `error('name')`, plus
214
+ whatever `defaultValues` adds. A `FormFields` is a `FormData`: the names are
215
+ types only, and nothing is checked in the browser. Include a field the backend
216
+ may refuse that the form doesn't post, such as `redirect`.
305
217
 
306
- When the form's `action` is the page the visitor is already on, there is no other page whose shell could stand in while the query runs: the shell would be this page with nothing in it. So the form does not show one. The page stays on screen, results and all, and the new results replace the old ones when they arrive. The input keeps what was typed, a Suspense boundary that was already showing its content keeps showing it instead of falling back to its skeleton, and Back returns to the query the visitor left.
218
+ ### Binding an argument first
307
219
 
308
- `pending` is true until the new results are on screen, so the button can say so:
220
+ For an action like `func(ctx, team string, in NewApp)`, bind the team and the
221
+ form fills the struct after it. Bind into a `const` first:
309
222
 
310
- ```tsx title="Lookup.tsx"
311
- "use client";
312
-
313
- import { Form } from "@rsc-kit/core/form";
314
-
315
- export default function Lookup() {
316
- return (
317
- <Form action="/lookup" method="get">
318
- {({ pending }) => (
319
- <>
320
- <input name="q" />
321
- <button disabled={pending}>{pending ? "Searching…" : "Search"}</button>
322
- </>
323
- )}
324
- </Form>
325
- );
326
- }
327
- ```
328
-
329
- To show a skeleton where the results are instead of the old results, style them from the form's own `data-pending` attribute. The results stay outside the form, and nothing in the page is a client component for it:
223
+ ```tsx
224
+ const create = apps.create.bind(null, team) // once, not inline
330
225
 
331
- ```css
332
- #results-skeleton { display: none }
333
- section:has(form[data-pending]) #results { display: none }
334
- section:has(form[data-pending]) #results-skeleton { display: block }
226
+ <Form action={create}>{({ error }) => error('name')}</Form>
335
227
  ```
336
228
 
337
- Only a `<Form>` does this. A `<Link>` or `visit()` to the same path with another query is still a page of its own. The form does not prefetch the page it is on, because it is already on it.
229
+ Written inline in the JSX, TypeScript loses the names: the form compiles, but
230
+ accepts any name. An action whose parameters are all plain strings has no
231
+ struct for a form to fill, so wrap it as above.
338
232
 
339
- ## Using it with shadcn/ui
233
+ ### A form that posts nothing
340
234
 
341
- It works, and mostly by doing nothing. `<Form>` reads a native `FormData`, so
342
- any component that ends up rendering a real form control is already compatible:
235
+ When the values live in React state, or the form is a single button, name the
236
+ fields on the form:
343
237
 
344
238
  ```tsx
345
- <Form action={createPost} schema={schema}>
346
- {({ pending, error }) => (
347
- <>
348
- <Label htmlFor="title">Title</Label>
349
- <Input id="title" name="title" />
350
- {error('title') && <p className="text-destructive">{error('title')}</p>}
351
-
352
- <Select name="kind">
353
- <SelectTrigger><SelectValue /></SelectTrigger>
354
- <SelectContent>
355
- <SelectItem value="post">Post</SelectItem>
356
- </SelectContent>
357
- </Select>
358
-
359
- <Checkbox name="draft" />
360
-
361
- <Button disabled={pending}>{pending ? 'Saving…' : 'Save'}</Button>
362
- </>
363
- )}
239
+ <Form action={resize} fields={['size', 'copies']}>
240
+ {({ error }) => error('size')} {/* error('sise') fails the typecheck */}
364
241
  </Form>
365
242
  ```
366
243
 
367
- `Input`, `Textarea`, `Button` and `Label` are styled native elements, so `name`
368
- does what it always does.
369
-
370
- **`Select`, `Checkbox`, `Switch` and `RadioGroup` also work**, whether your
371
- shadcn is built on Base UI or on Radix. Both render a hidden native control
372
- whenever you give the component a `name`, for exactly this. Omit the `name` and
373
- it is invisible to the form; that is the only thing to remember.
374
-
375
- A pick in a Base UI `Select` changes its hidden control without firing an
376
- event. `<Form>` watches its own controls, so `dirty` and `valid()` still see
377
- the change.
244
+ `fields` adds to the action's own names and `defaultValues`. It is types only.
245
+ It also names a field the backend reports under a different spelling, such as
246
+ an untagged Go field `Host` reported as `host`, though tagging the struct
247
+ (`json:"host"`) is the cleaner fix.
378
248
 
379
- :::caution[Not shadcn's own `<Form>`]
380
- shadcn's `<Form>`, `<FormField>` and `<FormControl>` are wrappers around
381
- [react-hook-form](https://react-hook-form.com), which is a different system for
382
- the same job — its own state, its own validation, its own submit. Use one or
383
- the other, not both.
384
-
385
- Ours gives you the field errors the *server* returned, which is the half a
386
- client-side library cannot do.
387
- :::
388
-
389
- ### shadcn's `Field` components
390
-
391
- The newer `Field`, `FieldLabel`, `FieldError` and `FieldGroup` are plain
392
- presentational components — they take props rather than reading a form
393
- library's context, which is what the older `<FormField>` did. So they work here
394
- directly:
249
+ A component below the form types its prop with `FieldNamesOf`:
395
250
 
396
251
  ```tsx
397
- <Form action={reportBug} schema={formSchema}>
398
- {({ pending, error }) => (
399
- <FieldGroup>
400
- <Field data-invalid={!!error('title')}>
401
- <FieldLabel htmlFor="title">Bug title</FieldLabel>
402
- <Input id="title" name="title" aria-invalid={!!error('title')} />
403
- <FieldDescription>Keep it short and specific.</FieldDescription>
404
- <FieldError>{error('title')}</FieldError>
405
- </Field>
252
+ import type { FieldNamesOf } from '@rsc-kit/core/form'
406
253
 
407
- <Button type="submit" disabled={pending}>
408
- {pending ? 'Sending…' : 'Submit'}
409
- </Button>
410
- </FieldGroup>
411
- )}
412
- </Form>
254
+ type Props = { name: FieldNamesOf<typeof orders.create> }
413
255
  ```
414
256
 
415
- `FieldError` renders its children, and renders nothing when there are none —
416
- so `error('title')` goes straight in. Everything else is the same markup you
417
- would write with any other form library.
418
-
419
- The difference is where the errors came from. With TanStack Form or
420
- react-hook-form those are the *client's* validation; here `error()` answers with
421
- the client's **and** whatever the server sent back, because a refused action
422
- returns its fields rather than throwing them away.
423
-
424
- ### Setting the values
257
+ ## Setting the values
425
258
 
426
- The fields are uncontrolled, so an initial value is `defaultValue` — React's
427
- own, nothing of ours:
259
+ An initial value is React's own `defaultValue`:
428
260
 
429
261
  ```tsx
430
262
  <Input id="title" name="title" defaultValue={post.title} />
431
263
  ```
432
264
 
433
- After a refused submit the values are still there, because the DOM kept them:
434
- nothing re-rendered the inputs, so nobody typed twice. That is the upside of
435
- not owning the value.
265
+ After a refused submit the values are still there, because nothing re-rendered
266
+ the inputs.
436
267
 
437
- The exception is a submit that happened **before hydration**, where the page
438
- genuinely reloads. Then the server renders the page again, and putting the
439
- values back is the server's job — return them from the action and render them
440
- as `defaultValue`.
268
+ The exception is a submit made before the page's JavaScript loaded, which
269
+ reloads the page. The server renders the page again, so return the values from
270
+ the action and render them as `defaultValue`.
441
271
 
442
- ### The schema is written for the shape it wants
272
+ ## How the values are read
443
273
 
444
- Every value in a `FormData` is a string or a file, and a control that is off
445
- is not there at all — a fact that used to leak into every schema as
446
- `z.coerce.number()` and a per-checkbox `.transform()`. It does not any more.
447
- The form is read *the way the schema means it*, on both sides:
274
+ Write the schema for the values you want, not for the strings a form posts:
448
275
 
449
276
  ```ts
450
277
  const settings = z.object({
@@ -463,29 +290,31 @@ const settings = z.object({
463
290
  })
464
291
  ```
465
292
 
466
- Nothing in that schema knows it will meet a form. A schema describes itself
467
- (Standard JSON Schema — Zod 4 and ArkType do; Valibot not yet, and its
468
- values arrive as strings), and the decoder coerces to it: an absent
469
- `boolean` is `false`, `"on"`/`"1"` is `true`; a numeric string for a
470
- `number` is the number, an empty one for an optional number is absent; an
471
- `array` given one value is a list of one and given nothing is empty; nested
472
- names nest (`fields[0][name]` and `fields[0].name` alike); a union takes the
473
- branch its discriminator names; a control left blank is absent for a field
474
- the schema does not require, whatever its type — `z.email().optional()`
475
- accepts the empty input, an optional union is not read as its first branch
476
- — and is `""` for one it requires, so `z.string().min(1)` can say so. A value the schema refuses is still refused as itself — `"many"` for a
477
- number is the error you expect.
478
-
479
- A leaf JSON Schema cannot describe — `z.date()`, a custom check — costs only
480
- that leaf, which arrives as posted; the fields beside it are still read the
481
- way the schema means. A schema that cannot describe itself at all is said
482
- once, in development, with the library's reason.
483
-
484
- `<Form>` validates that object in the browser and the action decodes the
485
- same object on the server, from one codec, so a form that passes here passes
486
- there. A value sent through `<Form transform>` is encoded the same way back
487
- — a boolean as `"1"`/`"0"`, a nested object as `key[prop]` — and decodes to
488
- what was given.
293
+ No `z.coerce.number()` and no `.transform()` per checkbox. The form is read the
294
+ way the schema describes it, in the browser and again in the action:
295
+
296
+ - A `boolean` that is absent is `false`. `"on"` or `"1"` is `true`.
297
+ - A numeric string for a `number` is the number. An empty one for an optional
298
+ number is absent.
299
+ - An `array` given one value is a list of one, and given nothing is empty.
300
+ - Nested names nest: `fields[0][name]` and `fields[0].name` alike.
301
+ - A union takes the branch its discriminator names.
302
+ - A blank control is absent for a field the schema doesn't require, so
303
+ `z.email().optional()` accepts an empty input. It is `""` for a field the
304
+ schema requires, so `z.string().min(1)` can refuse it.
305
+ - A value the schema refuses is refused as it was posted: `"many"` for a number
306
+ is the error you expect.
307
+
308
+ This needs a schema that describes itself (Standard JSON Schema). Zod 4 and
309
+ ArkType do. Valibot doesn't yet, and its values arrive as strings. A part the
310
+ JSON Schema can't describe, such as `z.date()` or a custom check, arrives as
311
+ posted, and the rest of the form is still read normally. A schema that can't
312
+ describe itself at all is reported once in development, with the library's
313
+ reason.
314
+
315
+ A value sent through `<Form transform>` is encoded the same way back, a boolean
316
+ as `"1"`/`"0"` and a nested object as `key[prop]`, and decodes to what was
317
+ given.
489
318
 
490
319
  ### Lists of values
491
320
 
@@ -497,17 +326,16 @@ A repeated name is an array:
497
326
  // → { tags: ['react', 'vite'] }
498
327
  ```
499
328
 
500
- With one ticked that is `'react'`, a string — which no `z.array()` will accept.
501
- So for anything that is a list by nature, end the name in `[]` and it is always
502
- an array:
329
+ With only one ticked, that is the string `'react'`, which `z.array()` refuses.
330
+ End the name in `[]` and it is always an array:
503
331
 
504
332
  ```tsx
505
333
  <Checkbox name="tags[]" value="react" />
506
334
  // → { tags: ['react'] }
507
335
  ```
508
336
 
509
- The brackets are dropped from the key, and it is the same spelling a value is
510
- serialised back into — so a list survives a round trip.
337
+ The brackets are dropped from the key, and a value is written back the same
338
+ way, so a list survives a round trip.
511
339
 
512
340
  ### Nested and repeating groups
513
341
 
@@ -519,11 +347,10 @@ Names that describe a shape build it:
519
347
  <input name="items[0][name]" /> // the same field, other spelling
520
348
  ```
521
349
 
522
- Which is the shape your schema was written against — and the shape whose errors
523
- come back keyed the same way, because Standard Schema issue paths join with
524
- dots too. A refused `address.city` is `error('address.city')`.
350
+ Errors come back under the same paths: a refused `address.city` is
351
+ `error('address.city')`.
525
352
 
526
- Rows you add and remove are ordinary state; only the *names* have to line up:
353
+ Rows you add and remove are ordinary state. Only the names have to line up:
527
354
 
528
355
  ```tsx
529
356
  {rows.map((row, i) => (
@@ -531,85 +358,43 @@ Rows you add and remove are ordinary state; only the *names* have to line up:
531
358
  ))}
532
359
  ```
533
360
 
534
- ### Controlling one field
361
+ ## When fields are checked
535
362
 
536
- Most fields need nothing — the DOM holds the value and it is read back on
537
- submit. Two cases need more: a control with no native element behind it, and a
538
- value you want to show *as it is typed*.
363
+ **A field is checked when it is left, not as it is typed**, and when the form is
364
+ submitted. So `error()` has nothing for a field nobody has reached yet, and
365
+ there's no separate "touched" state to check.
539
366
 
540
- `field(name)` is for both. Spread it, the same way you would spread
541
- react-hook-form's `<Controller>` render props:
367
+ The form listens for `focusout` itself, so a plain `<Input name="title" />` is
368
+ covered without binding it.
542
369
 
543
- ```tsx
544
- <Form action={reportBug} schema={formSchema} defaultValues={{ description: '' }}>
545
- {({ field, error }) => (
546
- <Field data-invalid={!!error('description')}>
547
- <FieldLabel htmlFor="description">Description</FieldLabel>
548
-
549
- <InputGroup>
550
- <InputGroupTextarea id="description" {...field('description')} rows={6} />
551
- <InputGroupAddon align="block-end">
552
- <InputGroupText>{field('description').value.length}/100 characters</InputGroupText>
553
- </InputGroupAddon>
554
- </InputGroup>
555
-
556
- <FieldError>{error('description')}</FieldError>
557
- </Field>
558
- )}
559
- </Form>
560
- ```
561
-
562
- It gives you `{ name, value, onChange, onBlur }` — the same four things
563
- `<Controller>` does, for the same reason.
564
-
565
- `onChange` takes either a DOM event or a bare value, so a native input and a
566
- `Select` from Base UI or Radix both work without a wrapper. A bound field is still an ordinary
567
- named input, so it arrives in `FormData` with everything else: there is one
568
- source of truth, and nothing merges.
370
+ ### Checking with the server before submit
569
371
 
570
- Mix freely. Bind the one field that needs a character count and leave the rest
571
- alone.
372
+ When a field is left **having changed**, the form asks the server to check it.
373
+ The action's guards and validation run for that field, and the action itself
374
+ doesn't. The answer shows on `error()` like any other. This catches what a
375
+ schema in the browser can't know, such as an email that is already subscribed
376
+ or a coupon that has expired.
572
377
 
573
- ### When a field is checked
378
+ There's nothing to turn on. The actions that can be asked:
574
379
 
575
- **A field is checked when it is left, not as it is typed.** An error that
576
- appears while someone is halfway through an email address is a form arguing
577
- with them; leaving the field is the moment they have finished saying what they
578
- meant. So `error()` has nothing for a field nobody has reached yet, and there is
579
- no separate "touched" to consult before showing it.
580
-
581
- It works on ordinary uncontrolled fields too — the form listens for `focusout`
582
- rather than each field listening for `blur`, so `<Input name="title" />` is
583
- covered without being bound to anything.
584
-
585
- ### Checked by the server before it is submitted
586
-
587
- A schema in the browser cannot know that an email is already subscribed, or
588
- that a coupon has expired. The server can, and `<Form>` asks it: when a field
589
- is left **having changed**, the form sends what it holds to the action marked
590
- as a check. The action's guards and validation run for that field; the action
591
- itself does not. Its answer lands on `error()` like any other.
592
-
593
- Nothing to opt into. Which actions can be asked:
594
-
595
- - a `createActionClient()` action with an input schema - its middleware and
596
- schema run, its handler is skipped;
597
- - a backend function the backend says it can check without running - in
598
- Laravel, any action whose first parameter is a form request (its
599
- `authorize()` and `rules()`, filtered to the field, as Laravel's
600
- Precognition does);
601
- - nothing else. A plain `"use server"` function cannot be stopped before its
380
+ - a `createActionClient()` action with an input schema. Its middleware and
381
+ schema run, and its handler is skipped.
382
+ - a backend function the backend can check without running it. In Laravel,
383
+ that is any action whose first parameter is a form request: its
384
+ `authorize()` and `rules()` run, filtered to the field, as Laravel's
385
+ Precognition does.
386
+ - nothing else. A plain `"use server"` function can't be stopped before its
602
387
  body, so it is never called to check, and the form stops asking after the
603
388
  first answer says so.
604
389
 
605
- A field the browser's schema already refuses costs no round trip, a field
606
- passed through without being changed is not asked about again, and a file goes
607
- only when its own field is the one being checked.
390
+ A field the browser's schema already refuses isn't sent. A field left without
391
+ being changed isn't asked about again. A file is sent only when its own field
392
+ is the one being checked.
608
393
 
609
394
  #### When a blur is not the moment
610
395
 
611
- `validate()` asks now, about the fields you name - or every field, with none.
612
- It resolves `true` when they pass. That is a wizard's step:
396
+ `validate()` asks now, about the fields you name, or every field with none. It
397
+ resolves `true` when they pass. Use it for a wizard's steps:
613
398
 
614
399
  ```tsx
615
400
  <Form action={register}>
@@ -635,19 +420,18 @@ It resolves `true` when they pass. That is a wizard's step:
635
420
  </Form>
636
421
  ```
637
422
 
638
- A step's fields stay in the form while hidden (render them with `hidden`
639
- rather than not at all), so the last step's submit sends every one.
640
-
641
- `*` stands for one segment of a nested name, as in Laravel: `validate('items.*.sku')`.
642
- For a field checked as it is typed, call `validate('handle')` from its
643
- `onChange` - and debounce it yourself; the form does not decide how often you
644
- may ask.
423
+ Keep each step's fields in the form while hidden (render them with `hidden`, not
424
+ conditionally), so the last step's submit sends every one.
645
425
 
646
- `validating` is true while a check is out. `valid(name)` is true once a check
647
- of that field passed and it has not been edited since - for a tick beside it,
648
- not for deciding anything.
426
+ - `*` stands for one segment of a nested name, as in Laravel:
427
+ `validate('items.*.sku')`.
428
+ - To check a field as it is typed, call `validate('handle')` from its
429
+ `onChange`, and debounce it yourself.
430
+ - `validating` is `true` while a check is out.
431
+ - `valid(name)` is `true` once a check of that field passed and it hasn't been
432
+ edited since. Use it for a tick beside the field, not for deciding anything.
649
433
 
650
- ### After a successful submit
434
+ ## After a successful submit
651
435
 
652
436
  ```tsx
653
437
  {({ succeeded, recentlySucceeded }) => (
@@ -655,12 +439,10 @@ not for deciding anything.
655
439
  )}
656
440
  ```
657
441
 
658
- `recentlySucceeded` is the same thing for two seconds — the tick that appears
659
- and fades. It is state rather than a timer in every form that wants one,
660
- because the timer has to be cleared when the component goes away and that is
661
- the part people forget.
442
+ `recentlySucceeded` is `succeeded` for two seconds only, for a tick that
443
+ appears and fades. The form clears the timer when the component goes away.
662
444
 
663
- ### Nothing to save yet
445
+ ## Disabling save until something changes
664
446
 
665
447
  ```tsx
666
448
  {({ dirty, reset }) => (
@@ -671,42 +453,49 @@ the part people forget.
671
453
  )}
672
454
  ```
673
455
 
674
- `dirty` is whether anything differs from what the form started with. It is
675
- read from the form itself — a snapshot of its `FormData` on mount, compared
676
- on every input — so an uncontrolled field counts, which is the reason it is
677
- the form's to answer and not something a component beside it could work
678
- out. A successful submit makes the current values the new baseline;
679
- `reset()` goes back to the first one. A bound control with no native
680
- element behind it counts too, through the store. Only a form that reads
681
- `dirty` is measured, and it renders once when the value first differs — not
682
- on the keystrokes after — so a field that subscribes for itself keeps its
683
- promise of rendering alone.
456
+ `dirty` is whether any value differs from what the form started with,
457
+ uncontrolled fields included. A successful submit makes the current values the
458
+ new starting point, and `reset()` goes back to the first one.
684
459
 
685
- ### Why not a `<Field>` component
460
+ A form only measures `dirty` when something reads it, and it renders once when
461
+ the value first differs, not on every keystroke after.
686
462
 
687
- TanStack Form and react-hook-form both hand you a field through a render prop —
688
- `<form.Field name="title" children={…}>`, `<Controller render={…}>`. It looks
689
- like the more capable design, and the reason they need it is worth being precise
690
- about, because the three of us are not in the same position.
463
+ ## Controlling one field
691
464
 
692
- **TanStack Form is controlled-first.** Every value lives in form state, so
693
- without per-field subscriptions one keystroke would re-render every field. The
694
- render prop is what scopes that, and the verbosity is the price of it.
465
+ Bind a field with `field(name)` when it has no native element behind it, or
466
+ when you want to show its value as it's typed:
695
467
 
696
- **react-hook-form is uncontrolled-first**, like this. Its `register` is refs, not
697
- state, so typing re-renders nothing — and `<Controller>` is the opt-in for the
698
- fields that cannot work that way. The render prop there is doing something
699
- narrower: it scopes the re-render of a *controlled* field to that field alone.
468
+ ```tsx
469
+ <Form action={reportBug} schema={formSchema} defaultValues={{ description: '' }}>
470
+ {({ field, error }) => (
471
+ <Field data-invalid={!!error('description')}>
472
+ <FieldLabel htmlFor="description">Description</FieldLabel>
700
473
 
701
- So the architecture here is react-hook-form's. The difference is what the
702
- controlled opt-in costs: `field()` is a function call rather than a render prop,
703
- which keeps the markup flat and means a bound field re-renders this component
704
- rather than only itself.
474
+ <InputGroup>
475
+ <InputGroupTextarea id="description" {...field('description')} rows={6} />
476
+ <InputGroupAddon align="block-end">
477
+ <InputGroupText>{field('description').value.length}/100 characters</InputGroupText>
478
+ </InputGroupAddon>
479
+ </InputGroup>
705
480
 
706
- That is the right trade for the number of controlled fields a form usually has —
707
- one or two, for a character count or a control with no native element.
481
+ <FieldError>{error('description')}</FieldError>
482
+ </Field>
483
+ )}
484
+ </Form>
485
+ ```
486
+
487
+ `field()` returns `{ name, value, onChange, onBlur }`, like react-hook-form's
488
+ `<Controller>`. `onChange` takes a DOM event or a bare value, so a native input
489
+ and a Base UI or Radix `Select` both work without a wrapper. A bound field is
490
+ still a named input, so it is submitted with everything else.
491
+
492
+ Bind only the fields that need it and leave the rest alone.
493
+
494
+ ### In its own component
708
495
 
709
- When it is not, put the field in its own component and subscribe there:
496
+ `field()` re-renders the component holding the form. When a form is large, put
497
+ the field in its own component with `useField`, which re-renders that component
498
+ and nothing else:
710
499
 
711
500
  ```tsx
712
501
  import { useField } from '@rsc-kit/core/form'
@@ -718,19 +507,9 @@ function Title() {
718
507
  }
719
508
  ```
720
509
 
721
- The same two words, for one name: `field` to spread, `error` to show.
510
+ ### Reading a value from elsewhere
722
511
 
723
- `useField` re-renders **that component and nothing else** — not the form, not
724
- its siblings. Which is what `<Controller>` achieves with a render prop, except
725
- that the component you were going to write anyway is the boundary.
726
-
727
- So the scoping is there when a form is large enough to need it, and the flat
728
- markup is there when it is not.
729
-
730
- ### Reading the values from elsewhere
731
-
732
- A preview, a summary, a count — something that shows a value without being the
733
- field — reads it the same way the field does:
512
+ A preview, a summary or a count reads a value the same way:
734
513
 
735
514
  ```tsx
736
515
  function Preview() {
@@ -740,27 +519,12 @@ function Preview() {
740
519
  }
741
520
  ```
742
521
 
743
- Only a **bound** value can be read this way. An uncontrolled input's value
744
- belongs to the DOM, and nothing can know it changed without listening to it —
745
- bind the field with `field()` or `useField` and it can be read.
522
+ Only a bound field can be read this way. An uncontrolled input's value is in
523
+ the DOM, so bind it with `field()` or `useField` first.
746
524
 
747
- :::note[Inside the form, not outside it]
748
- `useForm()` and `useField()` read a context, so they work anywhere below `<Form>`. That is usually
749
- enough, because the `<form>` element can wrap as much of the page as you like,
750
- and a submit button outside it is `form="the-id"`.
751
-
752
- Worth knowing what the alternatives do here, because it is not as different as
753
- it looks. Reaching a form from another component is a context in all three:
754
- react-hook-form has `<FormProvider>` and `useFormContext()`, and TanStack Form
755
- has `createFormHookContexts()` with `useFormContext()` — which its own
756
- documentation calls a bridge for integration constraints, to be avoided when
757
- passing the form as a prop is possible. Ours needs no extra provider only
758
- because `<Form>` already is one.
759
-
760
- Where they are genuinely more flexible is *where the state is created*: their
761
- `useForm()` is called by you, so it can be hoisted as far up as you like. For
762
- the case where that matters — something that is not a descendant — create the
763
- store yourself and hand it to the form:
525
+ `useForm()` and `useField()` work anywhere below `<Form>`. A submit button
526
+ outside the `<form>` element can use `form="the-id"`. For a component that isn't
527
+ below the form at all, create the store yourself and pass it to both:
764
528
 
765
529
  ```tsx
766
530
  function Page() {
@@ -781,44 +545,258 @@ function TopBar({ store }) {
781
545
  }
782
546
  ```
783
547
 
784
- `useFormStore` is the values and nothing else — no submit, no errors, no
785
- optimistic updates. Creating it does not subscribe to it, so the component
786
- holding it does not re-render on every keystroke and take the whole subtree
787
- with it.
548
+ `useFormStore` holds the values only: no submit, no errors. Creating it doesn't
549
+ subscribe to it, so the component holding it doesn't re-render on every
550
+ keystroke.
551
+
552
+ ## Optimistic updates
553
+
554
+ Pass `optimistic` and update React's `useOptimistic` state in it. It runs
555
+ inside the transition, so React reverts it if the action fails:
556
+
557
+ ```tsx title="TodoList.tsx"
558
+ "use client";
559
+
560
+ import { useOptimistic } from "react";
561
+ import { Form } from "@rsc-kit/core/form";
562
+ import { addTodo } from "./actions";
563
+
564
+ type Todo = { id: number; title: string; done: boolean };
565
+
566
+ export default function TodoList({ todos }: { todos: Todo[] }) {
567
+ const [optimisticTodos, addOptimistic] = useOptimistic(
568
+ todos,
569
+ (state, newTodo: Todo) => [...state, newTodo]
570
+ );
571
+
572
+ return (
573
+ <div>
574
+ <ul>
575
+ {optimisticTodos.map((todo) => (
576
+ <li key={todo.id}>{todo.title}</li>
577
+ ))}
578
+ </ul>
579
+
580
+ <Form
581
+ action={addTodo}
582
+ optimistic={(data) =>
583
+ addOptimistic({ id: Date.now(), title: data.title as string, done: false })
584
+ }
585
+ >
586
+ <input name="title" />
587
+ <button>Add</button>
588
+ </Form>
589
+ </div>
590
+ );
591
+ }
592
+ ```
593
+
594
+ ## Stopping bots
595
+
596
+ Put `<Honeypot />` inside the form:
597
+
598
+ ```tsx
599
+ import { Form } from '@rsc-kit/core/form'
600
+ import { Honeypot } from '@rsc-kit/core/honeypot'
601
+
602
+ <Form action={subscribe}>
603
+ <input name="email" type="email" />
604
+ <Honeypot />
605
+ <button>Subscribe</button>
606
+ </Form>
607
+ ```
608
+
609
+ It renders a field people never see. It is off screen, out of the tab order,
610
+ hidden from screen readers and not autofilled. A bot that fills in every input
611
+ fills that one too. Its post is answered as though it worked and dropped before
612
+ the action runs, so the action never sees it and the bot learns nothing.
613
+
614
+ - It works in any form that posts to a server action: `<Form>`, a plain
615
+ `<form action={…}>`, with JavaScript or without, and for a `"use server"`
616
+ function or a Laravel or Go action. The check happens in the renderer,
617
+ before the call reaches the backend.
618
+ - The trap is taken out of the form either way, so the action sees only the
619
+ fields a person filled in.
620
+ - The field is named `homepage`. `<Honeypot name="website" />` picks another
621
+ name, if the form has a real field called `homepage`. Forms without
622
+ `<Honeypot />` are not checked, so a `homepage` field elsewhere is ordinary.
623
+
624
+ It stops the crudest spam, not a determined attacker. A form worth attacking
625
+ wants a rate limit on its action as well, such as Laravel's `throttle`
626
+ middleware on the action class. [Blueprints](/guides/blueprints/#stopping-bots)
627
+ show it, and [protecting a server action](/guides/authorization/#protect-a-server-action)
628
+ covers guarding one written in JavaScript.
629
+
630
+ ## Search and filter forms
631
+
632
+ When `action` is a URL, the form navigates to it with the fields as the query
633
+ string, without a full page reload:
788
634
 
789
- `useField(name, store)` takes one explicitly; without one it reads the context,
790
- which is what almost every form wants.
635
+ ```tsx title="SearchForm.tsx"
636
+ "use client";
637
+
638
+ import { Form } from "@rsc-kit/core/form";
639
+
640
+ export default function SearchForm() {
641
+ return (
642
+ <Form action="/search" method="get" prefetch="hover">
643
+ <input name="q" placeholder="Search..." />
644
+ <select name="sort">
645
+ <option value="relevance">Relevance</option>
646
+ <option value="date">Date</option>
647
+ </select>
648
+ <button>Search</button>
649
+ </Form>
650
+ );
651
+ }
652
+ ```
653
+
654
+ This goes to `/search?q=hello&sort=date`, and the nearest Suspense boundary
655
+ streams in the results. With `prefetch="hover"`, hovering the submit button
656
+ starts loading the page.
657
+
658
+ ### A search on the page it is on
659
+
660
+ When the form's `action` is the page the visitor is on, the page stays on
661
+ screen while the query runs, and the new results replace the old ones when
662
+ they arrive. The input keeps what was typed, a Suspense boundary already
663
+ showing content keeps showing it, and Back returns to the previous query.
664
+
665
+ `pending` stays `true` until the new results are on screen:
666
+
667
+ ```tsx title="Lookup.tsx"
668
+ "use client";
669
+
670
+ import { Form } from "@rsc-kit/core/form";
671
+
672
+ export default function Lookup() {
673
+ return (
674
+ <Form action="/lookup" method="get">
675
+ {({ pending }) => (
676
+ <>
677
+ <input name="q" />
678
+ <button disabled={pending}>{pending ? "Searching…" : "Search"}</button>
679
+ </>
680
+ )}
681
+ </Form>
682
+ );
683
+ }
684
+ ```
685
+
686
+ To show a skeleton instead of the old results, style them from the form's
687
+ `data-pending` attribute. The results can stay outside the form, with no client
688
+ component for them:
689
+
690
+ ```css
691
+ #results-skeleton { display: none }
692
+ section:has(form[data-pending]) #results { display: none }
693
+ section:has(form[data-pending]) #results-skeleton { display: block }
694
+ ```
695
+
696
+ Only a `<Form>` does this. A `<Link>` or `visit()` to the same path with another
697
+ query loads it as a new page. The form doesn't prefetch the page it is already
698
+ on.
699
+
700
+ ## Using it with shadcn/ui
701
+
702
+ shadcn's inputs work as they are, because `<Form>` reads the form's native
703
+ `FormData`:
704
+
705
+ ```tsx
706
+ <Form action={createPost} schema={schema}>
707
+ {({ pending, error }) => (
708
+ <>
709
+ <Label htmlFor="title">Title</Label>
710
+ <Input id="title" name="title" />
711
+ {error('title') && <p className="text-destructive">{error('title')}</p>}
712
+
713
+ <Select name="kind">
714
+ <SelectTrigger><SelectValue /></SelectTrigger>
715
+ <SelectContent>
716
+ <SelectItem value="post">Post</SelectItem>
717
+ </SelectContent>
718
+ </Select>
719
+
720
+ <Checkbox name="draft" />
721
+
722
+ <Button disabled={pending}>{pending ? 'Saving…' : 'Save'}</Button>
723
+ </>
724
+ )}
725
+ </Form>
726
+ ```
727
+
728
+ - `Input`, `Textarea`, `Button` and `Label` are styled native elements.
729
+ - **`Select`, `Checkbox`, `Switch` and `RadioGroup` also work**, on Base UI or
730
+ Radix. Each renders a hidden native control when you give it a `name`. Without
731
+ a `name`, the form can't see it.
732
+ - A pick in a Base UI `Select` changes its hidden control without firing an
733
+ event. `<Form>` watches its own controls, so `dirty` and `valid()` still see
734
+ the change.
735
+
736
+ :::caution[Not shadcn's own `<Form>`]
737
+ shadcn's `<Form>`, `<FormField>` and `<FormControl>` wrap
738
+ [react-hook-form](https://react-hook-form.com), which has its own state,
739
+ validation and submit. Use one or the other, not both.
791
740
  :::
792
741
 
742
+ ### shadcn's `Field` components
743
+
744
+ `Field`, `FieldLabel`, `FieldError` and `FieldGroup` take props rather than
745
+ reading a form library's context, so they work directly:
746
+
747
+ ```tsx
748
+ <Form action={reportBug} schema={formSchema}>
749
+ {({ pending, error }) => (
750
+ <FieldGroup>
751
+ <Field data-invalid={!!error('title')}>
752
+ <FieldLabel htmlFor="title">Bug title</FieldLabel>
753
+ <Input id="title" name="title" aria-invalid={!!error('title')} />
754
+ <FieldDescription>Keep it short and specific.</FieldDescription>
755
+ <FieldError>{error('title')}</FieldError>
756
+ </Field>
757
+
758
+ <Button type="submit" disabled={pending}>
759
+ {pending ? 'Sending…' : 'Submit'}
760
+ </Button>
761
+ </FieldGroup>
762
+ )}
763
+ </Form>
764
+ ```
765
+
766
+ `FieldError` renders nothing when it has no children, so `error('title')` goes
767
+ straight in. Unlike with a client-side form library, `error()` includes the
768
+ errors the server sent back.
769
+
793
770
  ## It works before hydration
794
771
 
795
- The action goes on the `<form>` element as well as into the submit handler, so
796
- the markup is submittable on its own. Someone who hits enter before the
797
- javascript arrives still reaches the server; the page reloads with the result
798
- instead of updating in place.
799
-
800
- What happens on the wire: React writes the action's id into the form as a
801
- hidden field and points the form at the page's own url, and the browser
802
- posts there. The host reads the fields, runs the action they name exactly as
803
- the enhanced path would have called it, and renders the page again with what
804
- it returned seated in the form that posted — so a refusal shows on its
805
- fields, `error('email')` included, for a visitor with no
806
- javascript at all. A `redirect()` the action throws is followed as a
807
- document's would be; a cookie it sets is on the answer. Same origin only, as
808
- an action is, and the answer is never stored. A stored page is the one most
809
- likely to be submitted this way — it paints before its runtime arrives —
810
- which is why this is not optional.
811
-
812
- The seating is React's own `useActionState`, which `<Form>` uses under a
813
- wrapper bound to your action: React hands a form-state action a
814
- `(previousState, formData)` pair, and your action keeps taking the
815
- `FormData` alone. A `useActionState` of your own works the same way, with
816
- an action written for the pair.
817
-
818
- The two do not fight. The handler calls `preventDefault()` first, and React does
819
- not run a form action for a submit that was cancelled — so the enhanced path
820
- wins whenever there is one, and the native path is what is left when there is
821
- not.
822
-
823
- Nothing to turn on. It is why the fields are real `name` attributes rather than
824
- controlled state: a browser can read them without help.
772
+ A form can be submitted before the page's JavaScript has loaded. The browser
773
+ posts it, and the page reloads with the result instead of updating in place.
774
+ There is nothing to turn on.
775
+
776
+ - The action runs as it would have otherwise, and a refusal shows on its
777
+ fields, `error('email')` included, for a visitor with no JavaScript at all.
778
+ - A `redirect()` from the action is followed, and a cookie it sets is kept.
779
+ - It is same origin only, as an action is, and the answer is never stored.
780
+
781
+ A stored page is the one most likely to be submitted this way, since it shows
782
+ before its JavaScript arrives. It is also why fields are real `name` attributes
783
+ rather than state: the browser can read them without help.
784
+
785
+ `<Form>` uses React's `useActionState` for this, and your action still takes
786
+ the `FormData` alone. A `useActionState` of your own works too, with an action
787
+ written for `(previousState, formData)`. Once the page has hydrated, the form
788
+ cancels the native submit and handles it itself.
789
+
790
+ ## Coming from react-hook-form or TanStack Form
791
+
792
+ The default is react-hook-form's: fields are uncontrolled, and typing
793
+ re-renders nothing. TanStack Form is controlled-first, so it is the opposite.
794
+
795
+ | | react-hook-form | Here |
796
+ | --- | --- | --- |
797
+ | A plain field | `register('title')` | `name="title"` |
798
+ | A controlled field | `<Controller render={…}>` | `field('title')` |
799
+ | A field that re-renders alone | `<Controller>` | `useField('title')` in its own component |
800
+ | Reaching the form from below | `useFormContext()` | `useForm()` |
801
+ | State created above the form | `useForm()` | `useFormStore()` |
802
+ | Errors from the server | written by hand | `error()`, with the browser's |