@rsc-kit/mcp 0.30.38 → 0.30.42

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.
@@ -0,0 +1,109 @@
1
+ # Admin plugins
2
+
3
+ > Writing an @rsc-kit/press plugin, publishing it as a package, and selling it.
4
+
5
+ A plugin is a plain object that adds to an [admin panel](/guides/admin/)
6
+ without changing its code. Everything in one is something an app could write
7
+ itself; a plugin is the same thing in a package, so it can be installed,
8
+ versioned and sold.
9
+
10
+ ```ts
11
+ interface PanelPlugin {
12
+ name: string // unique in a panel: the package name
13
+ resources?: Resource[] // shown as if the app defined them
14
+ widgets?: Widget[] // dashboard cards
15
+ onChange?: (change: RecordChange) => void | Promise<void>
16
+ }
17
+ ```
18
+
19
+ ## A whole plugin
20
+
21
+ An audit log: it records every save and delete, and shows the latest on the
22
+ dashboard.
23
+
24
+ ```tsx title="src/index.tsx"
25
+ import { definePlugin } from '@rsc-kit/press'
26
+ import type { RecordChange, Tenant } from '@rsc-kit/press'
27
+
28
+ export function auditLog({ keep = 50 }: { keep?: number } = {}) {
29
+ const entries: (RecordChange & { at: Date })[] = []
30
+
31
+ function Recent({ tenant }: { tenant: Tenant | null }) {
32
+ const mine = entries.filter((entry) => entry.tenant?.id === tenant?.id).slice(0, 6)
33
+
34
+ return (
35
+ <ul className="space-y-2 text-sm">
36
+ {mine.map((entry, i) => (
37
+ <li key={i}>{entry.change} {entry.resource} #{entry.id}</li>
38
+ ))}
39
+ </ul>
40
+ )
41
+ }
42
+
43
+ return definePlugin({
44
+ name: 'audit-log',
45
+ widgets: [{ title: 'Recent activity', component: Recent }],
46
+ onChange(change) {
47
+ entries.unshift({ ...change, at: new Date() })
48
+ entries.length = Math.min(entries.length, keep)
49
+ },
50
+ })
51
+ }
52
+ ```
53
+
54
+ Export a function that takes the plugin's options and returns the plugin, so
55
+ an app writes `plugins: [auditLog({ keep: 500 })]`.
56
+
57
+ - **A widget is a server component**, given the current `tenant`. It can be
58
+ `async` and read data; show that tenant's numbers, never everyone's.
59
+ - **`onChange` runs after the record is written.** A plugin that throws is
60
+ logged and does not undo the change or fail the save - the person saving is
61
+ not the plugin's audience. Do slow work (an email, a webhook) without making
62
+ the save wait on it.
63
+ - **`change.tenant`** is whose record it was, in a panel with tenants. Keep
64
+ what you store split by it.
65
+ - **Resources** a plugin adds are ordinary `defineResource` resources. A name
66
+ shared with one of the app's is refused when the panel is defined, as is the
67
+ same plugin installed twice.
68
+
69
+ ## Publishing it
70
+
71
+ ```json title="package.json"
72
+ {
73
+ "name": "rsc-kit-admin-audit-log",
74
+ "type": "module",
75
+ "keywords": ["rsc-kit", "rsc-kit-admin-plugin"],
76
+ "exports": { ".": "./dist/index.js", "./styles.css": "./dist/styles.css" },
77
+ "peerDependencies": { "@rsc-kit/press": "^0.30.40", "react": "^19" }
78
+ }
79
+ ```
80
+
81
+ - `@rsc-kit/press` and React are **peers**, never dependencies: two copies of
82
+ either in one app break.
83
+ - Ship compiled JavaScript, not TypeScript source.
84
+ - Style with Tailwind classes and the shadcn theme's colours (`text-muted-foreground`,
85
+ `bg-card`), so the plugin matches the app it is installed in. If it has
86
+ components, ship a `styles.css` with `@source "./";` and tell the app to
87
+ import it, as the panel itself does.
88
+ - The `rsc-kit-admin-plugin` keyword is how plugins are found: search npm for
89
+ `keywords:rsc-kit-admin-plugin`.
90
+
91
+ ## Selling it
92
+
93
+ A paid plugin is an npm package behind a licence. The ways that work today,
94
+ the same as Filament's paid plugins:
95
+
96
+ - **A private registry with a licence key** - Anystack, Lemon Squeezy, or
97
+ your own. The buyer adds a scoped registry to `.npmrc` with their key as the
98
+ token, and installs as usual:
99
+
100
+ ```ini title=".npmrc"
101
+ @acme:registry=https://npm.acme.dev/
102
+ //npm.acme.dev/:_authToken=${ACME_LICENSE_KEY}
103
+ ```
104
+
105
+ - **A private GitHub repository** the buyer is invited to on purchase, installed
106
+ with `bun add github:acme/admin-plugin`.
107
+
108
+ Keep a free listing on npm - the README and the keyword - pointing at where it
109
+ is sold, so it is found the same way a free plugin is.
@@ -0,0 +1,401 @@
1
+ # Admin panels
2
+
3
+ > An admin panel over any data - a database, an ORM, a REST API, a Laravel or Go backend - with server or client tables, tenants and plugins.
4
+
5
+ `@rsc-kit/press` builds an admin panel from a list of resources. Each one is a
6
+ table, a form and a data source. The panel decides what each page shows and
7
+ who may see it; a [theme](#themes) draws it - shadcn's sidebar, data table and
8
+ dialogs is the one that ships - and the app keeps everything that is its own:
9
+ where the data lives, who may see it, and whose it is.
10
+
11
+ The package has three entry points:
12
+
13
+ - `@rsc-kit/press` - resources, data sources, tenants, plugins and blocks. Nothing here draws.
14
+ - `@rsc-kit/press/admin` - `definePanel`, and the url schemas its routes export.
15
+ - `@rsc-kit/press/forms` - `defineForm`, for [public forms](/guides/public-forms/) drawn from a schema.
16
+ - `@rsc-kit/press/pages` - `definePages`, for [pages an editor builds from blocks](/guides/pages/).
17
+ - `@rsc-kit/press/shadcn` - the shadcn theme, which draws both.
18
+
19
+ ## Install
20
+
21
+ The shadcn theme is styled by the app's shadcn variables, so the app has
22
+ Tailwind v4 and shadcn set up (`create-rsc-kit --tailwind --shadcn` does both):
23
+
24
+ ```sh
25
+ bun add @rsc-kit/press
26
+ ```
27
+
28
+ ```css title="src/app/styles.css"
29
+ @import "tailwindcss";
30
+ @import "shadcn/tailwind.css";
31
+ @import "@rsc-kit/press/shadcn.css";
32
+ ```
33
+
34
+ The last line tells Tailwind to scan the theme's components. Without it the
35
+ panel renders unstyled.
36
+
37
+ The header's theme menu is Light, Dark or System, and System - the default -
38
+ follows the OS. It sets the `dark` class on `<html>` before the first paint,
39
+ so give the root layout's `<html>` `suppressHydrationWarning`, as shadcn's own
40
+ theme setup does. `definePanel({ modeToggle: false })` hides it for an app
41
+ with its own.
42
+
43
+ ## A resource
44
+
45
+ ```ts title="src/admin/resources/products.ts"
46
+ import * as z from 'zod'
47
+ import { defineResource } from '@rsc-kit/press'
48
+
49
+ export const products = defineResource<Product>()({
50
+ name: 'products',
51
+ key: 'id',
52
+ title: 'name',
53
+ source: productsSource,
54
+ table: (col) => [
55
+ col.text('name').searchable().sortable(),
56
+ col.money('price').sortable(),
57
+ col.badge('status'),
58
+ col.boolean('featured').hidden(),
59
+ ],
60
+ filters: ['status'],
61
+ form: z.object({
62
+ name: z.string().min(2),
63
+ price: z.number().positive(),
64
+ status: z.enum(['draft', 'active']),
65
+ featured: z.boolean(),
66
+ }),
67
+ fields: { description: { type: 'textarea' } },
68
+ })
69
+ ```
70
+
71
+ Columns are `text`, `money`, `badge`, `boolean`, `date` and `relation`. `.hidden()` starts
72
+ a column switched off in the Columns menu, and `.cell((value, row) => ...)`
73
+ draws a cell yourself - a server component, so it can use the app's own shadcn
74
+ components.
75
+
76
+ ## The form is any Standard Schema
77
+
78
+ `form` is a Standard Schema of an object: zod, valibot, arktype, Effect Schema
79
+ - whatever the app already uses. The panel never imports a validation library.
80
+ The same schema checks every save on the server, and each refusal shows under
81
+ the field it is about.
82
+
83
+ The fields are read from the schema. A schema that describes itself as JSON
84
+ Schema - **Standard JSON Schema**, which zod 4.2+ implements - gives the form
85
+ its fields, their types, which are required and an enum's options. A schema
86
+ that does not still validates; list its fields in `fields`, and the panel says
87
+ so if you forget:
88
+
89
+ ```ts
90
+ form: v.object({ title: v.pipe(v.string(), v.minLength(1)) }),
91
+ fields: { title: { type: 'text' } },
92
+ ```
93
+
94
+ ### Checked in the browser first
95
+
96
+ The constraints the browser can check itself come from the schema too, as
97
+ attributes on the controls: `required`, `min` and `max`, `minlength` and
98
+ `maxlength`, an anchored `pattern`, `type="email"`, and `step="1"` for an
99
+ integer. A submit with a wrong field never leaves the page, and the browser's
100
+ message - in the visitor's language - shows under the field in the same
101
+ `FieldError` the server's refusals use. With JavaScript off, the browser shows
102
+ its own bubble instead.
103
+
104
+ The schema itself never reaches the browser, so this is the same for a schema
105
+ in the app and for rules that live in Laravel or Go. It is a courtesy only: a
106
+ custom message (`'Like ABC-123'`) and anything the browser cannot know - a
107
+ unique email - come from the server, which checks every save.
108
+
109
+ A number field arrives as a number, so the schema says `z.number()` - not
110
+ `z.coerce.number()` - and is the same schema an API would use. A switch that is
111
+ off is `false`, and an empty optional field is left out.
112
+
113
+ ## Any data source
114
+
115
+ A data source is five functions. The panel calls nothing else, so it is a
116
+ database, an ORM, a REST API or a backend behind `rpc()` alike:
117
+
118
+ ```ts title="src/admin/resources/customers.ts"
119
+ import type { DataSource } from '@rsc-kit/press'
120
+
121
+ const customersSource: DataSource<Customer, Values> = {
122
+ async list({ q, sort, dir, page, perPage, filters }, { tenant }) {
123
+ const res = await fetch(`${API}/customers?${new URLSearchParams({ q: q ?? '', page: String(page) })}`)
124
+ const { data, total } = await res.json()
125
+
126
+ return { rows: data, total }
127
+ },
128
+ find: (id) => fetch(`${API}/customers/${id}`).then((r) => (r.ok ? r.json() : null)),
129
+ create: (values) => post(`${API}/customers`, values),
130
+ update: (id, values) => put(`${API}/customers/${id}`, values),
131
+ delete: (id) => del(`${API}/customers/${id}`),
132
+ }
133
+ ```
134
+
135
+ A save says "Product saved." on the list it lands on, and a delete says
136
+ "Product deleted." in place, as a toast. Both use
137
+ [`flash()`](/guides/server-actions#a-message-for-the-next-page).
138
+
139
+ `find` answering `null` is a 404, for the page and for a save or delete of that
140
+ id. `memorySource(rows, key, make)` is one for tests and demos.
141
+
142
+ ### A Laravel or Go backend
143
+
144
+ On a backend the five functions are `rpc()` calls. The source runs in the
145
+ renderer, in a page and in the panel's save, and both forward the visitor's
146
+ cookie, so `auth()->user()` is them:
147
+
148
+ ```ts title="src/admin/resources/products.ts"
149
+ const productsSource: DataSource<Product, Values> = {
150
+ list: (query) => rpc('Products.list', query),
151
+ find: (id) => rpc('Products.find', Number(id)),
152
+ create: (values) => rpc('Products.create', values),
153
+ update: (id, values) => rpc('Products.update', Number(id), values),
154
+ delete: (id) => rpc('Products.delete', Number(id)),
155
+ }
156
+ ```
157
+
158
+ ```php title="app/Rsc/Products.php"
159
+ public function create(StoreProduct $request): Product
160
+ {
161
+ return Product::create($request->validated());
162
+ }
163
+ ```
164
+
165
+ The backend validates again, and its answer is the one that counts. A rule the
166
+ schema cannot know - `unique:products,sku`, a stock check - comes back as a 422,
167
+ and its messages show under the same fields as the schema's, with the form's
168
+ values kept. Nothing to catch: the panel treats the backend's refusal and its
169
+ own the same way.
170
+
171
+ ### Choices that read as words
172
+
173
+ An enum's options are shown humanized - `'in_stock'` reads "In stock" in the
174
+ form and the filter, and `'in_stock'` is still what is saved. Say them
175
+ yourself where that is not the word:
176
+
177
+ ```ts
178
+ fields: { status: { options: ['draft', { value: 'active', label: 'Live' }] } },
179
+ ```
180
+
181
+ An optional select starts on "None", which saves nothing.
182
+
183
+ ## Files and images
184
+
185
+ A field the schema holds as a string - the url of what was uploaded - can be
186
+ an upload instead:
187
+
188
+ ```ts title="src/admin/resources/products.ts"
189
+ form: z.object({ name: z.string(), photo: z.url().nullable().optional() }),
190
+ fields: {
191
+ photo: { type: 'image', storage: uploads, maxSize: 2 * 1024 * 1024 },
192
+ },
193
+ ```
194
+
195
+ `storage` is where the file goes. It is one function, and press ships none,
196
+ as it ships no database:
197
+
198
+ ```ts title="src/storage.ts"
199
+ import type { Storage } from '@rsc-kit/press'
200
+
201
+ export const uploads: Storage = {
202
+ async put(file, { field, tenant }) {
203
+ const key = `uploads/${crypto.randomUUID()}`
204
+
205
+ await Bun.s3.write(key, file, { type: file.type })
206
+
207
+ return `https://cdn.example.com/${key}`
208
+ },
209
+ }
210
+ ```
211
+
212
+ What `put` answers is what the record saves. On a Worker the same function
213
+ writes to an R2 binding; on a server, to a disk the app serves. A Laravel or Go
214
+ backend gets the url, not the file - `rpc()` carries JSON - so point `put` at
215
+ the bucket the backend's own disk reads, and the url means the same on both
216
+ sides.
217
+
218
+ The form shows what the field holds, a preview of a new image as it is chosen,
219
+ and, when the schema allows `null`, a **Remove** button that saves `null`.
220
+
221
+ - **Upload last.** The form is checked first with the file still a file; only
222
+ when nothing else is wrong is it stored. A refused save leaves nothing in
223
+ the bucket.
224
+ - **Checked twice.** `accept` and `maxSize` are checked in the browser as the
225
+ file is chosen and again on the server. An image field takes PNG, JPEG,
226
+ WebP, GIF and AVIF unless it says `accept`. Not SVG: an SVG can carry script,
227
+ and served from your own origin it runs as your app.
228
+ - **Kept values are checked.** A save that chooses nothing sends back what
229
+ the field held, and the server keeps it only if the record already had it.
230
+ A posted url is not an upload.
231
+ - **The body limit.** Files arrive in the action's body, 8 MB unless the host's
232
+ `maxActionBody` says more. Set `maxSize` below it, so the visitor reads which
233
+ field is too large rather than a refused request.
234
+ - **Replaced files stay.** Removing or replacing an upload does not delete the
235
+ old file; a bucket lifecycle rule, or a job that sweeps keys no record
236
+ names, does that.
237
+
238
+ The field works the same in a [block](/guides/pages/) and in a
239
+ [public form](/guides/public-forms/).
240
+
241
+ ## Relations
242
+
243
+ A belongsTo is a field that names another resource of the panel:
244
+
245
+ ```ts
246
+ table: (col) => [col.text('name'), col.relation('categoryId', 'categories')],
247
+ form: z.object({ name: z.string(), categoryId: z.number().int() }),
248
+ fields: { categoryId: { relation: 'categories' } },
249
+ ```
250
+
251
+ The form offers the categories as a select, labelled "Category": each one's
252
+ `key` saved, its `title` shown. The column shows "Lighting", not `3`, and a
253
+ client-mode table searches and sorts it by that word. A `z.number()` relation
254
+ arrives as a number, as a number field does.
255
+
256
+ The choices are the related resource's `list` with `perPage: null`, asked as
257
+ the visitor - scoped to their tenant like any list - so a relation is for a
258
+ resource with a select's worth of rows: categories, teams, plans. A save checks
259
+ the id it was sent with that resource's `find`, as the visitor, so an id posted
260
+ by hand from another tenant is refused under the field. A relation to a
261
+ resource the panel does not have fails when the panel is defined.
262
+
263
+ ## Bulk actions
264
+
265
+ Every table that is not `readOnly` can tick rows; ticking shows what can be
266
+ done to them below the table, with the panel's own **Delete**. Add your own:
267
+
268
+ ```ts
269
+ bulkActions: [
270
+ { name: 'publish', label: 'Publish', done: 'published', run: (rows) => rpc('Products.publish', rows.map((row) => row.id)) },
271
+ { name: 'archive', label: 'Archive', destructive: true, run: archiveAll },
272
+ ],
273
+ ```
274
+
275
+ `run` is given the rows themselves, each found by the source's `find` as the
276
+ visitor: an id the browser sent that is not theirs, or is already gone, never
277
+ reaches it. It runs after `authorize`, like every save. A `destructive` action
278
+ asks first, as Delete does. When it is done the table refreshes and a toast
279
+ says "3 products published." from `done`, as Delete says "deleted" - or
280
+ whatever `run` returns as a string.
281
+
282
+ ## Server or client tables
283
+
284
+ ```ts
285
+ mode: 'server' // the default
286
+ mode: 'client'
287
+ ```
288
+
289
+ **Server** - each search, filter, sort and page is a request, and `list` is
290
+ asked for one page (`perPage` a number). The url holds the state, so a table is
291
+ a link, the back button works and it works with JavaScript off. For data that
292
+ grows.
293
+
294
+ **Client** - `list` is asked once with `perPage: null` and returns every row;
295
+ search, filters, sorting and paging happen in the browser with no request. For
296
+ data that stays small - hundreds of rows, not thousands.
297
+
298
+ ## Who may use it
299
+
300
+ The panel has no login of its own. It asks the app's:
301
+
302
+ ```ts title="src/admin/panel.ts"
303
+ import { definePanel } from '@rsc-kit/press/admin'
304
+ import { shadcn } from '@rsc-kit/press/shadcn'
305
+
306
+ export const panel = definePanel({
307
+ path: '/admin',
308
+ theme: shadcn,
309
+ resources: [products, customers],
310
+ authorize: async () => (await currentUser())?.isAdmin === true,
311
+ user: currentUser,
312
+ signOut: () => endSession(),
313
+ })
314
+ ```
315
+
316
+ `authorize` runs on every page, and on every save, delete and team switch -
317
+ an action is reachable without the page that rendered it, so a guard on the
318
+ pages alone would not be one. A refusal is a 404. `user` fills the sidebar's
319
+ footer, and `signOut` runs in a server action and lands the visitor on `/`.
320
+
321
+ ## Tenants
322
+
323
+ ```ts
324
+ tenancy: {
325
+ label: 'Teams',
326
+ tenants: () => teamsOf(currentUser()),
327
+ current: () => teamFromSession(),
328
+ switch: (id) => rememberTeam(id),
329
+ },
330
+ ```
331
+
332
+ The sidebar gets a team switcher, and every data source call is told the
333
+ tenant as its last argument - `list(query, { tenant })`. A current tenant that
334
+ is not one of the visitor's own - a cookie naming someone else's team - is
335
+ refused, so `current` reads the session and the panel checks membership.
336
+ `switch` runs in a server action, so it may set a cookie.
337
+
338
+ `perTenant((tenantId) => source)` keeps a source per tenant, for data that is
339
+ already split that way.
340
+
341
+ ## Mounting it
342
+
343
+ The engine finds routes, url schemas and sections by their files, so the
344
+ panel is mounted with seven files of one or two lines each:
345
+
346
+ ```
347
+ src/app/admin/middleware.ts export default panel.middleware
348
+ src/app/admin/layout.tsx export default panel.Layout
349
+ src/app/admin/page.tsx export default panel.Dashboard
350
+ src/app/admin/[resource]/page.tsx export const params = resourceParams
351
+ export const searchParams = listSearch
352
+ export default panel.Index
353
+ src/app/admin/[resource]/admin-table.section.tsx export default panel.Table
354
+ src/app/admin/[resource]/new/page.tsx export const params = resourceParams
355
+ export default panel.Create
356
+ src/app/admin/[resource]/[id]/page.tsx export const params = recordParams
357
+ export default panel.Edit
358
+ ```
359
+
360
+ `resourceParams`, `recordParams`, `listSearch` and `pluginsSearch` come from
361
+ `@rsc-kit/press/admin`. The section must be named `admin-table.section.tsx`: a
362
+ delete refreshes the table by that name.
363
+
364
+ ## Themes
365
+
366
+ `theme` is what draws the panel. The panel works out everything a page needs -
367
+ whether the visitor may see it, which tenant's rows, the save already bound to
368
+ its record - and hands the theme the result as props. A theme is an object of
369
+ components, typed `AdminTheme` from `@rsc-kit/press/admin`:
370
+
371
+ | Component | Draws |
372
+ | --- | --- |
373
+ | `Shell` | The frame: `brand`, `nav`, `user` and `crumbs` arrive drawn, and the page as `children` |
374
+ | `Brand`, `TenantSwitcher`, `Nav`, `Breadcrumbs`, `UserMenu` | What goes in the frame |
375
+ | `Dashboard`, `Index`, `Form`, `Plugins` | Each page |
376
+ | `Table` | A resource's rows, in server or client mode |
377
+ | `Cell` | A `money`, `badge`, `boolean` or `date` value |
378
+ | `Loading` | What shows while a page waits for the request |
379
+
380
+ Every prop is data, a server action already bound, or an element already
381
+ drawn - never a component - so any of them may be a client component. The
382
+ panel keeps the Suspense boundaries, because it knows which parts read the
383
+ request; a theme only draws what shows meanwhile.
384
+
385
+ To change one page, spread the shipped theme and replace it:
386
+
387
+ ```tsx title="src/admin/panel.ts"
388
+ import { shadcn } from '@rsc-kit/press/shadcn'
389
+ import { BrandedDashboard } from './branded-dashboard'
390
+
391
+ export const panel = definePanel({
392
+ theme: { ...shadcn, Dashboard: BrandedDashboard },
393
+ // ...
394
+ })
395
+ ```
396
+
397
+ ## Plugins
398
+
399
+ A plugin adds resources, dashboard widgets and a reaction to every save and
400
+ delete, and is installed with `plugins: [auditLog()]`. Writing one to publish
401
+ or sell is [its own guide](/guides/admin-plugins/).
@@ -63,6 +63,27 @@ Reading a body is the web api: `request.json()`, `.formData()`, `.text()`.
63
63
  A route that exports no method at all fails the build rather than becoming a url
64
64
  that answers 405 to everything.
65
65
 
66
+ ## Posts from another site
67
+
68
+ A `POST`, `PUT`, `PATCH` or `DELETE` that a browser sends from another site is
69
+ answered **403** before your handler runs. Without that, any page on the web
70
+ could post a form to your route with your visitor's cookies, and a handler
71
+ reading `cookies()` would act as them. No token is involved: the browser's
72
+ `Sec-Fetch-Site` header says where the request came from, and an older browser's
73
+ `Origin` is compared with your host. It is the rule Go's
74
+ `http.CrossOriginProtection` and Laravel 13 use, and actions and forms are held
75
+ to it too.
76
+
77
+ A caller that is not a browser - a webhook, a cron job, another server - sends
78
+ neither header and is never refused. A browser app on another origin that should
79
+ be able to post is named:
80
+
81
+ ```ts title="vite.config.ts"
82
+ rscKit({ trustedOrigins: ['https://admin.example.com'] })
83
+ ```
84
+
85
+ `GET`, `HEAD` and `OPTIONS` change nothing and are answered from anywhere.
86
+
66
87
  ## Dynamic segments
67
88
 
68
89
  `[name]` and `[...rest]` work as they do for pages, and bind into the second
package/guides/caching.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Asking once per request
2
2
 
3
- > cache() — one lookup, however many places need it.
3
+ > cache() — one lookup, however many places need it, and with a key and a lifetime, however many requests.
4
4
 
5
5
  Middleware checks who you are. The layout wants their name. The page wants their
6
6
  permissions. That is three calls and one answer.
@@ -30,8 +30,8 @@ export default async function Page() {
30
30
 
31
31
  ## One request, and no further
32
32
 
33
- Two requests in flight never see each other's answers, and nothing survives into
34
- the next one. The scope opens when the request arrives and is torn down with it.
33
+ Without options, two requests in flight never see each other's answers, and
34
+ nothing survives into the next one. The scope opens when the request arrives and is torn down with it.
35
35
 
36
36
  That is the whole safety story: a table that outlived its request would not be a
37
37
  stale cache, it would be one visitor seeing another's data.
@@ -55,3 +55,85 @@ than an object when you want the reuse.
55
55
  Same idea, wider scope. Middleware runs before any component does, which is
56
56
  exactly where the duplicate lookups start — and React has no scope open yet.
57
57
  </Aside>
58
+
59
+ ## Across requests
60
+
61
+ Some answers are the same for every visitor: a page built in the panel, a menu,
62
+ a price list. Give `cache()` a key and a lifetime, and the answer is kept
63
+ between requests:
64
+
65
+ ```ts
66
+ import { cache } from '@rsc-kit/core/cache'
67
+
68
+ export const findPage = cache(
69
+ async (slug: string) => db.pages.findBySlug(slug),
70
+ { key: 'pages.find', revalidate: 3600, tags: ['pages'] },
71
+ )
72
+ ```
73
+
74
+ Each request still asks once, as above. Across requests, the answer for each
75
+ argument list is kept for `revalidate` seconds. When the data changes, say so,
76
+ and the next ask misses at once:
77
+
78
+ ```ts
79
+ 'use server'
80
+ import { changed } from '@rsc-kit/core/changed'
81
+
82
+ export async function savePage(values: PageValues) {
83
+ await db.pages.save(values)
84
+ await changed('pages')
85
+ }
86
+ ```
87
+
88
+ `changed()` is the same call that refreshes open tabs for
89
+ [live data](/guides/live-data). Nothing is purged. Each kept answer's key
90
+ includes its tags' versions, so a change makes a new key, and the old entry is
91
+ never read again. `tags` can also be a function of the arguments, for a tag per
92
+ record:
93
+
94
+ ```ts
95
+ cache(findBySlug, { key: 'pages.find', revalidate: 3600, tags: (slug) => [`page:${slug}`] })
96
+ ```
97
+
98
+ - **`key`** names the function in the store. Use the same key on every
99
+ instance, and a different key for every function.
100
+ - **Arguments and answers are JSON.** A `Date` comes back as a string, on the
101
+ first call as well as later ones.
102
+ - **It runs as nobody.** `cookies()` and `headers()` throw inside it, and a call
103
+ to Laravel or Go carries no session. A kept answer is handed to every visitor,
104
+ so it must not be about one of them.
105
+ - **A deploy starts empty.** Keys include the build, so a new deploy never reads
106
+ what an old one kept.
107
+
108
+ ### Where answers are kept
109
+
110
+ In memory by default: the 1,000 most recently used answers, one copy per
111
+ instance. To share them across instances, install a store. It needs only a
112
+ `get` and a `set`:
113
+
114
+ ```ts
115
+ // instrumentation.ts
116
+ import { installCacheStore } from '@rsc-kit/core/cache'
117
+
118
+ // Redis
119
+ installCacheStore(() => ({
120
+ get: (key) => redis.get(key),
121
+ set: (key, value, ttl) => redis.set(key, value, 'EX', ttl),
122
+ }))
123
+
124
+ // Workers KV (60 seconds is KV's shortest expiry)
125
+ installCacheStore(() => ({
126
+ get: (key) => env.CACHE.get(key),
127
+ set: (key, value, ttl) => env.CACHE.put(key, value, { expirationTtl: Math.max(60, ttl) }),
128
+ }))
129
+ ```
130
+
131
+ A store that fails makes pages slower, not broken: the engine warns once and
132
+ does the lookup itself.
133
+
134
+ <Aside type="caution" title="Changes on other instances">
135
+ `changed()` reaches every instance only when the versions are shared, as
136
+ set up for [live data](/guides/live-data#where-the-versions-live). With the
137
+ default in-memory versions, another instance sees a change once its kept
138
+ answer expires, after at most `revalidate` seconds.
139
+ </Aside>
@@ -48,7 +48,7 @@ out of `package.json` when the last page that imports them is gone.
48
48
  | `Route::get('/orders', [OrdersController::class, 'index'])` + `Inertia::render('Orders/Index', ['orders' => …])` | nothing. The controller's body moves to `app/Rsc/Orders.php::recent()`, and the page calls `rpc('Orders.recent')` — [Calling PHP](/hosts/laravel#calling-php) |
49
49
  | props from the controller | `await rpc<T>('Class.method', …args)` inside the server component — as many reads as the page wants; siblings in one render are one batched request |
50
50
  | `usePage().props.auth.user` and the rest of `HandleInertiaRequests::share()` | a read in the layout that needs it — `rpc('Shared.auth')` — passed down as props; there is no global props bag |
51
- | `usePage().props.flash` | the action's own return value: it comes back to the form that submitted, so nothing has to survive a redirect |
51
+ | `usePage().props.flash` | the action's own return value, for the form that submitted; for the page after a redirect, `Rsc::flash('Saved.')` (or `flash()` in a JS action) and `useFlash()`, which shows it once |
52
52
  | `<Link href={route('orders.show', id)}>` (Ziggy) | `<Link href="/orders/1">` from `@rsc-kit/core/Link` — `href` is typed to the route tree, so Ziggy and `@routes` go |
53
53
  | `router.visit()`, `router.get()` | `visit(url)` from `@rsc-kit/core/router` |
54
54
  | `router.reload({ only: ['orders'] })` | `revalidate('orders')` from the action re-renders the [section](/guides/sections) and sends it back with the answer — one request, the rest of the page untouched |
@@ -71,6 +71,7 @@ renders can be, and that one is fine.
71
71
  | `app/robots.ts`, `app/sitemap.ts` | the same files, the same shapes — [robots, sitemap and llms.txt](/guides/seo-files); `app/llms.ts` beside them |
72
72
  | `@react-email/render` in a server action | the same call, in a module that starts with `"use ssr"` — [emails](/guides/emails). Next fails the same way where it renders server components; the directive is how this one moves it |
73
73
  | `cache` from `react` | `cache` from `@rsc-kit/core/cache` — React's memoises only inside a component render; this one spans the request, so a guard, the layout and the action share one call. The build names server files still importing React's |
74
+ | `unstable_cache`, `revalidateTag` | `cache(fn, { key, revalidate, tags })` from `@rsc-kit/core/cache`, and `changed(tag)` from `@rsc-kit/core/changed`, which also refreshes open tabs. Kept in memory, or in any store with a `get` and a `set` — [across requests](/guides/caching/#across-requests) |
74
75
 
75
76
  ## Different on purpose
76
77