@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.
Files changed (60) hide show
  1. package/dist/recipes.js +12 -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 +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 +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,229 +2,234 @@
2
2
 
3
3
  > BAP — the model for an rsc-kit app with a backend behind it, and how to build for it.
4
4
 
5
- An rsc-kit app with a backend behind it — Laravel, Go, anything that answers
6
- the contract — is a **BAP: Backend-Answered Pages**. A page is rendered *in
7
- front of* the backend rather than *by* it. The renderer asks; the backend
8
- answers.
5
+ An rsc-kit app with a backend behind it, such as Laravel, Go, or anything that
6
+ answers the contract, is a **BAP: Backend-Answered Pages**. The page is
7
+ rendered *in front of* the backend, not *by* it. The renderer asks, and the
8
+ backend answers:
9
9
 
10
- This page is the whole idea, once. The [Laravel](/hosts/laravel) and
11
- [Go](/hosts/go) pages are how each backend answers, and
12
- [Your own backend](/hosts/your-own-backend) is the contract a third one
13
- implements.
10
+ ```tsx title="src/app/orders/page.tsx"
11
+ export default async function Orders() {
12
+ const orders = await rpc<Order[]>('Orders.recent', 5)
13
+
14
+ return <ul>{orders.map((o) => <li key={o.id}>{o.number}</li>)}</ul>
15
+ }
16
+ ```
17
+
18
+ ```php title="app/Rsc/Orders.php"
19
+ namespace App\Rsc;
20
+
21
+ class Orders
22
+ {
23
+ public function recent(int $limit = 5): array
24
+ {
25
+ return auth()->user()->orders()->latest()->take($limit)->get()->all();
26
+ }
27
+ }
28
+ ```
29
+
30
+ ```go title="main.go"
31
+ reg.Handle("Orders.recent", func(ctx context.Context, limit int) ([]Order, error) {
32
+ return db.RecentOrders(ctx, limit)
33
+ })
34
+ ```
35
+
36
+ This page covers the idea once. [Laravel](/hosts/laravel) and [Go](/hosts/go)
37
+ show how each backend answers, and [Your own backend](/hosts/your-own-backend)
38
+ is the contract a third one implements.
14
39
 
15
40
  ## Beside the shapes you know
16
41
 
17
- | | who renders the page | who the backend talks to | how a page gets data |
42
+ | | Who renders the page | Who talks to the backend | How a page gets data |
18
43
  | --- | --- | --- | --- |
