@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
@@ -2,9 +2,9 @@
2
2
 
3
3
  > Calling the server from a client component, as an ordinary function.
4
4
 
5
- A server action is an async function a client component can call directly. Mark
6
- the module `"use server"` and its exports become callable from the browser; the
7
- body stays on the server.
5
+ A server action is an async function that a client component calls like any
6
+ other function. It runs on the server. Mark its module `"use server"`, and
7
+ every export can be called from the browser.
8
8
 
9
9
  ## Writing one
10
10
 
@@ -35,11 +35,12 @@ export async function placeOrder(item: string): Promise<{ ok: true }> {
35
35
  ```
36
36
 
37
37
  Nothing is registered and nothing is generated. The build turns each export
38
- into a reference, and the import in a client component resolves to a stub that
39
- performs the call.
38
+ into a reference.
40
39
 
41
40
  ## Calling one
42
41
 
42
+ Import it into a client component and call it:
43
+
43
44
  ```tsx title="src/components/AddOrder.tsx"
44
45
  'use client'
45
46
 
@@ -69,122 +70,34 @@ export function AddOrder() {
69
70
  }
70
71
  ```
71
72
 
72
- `import { placeOrder }` does not pull `actions.ts` into the browser bundle.
73
- Anything that module imports — a database client, a secret — stays on the
74
- server with it.
75
-
76
- ## What happens on the wire
77
-
78
- 1. The client component calls the function.
79
- 2. React serialises the arguments in the Flight format.
80
- 3. The browser sends one `POST /_rsc/action` carrying the action's id and the encoded arguments.
81
- 4. The host decodes them and runs the real function.
82
- 5. The return value is serialised as Flight and streamed back.
83
-
84
- Files travel this way too, without any encoding of your own — see
85
- [File uploads](/guides/file-uploads).
86
-
87
- The id is a hash of the module and the export in a build —
88
- `9396f92f746f#createOrder` — and nothing about the file is in it. In
89
- development it is the module's path as Vite serves it
90
- (`/@fs/Users/…/actions.ts#createOrder`), which is what a
91
- `$ACTION_ID_…` hidden input in a form shows there; a build never carries it.
92
-
93
- ## Returning UI
94
-
95
- Step 5 is the same serialiser a page goes through, so an action can answer
96
- with elements instead of data — server components, client components, Suspense
97
- boundaries — and the caller receives real React elements to render:
98
-
99
- ```tsx title="src/actions.tsx"
100
- 'use server';
101
-
102
- import { Suspense } from 'react';
103
- import { Counter } from './Counter';
104
-
105
- export async function renderCard(name: string) {
106
- return (
107
- <section>
108
- <h2>{name}</h2>
109
- <Counter />
110
- <Suspense fallback={<p>loading…</p>}>
111
- <Related to={name} />
112
- </Suspense>
113
- </section>
114
- );
115
- }
116
- ```
117
-
118
- ```tsx title="src/CardButton.tsx"
119
- 'use client';
120
-
121
- const [ui, setUi] = useState<ReactNode>(null);
122
-
123
- <button onClick={async () => setUi(await renderCard('ada'))}>card</button>
124
- {ui}
125
- ```
126
-
127
- The answer streams. The promise resolves as soon as the root row arrives, so
128
- the card mounts with its fallback showing, and `<Related>` fills the hole when
129
- it is done — the action did not wait for it. The browser never receives
130
- `<Related>`'s code: it ran on the server, and only its output crossed.
131
-
132
- ### Streaming tokens
133
-
134
- That is the primitive behind "generative UI". An async component that renders
135
- one chunk and suspends on the next is a streamed answer, with nothing to
136
- install:
137
-
138
- ```tsx title="src/actions.tsx"
139
- 'use server';
73
+ The import doesn't bring `actions.ts` into the browser bundle. Whatever that
74
+ module imports, such as a database client or a secret, stays on the server.
140
75
 
141
- export async function ask(prompt: string) {
142
- const tokens = model.stream(prompt); // an AsyncIterator<string>
143
-
144
- return (
145
- <Suspense fallback={<p>thinking…</p>}>
146
- <Tokens from={tokens[Symbol.asyncIterator]()} />
147
- </Suspense>
148
- );
149
- }
76
+ Arguments and return values can be anything React can serialize, files
77
+ included. See [File uploads](/guides/file-uploads).
150
78
 
151
- async function Tokens({ from }: { from: AsyncIterator<string> }) {
152
- const { value, done } = await from.next();
79
+ With a Laravel or Go backend, the backend's actions are generated as one
80
+ module per class, and you call them the same way:
153
81
 
154
- if (done) return null;
82
+ ```tsx
83
+ import * as orders from './server-actions/orders'
155
84
 
156
- return (
157
- <>
158
- {value}
159
- <Suspense fallback={null}>
160
- <Tokens from={from} />
161
- </Suspense>
162
- </>
163
- );
164
- }
85
+ await orders.create(form)
165
86
  ```
166
87
 
167
- Each token is a row in the stream and each `<Suspense>` a hole the next one
168
- fills. That is what `createStreamableUI` from Vercel's AI SDK does under the
169
- hood, in Next as here — the same React serialiser.
170
-
171
- Reach for it when the server knows what to render and the client should not:
172
- a card, a chart, a widget. A chat wants data streamed to the client instead
173
- (`streamText` and `useChat` in the AI SDK), because a half-streamed element
174
- tree cannot be cancelled, resumed, retried or persisted, and this one is a
175
- tree as deep as the token count.
88
+ <Aside type="danger" title="An action is a public endpoint">
89
+ Anything exported from a `"use server"` module can be called by anyone who
90
+ can reach your server, without your page. Check who is calling **inside the
91
+ action**. Hiding the button is not a check. See
92
+ [Authorization](/guides/authorization#protect-a-server-action).
93
+ </Aside>
176
94
 
177
95
  ## Refreshing what the action changed
178
96
 
179
- An action that changes data usually makes something on screen wrong. Mark it
180
- stale with `revalidate`, and the re-rendered content travels back **with the
181
- action's own answer**:
182
-
183
- `placeOrder` in the module above does exactly that: it writes the order, then
184
- calls `revalidate('orders')`.
185
-
186
- The tag names a section — a region of the page registered under a name the
187
- server can address on its own:
97
+ Call `revalidate` with the name of what changed. `placeOrder` above writes the
98
+ order and then calls `revalidate('orders')`. The name is a
99
+ [section](/guides/sections), a region of the page the server can render on
100
+ its own:
188
101
 
189
102
  ```tsx title="src/app/orders/orders.section.tsx"
