@rsc-kit/mcp 0.40.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.
Files changed (60) hide show
  1. package/dist/recipes.js +37 -20
  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 -250
  7. package/guides/bap-vs-inertia.md +67 -25
  8. package/guides/blueprints.md +307 -174
  9. package/guides/bun.md +42 -25
  10. package/guides/caching.md +46 -49
  11. package/guides/coming-from-inertia.md +5 -5
  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 -538
  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 +251 -218
  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 +272 -150
  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 -538
  59. package/guides/laravel.md +0 -786
  60. package/guides/your-own-backend.md +0 -587
package/guides/go.md DELETED
@@ -1,538 +0,0 @@
1
- # Go
2
-
3
- > A Go process behind the renderer — functions, guards and actions in Go.
4
-
5
- Go owns the request: sessions, auth, the database. The renderer owns
6
- rendering, because that half is React. A server component reaches Go by
7
- calling `rpc()`, which leaves the renderer as an ordinary POST; a `middleware.ts`
8
- names guards Go runs before a page renders; a server action the browser calls
9
- is a Go function the build wrote a stub for.
10
-
11
- A [BAP](/hosts/backend-answered-pages) with Go behind it. There is no
12
- JavaScript to write for Go: the app is what the scaffold writes, and the Go
13
- side is one package answering
14
- [the endpoint every backend answers](/hosts/your-own-backend).
15
-
16
- ```sh
17
- go get github.com/rsc-kit/go
18
- ```
19
-
20
- ## Wiring
21
-
22
- In a Go module, `init` sees `go.mod` and does the JavaScript half — the
23
- project's first `package.json` if it has none, the route tree,
24
- `vite.config.ts`, `.env` with `RSC_BACKEND` and a generated secret, the scripts
25
- — and prints the Go half for you to add. Nothing in the Go module is touched:
26
-
27
- ```sh
28
- bunx rsc-kit@latest init # in the directory with go.mod
29
- bun create rsc-kit@latest my-app --backend=http://127.0.0.1:8080 # or a new app
30
- ```
31
-
32
- What it wrote is two lines, read by `vite` in development and by the built
33
- server in production:
34
-
35
- ```ini title=".env"
36
- RSC_BACKEND=http://127.0.0.1:8080
37
- RSC_HOST_CALL_SECRET=… # openssl rand -base64 32 - see Secrets under Deployment
38
- ```
39
-
40
- And the endpoint, on whatever mux you already have:
41
-
42
- ```go title="main.go"
43
- reg := rsckit.NewRegistry()
44
- // … Register, Middleware, RegisterAction below …
45
-
46
- callback, err := rsckit.NewCallbackHandler(reg, os.Getenv("RSC_HOST_CALL_SECRET"))
47
- if err != nil {
48
- log.Fatal(err) // refuses to exist without a secret
49
- }
50
-
51
- mux := http.NewServeMux()
52
- mux.Handle("POST /__rsc/host-call", callback)
53
-
54
- // PORT when the platform names one, 8080 otherwise, on every address: a
55
- // host that sends backend urls straight here (backendPaths) reaches it at
56
- // the machine's own address, not loopback. RSC_BACKEND stays
57
- // http://127.0.0.1:8080 - the renderer still calls over loopback.
58
- http.ListenAndServe(":"+cmp.Or(os.Getenv("PORT"), "8080"), mux)
59
- ```
60
-
61
- It listens on every address, not loopback alone. Once an app names
62
- [`backendPaths`](/hosts/backend-answered-pages/), a proxy in front may send
63
- those urls straight to the backend at the machine's own address, and a
64
- backend bound to `127.0.0.1` can't be reached. The secret is what guards
65
- the host-call endpoint, and the proxy refuses it from outside
66
- ([deployment](/hosts/deployment/#sending-the-backends-urls-past-the-renderer)).
67
-
68
- The renderer forwards any url its route tree does not own to `RSC_BACKEND`,
69
- so a Go route on that mux — `/login`, a webhook, an upload — is reachable at
70
- the renderer's origin too.
71
-
72
- ### When a page route would match it
73
-
74
- One url, one owner: the route tree has it, or the backend does. A dynamic route
75
- at the root, `[team]/[app]`, has every url of two segments, the backend's
76
- `/gitlab/connect` among them. It renders and says `notFound()`, and a page that
77
- said that is the app's 404, so it is not handed on. Sign-in and an OAuth
78
- callback become a team called `gitlab`.
79
-
80
- Name the prefixes Go owns, and they are forwarded before any page is asked:
81
-
82
- ```ts title="vite.config.ts"
83
- rscKit({ backendPaths: ['/auth', '/github', '/gitlab'] })
84
- ```
85
-
86
- Each is a prefix at a segment boundary: `/auth` is `/auth` and everything under
87
- it, for every method, and never `/authors`. A team called `auth` is then
88
- unreachable, which is the price of the name. `/` and the renderer's own `/_rsc`
89
- are refused where they are written, and with no backend where the server runs
90
- such a url is the app's not-found page. A test reaches it as it does any
91
- backend url, with `createTestApp({ backend })`.
92
-
93
- In the browser a named prefix is never a page. A `Link`, `visit()` or
94
- `redirect('/gitlab/connect')` to it loads the document and is never
95
- prefetched, so the Go route may answer with a redirect to another site, as an
96
- OAuth start does — see [redirects](/guides/redirects/#leaving-the-app).
97
-
98
- ### Running it locally
99
-
100
- Two processes: the Go program, and Vite, which is the renderer in
101
- development. Run Go with `RSC_DEBUG=1`, so a failure says where in Go it
102
- happened:
103
-
104
- ```sh
105
- RSC_DEBUG=1 go run . # the backend, on 127.0.0.1:8080
106
- bun run dev # the renderer; open its address
107
- ```
108
-
109
- Never set `RSC_DEBUG` in production: a trace names your files.
110
-
111
- ### Environment variables
112
-
113
- | Variable | Read by | What it is |
114
- | --- | --- | --- |
115
- | `RSC_BACKEND` | the renderer | Where the Go endpoint is, e.g. `http://127.0.0.1:8080`. Falls back to `APP_URL`. Read from `.env` by `vite`, and from the environment by the built server; the url forwarding is fixed at build time. |
116
- | `RSC_HOST_CALL_SECRET` | both | The shared secret. The renderer sends it; your Go code passes it to `NewCallbackHandler`. Without it neither side talks. |
117
- | `RSC_HOST_CALL_SECRET_PREVIOUS` | Go | The secret being rotated away from, answered as well while set, so a rotation refuses no call. [Rotating one](/hosts/deployment/). |
118
- | `RSC_HOST_CALL_PATH` | the renderer | The endpoint's path. Default `/__rsc/host-call`. |
119
- | `RSC_DEBUG` | Go | `1` sends a failure's trace with its answer. Development only. |
120
- | `RSC_TRUST_FORWARDED` | the renderer | `1` passes the visitor's `X-Forwarded-For` through to Go. Only behind a proxy you control that writes it. |
121
-
122
- The Go adapter reads only `RSC_DEBUG` itself. The secret reaches it through
123
- your code, as above.
124
-
125
- ## Reading from Go
126
-
127
- Register an ordinary Go function with `Handle`, and its types reach the app:
128
-
129
- ```go
130
- reg.Handle("Orders.recent", func(ctx context.Context, limit int) ([]Order, error) {
131
- // The visitor's cookie, forwarded from the page request: this runs as
132
- // them, not as nobody.
133
- return db.RecentOrders(ctx, rsckit.HeadersFrom(ctx).Get("Cookie"), limit)
134
- })
135
- ```
136
-
137
- ```tsx title="src/app/orders/page.tsx"
138
- const orders = await rpc('Orders.recent', 5) // Order[]; rpc('Orders.recent', 'five') fails the typecheck
139
- ```
140
-
141
- - **Any parameters, in order.** `rpc()`'s arguments are bound to the
142
- function's parameters positionally, whatever JSON can carry: numbers,
143
- strings, structs, slices, maps. A leading `context.Context` is the call's.
144
- - **Optional and variadic.** A trailing pointer parameter may be left out
145
- and is `nil`; a variadic one takes the rest.
146
- - **What it returns.** A value and an error, only an error, or only a value.
147
- - **Types for the app.** The parameter and result types are written to
148
- `rsc-host.json` as JSON Schema. The build turns each struct into a
149
- TypeScript interface in the `RscHost` namespace, by its `json` tags:
150
- `omitempty` is optional, a pointer is `| null`, `time.Time` is a string.
151
- A type with its own `MarshalJSON` is `unknown`, since its shape is its own,
152
- unless it says what it writes with a `JSONSchema` method (below).
153
- - **Empty, not null.** A nil slice or map in the result is sent as `[]` or
154
- `{}`, as its type says; only a nil pointer is `null`.
155
- - **Who is asking.** `rsckit.ClientIP(ctx)` and `rsckit.ClientUserAgent(ctx)`
156
- are the visitor's address and browser, sent by the renderer and believed
157
- because the call carried the secret. `r.RemoteAddr` and `r.UserAgent()`
158
- would be the renderer's own, the same for every visitor. Both are empty
159
- when there is no visitor: a build, or a page stored for everyone.
160
-
161
- ### A type that writes its own JSON
162
-
163
- A `MarshalJSON` says nothing about the shape it writes, so the build has nothing
164
- to type it by. Give the type a `JSONSchema` method that says it:
165
-
166
- ```go
167
- type Money struct{ cents int64 }
168
-
169
- func (m Money) MarshalJSON() ([]byte, error) { … } // "12.50"
170
- func (Money) JSONSchema() rsckit.Schema { return rsckit.Schema{"type": "string"} }
171
- ```
172
-
173
- `Money` is then `string` wherever it appears, `*Money` is `string | null` and
174
- `[]Money` is `string[]`, with no narrowing helper in the page. The method is
175
- called once on the zero value, at startup, with a value or a pointer receiver.
176
- Its schema is used as it stands, so keep to what the build reads: `type` (one
177
- name), `items`, `properties` with `required`, `additionalProperties`, `enum`
178
- and `anyOf`. Anything else is `unknown`. It needs `github.com/rsc-kit/go`
179
- v0.11.0.
180
-
181
- `Register` still takes the untyped form, binding by hand:
182
-
183
- ```go
184
- reg.Register("Orders.recent", func(ctx context.Context, args rsckit.Args) (any, error) {
185
- var limit int
186
- if err := args.Bind(&limit); err != nil {
187
- return nil, err
188
- }
189
-
190
- // The visitor's cookie, forwarded from the page request: this runs as
191
- // them, not as nobody.
192
- session := rsckit.HeadersFrom(ctx).Get("Cookie")
193
-
194
- return db.RecentOrders(ctx, session, limit)
195
- })
196
- ```
197
-
198
- ```tsx title="src/app/orders/page.tsx"
199
- export default async function Orders() {
200
- const orders = await rpc<Order[]>('Orders.recent', 5)
201
-
202
- return <ul>{orders.map((o) => <li key={o.id}>{o.number}</li>)}</ul>
203
- }
204
- ```
205
-
206
- `args.Bind` decodes the positional arguments `rpc()` was given; too few is an
207
- error, extra ones are ignored. Whatever the function returns is encoded as
208
- JSON and decoded on the other side as whatever `rpc<T>()` was told: an
209
- untyped function is `unknown` until you say.
210
-
211
- ### When it fails
212
-
213
- In development, set `Debug` on the callback handler, or `RSC_DEBUG=1` in the
214
- environment, and a failure says where in Go it happened: a panic sends the
215
- frames it unwound, an error the chain it wraps. The renderer shows them under
216
- its own stack, as the error's cause:
217
-
218
- ```text
219
- Error: Host call "Orders.recent" failed: host function panicked: runtime error: slice bounds out of range
220
- Caused in the backend by Backend panic(runtime.boundsError): …
221
- at backend/main.go:64 main.main.func3
222
- ```
223
-
224
- A server action that fails this way opens Vite's error overlay on the page in
225
- development, with the same type and frames; frames from the module cache are
226
- counted rather than listed. Never in production: a trace names your files.
227
-
228
- ### Refusing
229
-
230
- Return a value and it is the result. Return one of these and the render is
231
- told what happened, rather than handed a 500:
232
-
233
- | return | the render gets |
234
- | --- | --- |
235
- | `rsckit.InvalidField("name", "…")`, `rsckit.Invalid(map)` | 422, each message under its input on the form that submitted |
236
- | `rsckit.Unauthenticated()` | 401, the engine's own authentication error |
237
- | `rsckit.Unauthorized("…")` | 403 |
238
- | `rsckit.Redirect("/login")` | the browser goes there |
239
- | `rsckit.Refuse(429, "slow down")` | that status, kept. An action shows the message to the visitor as written |
240
- | `rsckit.RefuseWith(409, "still in use", data)` | the same, with data the page can act on: see [server actions](/guides/server-actions#refusing-with-something-to-act-on) |
241
- | any other `error` | 500, with the message |
242
-
243
- Wrapped errors still answer as what they are — `errors.As` finds the refusal
244
- inside `fmt.Errorf("…: %w", err)` — and a panic becomes an error for that one
245
- call rather than taking the server down.
246
-
247
- ## Route middleware
248
-
249
- ```ts title="src/app/admin/middleware.ts"
250
- export const middleware = ['auth', 'can:manage-orders', 'throttle:60,1']
251
- ```
252
-
253
- ```go
254
- reg.Middleware("auth", func(ctx context.Context, _ string) error {
255
- if !signedIn(rsckit.HeadersFrom(ctx)) {
256
- return rsckit.Redirect("/login")
257
- }
258
- return nil
259
- })
260
-
261
- reg.Middleware("can", func(ctx context.Context, ability string) error {
262
- if !allowed(ctx, ability) {
263
- return rsckit.Unauthorized("you may not " + ability)
264
- }
265
- return nil
266
- })
267
- ```
268
-
269
- The renderer sends the list before anything at or below `admin/` renders —
270
- including a page it froze at build time, before the file is served. A guard
271
- receives what follows the colon in its name (`"manage-orders"`, `"60,1"`,
272
- `""`); guards run in order and stop at the first refusal. A name nothing is
273
- registered for refuses rather than passes: a declared check that silently
274
- does not happen is the failure this exists to prevent.
275
-
276
- A guard is asked about a page, not about the call that carries it:
277
-
278
- ```go
279
- reg.Middleware("owns-order", func(ctx context.Context, _ string) error {
280
- page, _ := rsckit.PageFrom(ctx) // the url the visitor asked for, and the route's params
281
- if !owns(ctx, page.Params["order"]) {
282
- return rsckit.Unauthorized("not your order")
283
- }
284
- return nil
285
- })
286
-
287
- reg.Middleware("throttle", func(ctx context.Context, rule string) error {
288
- if !limiter.Allow(rsckit.ClientIP(ctx), rule) { // the visitor's address, not the renderer's
289
- return rsckit.Refuse(429, "slow down")
290
- }
291
- return nil
292
- })
293
- ```
294
-
295
- `page.URL` is under the public host and scheme when a proxy forwarded them,
296
- so a signature checks against the link the visitor followed; it is empty
297
- during a build. `page.Params` holds only what the route's segments bound,
298
- never the query. `ClientIP` is read only once the secret matched, and is
299
- empty when there is no visitor. One page load asks once, so a throttle
300
- counts it once.
301
-
302
- ## Server actions
303
-
304
- ```go
305
- reg.HandleAction("ordersCancel", "Orders.cancel", func(ctx context.Context, id int) error {
306
- if err := orders.Cancel(ctx, id); err != nil {
307
- return err
308
- }
309
-
310
- rsckit.Revalidate(ctx, "orders")
311
-
312
- return nil
313
- })
314
-
315
- // The actions and every function, for the build: stubs, and rpc()'s type.
316
- reg.WriteManifest("rsc-host.json")
317
- ```
318
-
319
- ```tsx title="src/app/orders/CancelButton.tsx"
320
- 'use client'
321
- import { ordersCancel } from '../../server-actions.generated'
322
-
323
- export function CancelButton({ id }: { id: number }) {
324
- return <button onClick={() => ordersCancel(id)}>Cancel</button>
325
- }
326
- ```
327
-
328
- The stub is typed from the Go function, plus the one answer Go can give it that
329
- is not its result: `ordersCancel(id: number): Promise<void | Redirected>`. An
330
- action that returns `rsckit.Redirect("/login")` (or a guard that does, for an
331
- expired session) resolves the call with `{ redirected }` once the browser is on
332
- its way, so narrow with `isRedirected` before reading a value or reporting
333
- success. A call the backend refuses (`rsckit.Refuse(429, "slow down")`) is not a
334
- result at all: awaited directly the stub rejects with an `ActionRefusedError`
335
- carrying the message and the status, and `<Form>` shows it as `formError`. An
336
- input the backend refuses (`rsckit.Invalid`) rejects with a
337
- `ServerValidationError`, whose `.fieldErrors` and `.formErrors` are the
338
- messages. Only a redirect resolves. See [Redirects](/guides/redirects).
339
- An action that signs someone in sets the session cookie with
340
- `rsckit.SetCookie(ctx, &http.Cookie{...})`, and the renderer puts it on the
341
- page's response.
342
- Tag the structs a form posts with `json` names. An untagged field goes into
343
- the manifest under Go's name, `Type`, while a form posts `type` and the backend
344
- refuses under `type`, so `error('type')` is a type error on a bound stub. A tag
345
- (`json:"type"`) gives the form, the manifest and the refusal one spelling.
346
- Where tags are not an option, `fields` adds the other names on top.
347
-
348
- A form can post to an action directly, `<Form action={ordersCreate}>`, and its
349
- fields arrive as the struct parameter: the first, or the one after the
350
- arguments you bound. An action scoped to a team, `func(ctx, team string, in NewApp)`,
351
- is `<Form action={appsCreate.bind(null, team)}>`. Numbers and booleans are
352
- coerced by the struct's types and a repeated field is a slice.
353
-
354
- An admin resource takes the generated actions in place of a schema, its create
355
- `func(ctx, in ProductInput)` and its update the record's key after the struct,
356
- `func(ctx, in ProductInput, id string)`. See
357
- [the admin guide](/guides/admin#the-backends-actions-as-the-form). A list too
358
- big to count pages by cursor: answer a struct tagged `json:"rows"`,
359
- `json:"next"` and `json:"prev"`, and read the cursor from the query's `cursor`
360
- ([pages by count, or by cursor](/guides/admin#pages-by-count-or-by-cursor)).
361
-
362
- `Revalidate` names a [section](/guides/sections) or `page`, and the answer to
363
- the action carries it re-rendered rather than the browser being told to ask
364
- again.
365
-
366
- Have Vite write the manifest, so it cannot go stale: give the program a flag
367
- that writes it and exits, and name the command in the config. It runs as dev
368
- and every build start, and a build fails if it does:
369
-
370
- ```ts title="vite.config.ts"
371
- rscKit({ hostManifest: { command: ['go', 'run', '.', '-manifest', '../rsc-host.json'], cwd: 'backend' } })
372
- ```
373
-
374
- The manifest also lists every registered function, so `rpc()` is typed by
375
- the names Go holds and `rpc('Orders.recnet')` fails the typecheck. Tests
376
- answer these functions without Go running:
377
- [Testing it](/hosts/backend-answered-pages#testing-it).
378
-
379
- ## Saying data changed
380
-
381
- An action can say what it changed. A webhook, a job or another visitor's
382
- action cannot reach the tab that is showing the data - so a section names
383
- what it depends on, and Go says when that changed, from anywhere with a
384
- context:
385
-
386
- ```tsx title="src/app/t/[team]/repos.section.tsx"
387
- export default section('repos', Repos, { refreshOn: ({ params }) => [`team:${params.team}:repos`] })
388
- ```
389
-
390
- ```go
391
- // in the GitHub webhook handler
392
- reg.Changed(ctx, "team:"+teamID+":repos")
393
- ```
394
-
395
- Every open tab showing the section refreshes it, the moment the webhook
396
- lands, with nothing polling. The registry answers `__rsc.changed` by holding
397
- the renderer's ask until a version moves - woken at once by a `Changed` in
398
- this process, checking the store every `rsckit.ChangedPoll` (1s) for one made
399
- by another instance.
400
-
401
- Versions live in a `VersionStore`. The default is in memory, which is one
402
- instance; with more than one, a webhook lands on whichever instance the
403
- balancer picked, so give them all the same store:
404
-
405
- ```go
406
- // CREATE TABLE rsc_versions (name TEXT PRIMARY KEY, version BIGINT NOT NULL)
407
- reg.Versions(&rsckit.SQLVersions{DB: db, Placeholder: rsckit.Dollar}) // Postgres; nil Placeholder is "?"
408
- ```
409
-
410
- To hear another instance's change at once instead of within the second - and
411
- stop reading the store while nothing changes - set `Notify` so each bump
412
- sends a `pg_notify`, and run a listener with `WakeOn`. The adapter depends on
413
- no driver, so the listener is yours; with pgx:
414
-
415
- ```go
416
- reg.Versions(&rsckit.SQLVersions{DB: db, Placeholder: rsckit.Dollar, Notify: "rsc_versions"})
417
-
418
- reg.WakeOn(ctx, func(ctx context.Context, connected, wake func()) error {
419
- conn, err := pool.Acquire(ctx)
420
- if err != nil {
421
- return err
422
- }
423
- defer conn.Release()
424
- if _, err := conn.Exec(ctx, "LISTEN rsc_versions"); err != nil {
425
- return err
426
- }
427
- connected()
428
- for {
429
- if _, err := conn.Conn().WaitForNotification(ctx); err != nil {
430
- return err
431
- }
432
- wake()
433
- }
434
- })
435
- ```
436
-
437
- A listener that drops runs again with backoff, and the poll covers the gap.
438
- Through PgBouncer in transaction mode, connect the listener straight to
439
- Postgres. One instance needs none of this.
440
-
441
- Anything with a `Bump` and a `Versions` fits. Set `RSC_SIGNING_SECRET` for the renderer, the same on every instance:
442
- it signs the names a page hands the tab, and is not the host-call secret.
443
- Generating and rotating both: [Secrets](/hosts/deployment#secrets). [Sections](/guides/live-data)
444
- has the whole picture.
445
-
446
- ## Pages kept between requests
447
-
448
- `export const revalidate = 60` keeps a page and refreshes it behind the visitor,
449
- and `reg.Changed(ctx, "posts")` renders it again at once on every instance, when
450
- it read that tag through `cache()`. A kept page calls Go as nobody: no `Cookie`,
451
- no `Authorization`. With `CDN_PURGE_URL` set, `Changed` purges the CDN as
452
- well; `reg.SetPurger` replaces it. Call it after your transaction commits.
453
- [ISR](/guides/isr) has the whole of it.
454
-
455
- ## Public forms
456
-
457
- A contact form or a sign-up anyone may fill in is an action that takes a
458
- struct, and a few lines of TypeScript handing that action to a form. There is
459
- no schema to write: the fields and the browser's checks come from the struct.
460
-
461
- **1. The action.** Its `json` tags are the field names, a `validate` tag adds
462
- what the browser can check, and `rsckit.InvalidField` is a refusal under that
463
- field:
464
-
465
- ```go
466
- type ContactInput struct {
467
- Name string `json:"name" validate:"required,min=2"`
468
- Email string `json:"email" validate:"required,email"`
469
- Topic string `json:"topic" validate:"required,oneof=sales support"`
470
- Message string `json:"message" validate:"required,min=10,max=2000"`
471
- }
472
-
473
- reg.HandleAction("contactSend", "Contact.send", func(ctx context.Context, in ContactInput) error {
474
- if blocked(in.Email) {
475
- return rsckit.InvalidField("email", "That address is blocked.")
476
- }
477
-
478
- return messages.Insert(ctx, in)
479
- })
480
- ```
481
-
482
- The tag is read, never run: check what was sent in the function too, since a
483
- post need not come from a browser.
484
-
485
- **2. The form.** The build generates `contactSend` from the manifest, and
486
- `bunx rsc-kit make:form contactSend` writes the form around it:
487
-
488
- ```ts title="src/forms/contact.ts"
489
- import { defineBlueprint } from '@rsc-kit/press/forms'
490
- import { shadcn } from '@rsc-kit/press/shadcn'
491
- import { contactSend } from '../server-actions.generated'
492
-
493
- export const contact = defineBlueprint({
494
- name: 'contact',
495
- actions: { create: contactSend },
496
- fields: { message: { type: 'textarea' } },
497
- theme: shadcn,
498
- done: 'Thanks - we will be in touch.',
499
- })
500
- ```
501
-
502
- Then place it in a page, which stays static:
503
-
504
- ```tsx title="src/app/contact/page.tsx"
505
- import { contact } from '../../forms/contact'
506
-
507
- export default function ContactPage() {
508
- return <contact.Form />
509
- }
510
- ```
511
-
512
- `oneof` draws a select, and a field is required unless its `json` tag says
513
- `omitempty`. `required_if=Topic support` shows the field only while `topic` is
514
- `support`. [Blueprints](/guides/blueprints#go) has every tag that is read.
515
- It needs `@rsc-kit/press` 0.30.52 and `github.com/rsc-kit/go` v0.16.0.
516
-
517
- ## Production
518
-
519
- `bun run build` and `bun run start` with the same two variables in the
520
- renderer's environment. Put the renderer in front and restrict
521
- `/__rsc/host-call` at the web server, as [Laravel's page](/hosts/laravel/#which-process-faces-the-internet)
522
- shows; a Go worker is held for the length of a host call, never a render.
523
-
524
- Or put Go in front: `rsckit.NewRenderer(url)` is a streaming reverse proxy
525
- to the renderer, and `rsckit.NewHandler(renderer, callback, path)` routes
526
- the callback path to the endpoint and everything else through it. Both sides
527
- mark what they forward, so a url neither owns is a 404 rather than a loop.
528
-
529
- On a Worker, the two variables are a var and a secret in `wrangler.json`,
530
- and the Go process has to be reachable from Cloudflare's network — an
531
- `https` origin behind the secret and, ideally, an allow-list, since loopback
532
- is not an option there.
533
-
534
- ---
535
-
536
- The runnable version is
537
- [`examples/go-backend`](https://github.com/rsc-kit/rsc-kit/tree/main/examples/go-backend)
538
- in the repository: `bun run backend`, `bun run dev`, open the renderer.