UNPKG

@rsc-kit/mcp

Version:

An MCP server over what an rsc-kit build decided: the routes, why each one is static or not, and what it costs the browser.

470 lines (372 loc) • 19.8 kB
# Backend-Answered Pages > BAP — the model for an rsc-kit app with a backend behind it, and how to build for it. An rsc-kit app with a backend behind it, such as Laravel, Go, or anything that answers the contract, is a **BAP: Backend-Answered Pages**. The page is rendered *in front of* the backend, not *by* it. The renderer asks, and the backend answers: ```tsx title="src/app/orders/page.tsx" export default async function Orders() { const orders = await rpc<Order[]>('Orders.recent', 5) return <ul>{orders.map((o) => <li key={o.id}>{o.number}</li>)}</ul> } ``` ```php title="app/Rsc/Orders.php" namespace App\Rsc; class Orders { public function recent(int $limit = 5): array { return auth()->user()->orders()->latest()->take($limit)->get()->all(); } } ``` ```go title="main.go" reg.Handle("Orders.recent", func(ctx context.Context, limit int) ([]Order, error) { return db.RecentOrders(ctx, limit) }) ``` This page covers the idea once. [Laravel](/hosts/laravel) and [Go](/hosts/go) show how each backend answers, and [Your own backend](/hosts/your-own-backend) is the contract a third one implements. ## Beside the shapes you know | | Who renders the page | Who talks to the backend | How a page gets data | | --- | --- | --- | --- | | **MPA**: Blade, Rails views, Inertia | the backend | the browser | in the controller, before the view | | **SPA**: React and an API | the browser | the browser, over an API | `fetch('/api/orders')` after load | | **BAP**: rsc-kit | a renderer, on the server | the renderer, over loopback | `await rpc('Orders.recent')` in the component | If you have built a SPA with an API, you know most of this. The React app is what the visitor sees, and the backend is what it asks for data. The one change: the React app is rendered on a server, and **that server asks the backend**, not the browser. The visitor gets a finished, streamed page, and the backend never builds one. Think of a restaurant. In an MPA the kitchen sends out the whole plate. In a SPA the kitchen hands you a recipe and your browser cooks at the table. In a BAP a chef stands between you and the kitchen. The chef plates your page and asks the kitchen, through a hatch, for what only it has: your orders, whether you are signed in, whether you may be in this room. The kitchen only answers. Dishes that never change are plated in advance. ## Reading from the backend A server component calls a backend function by name, as if it were a local function: ```tsx const orders = await rpc<Order[]>('Orders.recent', 5) const [account, stats] = await Promise.all([rpc('Account.current'), rpc('Stats.today')]) ``` - **No API to design.** There are no routes, serialisers or clients between a component and a method. - **A global, not an import.** The build declares `rpc()` in `.rsc-kit/rsc-env.d.ts`. It exists in server components during a render and nowhere else: a `"use client"` file can't call it. - **As the visitor.** Each call is one `POST` carrying `{ "function": "Orders.recent", "args": [5] }`, the shared secret, and the visitor's cookie. The backend's session and auth are the visitor's. - **Batched and deduped.** Calls made by sibling components in the same tick travel as one batch. `cache()` dedupes a repeated call within the request. - **Refusals keep their kind.** A validation error, unauthenticated, unauthorized or a redirect reaches the page as itself, never as a 500. It costs the browser nothing. The browser bundle carries no client for `rpc()`, no endpoint URL and no secret. The server bundle has no database driver, ORM or auth library either, because the backend owns those. That is why the built server for a Laravel or Go app is a fraction of the size of the same pages with their data layer in JavaScript. ## Typing the calls The backend writes `rsc-host.json` at the project root, beside `vite.config.ts`: ```json title="rsc-host.json" { "actions": { "orders": { "cancel": "Orders.cancel", "create": "Orders.create" } }, "functions": ["Orders.cancel", "Orders.create", "Orders.recent"] } ``` - **`functions`** are the names `rpc()` accepts. They become the type of its first argument, so `rpc('Orders.recnet')` fails the typecheck. - **`actions`** are the backend's server actions, by module and then by the name the app imports them under. The build writes a `"use server"` module for each: here `src/server-actions/orders.ts`, exporting `cancel` and `create`. A class's `__invoke`, or a Go function with no method, is the module's `default`. ### Keeping it current Let Vite write the file, so it can't go stale. `hostManifest` runs the backend's command when `vite` and `vite build` start: ```ts title="vite.config.ts" // Laravel rscKit({ hostManifest: { command: ['php', 'artisan', 'rsc:host-manifest'] } }) // Go, run again whenever a file under backend/ changes rscKit({ hostManifest: { command: ['go', 'run', '.', '-manifest', '../rsc-host.json'], cwd: 'backend', watch: ['backend'], }, }) ``` - A build fails if the command fails. Under dev the failure is reported, and the file already there is used. - The dev server restarts when the file changes, so a function added in Go is typed a moment after it is saved. - `watch` names the backend's source, relative to the project root. ### Answered at build time With `hostManifest`, the build also asks the backend what `rpc()` answers while it renders each page: ```tsx title="src/app/register/page.tsx" export default async function Register() { const rules = await rpc('Passwords.rules') // the same for everyone: stored return <RegisterForm rules={rules} /> } ``` There is nothing to mark. The backend notices whether a function read who is asking: | The function | What the build does | | --- | --- | | reads nothing of the visitor's | stores the answer with the page | | reads the session, a cookie, a header, who is signed in, or the visitor's address | leaves it to the request: the page [streams](/guides/ppr) that part | | refuses as not signed in or not allowed, or sets a cookie | the same | | fails | fails the build, with the backend's error | The build's report names the calls each page stores, and what the others read: ```text ○ /register rpc("Passwords.rules") answered at build time, and stored ◐ /login rpc("Auth.options") (the session) streams per request; the rest is stored ``` A stored answer is kept until the next build. No tag, `Rsc::changed` or `cache()` refreshes a page stored whole, as with any page that read its data while it was built. To have it read again: - `await connection()` before the call asks per request. - `export const revalidate = 60` keeps the page [for a time](/guides/isr) instead; the build doesn't store it. What to know before the first build that does this: - **The build runs your functions**, so it needs what they need: the database, its environment. A function a render calls that writes something writes it during the build. - **Only what goes through the framework is noticed.** A function reading `$_COOKIE` itself, or a package's own per-visitor state, looks the same for everyone, and is stored as a guest would see it. Put `await connection()` before it. - **Guards still run per request.** A page under `middleware.ts` is not answered to anyone its guards refuse. `rscKit({ hostManifest: { command, calls: false } })` stops the build asking. Every page that calls `rpc()` then streams it. `calls` can also be a whole command of its own, such as `['./api', '-calls']`. Laravel's `rsc:host-manifest` answers these calls itself. In Go, a [flag does](/hosts/go/reading-from-go/#answered-at-build-time); an adapter of your own says [how it is asked](/hosts/your-own-backend/calls/#during-a-build). ### Going to the backend's function A backend that also writes `sources` gives your editor somewhere to go: ```json title="rsc-host.json" { "functions": ["Orders.recent"], "types": { "Orders.recent": { "params": [], "result": { "type": "string" } } }, "sources": { "Orders.recent": { "file": "app/Rsc/Orders.php", "line": 24, "name": "App\\Rsc\\Orders::recent" } } } ``` Cmd+click (Ctrl+click) `rpc` in `rpc('Orders.recent')` opens `Orders.php` at line 24, and hovering it names the method. No extension is needed: the build writes a source map beside `rsc-env.d.ts`, which editors already follow. - Click the word `rpc`. TypeScript has nothing to offer for the name in quotes. - The function needs an entry in `types`. - `file` is relative to `rsc-host.json`, and `line` starts at 1. `name` is optional. - Lines move as you edit the backend. A change to `sources` alone doesn't restart the dev server, and `--check` doesn't call it stale. ### Checking it in CI If you commit `rsc-host.json` or the generated types, fail CI when they are stale: ```sh bunx rsc-kit-typegen --check ``` It regenerates them as a build would, compares them with the committed ones, puts them back, and exits non-zero naming each file that changed. A file you don't commit is written by every build and can't be stale. ## Guarding a route The backend decides whether a route may render, in its own vocabulary. Name its guards in a `middleware.ts`: ```ts title="src/app/admin/middleware.ts" export const middleware = ['auth', 'can:manage-orders'] ``` The renderer asks before anything at or below that folder renders, including a page frozen at build time. A refusal keeps its kind: unauthenticated, unauthorized, a redirect, or a throttle's 429. It reaches the page as that, never as a 500. [Laravel](/hosts/laravel/middleware) and [Go](/hosts/go/middleware) cover their guards. ## Changing data A function the backend registers as an action gets a `"use server"` module from the build. A client component imports and calls it: ```tsx title="src/app/orders/CancelButton.tsx" 'use client' import * as orders from '../../server-actions/orders' export function CancelButton({ id }: { id: number }) { return <button onClick={() => orders.cancel(id)}>Cancel</button> } ``` The action says what it made stale, and the answer carries the re-rendered part back: ```php Rsc::revalidate('orders'); ``` ```go rsckit.Revalidate(ctx, "orders") ``` [Laravel](/hosts/laravel/server-actions) and [Go](/hosts/go/server-actions) cover forms, validation and redirects. ## Reading from the browser A `query()` is a JavaScript server function, so its body can be one call into the backend: ```ts export const recentOrders = client.query(async () => rpc<Order[]>('Orders.recent', 5)) ``` The browser reads it over GET, with [`fetchQuery`, `usePolling`, TanStack or SWR](/guides/queries) on top. ## URLs the backend keeps Any URL the React tree doesn't own is forwarded to the backend as it is: `/login`, a webhook, an OAuth callback, a file under `/storage`, an admin panel. Per URL, if the React tree has it, React renders it. Otherwise the backend does. Nothing is half-and-half on one URL. A dynamic root route would also match the backend's URLs. Name the backend's prefixes with `backendPaths`, and they go first: ```ts title="vite.config.ts" rscKit({ backendPaths: ['/auth', '/login/[provider]', '/storage'] }) ``` - **A prefix covers everything under it.** `'/auth'` is `/auth` and `/auth/callback`. - **A bracket is one whole segment.** `'/login/[provider]'` is `/login/google` and what is under it, not `/login`. An entry can't start with one. - **A page an entry covers stops the build.** `'/login'` with `app/login/page.tsx` would never render. So does an entry under a folder named in `subdomains`, whose visitors never send that path. - **For a proxy in front.** The build lists the plain prefixes in `.output/rsc-kit.json`, so a proxy can send them straight to the backend ([deployment](/hosts/deployment/build-output/#sending-the-backends-urls-past-the-renderer)). - **Never a page to the browser.** A `Link`, `visit()` or `redirect()` to a named prefix loads the document and is never prefetched, so it may bounce on to another site, as an OAuth start does ([redirects](/guides/redirects/#leaving-the-app)). ## Testing it `createTestApp` answers the backend in the test, through the same client the app uses against a real one, so nothing has to be running: ```ts title="tests/app.test.ts" import { createTestApp, hostReply, HOST_MIDDLEWARE } from '@rsc-kit/core/testing' const app = await createTestApp({ host: { 'Orders.recent': ({ args }) => [{ id: 1, total: Number(args[0]) * 100 }], 'Orders.create': ({ args }) => (args[0] ? { created: args[0] } : hostReply.invalid({ name: ['Required.'] })), // The guards middleware.ts names: true lets the page render. [HOST_MIDDLEWARE]: ({ headers }) => headers.get('cookie')?.includes('session=') ? true : hostReply.unauthenticated(), }, }) expect((await app.fetch('/admin')).status).toBe(401) ``` Each handler gets the call's `args` and the visitor `headers` the renderer forwarded. A name with no handler fails the call, naming it. **The fakes can't drift.** The handlers are typed from `rsc-host.json`. A handler for a function the backend doesn't have is a type error, its `args` are the function's parameters, and it returns the function's result type or a `hostReply` answer, never another shape. Removing a field in Go fails the test that still sends it. `hostReply` passes the same [conformance suite](/hosts/your-own-backend/conformance) 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: | Answer | Means | | --- | --- | | `hostReply.unauthenticated()` | not signed in | | `hostReply.unauthorized()` | signed in, not allowed | | `hostReply.redirect(to)` | go elsewhere, 307 unless a status is given | | `hostReply.refuse(status, message)` | refused with that status | | `hostReply.invalid(errors)` | validation errors, by field | | `hostReply.fail(message)` | an unexpected error | | `hostReply.revalidating(result, ...regions)` | a result that made regions stale | A URL the app doesn't own, such as a Go route or `/login`, is forwarded to the backend, and in a test that is a 502. `backend` answers those instead, handed the request as the backend would receive it: ```ts const app = await createTestApp({ host: { /* … */ }, backend: (request) => new Response('the login page', { headers: { 'content-type': 'text/html' } }), }) ``` ## Running it There are two processes, and the decision that matters is which one faces the internet. - **The renderer in front** is the one to reach for. It serves assets and frozen pages straight off disk, renders the rest, and forwards what it doesn't own. It holds a backend worker for the length of a host call, never a render. Restrict the host-call endpoint at the web server, so only the renderer reaches it. - **The backend in front** proxies pages to the renderer. This is the dev-mode shape, and what a Laravel app does with `RSC_RENDERER_URL`. It holds a worker for the whole render while the render calls back for data, so it needs several workers and caps concurrency at one fewer than it has. A call costs one request to the backend: a framework boot under PHP-FPM, about a millisecond under Octane or in a Go process. Multiply that by the number of *sequential* rounds a page needs, which batching keeps to one or two. [Deployment](/hosts/deployment) has the setups. ## When to choose it A BAP earns its second process when the pages want what a server-rendered React app gives (streaming, server components with no client bundle, static and partially prerendered pages, typed routes and actions) *and* the data, identity and rules already live in a backend you are keeping. - An app whose backend is only a database is better as a plain rsc-kit app, where the "backend" is an import. - An app whose pages are simple forms over a Laravel model may be happier as an MPA. [BAP vs Inertia](/hosts/bap-vs-inertia) compares the two. **What you gain:** - **No API layer.** No endpoint to design, no serialiser, no client, and no versioning between your own frontend and backend. The one endpoint that exists is private and generic. - **The backend keeps what it is good at.** Sessions, auth, policies, validation, queues, mail and migrations stay where they are, one line from a page. A SPA rebuilds half of that in the browser. - **Nothing ships to the browser for data.** Server components render with the data in them: no spinners on first paint, no fetch waterfall, no client bundle for parts that only display. - **Streaming and prerendering, on top of a backend.** The shell paints before the slow query answers. Pages the same for everyone are frozen at build time and served as files, and partial prerendering does both on one page. - **The backend is never reached from the browser.** The host-call endpoint is private to the renderer, behind a secret: one loopback route, not an API a visitor can enumerate. - **A worker per call, not per page.** The backend answers short calls, and the renderer holds the long connection. Load a Laravel MPA feels first in its PHP workers, a BAP feels in the renderer, the cheaper process to scale. - **Typed end to end.** Routes, search params, actions, backend function names and their arguments are typed by the build. A link to a page that doesn't exist fails `tsc`, not the visitor. - **Any backend.** Laravel and Go today. The contract is one endpoint, so a Rails or .NET app is a small package, not a port. **What it costs:** - **Two processes**, in development and in production. `rsc:install` makes it one command, but it is still two things to run. - **A hop per read.** Loopback, batched, deduped by `cache()`, and gone for frozen pages. Under PHP-FPM, a page that reads per visitor is a framework boot per request; Octane makes it a millisecond. - **A new shape to learn.** Server components, actions and streaming are neither a Blade view nor a React SPA, and the backend's job changes from serving pages to answering them. ## How it works ```text browser → renderer ──render──▶ React │ ├─ before rendering: POST /__rsc/host-call { "function": "__rsc.middleware", "args": [["auth"]] } └─ during rendering: POST /__rsc/host-call { "calls": [{ "function": "Orders.recent", "args": [5] }, …] } │ ▼ your backend ``` - **The renderer is the front door.** It is what `vite dev` serves and what Nitro builds into `.output/server`. It routes, renders, serves the frozen pages and assets, and streams the rest. - **One endpoint, one direction.** The renderer calls the backend, never the reverse, with a shared secret the backend checks on every call. The backend needs no credential to reach the renderer: the renderer's pages are the public site. - **Answered as they finish.** The backend answers a batch one line per call, the moment each is done. A fast read paints while a slow one is still running, so batching costs the page none of its streaming. A guarded page is typically two backend requests: the guard, then the batch of its reads. - **What the backend becomes.** It is neither an API nor an MPA. It is the part of the application that isn't a page: models, sessions and auth, policies, validation, queues, mail, events. Laravel stops being the app that serves pages and becomes the app that answers them. Eloquent, policies, form requests and notifications all stay, and none of it is behind a controller any more. --- Next: [Laravel](/hosts/laravel) · [Go](/hosts/go) · [Your own backend](/hosts/your-own-backend)