190
103
  import { section } from '@rsc-kit/core/section'
@@ -208,50 +121,42 @@ async function Orders() {
208
121
  export default section('orders', Orders)
209
122
  ```
210
123
 
211
- One request, not two: the caller sees only what its action returned, and the
212
- page updates around it. Nothing else is re-rendered — which is what the second input in
213
- `AddOrder` is there to prove. Type into it, place an order, and
214
- what you typed is still there.
215
-
216
- `section()` is deliberately not a client module. The boundary it wraps things in
217
- is one, but the thing it wraps is a server component that fetches its own data,
218
- and a client reference cannot be async.
219
-
220
- Three things follow from an action that revalidated, and none of them needs
221
- code:
222
-
223
- - **What is re-rendered replaces what is on screen in place.** `revalidate('page')`
224
- and `revalidate('all')` render the same tree a navigation to the page would,
225
- so a form's state, a modal opened from `onSuccess`, a toast in the layout all
226
- survive. A one-time secret shown after the action is still there.
227
- - **The re-render sees the write.** A `cache()`d read the middleware or the
228
- action made before the write is forgotten before the page renders again, so
229
- a renamed row is renamed in the sidebar too, not only in the table.
230
- - **What was fetched before the write is dropped.** Payloads prefetched for
231
- other links and the pages held behind this one for the back button are from
232
- before the mutation. A visit to the list after creating a row fetches the
233
- list, with the row in it, rather than revealing the one prefetched a moment
234
- earlier. `refresh()` does the same.
235
- - **What comes back is for the page it was invoked on.** A tap that left the
236
- page while the action was in flight — Add to cart, then the brand link at
237
- once — changed what is showing, and the trees the host rendered for the
238
- page before are not put under the url after. The page on screen was
239
- fetched before the write, so it is asked for again whole, as `refresh('all')`
240
- would; a modal opened over the page in the meantime does not count as
241
- leaving it.
242
-
243
- ## Building one with a schema and middleware
244
-
245
- A bare `"use server"` function takes whatever it is given and defends itself by
246
- hand. `createActionClient` gives you a shape where the checking, the context
247
- and the types come from one declaration:
124
+ The re-rendered section comes back **with the action's own answer**, in one
125
+ request. Nothing else on the page renders again. Type into the second input in
126
+ `AddOrder`, place an order, and what you typed is still there.
127
+
128
+ `revalidate('page')` re-renders the whole page, and `revalidate('all')` the
129
+ layouts too. Either way:
130
+
131
+ - **What is on screen is updated in place.** A form's state, a modal opened
132
+ from `onSuccess` and a toast in the layout all survive. A one-time secret
133
+ shown after the action is still there.
134
+ - **The new render sees the write.** A `cache()`d read made before the write is
135
+ forgotten, so a renamed row is renamed in the sidebar too, not only in the
136
+ table.
137
+ - **Older prefetches are dropped.** Pages prefetched for other links, and pages
138
+ kept for the back button, are from before the write. Visiting the list after
139
+ creating a row fetches it again, with the row in it. `refresh()` does the
140
+ same.
141
+ - **The answer only applies to the page that sent it.** If the visitor
142
+ navigated away while the action ran, the page now on screen was fetched
143
+ before the write, so it is fetched again whole, as `refresh('all')` would. A
144
+ modal opened over the page in the meantime doesn't count as leaving.
145
+
146
+ `section()` is not a client module: what it wraps is a server component that
147
+ fetches its own data.
148
+
149
+ ## Validating input
150
+
151
+ `createActionClient` builds actions with a schema and middleware, so the
152
+ checks, the context and the types come from one declaration:
248
153
 
249
154
  ```ts title="src/lib/action.ts"
250
155
  import { createActionClient } from '@rsc-kit/core/action';
251
156
 
252
157
  export const action = createActionClient({
253
- // Everything reaching here is a bug or an outage, and its message may name a
254
- // query, a path, a host. Say something fixed unless you raised it yourself.
158
+ // A failure's message may name a query, a path or a host.
159
+ // Show something fixed unless you raised the error yourself.
255
160
  onError: (error) => (error instanceof AppError ? error.message : 'Something went wrong.'),
256
161
  });
257
162
  ```
@@ -275,25 +180,21 @@ export const createPost = action
275
180
  });
276
181
  ```
277
182
 
278
- `input` is typed from the schema and `ctx` from every middleware that ran, so
279
- the handler is checked against both without either being written twice. Add a
280
- `.use()` and the handler's `ctx` grows; change the schema and the handler stops
281
- compiling.
183
+ - `input` is typed from the schema, and `ctx` from every middleware that ran.
184
+ Add a `.use()` and the handler's `ctx` grows; change the schema and the
185
+ handler stops compiling.
186
+ - Middleware runs outermost first and wraps what follows, so a step can time
187
+ or clean up around the rest. Throw to refuse.
188
+ - Return what `next()` gave you. A step that neither calls `next()` nor throws
189
+ is reported as a mistake, since a forgotten `next()` would otherwise look
190
+ like a check that passed.
282
191
 
283
- Middleware runs outermost first and wraps what follows, so a step can time or
284
- clean up around the rest, not only check before it. Throw to refuse.
192
+ This is a different thing from `middleware.ts`, which decides whether a page
193
+ may render. An action can be called without any page, so it defends itself.
285
194
 
286
- Return what `next()` gave you — it carries the value from everything inside. A
287
- step that neither calls `next()` nor throws is reported as a mistake, because a
288
- forgotten `next()` would otherwise look exactly like a check that passed.
289
-
290
- <Aside type="note" title="A different thing from middleware.ts">
291
- `middleware.ts` in a route directory decides whether a page may render. This
292
- wraps one action. They are separate because an action is reachable without
293
- any page — which is why it defends itself.
294
- </Aside>
195
+ ### Reading the result
295
196
 
296
- ### Failures come back, they are not thrown
197
+ An action built this way never throws. It returns an object:
297
198
 
298
199
  ```ts
299
200
  const result = await createPost({ title: 'x', body: 'y' });
@@ -305,40 +206,33 @@ result.refusal // what refuse() carried beside it, typed - see below
305
206
  result.redirected // '/dashboard' - it redirect()ed
306
207
  ```
307
208
 
308
- `serverError` is the backend's own message when the backend turned the call
309
- down rather than failed: a refusal with a status (Go's `Refuse(503, "busy")`,
310
- Laravel's `abort(429)`), not signed in, not allowed, or nothing there. Only a
311
- failure is replaced by `onError`'s. A read built with `.query()` rejects with
312
- the same message, and a page that reads through it answers 401, 403 or its
313
- not-found page, as it would calling the backend directly.
209
+ - `serverError` is the backend's own message when the backend turned the call
210
+ down rather than failed: a refusal with a status (Go's `Refuse(503, "busy")`,
211
+ Laravel's `abort(429)`), not signed in, not allowed, or nothing there. Only a
212
+ failure is replaced by `onError`'s message.
213
+ - A read built with `.query()` rejects with the same message, and a page that
214
+ reads through it answers 401, 403 or its not-found page.
215
+ - An action that `redirect()`s resolves with `redirected` set once the
216
+ navigation has started, and every other field is `undefined`.
217
+ - The argument is typed by the schema, so `createPost({ title: 1 })` fails the
218
+ typecheck. `FormData` is accepted too, which is how a form calls it.
314
219
 
315
- Always an object. An action that `redirect()`s resolves with `redirected` set
316
- once the navigation is under way — the page is on its way elsewhere — and
317
- every other field reads `undefined`, never a `TypeError` inside a transition.
220
+ Failures are returned rather than thrown because React hides a thrown error's
221
+ message in production, so the fields it named would be lost.
318
222
 
319
- The argument is typed by the schema: `createPost({ title: 1 })` fails the
320
- typecheck, and so does `createPost()` when the schema takes input. `FormData`
321
- is accepted beside it, which is how a form calls the same action.
322
-
323
- Returned rather than thrown, and that is not a style choice: React serialises a
324
- rejected server action opaquely — production strips the message and leaves a
325
- digest — so a thrown validation error reaches the browser as "an error
326
- occurred" with the fields it named gone. A returned object crosses intact.
327
-
328
- `<Form>` reads that shape directly, so there is nothing to wire:
223
+ `<Form>` reads this shape directly:
329
224
 
330
225
  ```tsx
331
226
  <Form action={createPost} schema={schema}>
332
227
  ```
333
228
 
334
- The schema then runs twice, in the two places it has to: in the browser so a
335
- mistake costs no round trip, and in the action because the action is a public
336
- endpoint reachable without the form.
229
+ The schema then runs in the browser, so a mistake costs no round trip, and
230
+ again in the action, because the action can be called without the form.
337
231
 
338
- ### From a button
232
+ ### Calling one from a button
339
233
 
340
- Without a form, `useAction` is the transition around the call and the last
341
- result, with callbacks that say which way it went:
234
+ Without a form, use `useAction`. It wraps the call in a transition and keeps
235
+ the last result:
342
236
 
343
237
  ```tsx title="src/app/posts/archive-button.tsx"
344
238
  'use client'
@@ -361,21 +255,19 @@ export function Posts({ posts }) {
361
255
  }
362
256
  ```
363
257
 
364
- - `execute` takes what the action's schema takes, and `onSuccess` is handed
365
- what its handler returned. `executeAsync` resolves with the result.
366
- - `onError` gets a `serverError`, or the first validation message, so a button
367
- with no field beside it still has something to show. `onSettled` runs after
258
+ - `execute` takes what the action's schema takes. `executeAsync` resolves with
259
+ the result.
260
+ - `onSuccess` gets what the handler returned. `onError` gets the
261
+ `serverError`, or the first validation message. `onSettled` runs after
368
262
  either.
369
- - `optimistic` runs inside the action's transition, before the call — where
370
- React's `useOptimistic` setter has to be. A failed action takes the change
371
- back on its own, because the optimistic state ends with the transition.
263
+ - `optimistic` runs inside the transition, before the call. A failed action
264
+ undoes it on its own, because the optimistic state ends with the transition.
372
265
  - Neither call throws. Anything thrown on the way, the network included,
373
- becomes a `serverError`, so the transition always settles.
374
- - An action that redirected runs no callback and sets no state: the page is
375
- leaving.
266
+ becomes a `serverError`.
267
+ - An action that redirected runs no callback and sets no state.
376
268
  - `status` is `"idle"`, `"executing"`, `"hasSucceeded"` or `"hasErrored"`,
377
269
  `result` is the last answer, and `reset()` forgets it. `execute` keeps one
378
- identity across renders, and reads the newest callbacks when it runs.
270
+ identity across renders.
379
271
 
380
272
  ### Failing on something a schema cannot know
381
273
 
@@ -387,23 +279,16 @@ export function Posts({ posts }) {
387
279
  })
388
280
  ```
389
281
 
390
- It arrives as `validationErrors`, on the field you named, exactly like a schema
391
- failure — so the form renders it in the same place with no extra handling.
392
-
393
- `fieldErrors` comes in with the handler's arguments rather than being imported,
394
- and that is what makes it typed: the field names are the schema's, so
395
- `fieldErrors({ slgu: … })` does not compile. There is nothing to pass — the
396
- handler already knows its input.
282
+ The message arrives in `validationErrors` on the field you named, like a schema
283
+ failure, so a form shows it in the same place. The field names are typed from
284
+ the schema: `fieldErrors({ slgu: … })` doesn't compile.
397
285
 
398
- **Write `return fieldErrors(…)`.** It throws either way, so nothing after it
399
- runs — but TypeScript cannot see that from a destructured argument. Without the
400
- `return`, a `user` you checked is still `possibly undefined` on the next line.
401
- With it, the type narrows and the code reads as what it is: this branch is
402
- over. A forgotten `return` is not a runtime bug; it is a type error that tells
403
- you to add one.
286
+ Write `return fieldErrors(…)`. It throws either way, but without the `return`
287
+ TypeScript can't tell that the branch is over, and a value you checked is still
288
+ `possibly undefined` on the next line.
404
289
 
405
- A string is one message; an array is several. The empty key is the whole
406
- submission, for a refusal that is about no field in particular:
290
+ A string is one message and an array is several. The empty key is for a
291
+ message about no field in particular:
407
292
 
408
293
  ```ts
409
294
  return fieldErrors({ '': 'Sign-ups are closed for the weekend' });
@@ -411,16 +296,15 @@ return fieldErrors({ '': 'Sign-ups are closed for the weekend' });
411
296
 
412
297
  :::note[Porting from next-safe-action]
413
298
  `return returnValidationErrors(schema, { email: { _errors: ['Account not found'] } })`
414
- becomes `return fieldErrors({ email: 'Account not found' })`. No schema
415
- argument, because the typing comes from the handler, and no `_errors` nesting.
299
+ becomes `return fieldErrors({ email: 'Account not found' })`.
416
300
  :::
417
301
 
418
302
  ### Refusing, with something to act on
419
303
 
420
- Sometimes the input is fine and the answer is still no: a project that cannot
421
- be deleted while orders are attached, a plan that does not include the
422
- feature. That is a refusal, not a validation error, and the page usually needs
423
- more than a sentence — the orders, as links.
304
+ Sometimes the input is fine and the answer is still no: a project that can't be
305
+ deleted while orders are attached to it. The page usually needs more than a
306
+ sentence, such as links to those orders. Declare what a refusal carries with
307
+ `.refusal()`:
424
308
 
425
309
  ```ts
426
310
  const blockers = z.object({
@@ -450,44 +334,7 @@ result.serverError // 'Still in use'
450
334
  result.refusal?.blockers // [{ id: 7, href: '/orders/7' }], typed from the schema
451
335
  ```
452
336
 
453
- - **The message is always sent.** `refuse()` is deliberate, so its message is
454
- never replaced by `onError`'s "Something went wrong." It is the result's
455
- `serverError`, which is where `<Form>`'s `formError` already reads.
456
- - **The data is checked.** It reaches the page only through the schema given
457
- to `.refusal()`, and is typed from it. Data that does not match is a bug in
458
- the server and is answered as one; data from an action that declares no
459
- schema is not sent, and the server's log says so.
460
- - **From anywhere.** The handler's `refuse` is typed to the schema; the
461
- exported `refuse` from `@rsc-kit/core/action` takes anything, for a
462
- middleware or a helper. A **backend** refuses the same way — Laravel's
463
- `Rsc::refuse()`, Go's `RefuseWith` — and its refusal arrives as the same
464
- `result.refusal`, so a delete the backend turns down at the last moment,
465
- because something was attached a second earlier, still shows its links.
466
- - **One rule for a plain function, a generated stub included:** anything that
467
- did not happen **rejects**, and only a redirect resolves. A refusal is an
468
- `ActionRefusedError`; an input the backend refused, by `fieldErrors()` or a
469
- `ValidationException`, is a `ServerValidationError` with `.fieldErrors` and
470
- `.formErrors` (both from `@rsc-kit/core/errors`). `<Form>` shows either as it
471
- always showed them, and `useAction` returns the fields as `validationErrors`.
472
- So `isRedirected` is the only check a caller needs on what resolved, and a
473
- navigation to the id it expected never runs on bad input.
474
- - **Through a generated stub**, `<Form action={ordersDelete}>`, the message
475
- arrives as `formError`, as the backend wrote it. Awaited directly, the stub
476
- **rejects** with an `ActionRefusedError` (from `@rsc-kit/core/errors`) carrying
477
- the message and the backend's `status`, so a success toast or a navigation to
478
- the id it expected does not run for a write that did not happen; `useAction`
479
- reports it as `serverError`. A backend that turns the caller away is answered
480
- the same way, with its message and a `status` of 401 (not signed in), 403
481
- (not allowed) or 404 (nothing there - Go's `Refuse(404, ...)`, Laravel's
482
- `abort(404)`, or the action's own `notFound()`). An action has no not-found
483
- page, so a 404 is the message, never a 500. Only a redirect resolves, because the page is
484
- already on its way. The data does not travel: a plain function has no
485
- `.refusal(schema)` to check it against, so it is left out and the server's log
486
- says so. To act on the data, call the backend with `rpc()` from an action
487
- built on `createActionClient()` and declare `.refusal(schema)`.
488
-
489
- In a form, `formRefusal` carries the data beside `formError`, and goes when it
490
- does:
337
+ In a form, `formRefusal` carries the data beside `formError`:
491
338
 
492
339
  ```tsx
493
340
  <Form action={deleteProject}>
@@ -502,16 +349,45 @@ does:
502
349
  </Form>
503
350
  ```
504
351
 
505
- `formRefusal` is typed from the form's `action` — its `.refusal(schema)` — so
506
- there is nothing to cast. A component further down reads it with
507
- `useForm<Values, Refusal>()`, and `useAction` hands back the whole result,
508
- `refusal` included.
352
+ - **The message is always sent.** `onError` never replaces it.
353
+ - **The data is checked** against the schema given to `.refusal()`. Data that
354
+ doesn't match is answered as a server bug. An action that declares no schema
355
+ sends no data, and the server's log says so.
356
+ - **Refuse from anywhere.** The handler's `refuse` is typed to the schema. The
357
+ `refuse` exported from `@rsc-kit/core/action` takes anything, for a
358
+ middleware or a helper. A backend refuses the same way, with Laravel's
359
+ `Rsc::refuse()` or Go's `RefuseWith`, and its refusal arrives as the same
360
+ `result.refusal`.
361
+ - **Elsewhere:** `formRefusal` is typed from the form's `action`. A component
362
+ further down reads it with `useForm<Values, Refusal>()`, and `useAction`
363
+ returns the whole result, `refusal` included.
364
+
365
+ ### Plain functions and generated actions
366
+
367
+ A plain `"use server"` function, or a backend's generated action, has no result
368
+ object. **Anything that didn't happen rejects, and only a redirect resolves:**
369
+
370
+ - A refusal rejects with an `ActionRefusedError` carrying the message and the
371
+ backend's `status`. A backend that turns the caller away answers 401 (not
372
+ signed in), 403 (not allowed) or 404 (nothing there: Go's
373
+ `Refuse(404, ...)`, Laravel's `abort(404)`, or the action's own
374
+ `notFound()`). An action has no not-found
375
+ page, so a 404 is the message, never a 500.
376
+ - Input the backend refused, with `fieldErrors()` or a `ValidationException`,
377
+ rejects with a `ServerValidationError` with `.fieldErrors` and `.formErrors`.
378
+ Both errors come from `@rsc-kit/core/errors`.
379
+ - Through a generated stub, `<Form action={orders.delete}>` shows either as it
380
+ always does, the refusal as `formError`, and `useAction` reports it as
381
+ `serverError`.
382
+
383
+ So a success toast or a navigation to an id that never came back doesn't run
384
+ for a write that didn't happen, and `isRedirected` is the only check you need
385
+ on what resolved. A refusal's data isn't sent, since there is no
386
+ `.refusal(schema)` to check it against. To act on it, call the backend with
387
+ `rpc()` from an action built with `createActionClient()` that declares one.
509
388
 
510
389
  ## Setting a cookie
511
390
 
512
- Signing someone in is a mutation whose entire result is a cookie, so an action
513
- can write one:
514
-
515
391
  ```ts
516
392
  'use server';
517
393
 
@@ -529,19 +405,16 @@ export async function login(formData: FormData) {
529
405
  }
530
406
  ```
531
407
 
532
- It lands on the action's own response, so the next navigation already carries
533
- it. `delete` expires one, which is what signing out is.
534
-
535
- That `get`/`set`/`delete` trio is the whole surface an auth library needs, so
536
- one can be wired in without this package having an opinion about which. See
408
+ The cookie is set on the action's response, so the next navigation carries it.
409
+ `delete` expires one, which is what signing out is. `get`, `set` and `delete`
410
+ are all an auth library needs, so you can wire in whichever one you use. See
537
411
  [Writing to the response](/guides/authorization#writing-to-the-response) for
538
- where else it works, and where it does not.
412
+ where else it works.
539
413
 
540
414
  ## A message for the next page
541
415
 
542
- An action's return value goes back to the form that submitted it. When the
543
- action redirects, that form is gone, so "Saved." on the list it lands on is a
544
- one-time message instead:
416
+ When an action redirects, the form that called it is gone. To show "Saved." on
417
+ the page it lands on, flash a one-time message:
545
418
 
546
419
  ```ts
547
420
  'use server';
@@ -557,6 +430,8 @@ export async function saveProduct(formData: FormData) {
557
430
  }
558
431
  ```
559
432
 
433
+ Show it with `useFlash`, in a component you render once in the root layout:
434
+
560
435
  ```tsx title="src/app/toasts.tsx"
561
436
  'use client';
562
437
 
@@ -570,25 +445,23 @@ export function Toasts() {
570
445
  }
571
446
  ```
572
447
 
573
- Render `<Toasts />` once, in the root layout. `kind` is `'success'` (the
574
- default), `'error'`, `'info'` or `'warning'`; two calls are two messages.
575
-
576
- `flash()` sets a cookie, so call it where a cookie can still be set: an action,
577
- middleware or a `route.ts`, not a page. The browser takes it, not the server:
578
- `useFlash` looks when it mounts, after every navigation and, where the browser
579
- supports CookieStore, whenever a response sets it, so an action that stays on
580
- the page shows its message too. Each message is handed over once, then cleared.
581
- A page never reads it, so a stored or edge-cached page stays cacheable. Unread,
582
- it lapses after a minute.
448
+ - `kind` is `'success'` (the default), `'error'`, `'info'` or `'warning'`. Two
449
+ calls are two messages.
450
+ - `flash()` sets a cookie, so call it where a cookie can be set: an action,
451
+ middleware or a `route.ts`, not a page.
452
+ - `useFlash` checks when it mounts, after every navigation and, where the
453
+ browser supports CookieStore, whenever a response sets it, so an action that
454
+ stays on the page shows its message too.
455
+ - Each message is shown once, then cleared. Unread, it lapses after a minute.
456
+ - A page never reads it, so a stored or edge-cached page stays cacheable.
583
457
 
584
- The cookie is readable by script, so it holds a message and never data. Render
585
- the message as text.
458
+ The cookie is readable by script, so put a message in it, never data, and
459
+ render it as text.
586
460
 
587
461
  ## Work the visitor should not wait for
588
462
 
589
- An audit row, a welcome email, a cache warm: the action's answer should not
590
- wait for it, and it must still finish. `after()` queues work to run once the
591
- answer is on its way:
463
+ `after()` runs work once the answer is on its way, such as an audit row or a
464
+ welcome email:
592
465
 
593
466
  ```ts
594
467
  'use server';
@@ -605,73 +478,122 @@ export async function signup(formData: FormData) {
605
478
  }
606
479
  ```
607
480
 
608
- Why not a detached promise: on a long-lived process it happens to run to
609
- completion; on a Worker the isolate is torn down when the response ends
610
- unless the work was handed to the platform's `waitUntil`, so a promise nobody
611
- awaited dies silently — some of the time, which is the worst way. `after()`
612
- is the same call on every host: handed to `waitUntil` where one exists, kept
613
- by the process elsewhere. A rejection is reported to the log and never
614
- reaches the response, which has already gone. It works from a component, a
615
- `middleware.ts`, an api route and an action alike; outside a request — a
616
- build — the work simply runs.
481
+ Don't use a promise you never await instead. On a Worker, the isolate is torn
482
+ down when the response ends, and the work dies some of the time. `after()`
483
+ hands it to the platform's `waitUntil` where there is one, and the process
484
+ keeps it elsewhere. A rejection is logged and never reaches the response.
617
485
 
618
- ## Two at once
486
+ It works in a component, a `middleware.ts`, an API route and an action.
487
+ Outside a request, during a build, the work simply runs.
619
488
 
620
- Nothing queues them. Each call is an ordinary `fetch`, so two submits fired
621
- together really do overlap — they are not serialised behind one another.
489
+ ## Returning UI
622
490
 
623
- That is a difference from Next, which runs one server action at a time per
624
- client — and it is worth being deliberate about, because Next's queue was
625
- doing something for you that you may not have noticed.
491
+ An action can return elements instead of data: server components, client
492
+ components and Suspense boundaries. The caller gets React elements to render:
626
493
 
627
- A double-clicked "add to cart" sends two calls either way. Next runs them one
628
- after the other; here they run together.
494
+ ```tsx title="src/actions.tsx"
495
+ 'use server';
629
496
 
630
- So if a handler reads a value, changes it and writes it back, two of them can
631
- lose an update. That is ordinary database concurrency, which a per-client queue
632
- was quietly absorbing for you. Fix it where you would fix it anywhere else:
497
+ import { Suspense } from 'react';
498
+ import { Counter } from './Counter';
499
+
500
+ export async function renderCard(name: string) {
501
+ return (
502
+ <section>
503
+ <h2>{name}</h2>
504
+ <Counter />
505
+ <Suspense fallback={<p>loading…</p>}>
506
+ <Related to={name} />
507
+ </Suspense>
508
+ </section>
509
+ );
510
+ }
511
+ ```
512
+
513
+ ```tsx title="src/CardButton.tsx"
514
+ 'use client';
515
+
516
+ const [ui, setUi] = useState<ReactNode>(null);
517
+
518
+ <button onClick={async () => setUi(await renderCard('ada'))}>card</button>
519
+ {ui}
520
+ ```
521
+
522
+ The answer streams. The card mounts with its fallback showing, and `<Related>`
523
+ fills in when it is done. The browser never receives `<Related>`'s code, only
524
+ its output.
525
+
526
+ ### Streaming tokens
527
+
528
+ An async component that renders one chunk and suspends on the next streams an
529
+ answer token by token:
530
+
531
+ ```tsx title="src/actions.tsx"
532
+ 'use server';
533
+
534
+ export async function ask(prompt: string) {
535
+ const tokens = model.stream(prompt); // an AsyncIterator<string>
536
+
537
+ return (
538
+ <Suspense fallback={<p>thinking…</p>}>
539
+ <Tokens from={tokens[Symbol.asyncIterator]()} />
540
+ </Suspense>
541
+ );
542
+ }
543
+
544
+ async function Tokens({ from }: { from: AsyncIterator<string> }) {
545
+ const { value, done } = await from.next();
546
+
547
+ if (done) return null;
548
+
549
+ return (
550
+ <>
551
+ {value}
552
+ <Suspense fallback={null}>
553
+ <Tokens from={from} />
554
+ </Suspense>
555
+ </>
556
+ );
557
+ }
558
+ ```
559
+
560
+ This is what `createStreamableUI` from Vercel's AI SDK does, in Next as here.
561
+ Use it when the server decides what to render: a card, a chart, a widget. For a
562
+ chat, stream data instead (`streamText` and `useChat` in the AI SDK): a
563
+ half-streamed element tree can't be cancelled, resumed, retried or saved.
564
+
565
+ ## Two actions at once
566
+
567
+ Two calls fired together run at the same time. Next runs one server action at
568
+ a time per client; rsc-kit doesn't queue them. A double-clicked "add to cart"
569
+ sends two calls either way, and here they overlap.
570
+
571
+ So a handler that reads a value, changes it and writes it back can lose an
572
+ update. Fix it as you would anywhere:
633
573
 
634
574
  - do the read and the write in one transaction
635
575
  - use an atomic update instead of read-modify-write
636
576
  - accept an idempotency key from the form
637
577
 
638
- None of that is new advice. It just stops being optional.
639
-
640
- The engine itself is safe under concurrency, and that part is tested rather
641
- than assumed: two actions running at the same moment each get their own
642
- request scope, so their cookies, headers and revalidation marks never reach
643
- each other's response.
644
-
645
- An action's answer can carry a re-rendered region with it, and applying two of
646
- those is last-response-wins. Two actions that both `revalidate('orders')` will
647
- leave whichever response *arrived* last on screen, which is usually the one
648
- that committed last — but not necessarily, and nothing detects the difference.
649
-
650
- <Aside type="note" title="Why not just order them">
651
- Tagging each call with a sequence number and ignoring the older one sounds
652
- like the fix and is worse than the problem. The order they were *sent* in is
653
- not the order they *committed* in: a slow first action can commit after a
654
- fast second one, and its tree is then the newer state. Rejecting it because
655
- it was sent first shows older data. Only the server knows which write won,
656
- so ordering has to come from there or not at all.
657
- </Aside>
658
-
659
- Fire as many as you like when they touch different things. When several touch
660
- the same region, either let the last answer win or serialise them yourself.
578
+ Each action gets its own request scope, so two at once never mix their
579
+ cookies, headers or revalidations.
661
580
 
662
- `<Form>` gives you `pending` for that. It does not guard itself, so a
663
- double-click sends two requests unless you disable the button.
581
+ When both re-render the same region, the response that arrives last wins.
582
+ That is usually the one that committed last, but not always, and nothing
583
+ detects it. Sorting them by when they were sent would be worse: a slow first
584
+ action can commit after a fast second one. If several actions touch the same
585
+ region, let the last answer win or run them one at a time.
664
586
 
665
- ## Errors
587
+ `<Form>` gives you `pending` for that, but doesn't guard itself: disable the
588
+ button, or a double-click sends two requests.
666
589
 
667
- An action that fails does not answer with a Flight stream, so the client turns
668
- the response into an error before the decoder ever sees it:
590
+ ## Handling errors
669
591
 
670
- | Response | What the client does | What you do |
671
- | --- | --- | --- |
672
- | `X-RSC-Redirect` header | Starts the navigation and **resolves** with `{ redirected }` | Nothing — the page is on its way to the location, and there is nothing to catch. |
673
- | `422` | Throws `ServerValidationError`, carrying `errors` | Show the messages. `<Form>` does it for you. |
674
- | Any other failure | Throws `Error`, naming the status | Whatever the app needs. |
592
+ | The action | The call |
593
+ | --- | --- |
594
+ | redirected | **resolves** with `{ redirected }` and starts the navigation. Nothing to catch. |
595
+ | answered 422 | throws `ServerValidationError`, with the messages in `errors`. `<Form>` shows them. |
596
+ | failed any other way | throws an `Error` naming the status. |
675
597
 
676
598
  ```tsx
677
599
  "use client";
@@ -688,15 +610,21 @@ try {
688
610
  }
689
611
  ```
690
612
 
691
- A redirect is treated as an instruction rather than something to display: an
692
- expired session answers that way, and the right response is the login page, not
693
- a message about one. See [Validation](/guides/validation) for the form-shaped
694
- version of the same flow, which needs no `try`/`catch` at all.
613
+ An expired session answers with a redirect, so the visitor lands on the login
614
+ page rather than seeing a message about it. [Validation](/guides/validation)
615
+ shows the same flow in a form, with no `try`/`catch`.
695
616
 
696
- <Aside type="danger" title="An action is a public endpoint">
697
- The id is not a secret and the endpoint takes no session: anything exported
698
- from a `"use server"` module can be invoked by anyone who can reach your
699
- server. Check the caller **inside the action** — rendering the button
700
- conditionally is a UI decision, not a control. See
701
- [Authorization](/guides/authorization).
702
- </Aside>
617
+ ## How a call travels
618
+
619
+ 1. The client component calls the function.
620
+ 2. React serializes the arguments.
621
+ 3. The browser sends one `POST /_rsc/action` with the action's id and the
622
+ arguments.
623
+ 4. The server decodes them and runs the function.
624
+ 5. The return value is serialized and streamed back.
625
+
626
+ A redirect travels as an `X-RSC-Redirect` header. The id is a hash of the
627
+ module and the export in a build, such as `9396f92f746f#createOrder`, and
628
+ nothing about the file is in it. In development it is the module's path as
629
+ Vite serves it (`/@fs/Users/…/actions.ts#createOrder`), which is what a
630
+ `$ACTION_ID_…` hidden input in a form shows there.