19
- | **MPA** — Blade, Rails views, Inertia | the backend | the browser | in the controller, before the view |
20
- | **SPA** — React + an API | the browser | the browser, over an API | `fetch('/api/orders')` after load |
21
- | **BAP** — rsc-kit | a renderer, on the server | the renderer, over loopback | `await rpc('Orders.recent')` inside the component |
22
-
23
- If you have built a SPA with an API behind it, you know most of the shape:
24
- the React app is what the visitor sees, and the backend is the thing it asks
25
- for data. The one change is that **the React app is rendered on a server, and
26
- that server is the one asking the backend** — not the browser. The visitor
27
- gets a finished, streamed page; the backend never builds one.
28
-
29
- In plain terms: a restaurant. In an MPA you order from the kitchen and the
30
- kitchen sends out the whole plate. In a SPA the kitchen hands you an empty
31
- plate and a recipe, and your browser cooks at the table, running back for
32
- every ingredient. In a BAP there is a chef between you and the kitchen — the
33
- renderer. You order a page; the chef plates it right there, asking the kitchen
34
- through a hatch for what only the kitchen has: your orders, whether you are
35
- signed in, whether you may be in this room. The kitchen only ever answers. And
36
- the dishes that never change, the chef plated in advance.
37
-
38
- ## Why
39
-
40
- What a BAP gives you that the other two shapes do not:
41
-
42
- - **No API layer.** A page calls a backend function by name; there is no
43
- endpoint to design, no serialiser, no client, no versioning of a contract
44
- between your own frontend and your own backend. The one endpoint that
45
- exists is private and generic.
46
- - **The backend keeps everything it is good at.** Sessions, auth, policies,
47
- validation, queues, mail, migrations — untouched, and reachable from a
48
- page in one line. A SPA rebuilds half of that in the browser; a BAP never
49
- moves it.
50
- - **Nothing ships to the browser for data.** Server components render with
51
- the data in them. No loading spinners for the first paint, no fetch
52
- waterfall, no client bundle for the parts that only display.
53
- - **Streaming and prerendering, on top of a backend.** The shell paints
54
- before the slow query answers; pages that need nothing per visitor are
55
- frozen at build time and served as files, and partial prerendering does
56
- both on one page — none of which an MPA can do, and none of which a SPA
57
- gets without a second server.
58
- - **The backend is never reached from the browser.** The host-call
59
- endpoint is private to the renderer, behind a secret. The attack surface
60
- is one loopback route rather than an API a visitor can enumerate.
61
- - **A worker per call, not per page.** The backend answers short calls and
62
- is free; the renderer holds the long connection. Under a load a Laravel
63
- MPA feels first in its PHP workers, a BAP feels in the renderer, which is
64
- the cheaper process to scale.
65
- - **Typed end to end.** Routes, search params, actions and their inputs are
66
- typed by the build; a link to a page that does not exist fails
67
- `tsc`, not the visitor. Backend function names and arguments are next.
68
- - **Any backend.** Laravel and Go today; the contract is one endpoint, so a
69
- Rails or .NET app is a small package, not a port.
44
+ | **MPA**: Blade, Rails views, Inertia | the backend | the browser | in the controller, before the view |
45
+ | **SPA**: React and an API | the browser | the browser, over an API | `fetch('/api/orders')` after load |
46
+ | **BAP**: rsc-kit | a renderer, on the server | the renderer, over loopback | `await rpc('Orders.recent')` in the component |
47
+
48
+ If you have built a SPA with an API, you know most of this. The React app is
49
+ what the visitor sees, and the backend is what it asks for data. The one
50
+ change: the React app is rendered on a server, and **that server asks the
51
+ backend**, not the browser. The visitor gets a finished, streamed page, and the
52
+ backend never builds one.
53
+
54
+ Think of a restaurant. In an MPA the kitchen sends out the whole plate. In a
55
+ SPA the kitchen hands you a recipe and your browser cooks at the table. In a
56
+ BAP a chef stands between you and the kitchen. The chef plates your page and
57
+ asks the kitchen, through a hatch, for what only it has: your orders, whether
58
+ you are signed in, whether you may be in this room. The kitchen only answers.
59
+ Dishes that never change are plated in advance.
60
+
61
+ ## Reading from the backend
62
+
63
+ A server component calls a backend function by name, as if it were a local
64
+ function:
65
+
66
+ ```tsx
67
+ const orders = await rpc<Order[]>('Orders.recent', 5)
68
+ const [account, stats] = await Promise.all([rpc('Account.current'), rpc('Stats.today')])
69
+ ```
70
70
 
71
- And what it costs, said plainly:
71
+ - **No API to design.** There are no routes, serialisers or clients between a
72
+ component and a method.
73
+ - **A global, not an import.** The build declares `rpc()` in
74
+ `.rsc-kit/rsc-env.d.ts`. It exists in server components during a render and
75
+ nowhere else: a `"use client"` file can't call it.
76
+ - **As the visitor.** Each call is one `POST` carrying
77
+ `{ "function": "Orders.recent", "args": [5] }`, the shared secret, and the
78
+ visitor's cookie. The backend's session and auth are the visitor's.
79
+ - **Batched and deduped.** Calls made by sibling components in the same tick
80
+ travel as one batch. `cache()` dedupes a repeated call within the request.
81
+ - **Refusals keep their kind.** A validation error, unauthenticated,
82
+ unauthorized or a redirect reaches the page as itself, never as a 500.
83
+
84
+ It costs the browser nothing. The browser bundle carries no client for
85
+ `rpc()`, no endpoint URL and no secret. The server bundle has no database
86
+ driver, ORM or auth library either, because the backend owns those. That is
87
+ why the built server for a Laravel or Go app is a fraction of the size of the
88
+ same pages with their data layer in JavaScript.
89
+
90
+ ## Typing the calls
72
91
 
