@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
package/guides/laravel.md DELETED
@@ -1,787 +0,0 @@
1
- # Laravel
2
-
3
- > React Server Components in front, a Laravel application behind them.
4
-
5
- ## The model
6
-
7
- A [BAP — Backend-Answered Pages](/hosts/backend-answered-pages): the page is
8
- rendered in front of Laravel rather than by it. The renderer — what `vite dev`
9
- serves, and what Nitro builds into `.output/server` — is the front door; it
10
- routes, renders and serves the frozen pages and the assets. Laravel answers
11
- what only Laravel can — the data, the session, whether a route may render —
12
- on one private endpoint, and keeps every route of its own: `/login`, a Blade
13
- page, a webhook, a file under `/storage` are forwarded to it as they are.
14
-
15
- A page reads from PHP the way a SPA would have fetched, except it is a server
16
- component, so there is no loading state to write and nothing ships to the
17
- browser:
18
-
19
- ```tsx title="resources/js/app/orders/page.tsx"
20
- export default async function Orders() {
21
- const orders = await rpc<Order[]>('Orders.recent', 5) // → App\Rsc\Orders::recent(5)
22
-
23
- return <ul>{orders.map((o) => <li key={o.id}>{o.number}</li>)}</ul>
24
- }
25
- ```
26
-
27
- The call runs as the visitor — their cookie travels with it, so `auth()->user()`
28
- inside `Orders::recent` is them. Laravel stops being the app that serves pages
29
- and becomes the app that answers them; what that means for what stays in
30
- Laravel is on [the BAP page](/hosts/backend-answered-pages#what-the-backend-is-then).
31
-
32
- ## Install
33
-
34
- ```sh
35
- composer require rsc-kit/laravel
36
- php artisan rsc:install
37
- ```
38
-
39
- `rsc:install` does the PHP half — publishes `config/rsc.php`, generates
40
- `RSC_HOST_CALL_SECRET` into `.env` — and runs `rsc-kit init` for the
41
- JavaScript half. Nothing you already have is overwritten: where a file exists,
42
- the exact edit is printed for you to make instead.
43
-
44
- In a terminal, `init` asks the questions that are the app's to answer:
45
-
46
- - the React Compiler;
47
- - Tailwind CSS, unless it is already there;
48
- - shadcn/ui, when Tailwind is there;
49
- - oxlint, unless oxlint or ESLint already is.
50
-
51
- It asks nothing about validation or typed environment variables, because
52
- Laravel already does both: a FormRequest validates, and `.env` holds the
53
- settings. `composer require` can't ask anything itself, since Composer never
54
- runs a package's own scripts, so `rsc:install` is where the questions are
55
- asked. Run without a terminal, as in CI, it takes the defaults and adds no
56
- linter.
57
-
58
- What lands:
59
-
60
- | | |
61
- | --- | --- |
62
- | `config/rsc.php` | the settings, published |
63
- | `.env` | `RSC_HOST_CALL_SECRET`, generated once |
64
- | `vite.config.ts` | the renderer's config, with `rscKit()` in it |
65
- | `resources/js/app/` | a root layout and a page |
66
- | `package.json` | `dev`, `build` and `start`, and `laravel-vite-plugin` removed |
67
-
68
- Requirements: PHP 8.3 and Laravel 13; Bun or Node 24 for the renderer; Vite
69
- 8, which the plugin needs and a Laravel application does not ship — the
70
- installer reports the version it found rather than upgrading it for you.
71
-
72
- ### One Vite config
73
-
74
- A Laravel application arrives with a `vite.config.js` that
75
- `laravel-vite-plugin` owns: it sets the base, the public directory, the
76
- output directory, the input list and the dev server's origin. So does the
77
- renderer's build, and whichever plugin runs second wins.
78
-
79
- There used to be a second file for that. There is not now, because once the
80
- renderer owns the frontend there is nothing left for `laravel-vite-plugin` to
81
- do — no `@vite` directive, no `public/hot`, no Blade asset pipeline. `init`
82
- moves the stock config aside as `vite.config.blade.js`, writes its own
83
- `vite.config.ts`, and drops the plugin from `package.json`. If something of
84
- yours still needs the Blade pipeline, run it from the moved file:
85
- `vite --config vite.config.blade.js`.
86
-
87
- ```ts title="vite.config.ts"
88
- import { defineConfig } from 'vite'
89
- import react from '@vitejs/plugin-react'
90
- import { rscKit } from '@rsc-kit/core/vite'
91
- import { nitro } from 'nitro/vite'
92
-
93
- export default defineConfig({
94
- plugins: [
95
- nitro({ preset: 'bun', serveStatic: 'inline' }),
96
- rscKit({
97
- sourceDir: 'resources/js',
98
- outDir: 'bootstrap/rsc/vite',
99
- hotFile: 'public/rsc-hot',
100
- hostManifest: { command: ['php', 'artisan', 'rsc:host-manifest'] },
101
- }),
102
- react(),
103
- ],
104
- })
105
- ```
106
-
107
- `outDir` is under `bootstrap/` because that is already where a Laravel
108
- application keeps generated code. `hotFile` is how Laravel finds a running
109
- dev server — read below.
110
-
111
- ### The scripts
112
-
113
- ```json title="package.json"
114
- {
115
- "scripts": {
116
- "dev": "vite",
117
- "build": "vite build",
118
- "start": "bun .output/server/index.mjs"
119
- }
120
- }
121
- ```
122
-
123
- `vite.config.ts` runs `php artisan rsc:host-manifest` as dev and every build
124
- start (`hostManifest`). Your server actions are found by reflection through
125
- Composer's autoloader — the only thing that sees what a class inherits from
126
- its parents and traits — so PHP writes them to `rsc-host.json` and the build
127
- reads it. It lists every callable too, which types `rpc()`'s first argument.
128
- Part of starting Vite rather than a step to remember: a stale manifest names a
129
- method that has since been renamed, and nothing fails until the browser calls
130
- it.
131
-
132
- It is rewritten every time, so it is not committed: `init`, and
133
- `create-rsc-kit` for an app with a backend, add `rsc-host.json` to
134
- `.gitignore` beside the generated stubs. A CI step that
135
- type-checks before building runs `php artisan rsc:host-manifest` first, or
136
- `rpc()` has no names to check against.
137
-
138
- If you had customised `dev` or `build` yourself, `init` leaves them alone and
139
- puts the renderer's at `rsc:dev` and `rsc:build`, and says so.
140
-
141
- ## Development
142
-
143
- ```sh
144
- npm run dev
145
- ```
146
-
147
- Then open the application at its own address — `my-app.test`, whatever you
148
- already use. Vite **is** the renderer in development. It writes
149
- `public/rsc-hot` while it runs, Laravel reads that file, and any request
150
- Laravel does not route is handed through to the address inside it. Stop the
151
- dev server and the file goes with it, and so does the proxy.
152
-
153
- One dev server per application. A second `vite` in the same app names the
154
- one already running, because two at once would share Vite's pre-bundle cache
155
- and break each other (`ERR_OUTDATED_OPTIMIZED_DEP`). `composer dev`, or Herd
156
- running `artisan dev`, may already have started one for you; use it. What the
157
- second one does next depends on how it was started:
158
-
159
- - **In a terminal it exits**, with the pid to stop if this is the one you
160
- wanted.
161
- - **Under a runner it waits** — `composer dev`, `artisan dev`, an editor
162
- task — and starts when the first stops, so Laravel is never left without a
163
- renderer.
164
-
165
- Per url the rule is: **if the React tree has it, React renders it**;
166
- otherwise Laravel does. That holds for a url Laravel also routes — a fresh
167
- application ships `Route::get('/', …)` to its welcome page, and after
168
- install `/` is `resources/js/app/page.tsx`, not the welcome page. The build
169
- writes its route table to `bootstrap/rsc/vite/routes.json` on every `vite`
170
- and `vite build`, and the package registers those urls after `routes/web.php`
171
- loads, so a page added to the tree is routed on the next request. The
172
- welcome route can stay or go; it answers nothing while the page exists.
173
- Until the first `vite` there is no table, and Laravel answers everything.
174
-
175
- The other direction works too. The renderer reads `APP_URL` and
176
- `RSC_HOST_CALL_SECRET` from the app's own `.env`, and a url the route tree does
177
- not own — `/login`, a Blade page, a webhook, a file under `/storage` — is
178
- forwarded to Laravel with `X-Forwarded-Host` set. So the renderer's own origin
179
- is the whole application as well, not the RSC half of it, and a browser can
180
- sit on either. The two proxies cannot loop: each marks what it forwards, and a
181
- url neither side owns is a 404 from whichever saw it second.
182
-
183
- :::caution[`php artisan serve` needs workers]
184
- `artisan serve` is `php -S`: one worker by default, which cannot answer a
185
- second request while it is blocked on the first. When Laravel proxies a page
186
- it holds that worker for the whole render, and the renderer calls back to the
187
- same server for the page's data — with nobody left to answer. The call would
188
- time out after 30 seconds into a page that answers **200** with its data
189
- missing, because a failed host call is reported inside its Suspense boundary.
190
- The package refuses that shape up front instead.
191
-
192
- Give it workers and the refusal stands down:
193
-
194
- ```ini title=".env"
195
- PHP_CLI_SERVER_WORKERS=4
196
- ```
197
-
198
- ```sh
199
- php artisan serve --no-reload
200
- ```
201
-
202
- `--no-reload` is Laravel's rule, not this package's: without it `serve`
203
- warns that it cannot respect the variable and starts one worker anyway.
204
- Herd, Valet, PHP-FPM and Octane run several without being asked. Or skip
205
- the proxy: open the renderer's origin directly and let Laravel answer host
206
- calls only, one short request each.
207
- :::
208
-
209
- ## Calling PHP
210
-
211
- A class under `app/Rsc/` is discovered by convention. Its public methods are
212
- what `rpc()` can reach, named `Class.method`; a class with `__invoke` is
213
- reached by its class name alone.
214
-
215
- ```php title="app/Rsc/Orders.php"
216
- namespace App\Rsc;
217
-
218
- class Orders
219
- {
220
- public function __construct(private OrderRepository $orders) {}
221
-
222
- public function recent(int $limit = 5): array
223
- {
224
- return $this->orders->forUser(auth()->user())->latest()->take($limit)->get()->all();
225
- }
226
- }
227
- ```
228
-
229
- ```tsx title="resources/js/app/orders/page.tsx"
230
- export default async function Orders() {
231
- const orders = await rpc<Order[]>('Orders.recent', 5)
232
-
233
- return <ul>{orders.map((o) => <li key={o.id}>{o.number}</li>)}</ul>
234
- }
235
- ```
236
-
237
- The class is resolved through the container, so constructor injection works.
238
- `auth()->user()` is the visitor: the renderer forwards their `Cookie` header on
239
- every call, `EncryptCookies` and `StartSession` run on the endpoint, and the
240
- session bound is theirs.
241
-
242
- `rpc()` is a global the renderer installs, declared for the typechecker in
243
- `.rsc-kit/rsc-env.d.ts`. It exists in server components during a render and
244
- nowhere else — a client component reaches PHP through a server action.
245
-
246
- ### Typed from the PHP signature
247
-
248
- `rsc:host-manifest` writes what each method takes and returns, so the call
249
- is typed without a type argument:
250
-
251
- ```php
252
- public function find(int $id, ?FindOptions $options = null): OrderData
253
- ```
254
-
255
- ```tsx
256
- const order = await rpc('Orders.find', 7) // OrderData; rpc('Orders.find', 'seven') fails the typecheck
257
- ```
258
-
259
- - **Parameters** are positional, as the call is made: `int`, `float`,
260
- `string` and `bool` are typed, a nullable one adds `| null`, one with a
261
- default may be left out, and a variadic one takes the rest.
262
- - **A form request** in front is the call's one argument, typed from its
263
- `rules()`: `integer`, `numeric`, `boolean` and `array` as such, the rest as
264
- strings, `required` ones required.
265
- - **A result** is typed when PHP can say what `json_encode` will write: a
266
- scalar, a backed enum (its values), or a plain class with public typed
267
- properties — a data object — which becomes an interface named for it.
268
- - **Left open** as `unknown`: `array`, a model, a collection, anything
269
- `JsonSerializable`, and an untyped parameter. Their shape is decided at
270
- runtime, so say it at the call: `rpc<Order[]>('Orders.recent')`.
271
-
272
- Action stubs are typed the same way, and accept the posting `FormData` too.
273
-
274
- ### Refusing
275
-
276
- Attributes on the class or the method, and the refusal travels as itself
277
- rather than as a broken page:
278
-
279
- ```php
280
- use RscKit\Attributes\Authenticated;
281
- use RscKit\Attributes\Can;
282
- use Illuminate\Routing\Attributes\Controllers\Middleware;
283
-
284
- #[Authenticated]
285
- #[Middleware('throttle:60,1')]
286
- class Orders
287
- {
288
- #[Can('update', Order::class)]
289
- public function cancel(int $id): void { … }
290
- }
291
- ```
292
-
293
- | thrown in PHP | reaches the render as |
294
- | --- | --- |
295
- | `AuthenticationException` | the engine's `ServerAuthenticationError`: the request answers **401** |
296
- | `AuthorizationException` | its `ServerAuthorizationError`: **403** |
297
- | `ValidationException` | a `validationErrors` map, field to messages, on the form that submitted |
298
- | `abort(404)` | the app's `not-found.tsx`, a real 404 |
299
- | a middleware `abort(429, 'Slow down')` | its own status: throttle's 429 stays a 429 |
300
- | `Rsc::refuse('Still in use', ['blockers' => $links])` | the message and the data, 409 by default: see [server actions](/guides/server-actions#refusing-with-something-to-act-on) |
301
- | `RscRedirectException` | a redirect the browser performs |
302
-
303
- An action shows an `abort()`'s message to the visitor as it is written, so give
304
- it one: `abort(429, 'Slow down')`. Without one the form says "Refused." Only a
305
- failure is replaced by `onError`'s generic message.
306
-
307
- A form request type-hinted on a method is resolved and validated before the
308
- method runs, which is where `ValidationException` usually comes from.
309
-
310
- Anything else thrown is a failure: reported to Laravel's log, and answered
311
- `Server Error`. With `app.debug` on, the answer also carries the exception's
312
- class, message and trace, and the renderer shows them under its own stack as
313
- the error's cause - so a failed `rpc()` in development points at the line of
314
- PHP that threw.
315
-
316
- A server action that fails the same way opens Vite's error overlay on the page,
317
- in development only. It leads with the exception's class and message, then names the
318
- first frame in your own code, such as `app/Rsc/Actions/Notification.php:20`.
319
- Laravel's own frames are counted rather than listed. In production the page
320
- gets a bare 500 and the trace stays in Laravel's log.
321
-
322
- ## Server actions
323
-
324
- A class under `app/Rsc/Actions/` is a server action. `rsc:host-manifest`
325
- writes it to the manifest, and the build writes a `"use server"` module beside your pages
326
- exporting one function per method, named `classMethod`.
327
-
328
- Make one with its guards already on it:
329
-
330
- ```sh
331
- php artisan make:rsc-action Orders --method=cancel --auth --can=update,Order --revalidate=orders
332
- ```
333
-
334
- `--method` per call (none makes the class invokable, reached as `orders`),
335
- `--auth` for `#[Authenticated]`, `--can=ability` or `--can=ability,Model` for
336
- `#[Can]`, `--middleware=throttle:60,1` for `#[Middleware]`, `--revalidate`
337
- for the `Rsc::revalidate()` line, and `--rpc` to make a class for `rpc()`
338
- under `app/Rsc` instead. A slash nests: `Billing/Invoices`, discovered like
339
- any other. The attributes it writes are the ones the registry reads, so what
340
- you asked for at the prompt is what runs.
341
-
342
- It writes the manifest as well, and a dev server that is running starts again
343
- when the manifest changes — so the export is there to import the moment the
344
- command returns, with nothing to restart by hand. A class you write yourself
345
- is picked up the next time `rsc:host-manifest` runs, which starting Vite
346
- does.
347
-
348
- ```php title="app/Rsc/Actions/Orders.php"
349
- namespace App\Rsc\Actions;
350
-
351
- use RscKit\Rsc;
352
-
353
- class Orders
354
- {
355
- #[Authenticated]
356
- public function cancel(CancelOrder $request): void
357
- {
358
- $request->order()->cancel();
359
-
360
- Rsc::revalidate('orders');
361
- }
362
- }
363
- ```
364
-
365
- ```tsx title="resources/js/app/orders/CancelButton.tsx"
366
- 'use client'
367
- import * as orders from '../../server-actions/orders'
368
-
369
- export function CancelButton({ id }: { id: number }) {
370
- return <button onClick={() => orders.cancel(id)}>Cancel</button>
371
- }
372
- ```
373
-
374
- The stub's type is the method's return type plus `Redirected`: a method that
375
- throws `RscRedirectException`, or a guard that redirects an expired session,
376
- resolves the call with `{ redirected }` once the browser is on its way. Narrow
377
- with `isRedirected` from `@rsc-kit/core/errors` before reading a value or
378
- reporting success; [Redirects](/guides/redirects) has the pattern. A call
379
- Laravel refuses (`abort(429, 'Slow down')`, `Rsc::refuse()`) is not a result at
380
- all: awaited directly the stub rejects with an `ActionRefusedError` carrying the
381
- message and the status, and `<Form>` shows it as `formError`. A
382
- `ValidationException` rejects with a `ServerValidationError`, whose
383
- `.fieldErrors` and `.formErrors` are the messages. Only a redirect resolves.
384
-
385
- `Rsc::revalidate('orders')` says what the action made stale. The names ride
386
- back with the result, and the answer to the action carries the re-rendered
387
- region with it rather than the browser being told to ask again — the same
388
- thing `revalidate()` does from a JavaScript action, described in
389
- [Sections](/guides/sections).
390
-
391
- `Rsc::flash('Invoice sent.')` leaves a message for the page the visitor lands
392
- on next - after a redirect, or in place - and `useFlash()` from
393
- `@rsc-kit/core/useFlash` shows it once, the same message `flash()` leaves from
394
- a JavaScript action ([A message for the next page](/guides/server-actions#a-message-for-the-next-page)).
395
- A second argument is the kind: `'error'`, `'info'` or `'warning'`. It works
396
- from a controller too, on its own response. The cookie is read by the browser,
397
- so the package leaves it unencrypted: nothing secret goes in a flash.
398
-
399
- ## Saying data changed
400
-
401
- `Rsc::revalidate()` is for the action that made the change. A webhook, a
402
- job, a listener, another user - none of those is in the tab showing the
403
- data. For those a section names what it depends on, and PHP says when that
404
- changed, from anywhere:
405
-
406
- ```tsx title="src/app/t/[team]/repos.section.tsx"
407
- export default section('repos', Repos, { refreshOn: ({ params }) => [`team:${params.team}:repos`] })
408
- ```
409
-
410
- ```php
411
- // a webhook controller, a job's handle(), a listener
412
- Rsc::changed("team:$teamId:repos");
413
- ```
414
-
415
- Every open tab showing the section refreshes it, with nothing polling. The
416
- versions live in the cache - the store every server already shares, or the
417
- one `rsc.tags_store` names; a store that is per server, like `file`, is one
418
- server's. PHP answers the renderer's ask at once rather than holding it, so
419
- a change reaches the tab on the renderer's next ask, a couple of seconds
420
- later. Set `RSC_SIGNING_SECRET` for the renderer, the same on every instance:
421
- it signs the names a page hands the tab, and is not the host-call secret.
422
- Generating and rotating both: [Secrets](/hosts/deployment#secrets).
423
-
424
- **What watching costs PHP.** The renderer asks Laravel which versions moved
425
- once for every tab it serves, not once per tab: one request about every two
426
- seconds per renderer process while any tab is watching, each a cache read.
427
- Three renderers are one or two small requests a second for the whole fleet.
428
- That is the default and the recommendation - Laravel stays the only thing
429
- that talks to its database.
430
-
431
- **Keeping versions in a table** (`RSC_VERSIONS=database`) is for when you
432
- want them in the database rather than the cache: pruned on a schedule with
433
- `rsc:prune-versions`, or written by something outside Laravel - a Go service,
434
- a worker in another language - through the [shared table](/guides/live-data#the-table).
435
- Laravel still answers the renderer from it; nothing else changes.
436
-
437
- ```sh
438
- php artisan vendor:publish --tag=rsc-migrations && php artisan migrate
439
- RSC_VERSIONS=database
440
- ```
441
-
442
- **Instant, with broadcasting.** If the app has Laravel's broadcasting set up
443
- (`php artisan install:broadcasting`) with a server that speaks the Pusher
444
- protocol - Reverb, Pusher, Soketi - each `Rsc::changed()` can announce itself,
445
- and the renderer asks the moment it hears:
446
-
447
- ```sh
448
- RSC_BROADCAST=true # Laravel: announce every change
449
- RSC_BROADCAST_URL=wss://ws.example.com # the renderer: where to listen
450
- RSC_BROADCAST_KEY=your-app-key # the renderer: the server's app key
451
- ```
452
-
453
- A change then reaches the tabs at once, and between changes the renderer asks
454
- only every thirty seconds, as a safety net. The announcement carries nothing -
455
- the channel is public, and names may be one visitor's - so Laravel still
456
- answers which names moved, and the renderer never touches the database. It is
457
- sent after the transaction commits.
458
-
459
- ## Pages kept between requests
460
-
461
- `export const revalidate = 60` keeps a page and refreshes it behind the visitor,
462
- and `Rsc::changed('posts')` renders it again at once on every instance, when it
463
- read that tag through `cache()`. A kept page calls PHP as nobody, so
464
- `auth()->user()` is null there. With `CDN_PURGE_URL` set, `Rsc::changed()`
465
- purges the CDN as well, after the transaction commits and the response has gone.
466
- [ISR](/guides/isr) has the whole of it.
467
-
468
- ## Public forms
469
-
470
- A contact form or a sign-up anyone may fill in is declared in three places: the
471
- rules in a `FormRequest`, the action that takes it, and a few lines of
472
- TypeScript handing that action to a form. `php artisan make:rsc-action Contact --method=send
473
- --form` writes all three, as below, for you to fill in (`rsc-kit/laravel`
474
- 0.18). There is no schema to write: the fields and the browser's
475
- checks are read from `rules()`.
476
-
477
- **1. The rules.** `php artisan make:request SendContact`, and let anyone send it:
478
-
479
- ```php title="app/Http/Requests/SendContact.php"
480
- namespace App\Http\Requests;
481
-
482
- use Illuminate\Foundation\Http\FormRequest;
483
-
484
- class SendContact extends FormRequest
485
- {
486
- public function authorize(): bool
487
- {
488
- return true; // make:request writes false, which refuses everyone
489
- }
490
-
491
- public function rules(): array
492
- {
493
- return [
494
- 'name' => ['required', 'string', 'min:2'],
495
- 'email' => ['required', 'email', 'unique:subscribers,email'],
496
- 'topic' => ['required', 'in:sales,support'],
497
- 'message' => ['required', 'string', 'min:10', 'max:2000'],
498
- ];
499
- }
500
- }
501
- ```
502
-
503
- **2. The action.** Under `app/Rsc/Actions`, taking the request alone:
504
-
505
- ```php title="app/Rsc/Actions/Contact.php"
506
- namespace App\Rsc\Actions;
507
-
508
- use App\Http\Requests\SendContact;
509
- use App\Models\Message;
510
-
511
- class Contact
512
- {
513
- public function send(SendContact $request): void
514
- {
515
- Message::create($request->validated());
516
- }
517
- }
518
- ```
519
-
520
- **3. The form.** The build generates `server-actions/contact.ts` from the
521
- class, exporting `send`, and
522
- `bunx rsc-kit make:form Contact.send` writes the form around it:
523
-
524
- ```ts title="resources/js/forms/contact.ts"
525
- import { defineBlueprint } from '@rsc-kit/press/forms'
526
- import { shadcn } from '@rsc-kit/press/shadcn'
527
- import { send } from '../server-actions/contact'
528
-
529
- export const contact = defineBlueprint({
530
- name: 'contact',
531
- actions: { create: send },
532
- fields: { message: { type: 'textarea' } },
533
- theme: shadcn,
534
- done: 'Thanks - we will be in touch.',
535
- })
536
- ```
537
-
538
- Then place it in a page, which stays static:
539
-
540
- ```tsx title="resources/js/app/contact/page.tsx"
541
- import { contact } from '../../forms/contact'
542
-
543
- export default function ContactPage() {
544
- return <contact.Form />
545
- }
546
- ```
547
-
548
- The fields are drawn in the order of `rules()`. `email`, `url`, `date`, `min`,
549
- `max`, `size` and `between` become the browser's checks, and `in` or `Rule::in()`
550
- draws a select. Everything else, `unique` included, is checked by Laravel alone:
551
- its 422 shows under the field, with what was typed kept. A field named in
552
- `fields` that `rules()` does not have fails the typecheck.
553
-
554
- A file field, or a check in TypeScript first, needs a schema and a `handle`
555
- instead. [Blueprints](/guides/blueprints#laravel) has the rest. `action`
556
- taking the generated action, and `rsc-kit make:form`, need `@rsc-kit/press`
557
- 0.30.49, and the browser's checks from `rules()` need
558
- `rsc-kit/laravel` 0.17; an older package draws the fields with `required` and
559
- their types only.
560
-
561
- An admin resource takes the same generated actions in place of a schema, and
562
- its update takes the record's key after the request:
563
- `update(UpdateProductRequest $request, string $product)`. The key is the
564
- request's route parameter under that name, so
565
- `Rule::unique('products')->ignore($this->route('product'))` keeps the record's
566
- own value. [The admin guide](/guides/admin#the-backends-actions-as-the-form)
567
- has it; it needs `@rsc-kit/press` 0.30.51 and `rsc-kit/laravel` 0.19.
568
-
569
- A rule `required_if:topic,support` shows its field only while `topic` is
570
- `support`, and requires it then; it needs `@rsc-kit/press` 0.30.52 and
571
- `rsc-kit/laravel` 0.20. [Blueprints](/guides/blueprints#fields-that-depend-on-others)
572
- has the rest.
573
-
574
- ## Route middleware
575
-
576
- The renderer owns the route table, but Laravel still decides whether a route
577
- may render. A `middleware.ts` beside or above a page names middleware in Laravel's
578
- own vocabulary:
579
-
580
- ```ts title="resources/js/app/admin/middleware.ts"
581
- export const middleware = ['auth', 'verified', 'can:update,post']
582
- ```
583
-
584
- Before anything at or below that directory renders, the names are sent to
585
- PHP with the page they guard, and run through the real pipeline against that
586
- page's request: its url, its route parameters, the visitor's address, cookie
587
- and session. So the vocabulary means what it does in `routes/web.php`:
588
-
589
- - `signed` checks the link the visitor followed. `signed:relative` too.
590
- - `throttle:5,1` counts per visitor, and once per page load.
591
- - `can:update,post` gets a `post`: the `{post}` the route bound, through
592
- `Route::bind` or `Route::model` in a service provider. Implicit binding
593
- needs a controller signature to read, and a page has none, so bind the names
594
- your guards use explicitly. Without a binding the ability receives the
595
- string.
596
- - `request()` and the `Request` a middleware is handed are the page's, not the
597
- host call's.
598
- - `auth` sends a guest to `route('login')`, and the page redirects there. An
599
- app with no route of that name fails with "Route [login] not defined", so
600
- say where guests go in `bootstrap/app.php`. When the login page is on
601
- another host (a `merchant.` subdomain signing in on the main site), give the
602
- full url:
603
-
604
- ```php title="bootstrap/app.php"
605
- ->withMiddleware(function (Middleware $middleware): void {
606
- $middleware->redirectGuestsTo('/login');
607
- // or: fn () => config('app.url').'/login'
608
- })
609
- ```
610
-
611
- It fails
612
- closed: anything that is not a literal `true` is a refusal, so a middleware
613
- that aborts, redirects or simply errors keeps the page from rendering rather
614
- than being read as silence. A page frozen at build time is asked too, before
615
- the file is served — a guard that held until the build froze the page would
616
- otherwise stop holding, silently.
617
-
618
- ## Production
619
-
620
- ```sh
621
- composer install --no-dev --optimize-autoloader
622
- npm ci && npm run build
623
- ```
624
-
625
- The build runs `rsc:host-manifest`, so PHP has to boot on the build
626
- machine. It writes `.output/` — the server, the engine, the frozen pages and
627
- the assets — which travels with the deployment; nothing in it is read from the
628
- source tree at runtime.
629
-
630
- Both processes read `RSC_HOST_CALL_SECRET`, and the renderer also needs
631
- `APP_URL` (or `RSC_BACKEND`) to know where Laravel is. To rotate the secret,
632
- Laravel takes `RSC_HOST_CALL_SECRET_PREVIOUS` as well
633
- ([rotating one](/hosts/deployment/)). Run it with the app's
634
- `.env` and it has both:
635
-
636
- ```ini title="/etc/systemd/system/rsc-renderer.service"
637
- [Service]
638
- User=www-data
639
- WorkingDirectory=/var/www/app
640
- EnvironmentFile=/var/www/app/.env
641
- ExecStart=/usr/local/bin/bun /var/www/app/.output/server/index.mjs
642
- Restart=always
643
- ```
644
-
645
- ### Which process faces the internet
646
-
647
- The renderer, unless you have a reason. It serves assets and frozen pages
648
- straight off disk, renders the rest, forwards what it does not own to Laravel,
649
- and holds a PHP worker for the length of a **host call** — a query, a policy
650
- check — never a whole render.
651
-
652
- A page route that matches a Laravel url keeps it. A dynamic route at the root,
653
- `[team]/[app]`, has every url of two segments, `/auth/github` and Breeze's
654
- `/login/verify` among them: it renders, says `notFound()`, and a page that said
655
- that is the app's 404, so it is not handed to Laravel. Name the prefixes Laravel
656
- answers and they are forwarded before any page is asked:
657
-
658
- ```ts title="vite.config.ts"
659
- rscKit({ backendPaths: ['/auth', '/login', '/oauth'] })
660
- ```
661
-
662
- Each is a prefix at a segment boundary, for every method, and a team called
663
- `auth` is then unreachable. With Laravel in front instead, the routes you
664
- registered win over a page route's, which is registered after them.
665
-
666
- A whole segment in brackets is any one segment, for a Laravel route with a
667
- parameter under a url that is a page:
668
-
669
- ```ts title="vite.config.ts"
670
- // Route::get('/login/{provider}', …) beside the page at /login
671
- rscKit({ backendPaths: ['/login/[provider]'] })
672
- ```
673
-
674
- - **What it covers.** `/login/google` and everything under it, such as
675
- `/login/google/callback`. Not `/login` itself, which stays your page.
676
- - **What it refuses.** A page it would cover, `login/forgot/page.tsx` here,
677
- stops `vite dev` and the build with both named: the page would never render,
678
- since a backend path is forwarded before any page is asked. Nothing is
679
- checked per request. A dynamic first segment (`/[team]/hooks`) and a
680
- catch-all are refused too.
681
- - **A prefix of its own is still simpler.** `Route::prefix('auth')` and
682
- `backendPaths: ['/auth']` needs no bracket and cannot cover a page by
683
- accident.
684
-
685
- In the browser a named prefix is never a page. A `Link`, `visit()` or
686
- `redirect('/oauth/github')` to it loads the document and is never
687
- prefetched, so the Laravel route may answer with a redirect to another site, as
688
- a Socialite redirect does — see [redirects](/guides/redirects/#leaving-the-app).
689
-
690
- Where it forwards to is decided at build time: `vite build` reads `APP_URL`
691
- (or `RSC_BACKEND`) from `.env` and bakes it in, while host calls read the same
692
- names from the process at runtime. Building on a machine whose `.env` names a
693
- different backend than production's means setting `RSC_BACKEND` for the
694
- build.
695
-
696
- ```nginx
697
- server {
698
- server_name example.com;
699
-
700
- location / {
701
- proxy_pass http://127.0.0.1:3000;
702
- proxy_http_version 1.1;
703
- proxy_buffering off; # Suspense boundaries stream; buffering holds them to the end
704
- }
705
-
706
- # The host-call endpoint is PHP's, and must not be reachable from outside.
707
- location /__rsc/host-call {
708
- allow 127.0.0.1;
709
- deny all;
710
- include fastcgi_params;
711
- fastcgi_pass unix:/run/php/php8.3-fpm.sock;
712
- }
713
- }
714
- ```
715
-
716
- Laravel needs the renderer in `trustProxies` for `url()`, `route()` and its
717
- redirects to come out against the public origin rather than its own.
718
-
719
- Trusting it means trusting what it forwards, so the renderer drops any
720
- `X-Forwarded-For`, `Forwarded` or `X-Real-IP` the browser sent: otherwise a
721
- visitor would pick their own address for Laravel's throttles. It sends the
722
- address it accepted the page request from instead, and the package makes that
723
- `$request->ip()` once the secret matches, whatever `trustProxies` says. If the
724
- renderer sits behind a proxy of its own that writes those headers (a load
725
- balancer, Cloudflare), set `RSC_TRUST_FORWARDED=1` on the renderer and the
726
- first hop is the visitor's address.
727
-
728
- Setting `RSC_RENDERER_URL` puts Laravel in front instead: it proxies anything
729
- it does not route, which is what development does. In production it has the
730
- cost the caution above describes, at scale — a worker is held for the whole
731
- render, the render calls back for data, and with `W` workers that caps you at
732
- `W − 1` concurrent renders, deadlocking when every worker is busy proxying.
733
- If you want it anyway, give `/__rsc/host-call` its own PHP-FPM pool so a
734
- proxying worker can never starve a data worker.
735
-
736
- ### What a host call costs
737
-
738
- The transport is loopback, well under a millisecond. The cost is Laravel
739
- handling a request: under PHP-FPM every call boots the framework, under
740
- [Octane](https://laravel.com/docs/octane) it stays booted and a call is
741
- closer to a millisecond. What matters is how many *sequential* calls a page
742
- needs. A page with no `middleware.ts` middleware makes no guard call; sibling
743
- components awaiting `rpc()` are rendered concurrently, so their calls
744
- overlap — and calls issued in the same tick travel as **one** request, a
745
- batch the package answers in one Laravel request, one line per call as
746
- each finishes, so a fast read is not held behind a slow one; `cache()` dedupes
747
- identical calls within a request; a frozen page makes none at all and a
748
- shell only for its holes. A guarded page is therefore typically two Laravel
749
- requests — the guard, then the batch of its reads — and a host-call-heavy app
750
- is better served by Octane, where each is a millisecond rather than a boot.
751
-
752
- ## Why there is a secret
753
-
754
- Inertia runs a second process too, and posts to it with no secret at all. The
755
- difference is direction. Inertia's SSR server *receives*: Laravel has already
756
- resolved the data and hands it over. This one is *asked*: the renderer has no
757
- data, so it calls back and runs a named function in your application, against
758
- your database, under the visitor's session — and that function has to be a
759
- Laravel route, because a Laravel route is the only thing that has your session,
760
- your container and your models. It is on the same public surface as the rest
761
- of the site.
762
-
763
- So without a secret the endpoint is not registered at all — absent, not open.
764
- The renderer presents it in `X-Rsc-Host-Secret`; a mismatch is 403 before
765
- anything is dispatched. The visitor's cookie also travels, and the two answer
766
- different questions: the cookie says who the page is *for*, the secret says who
767
- is *asking*. Neither substitutes for the other, which is also why the endpoint
768
- carries no CSRF check — a browser can be tricked into sending cookies, never
769
- into sending a header it does not know.
770
-
771
- Restrict it at the web server as well, as above. The secret is the layer this
772
- package can guarantee; the network is the one it cannot.
773
-
774
- ## Build-time
775
-
776
- The prerender probe replaces `rpc()` with a promise that never settles, so a
777
- component awaiting PHP suspends by construction and the page is classified as
778
- a shell or dynamic — never frozen with yesterday's rows baked in. That is a
779
- stronger guarantee than a pure JavaScript app gets. See
780
- [Partial prerendering](/guides/ppr).
781
-
782
- ---
783
-
784
- The package is `rsc-kit/laravel` on Packagist, source and issues at
785
- [rsc-kit/laravel](https://github.com/rsc-kit/laravel). A backend in another
786
- language answers the same endpoint — [Go](/hosts/go) does — and the contract
787
- is [Your own backend →](/hosts/your-own-backend)