@rsc-kit/mcp 0.41.0 → 0.42.0
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.
- package/dist/recipes.js +12 -2
- package/dist/recipes.js.map +1 -1
- package/guides/admin-plugins.md +206 -6
- package/guides/api-routes.md +159 -215
- package/guides/authorization.md +103 -114
- package/guides/backend-answered-pages.md +301 -252
- package/guides/bap-vs-inertia.md +67 -25
- package/guides/blueprints.md +300 -169
- package/guides/bun.md +42 -25
- package/guides/caching.md +46 -49
- package/guides/coming-from-inertia.md +2 -2
- package/guides/commands.md +251 -200
- package/guides/connection.md +50 -54
- package/guides/content-security-policy.md +133 -84
- package/guides/domains.md +190 -149
- package/guides/edge-caching.md +242 -268
- package/guides/emails.md +96 -45
- package/guides/errors.md +116 -137
- package/guides/feature-flags.md +100 -30
- package/guides/file-uploads.md +101 -26
- package/guides/fonts.md +139 -110
- package/guides/forms.md +520 -542
- package/guides/images.md +87 -28
- package/guides/index.json +13 -33
- package/guides/instrumentation.md +134 -95
- package/guides/isr.md +3 -3
- package/guides/live-data-in-production.md +695 -0
- package/guides/live-data.md +170 -839
- package/guides/mcp.md +83 -59
- package/guides/metadata.md +124 -179
- package/guides/navigation.md +118 -147
- package/guides/no-javascript.md +49 -57
- package/guides/offline.md +118 -153
- package/guides/openapi.md +100 -35
- package/guides/pages.md +160 -50
- package/guides/ppr.md +178 -256
- package/guides/pwa.md +251 -218
- package/guides/queries.md +171 -300
- package/guides/react-compiler.md +90 -50
- package/guides/redirects.md +141 -177
- package/guides/response-headers.md +76 -74
- package/guides/route-interception.md +112 -111
- package/guides/routing.md +216 -322
- package/guides/sections.md +63 -66
- package/guides/seo-files.md +127 -65
- package/guides/server-actions.md +285 -357
- package/guides/static-generation.md +131 -199
- package/guides/testing.md +269 -147
- package/guides/third-party-scripts.md +94 -47
- package/guides/typed-routes.md +115 -113
- package/guides/url-validation.md +113 -61
- package/guides/validation.md +53 -62
- package/guides/view-transitions.md +159 -132
- package/guides/where-it-runs.md +226 -162
- package/package.json +2 -2
- package/guides/admin.md +0 -520
- package/guides/deployment.md +0 -598
- package/guides/go.md +0 -539
- package/guides/laravel.md +0 -787
- package/guides/your-own-backend.md +0 -602
package/guides/server-actions.md
CHANGED
|
@@ -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
|
|
6
|
-
the module `"use server"
|
|
7
|
-
|
|
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
|
|
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
|
-
|
|
73
|
-
|
|
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
|
-
|
|
142
|
-
|
|
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
|
-
|
|
152
|
-
|
|
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
|
-
|
|
82
|
+
```tsx
|
|
83
|
+
import * as orders from './server-actions/orders'
|
|
155
84
|
|
|
156
|
-
|
|
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
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
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
|
-
|
|
180
|
-
|
|
181
|
-
|
|
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
|
-
|
|
212
|
-
|
|
213
|
-
`AddOrder
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
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
|
-
//
|
|
254
|
-
//
|
|
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
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
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
|
-
|
|
284
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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.
|
|
312
|
-
the same message, and a page that
|
|
313
|
-
|
|
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
|
-
|
|
316
|
-
|
|
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
|
-
|
|
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
|
|
335
|
-
|
|
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
|
-
###
|
|
232
|
+
### Calling one from a button
|
|
339
233
|
|
|
340
|
-
Without a form, `useAction
|
|
341
|
-
|
|
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
|
|
365
|
-
|
|
366
|
-
- `
|
|
367
|
-
|
|
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
|
|
370
|
-
|
|
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
|
|
374
|
-
- An action that redirected runs no callback and sets no state
|
|
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
|
|
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
|
-
|
|
391
|
-
failure
|
|
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
|
-
|
|
399
|
-
|
|
400
|
-
`
|
|
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
|
|
406
|
-
|
|
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' })`.
|
|
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
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
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
|
-
|
|
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
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
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
|
-
|
|
533
|
-
|
|
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
|
|
412
|
+
where else it works.
|
|
539
413
|
|
|
540
414
|
## A message for the next page
|
|
541
415
|
|
|
542
|
-
|
|
543
|
-
|
|
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
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
A page never reads it, so a stored or edge-cached page stays cacheable.
|
|
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
|
|
585
|
-
|
|
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
|
-
|
|
590
|
-
|
|
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
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
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
|
-
|
|
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
|
-
|
|
621
|
-
together really do overlap — they are not serialised behind one another.
|
|
489
|
+
## Returning UI
|
|
622
490
|
|
|
623
|
-
|
|
624
|
-
|
|
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
|
-
|
|
628
|
-
|
|
494
|
+
```tsx title="src/actions.tsx"
|
|
495
|
+
'use server';
|
|
629
496
|
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
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
|
-
|
|
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
|
-
|
|
663
|
-
|
|
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
|
-
|
|
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
|
-
|
|
668
|
-
the response into an error before the decoder ever sees it:
|
|
590
|
+
## Handling errors
|
|
669
591
|
|
|
670
|
-
|
|
|
671
|
-
| --- | --- |
|
|
672
|
-
|
|
|
673
|
-
|
|
|
674
|
-
|
|
|
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
|
-
|
|
692
|
-
|
|
693
|
-
|
|
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
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
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.
|