73
- - **Two processes.** A JavaScript runtime beside the backend, in
74
- development and in production. `rsc:install` and the docs make it one
75
- command; it is still two things to run.
76
- - **A hop per read.** Loopback, batched, deduped by `cache()`, and gone for
77
- frozen pages — but a page that reads per visitor asks the backend, and
78
- under PHP-FPM that is a framework boot per request. Octane makes it a
79
- millisecond.
80
- - **A new shape to learn.** The pages are React on the server — server
81
- components, actions, streaming — which is not the mental model of either
82
- a Blade view or a React SPA, and the backend's job changes from serving
83
- pages to answering them.
92
+ The backend writes `rsc-host.json` at the project root, beside
93
+ `vite.config.ts`:
84
94
 
85
- ## How it works
95
+ ```json title="rsc-host.json"
96
+ {
97
+ "actions": { "orders": { "cancel": "Orders.cancel", "create": "Orders.create" } },
98
+ "functions": ["Orders.cancel", "Orders.create", "Orders.recent"]
99
+ }
100
+ ```
86
101
 
87
- ```text
88
- browser → renderer ──render──▶ React
89
- │
90
- ├─ before rendering: POST /__rsc/host-call { "function": "__rsc.middleware", "args": [["auth"]] }
91
- └─ during rendering: POST /__rsc/host-call { "calls": [{ "function": "Orders.recent", "args": [5] }, …] }
92
- │
93
- ▼
94
- your backend
102
+ - **`functions`** are the names `rpc()` accepts. They become the type of its
103
+ first argument, so `rpc('Orders.recnet')` fails the typecheck.
104
+ - **`actions`** are the backend's server actions, by module and then by the
105
+ name the app imports them under. The build writes a `"use server"` module for
106
+ each: here `src/server-actions/orders.ts`, exporting `cancel` and `create`. A
107
+ class's `__invoke`, or a Go function with no method, is the module's
108
+ `default`.
109
+
110
+ ### Keeping it current
111
+
112
+ Let Vite write the file, so it can't go stale. `hostManifest` runs the
113
+ backend's command when `vite` and `vite build` start:
114
+
115
+ ```ts title="vite.config.ts"
116
+ // Laravel
117
+ rscKit({ hostManifest: { command: ['php', 'artisan', 'rsc:host-manifest'] } })
118
+
119
+ // Go, run again whenever a file under backend/ changes
120
+ rscKit({
121
+ hostManifest: {
122
+ command: ['go', 'run', '.', '-manifest', '../rsc-host.json'],
123
+ cwd: 'backend',
124
+ watch: ['backend'],
125
+ },
126
+ })
95
127
  ```
96
128
 
97
- - **The renderer is the front door.** It is what `vite dev` serves and what
98
- Nitro builds into `.output/server`: it routes, renders, serves the pages it
99
- froze at build time and the assets, and streams the rest.
100
- - **One endpoint, one direction.** The renderer calls the backend, never the
101
- reverse, with a shared secret the backend checks on every call. The
102
- visitor's cookie travels with the call, so the backend's session and auth
103
- are the visitor's. The backend needs no credential to reach the renderer;
104
- the renderer's pages are the public site.
105
- - **Everything else stays the backend's.** Any url the React tree does not
106
- own — `/login`, a webhook, an OAuth callback, a file under `/storage`, an
107
- admin panel — is forwarded to the backend as it is. Per url the rule is: if
108
- the React tree has it, React renders it; otherwise the backend does. Nothing
109
- is half-and-half on one url. A dynamic root route that would also match one
110
- of the backend's urls does not get it: name the backend's prefixes with
111
- `backendPaths` and they go first. A whole segment in brackets is any one
112
- segment (`'/login/[provider]'` is `/login/google` and what is under it, not
113
- `/login`). A page any entry would cover - `'/login'` with `app/login/page.tsx` -
114
- stops the build, since it would never render; so does an entry under a folder
115
- named in `subdomains`, whose visitors never send that path. The build lists the plain prefixes in
116
- `.output/rsc-kit.json`, so a proxy in front can send them straight to the
117
- backend without going through the renderer
118
- ([deployment](/hosts/deployment/#sending-the-backends-urls-past-the-renderer)).
119
- A named prefix is also never a page to the
120
- browser: a `Link`, `visit()` or `redirect()` to it loads the document and is
121
- never prefetched, so it may bounce on to another site, as an OAuth start does
122
- ([redirects](/guides/redirects/#leaving-the-app)).
123
- - **Calls are batched, and answered as they finish.** Sibling components
124
- each awaiting `rpc()` are one request to the backend, which answers one
125
- line per call the moment that call is done — so a fast read paints while
126
- a slow one is still running, and batching costs the page none of its
127
- streaming. A guarded page is typically two backend requests — the guard,
128
- then the batch of its reads.
129
+ - A build fails if the command fails. Under dev the failure is reported, and
130
+ the file already there is used.
131
+ - The dev server restarts when the file changes, so a function added in Go is
132
+ typed a moment after it is saved.
133
+ - `watch` names the backend's source, relative to the project root.
129
134
 
130
- ## What the backend is, then
135
+ ### Checking it in CI
131
136
 
132
- Neither an API nor an MPA. It is the **backend** in the literal sense — the
133
- part of the application that is not a page: models and the database, sessions
134
- and auth, policies, validation, queues, mail, events. It does not build pages,
135
- so it is not an MPA; it does not expose a JSON API to the browser, so it is
136
- not an API server. It answers one private endpoint that only the renderer can
137
- call, with functions you write as ordinary classes.
137
+ If you commit `rsc-host.json` or the generated types, fail CI when they are
138
+ stale:
138
139
 
139
- For a Laravel app that means: Laravel stops being the app that serves pages
140
- and becomes the app that answers them. Eloquent, policies, form requests,
141
- queues, notifications — all of it stays, and none of it is behind a controller
142
- any more.
140
+ ```sh
141
+ bunx rsc-kit-typegen --check
142
+ ```
143
143
 
144
- ## Building for it
144
+ It regenerates them as a build would, compares them with the committed ones,
145
+ puts them back, and exits non-zero naming each file that changed. A file you
146
+ don't commit is written by every build and can't be stale.
145
147
 
146
- **Pages read by name.** A server component calls the backend the way it would
147
- call a function, because from its side it is one:
148
+ ## Guarding a route
148
149
 
149
- ```tsx title="src/app/orders/page.tsx"
150
- export default async function Orders() {
151
- const orders = await rpc<Order[]>('Orders.recent', 5)
150
+ The backend decides whether a route may render, in its own vocabulary. Name its
151
+ guards in a `middleware.ts`:
152
152
 
153
- return <ul>{orders.map((o) => <li key={o.id}>{o.number}</li>)}</ul>
154
- }
153
+ ```ts title="src/app/admin/middleware.ts"
154
+ export const middleware = ['auth', 'can:manage-orders']
155
155
  ```
156
156
 
157
- No API to design, no routes to declare, no JSON layer between a component and
158
- a method. `rpc()` exists in server components during a render and nowhere
159
- else — the browser never calls the backend directly.
160
-
161
- ### What `rpc()` is
162
-
163
- A global the renderer installs in its own process, not something you import:
164
- `rpc<T>(name, ...args)` is one `POST` to the backend's host-call endpoint
165
- carrying `{ "function": "Orders.recent", "args": [5] }`, the shared secret,
166
- and the visitor's cookie — so the backend's session and auth are the
167
- visitor's — answered with the function's return value as JSON, typed by the
168
- `T` you give it. The build declares it in `.rsc-kit/rsc-env.d.ts`, so there is
169
- nothing to import and no `declare` to write. A refusal
170
- comes back as itself — a validation error, unauthenticated, unauthorized, a
171
- redirect — and reaches the page as that kind, never as a 500. Calls made by
172
- sibling components in the same tick travel as one batch and are answered in
173
- order; `cache()` dedupes a repeated call within the request.
174
-
175
- It costs the browser nothing. `rpc()` is server-side only: the browser bundle
176
- carries no client for it, no endpoint url, no secret — a `"use client"` file
177
- cannot call it, and the host-call endpoint is reachable from the renderer
178
- alone. The same is true of the whole backend half: a BAP's server bundle has
179
- no database driver, no ORM, no auth library in it, because the backend owns
180
- those, which is why the built server for a Laravel or Go app is a fraction of
181
- the size of the same pages with their data layer in JavaScript.
182
-
183
- ### What the backend tells the build
157
+ The renderer asks before anything at or below that folder renders, including a
158
+ page frozen at build time. A refusal keeps its kind: unauthenticated,
159
+ unauthorized, a redirect, or a throttle's 429. It reaches the page as that,
160
+ never as a 500. [Laravel](/hosts/laravel/middleware) and
161
+ [Go](/hosts/go/middleware) cover their guards.
184
162
 
185
- The backend writes `rsc-host.json` at the project root, beside
186
- `vite.config.ts`:
163
+ ## Changing data
187
164
 
188
- ```json title="rsc-host.json"
189
- {
190
- "actions": { "orders": { "create": "Orders.create" } },
191
- "functions": ["Orders.create", "Orders.recent"]
165
+ A function the backend registers as an action gets a `"use server"` module
166
+ from the build. A client component imports and calls it:
167
+
168
+ ```tsx title="src/app/orders/CancelButton.tsx"
169
+ 'use client'
170
+ import * as orders from '../../server-actions/orders'
171
+
172
+ export function CancelButton({ id }: { id: number }) {
173
+ return <button onClick={() => orders.cancel(id)}>Cancel</button>
192
174
  }
193
175
  ```
194
176
 
195
- `actions` are its server actions, by module and then by the name the app
196
- imports them under; the build writes a `"use server"` module for each, here
197
- `src/server-actions/orders.ts` exporting `create`. A class's `__invoke`, or a
198
- Go function with no method, is the module's `default`.
199
- `functions` are the names `rpc()` may be called with, and become the type of
200
- its first argument, so `rpc('Orders.recnet')` fails the typecheck.
177
+ The action says what it made stale, and the answer carries the re-rendered
178
+ part back:
201
179
 
202
- Have Vite write it, so it cannot go stale. `hostManifest` runs the backend's
203
- command as `vite` and `vite build` start:
180
+ ```php
181
+ Rsc::revalidate('orders');
182
+ ```
204
183
 
205
- ```ts title="vite.config.ts"
206
- rscKit({ hostManifest: { command: ['go', 'run', '.', '-manifest', '../rsc-host.json'], cwd: 'backend' } })
207
- rscKit({ hostManifest: { command: ['php', 'artisan', 'rsc:host-manifest'] } })
184
+ ```go
185
+ rsckit.Revalidate(ctx, "orders")
208
186
  ```
209
187
 
210
- A build fails if the command does. Under dev it is reported, and the file
211
- already there is used. A dev server restarts when the file changes.
188
+ [Laravel](/hosts/laravel/server-actions) and [Go](/hosts/go/server-actions)
189
+ cover forms, validation and redirects.
212
190
 
213
- `watch` names the backend's source, relative to the project root. The dev
214
- server runs the command again when a file there changes, so a function added
215
- in Go is typed a moment after it is saved:
191
+ ## Reading from the browser
192
+
193
+ A `query()` is a JavaScript server function, so its body can be one call into
194
+ the backend:
216
195
 
217
196
  ```ts
218
- hostManifest: { command: ['go', 'run', '.', '-manifest', '../rsc-host.json'], cwd: 'backend', watch: ['backend'] }
197
+ export const recentOrders = client.query(async () => rpc<Order[]>('Orders.recent', 5))
219
198
  ```
220
199
 
221
- If you commit `rsc-host.json` or the generated types, fail CI when they are
222
- stale. `rsc-kit-typegen --check` regenerates them as a build would, compares
223
- the committed ones, puts them back, and exits non-zero naming each that
224
- changed. A file you do not commit is written by every build and cannot be
225
- stale.
200
+ The browser reads it over GET, with [`fetchQuery`, `usePolling`, TanStack or
201
+ SWR](/guides/queries) on top.
202
+
203
+ ## URLs the backend keeps
226
204
 
227
- ### Testing it
205
+ Any URL the React tree doesn't own is forwarded to the backend as it is:
206
+ `/login`, a webhook, an OAuth callback, a file under `/storage`, an admin
207
+ panel. Per URL, if the React tree has it, React renders it. Otherwise the
208
+ backend does. Nothing is half-and-half on one URL.
209
+
210
+ A dynamic root route would also match the backend's URLs. Name the backend's
211
+ prefixes with `backendPaths`, and they go first:
212
+
213
+ ```ts title="vite.config.ts"
214
+ rscKit({ backendPaths: ['/auth', '/login/[provider]', '/storage'] })
215
+ ```
216
+
217
+ - **A prefix covers everything under it.** `'/auth'` is `/auth` and
218
+ `/auth/callback`.
219
+ - **A bracket is one whole segment.** `'/login/[provider]'` is `/login/google`
220
+ and what is under it, not `/login`. An entry can't start with one.
221
+ - **A page an entry covers stops the build.** `'/login'` with
222
+ `app/login/page.tsx` would never render. So does an entry under a folder named
223
+ in `subdomains`, whose visitors never send that path.
224
+ - **For a proxy in front.** The build lists the plain prefixes in
225
+ `.output/rsc-kit.json`, so a proxy can send them straight to the backend
226
+ ([deployment](/hosts/deployment/build-output/#sending-the-backends-urls-past-the-renderer)).
227
+ - **Never a page to the browser.** A `Link`, `visit()` or `redirect()` to a
228
+ named prefix loads the document and is never prefetched, so it may bounce on
229
+ to another site, as an OAuth start does
230
+ ([redirects](/guides/redirects/#leaving-the-app)).
231
+
232
+ ## Testing it
228
233
 
229
234
  `createTestApp` answers the backend in the test, through the same client the
230
235
  app uses against a real one, so nothing has to be running:
@@ -246,21 +251,29 @@ expect((await app.fetch('/admin')).status).toBe(401)
246
251
  ```
247
252
 
248
253
  Each handler gets the call's `args` and the visitor `headers` the renderer
249
- forwarded.
250
-
251
- The handlers are typed from `rsc-host.json`. A handler for a function the
252
- backend does not have is a type error, its `args` are the function's
253
- parameters, and it returns the function's result type or a `hostReply`
254
- answer, never another shape. So a fake cannot drift from the backend in a way
255
- the typecheck misses: removing a field in Go fails the test that still sends
256
- it. `hostReply` itself passes the same
257
- [conformance suite](/hosts/your-own-backend#before-you-ship-the-conformance-suite)
258
- the Laravel and Go adapters do, so each answer is the one they send. Return a value for the result, or one of the protocol's answers:
259
- `hostReply.unauthenticated()`, `unauthorized()`, `redirect(to)`,
260
- `refuse(status, message)`, `invalid(errors)`, `fail(message)` for an
261
- unexpected error, or `revalidating(result, ...regions)`. A name with no handler fails the call, naming it.
262
-
263
- A url the app does not own, such as a Go route or `/login`, is forwarded to the
254
+ forwarded. A name with no handler fails the call, naming it.
255
+
256
+ **The fakes can't drift.** The handlers are typed from `rsc-host.json`. A
257
+ handler for a function the backend doesn't have is a type error, its `args`
258
+ are the function's parameters, and it returns the function's result type or a
259
+ `hostReply` answer, never another shape. Removing a field in Go fails the test
260
+ that still sends it. `hostReply` passes the same
261
+ [conformance suite](/hosts/your-own-backend/conformance)
262
+ the Laravel and Go adapters do, so each answer is the one they send.
263
+
264
+ Return a value for the result, or one of the protocol's answers:
265
+
266
+ | Answer | Means |
267
+ | --- | --- |
268
+ | `hostReply.unauthenticated()` | not signed in |
269
+ | `hostReply.unauthorized()` | signed in, not allowed |
270
+ | `hostReply.redirect(to)` | go elsewhere, 307 unless a status is given |
271
+ | `hostReply.refuse(status, message)` | refused with that status |
272
+ | `hostReply.invalid(errors)` | validation errors, by field |
273
+ | `hostReply.fail(message)` | an unexpected error |
274
+ | `hostReply.revalidating(result, ...regions)` | a result that made regions stale |
275
+
276
+ A URL the app doesn't own, such as a Go route or `/login`, is forwarded to the
264
277
  backend, and in a test that is a 502. `backend` answers those instead, handed
265
278
  the request as the backend would receive it:
266
279
 
@@ -271,68 +284,104 @@ const app = await createTestApp({
271
284
  })
272
285
  ```
273
286
 
274
- **Guards are the backend's, named in `middleware.ts`.** The backend decides
275
- whether a route may render, in its own vocabulary, and the renderer asks
276
- before anything at or below that directory renders — including a page frozen
277
- at build time:
287
+ ## Running it
278
288
 
279
- ```ts title="src/app/admin/middleware.ts"
280
- export const middleware = ['auth', 'can:manage-orders']
281
- ```
289
+ There are two processes, and the decision that matters is which one faces the
290
+ internet.
282
291
 
283
- A refusal is its own kind on the wire — unauthenticated, unauthorized, a
284
- redirect, a throttle's 429 — and reaches the page as that, never as a 500.
292
+ - **The renderer in front** is the one to reach for. It serves assets and
293
+ frozen pages straight off disk, renders the rest, and forwards what it
294
+ doesn't own. It holds a backend worker for the length of a host call, never a
295
+ render. Restrict the host-call endpoint at the web server, so only the
296
+ renderer reaches it.
297
+ - **The backend in front** proxies pages to the renderer. This is the dev-mode
298
+ shape, and what a Laravel app does with `RSC_RENDERER_URL`. It holds a worker
299
+ for the whole render while the render calls back for data, so it needs
300
+ several workers and caps concurrency at one fewer than it has.
285
301
 
286
- **Mutations are server actions the backend implements.** A function the
287
- backend registers as an action gets a `"use server"` stub written by the
288
- build, and a client component imports and calls it. The action says what it
289
- made stale (`Rsc::revalidate('orders')`, `rsckit.Revalidate(ctx, "orders")`)
290
- and the answer carries the re-rendered region back.
302
+ A call costs one request to the backend: a framework boot under PHP-FPM, about
303
+ a millisecond under Octane or in a Go process. Multiply that by the number of
304
+ *sequential* rounds a page needs, which batching keeps to one or two.
305
+ [Deployment](/hosts/deployment) has the setups.
291
306
 
292
- **Browser-driven reads are queries that call `rpc()`.** A `query()` is a
293
- JavaScript server function, so its body can be one call into the backend, and
294
- the browser reads it over GET with [`fetchQuery`, `usePolling`, TanStack or
295
- SWR](/guides/queries) on top:
307
+ ## When to choose it
296
308
 
297
- ```ts
298
- export const recentOrders = client.query(async () => rpc<Order[]>('Orders.recent', 5))
299
- ```
309
+ A BAP earns its second process when the pages want what a server-rendered
310
+ React app gives (streaming, server components with no client bundle, static
311
+ and partially prerendered pages, typed routes and actions) *and* the data,
312
+ identity and rules already live in a backend you are keeping.
300
313
 
301
- **Put things where they belong.** Data, identity, rules and jobs are the
302
- backend's; layout, interaction and everything a visitor sees is React's. A
303
- page that needs nothing from the backend is frozen at build time and never
304
- touches it; one that reads per visitor is a shell with holes the backend
305
- fills. The build's table says which is which.
314
+ - An app whose backend is only a database is better as a plain rsc-kit app,
315
+ where the "backend" is an import.
316
+ - An app whose pages are simple forms over a Laravel model may be happier as an
317
+ MPA. [BAP vs Inertia](/hosts/bap-vs-inertia) compares the two.
306
318
 
307
- ## Running it
319
+ **What you gain:**
308
320
 
309
- Two processes, and the decision that matters is which faces the internet.
321
+ - **No API layer.** No endpoint to design, no serialiser, no client, and no
322
+ versioning between your own frontend and backend. The one endpoint that
323
+ exists is private and generic.
324
+ - **The backend keeps what it is good at.** Sessions, auth, policies,
325
+ validation, queues, mail and migrations stay where they are, one line from a
326
+ page. A SPA rebuilds half of that in the browser.
327
+ - **Nothing ships to the browser for data.** Server components render with the
328
+ data in them: no spinners on first paint, no fetch waterfall, no client
329
+ bundle for parts that only display.
330
+ - **Streaming and prerendering, on top of a backend.** The shell paints before
331
+ the slow query answers. Pages the same for everyone are frozen at build time
332
+ and served as files, and partial prerendering does both on one page.
333
+ - **The backend is never reached from the browser.** The host-call endpoint is
334
+ private to the renderer, behind a secret: one loopback route, not an API a
335
+ visitor can enumerate.
336
+ - **A worker per call, not per page.** The backend answers short calls, and the
337
+ renderer holds the long connection. Load a Laravel MPA feels first in its PHP
338
+ workers, a BAP feels in the renderer, the cheaper process to scale.
339
+ - **Typed end to end.** Routes, search params, actions, backend function names
340
+ and their arguments are typed by the build. A link to a page that doesn't
341
+ exist fails `tsc`, not the visitor.
342
+ - **Any backend.** Laravel and Go today. The contract is one endpoint, so a
343
+ Rails or .NET app is a small package, not a port.
310
344
 
311
- **The renderer in front** is the arrangement to reach for: it serves assets
312
- and frozen pages straight off disk, renders the rest, forwards what it does
313
- not own, and holds a backend worker for the length of a *host call*, never a
314
- render. Restrict the host-call endpoint at the web server so only the renderer
315
- reaches it.
345
+ **What it costs:**
316
346
 
317
- **The backend in front** proxies pages to the renderer — the dev-mode shape,
318
- and what a Laravel app does with `RSC_RENDERER_URL`. It holds a worker for the
319
- whole render while the render calls back for data, so it needs several
320
- workers and caps concurrency at one fewer than it has.
347
+ - **Two processes**, in development and in production. `rsc:install` makes it
348
+ one command, but it is still two things to run.
349
+ - **A hop per read.** Loopback, batched, deduped by `cache()`, and gone for
350
+ frozen pages. Under PHP-FPM, a page that reads per visitor is a framework boot
351
+ per request; Octane makes it a millisecond.
352
+ - **A new shape to learn.** Server components, actions and streaming are
353
+ neither a Blade view nor a React SPA, and the backend's job changes from
354
+ serving pages to answering them.
321
355
 
322
- **What a call costs** is the backend handling a request — under PHP-FPM a
323
- framework boot, under Octane or a Go process about a millisecond — times the
324
- number of *sequential* rounds a page needs, which batching keeps to one or
325
- two.
356
+ ## How it works
326
357
 
327
- ## When to choose it
358
+ ```text
359
+ browser → renderer ──render──▶ React
360
+ │
361
+ ├─ before rendering: POST /__rsc/host-call { "function": "__rsc.middleware", "args": [["auth"]] }
362
+ └─ during rendering: POST /__rsc/host-call { "calls": [{ "function": "Orders.recent", "args": [5] }, …] }
363
+ │
364
+ ▼
365
+ your backend
366
+ ```
328
367
 
329
- A BAP earns its second process when the pages want what a server-rendered
330
- React app gives — streaming, server components with no client bundle, static
331
- and partially-prerendered pages, typed routes and actions — *and* the data,
332
- identity and rules already live in a backend you are keeping. An app whose
333
- backend is only a database is better as a plain rsc-kit app, where the
334
- "backend" is an import. An app whose pages are simple forms over a Laravel
335
- model may be happier as an MPA. Everything in between is what this is for.
368
+ - **The renderer is the front door.** It is what `vite dev` serves and what
369
+ Nitro builds into `.output/server`. It routes, renders, serves the frozen
370
+ pages and assets, and streams the rest.
371
+ - **One endpoint, one direction.** The renderer calls the backend, never the
372
+ reverse, with a shared secret the backend checks on every call. The backend
373
+ needs no credential to reach the renderer: the renderer's pages are the
374
+ public site.
375
+ - **Answered as they finish.** The backend answers a batch one line per call,
376
+ the moment each is done. A fast read paints while a slow one is still
377
+ running, so batching costs the page none of its streaming. A guarded page is
378
+ typically two backend requests: the guard, then the batch of its reads.
379
+ - **What the backend becomes.** It is neither an API nor an MPA. It is the part
380
+ of the application that isn't a page: models, sessions and auth, policies,
381
+ validation, queues, mail, events. Laravel stops being the app that serves
382
+ pages and becomes the app that answers them. Eloquent, policies, form
383
+ requests and notifications all stay, and none of it is behind a controller
384
+ any more.
336
385
 
337
386
  ---
338
387