@rsc-kit/mcp 0.40.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/recipes.js +37 -20
  2. package/dist/recipes.js.map +1 -1
  3. package/guides/admin-plugins.md +206 -6
  4. package/guides/api-routes.md +159 -215
  5. package/guides/authorization.md +103 -114
  6. package/guides/backend-answered-pages.md +301 -250
  7. package/guides/bap-vs-inertia.md +67 -25
  8. package/guides/blueprints.md +307 -174
  9. package/guides/bun.md +42 -25
  10. package/guides/caching.md +46 -49
  11. package/guides/coming-from-inertia.md +5 -5
  12. package/guides/commands.md +251 -200
  13. package/guides/connection.md +50 -54
  14. package/guides/content-security-policy.md +133 -84
  15. package/guides/domains.md +190 -149
  16. package/guides/edge-caching.md +242 -268
  17. package/guides/emails.md +96 -45
  18. package/guides/errors.md +116 -137
  19. package/guides/feature-flags.md +100 -30
  20. package/guides/file-uploads.md +101 -26
  21. package/guides/fonts.md +139 -110
  22. package/guides/forms.md +520 -538
  23. package/guides/images.md +87 -28
  24. package/guides/index.json +13 -33
  25. package/guides/instrumentation.md +134 -95
  26. package/guides/isr.md +3 -3
  27. package/guides/live-data-in-production.md +695 -0
  28. package/guides/live-data.md +170 -839
  29. package/guides/mcp.md +83 -59
  30. package/guides/metadata.md +124 -179
  31. package/guides/navigation.md +118 -147
  32. package/guides/no-javascript.md +49 -57
  33. package/guides/offline.md +118 -153
  34. package/guides/openapi.md +100 -35
  35. package/guides/pages.md +160 -50
  36. package/guides/ppr.md +178 -256
  37. package/guides/pwa.md +251 -218
  38. package/guides/queries.md +171 -300
  39. package/guides/react-compiler.md +90 -50
  40. package/guides/redirects.md +141 -177
  41. package/guides/response-headers.md +76 -74
  42. package/guides/route-interception.md +112 -111
  43. package/guides/routing.md +216 -322
  44. package/guides/sections.md +63 -66
  45. package/guides/seo-files.md +127 -65
  46. package/guides/server-actions.md +285 -357
  47. package/guides/static-generation.md +131 -199
  48. package/guides/testing.md +272 -150
  49. package/guides/third-party-scripts.md +94 -47
  50. package/guides/typed-routes.md +115 -113
  51. package/guides/url-validation.md +113 -61
  52. package/guides/validation.md +53 -62
  53. package/guides/view-transitions.md +159 -132
  54. package/guides/where-it-runs.md +226 -162
  55. package/package.json +2 -2
  56. package/guides/admin.md +0 -520
  57. package/guides/deployment.md +0 -598
  58. package/guides/go.md +0 -538
  59. package/guides/laravel.md +0 -786
  60. package/guides/your-own-backend.md +0 -587
@@ -2,27 +2,41 @@
2
2
 
3
3
  > Keep what a page shows current as the data changes - refreshOn, events, polling.
4
4
 
5
- A page rendered on the server shows the data as it was. When it changes
6
- while someone is looking - a teammate edits it, a webhook lands, a job
7
- finishes - there are three ways to show the change, and which to use depends
8
- on where the change comes from.
9
-
10
- | | The change comes from | What travels | Use it for |
11
- | --- | --- | --- | --- |
12
- | [`refreshOn`](#refresh-a-section-when-its-data-changes) | your backend: a webhook, a job, another visitor's action | a one-line signal; the section re-renders through its own queries and guards | almost everything - dashboards, inboxes, build status, anything a backend can say changed |
13
- | [`events()` + `useEvents`](/guides/api-routes#a-route-that-streams) | a stream of values: prices, progress, logs | each value, as it is produced | data that *is* a stream, rendered on the client |
14
- | [`usePolling`](/guides/queries#live-data) | nowhere you can hook: a third-party API | the whole answer, every interval | values with no change signal at all |
15
-
16
- Inside the tab that made a change, none of these is needed: an action says
17
- what it changed, and its answer carries those sections back -
5
+ A page shows its data as it was when it rendered. When the data changes while
6
+ someone is looking - a teammate edits it, a webhook lands, a job finishes - a
7
+ section can refresh itself in every open tab.
8
+
9
+ ```tsx title="src/app/t/[team]/repos.section.tsx"
10
+ export default section('repos', Repos, {
11
+ refreshOn: ({ params }) => [`team:${params.team}:repos`],
12
+ })
13
+ ```
14
+
15
+ ```ts
16
+ await changed(`team:${team}:repos`) // every open tab showing it refreshes
17
+ ```
18
+
19
+ Inside the tab that made the change you don't need this: an action says what
20
+ it changed, and its answer brings those sections back. See
18
21
  [revalidate](/guides/sections#refreshing-it).
19
22
 
20
- ## Refresh a section when its data changes
23
+ | The change comes from | Use |
24
+ | --- | --- |
25
+ | your own code: a webhook, a job, another visitor's action | [`refreshOn`](#refreshing-a-section-when-its-data-changes) |
26
+ | a stream of values: prices, progress, logs | [`events()` and `useEvents`](/guides/api-routes#a-route-that-streams) |
27
+ | somewhere you can't hook into, such as a third-party API | [`usePolling`](/guides/queries#live-data) |
28
+
29
+ ## Refreshing a section when its data changes
30
+
31
+ Give a [section](/guides/sections) a `refreshOn` list of names. A name stands
32
+ for a piece of data:
33
+
34
+ ```tsx title="src/app/status/board.section.tsx"
35
+ export default section('board', Board, { refreshOn: ['board'] })
36
+ ```
21
37
 
22
- An action can say what it changed because it is the thing changing it. A
23
- webhook, a job finishing in a worker, another visitor's action - none of
24
- those is in the tab that is showing the data. For those a section says what
25
- it depends on, by name:
38
+ When the names depend on the URL, pass a function. It receives the page's
39
+ `params` and `searchParams`, already awaited:
26
40
 
27
41
  ```tsx title="src/app/t/[team]/repos.section.tsx"
28
42
  export default section('repos', Repos, {
@@ -30,37 +44,29 @@ export default section('repos', Repos, {
30
44
  })
31
45
  ```
32
46
 
33
- and whatever changes the data says so, from wherever it is:
47
+ The function runs on each request, so it can read the request too:
34
48
 
35
- ```ts title="src/app/api/github/webhook/route.ts"
36
- import { changed } from '@rsc-kit/core/changed'
49
+ ```tsx
50
+ import { cookies } from '@rsc-kit/core/request'
37
51
 
38
- export async function POST(request: Request) {
39
- const { team, repos } = await request.json()
40
- await saveRepos(team, repos)
41
- await changed(`team:${team}:repos`)
42
- return new Response(null, { status: 204 })
43
- }
52
+ refreshOn: async () => [`inbox:${(await cookies()).get('agent')?.value}`]
44
53
  ```
45
54
 
46
- Every open tab showing the section refreshes it - the same refresh as above,
47
- with nothing polling and no client code. `refreshOn` is a list of names, or a
48
- function of the section's props - the page's `params` and `searchParams` -
49
- that makes them. A page can declare its own with `export const refreshOn`,
50
- and a change refreshes the page as `refresh('page')` does.
55
+ When a name changes, every open tab showing the section renders it again
56
+ through its own queries and guards. Nothing polls, and you write no client
57
+ code.
51
58
 
52
- The function is given the page's `params` and `searchParams` already awaited,
53
- and runs per request, so it can read the request too - a name for the person
54
- signed in is the usual one on a dashboard:
59
+ ### Refreshing a whole page
55
60
 
56
- ```tsx title="src/app/dashboard/page.tsx"
57
- import { cookies } from '@rsc-kit/core/request'
61
+ A page can export its own `refreshOn`. A change then refreshes the page, as
62
+ `refresh('page')` does:
58
63
 
59
- export const refreshOn = async () => [`inbox:${(await cookies()).get('agent')?.value}`]
64
+ ```tsx title="src/app/dashboard/page.tsx"
65
+ export const refreshOn = async () => [`inbox:${await currentUserId()}`]
60
66
  ```
61
67
 
62
- A page with url schemas types its `refreshOn` from them, so `params` arrives
63
- parsed and typed rather than typed by hand:
68
+ With [URL schemas](/guides/url-validation), type it from the schema so `params`
69
+ arrives parsed:
64
70
 
65
71
  ```tsx title="src/app/teams/[team]/page.tsx"
66
72
  import type { PageRefreshOn } from '@rsc-kit/core/section'
@@ -69,303 +75,125 @@ export const params = z.object({ team: z.string() })
69
75
  export const refreshOn: PageRefreshOn<typeof params> = ({ params }) => [`team:${params.team}`]
70
76
  ```
71
77
 
72
- A page without a schema names its route's pattern instead, and each param is
73
- a string. The pattern is checked against the routes the build found, so a
74
- misspelt param - `params.ap` - or a pattern that is not a page fails the
75
- typecheck:
78
+ Without a schema, name the route's pattern. A misspelt param, or a pattern
79
+ that isn't a page, fails the typecheck:
76
80
 
77
81
  ```tsx title="src/app/[team]/[app]/[env]/page.tsx"
78
82
  export const refreshOn: PageRefreshOn<'/[team]/[app]/[env]'> = ({ params }) => [`app:${params.app}:${params.env}`]
79
83
  ```
80
84
 
81
- `export const refreshOn`, `export function refreshOn` and a list -
82
- `export { refreshOn } from './names'` - all count. `export * from` does not:
83
- the build reads the page, not what it re-exports wholesale, so name it in a
84
- list.
85
+ `export const refreshOn`, `export function refreshOn` and
86
+ `export { refreshOn } from './names'` all work. `export * from` does not: the
87
+ build reads the page, not what it re-exports wholesale, so name it in a list.
85
88
 
86
- That is the whole feature for an app that is only JavaScript. With a Go or
87
- Laravel backend the backend says it instead -
88
- [`reg.Changed(ctx, …)`](/hosts/go#saying-data-changed) or
89
- [`Rsc::changed(…)`](/hosts/laravel#saying-data-changed) - and the page is the same.
89
+ ## Saying that data changed
90
90
 
91
- ## Whose data a name shows
91
+ Call `changed()` with the names, wherever the write happens:
92
92
 
93
- A name is a signal, not data and not a permission. Hearing that
94
- `conversation:42` changed tells a tab only to ask for its section again; what
95
- comes back is rendered for that tab's visitor, through their own session, by
96
- the same queries and guards as the first render. So two people never see each
97
- other's data through a name - they see whatever their own render shows.
98
-
99
- A chat between Ada and Ben:
100
-
101
- ```tsx title="src/app/chats/[id]/messages.section.tsx"
102
- export default section('messages', async function Messages({ params }) {
103
- const { id } = await params
104
- const messages = await rpc('Chats.messages', id) // the backend checks the viewer is in it
105
-
106
- return <Thread messages={messages} />
107
- }, { refreshOn: ({ params }) => [`conversation:${params.id}`] })
108
- ```
93
+ ```ts title="src/app/api/github/webhook/route.ts"
94
+ import { changed } from '@rsc-kit/core/changed'
109
95
 
110
- ```tsx title="src/app/inbox/page.tsx"
111
- // Each person's own list of conversations, with unread counts.
112
- export const refreshOn = async () => [`inbox:${await currentUserId()}`]
96
+ export async function POST(request: Request) {
97
+ const { team, repos } = await request.json()
98
+ await saveRepos(team, repos)
99
+ await changed(`team:${team}:repos`)
100
+ return new Response(null, { status: 204 })
101
+ }
113
102
  ```
114
103
 
115
- ```go
116
- // Ada sends a message.
117
- reg.Changed(ctx, "conversation:42", "inbox:"+ben.ID, "inbox:"+ada.ID)
118
- ```
104
+ With a Go or Laravel backend, the backend says it instead:
105
+ [`reg.Changed(ctx, …)`](/hosts/go/data-changed) or
106
+ [`Rsc::changed(…)`](/hosts/laravel/data-changed). The page is the same.
119
107
 
120
- - Both have conversation 42 open, so both tabs refresh it, and each render
121
- asks `Chats.messages` as its own visitor. If the thread shows "you" and
122
- "them", each sees it from their side.
123
- - Ben's inbox refreshes; so does Ada's. Nobody else's does: their pages were
124
- rendered with their own `inbox:` names.
125
- - Someone who is not in the conversation cannot open the page - its guards
126
- refuse - so no render ever hands them `conversation:42` to listen for. A
127
- tab can only listen for names its page was rendered with: the renderer
128
- signs them, and a name a browser makes up is refused.
129
-
130
- **Name the data, as narrowly as the data.** One name per thing that changes
131
- together: `conversation:{id}`, `inbox:{userId}`, `team:{id}:repos`. Two
132
- different things sharing one name only refresh too often; one thing split
133
- across names refreshes too little. Use ids, not emails or titles - a name
134
- sits in the page and in the stream's url, and its version says when it last
135
- changed, so a name must not be something its visitor should not see.
136
-
137
- A section that shows anything per visitor - "you", their unread count, what
138
- they may do - must never be `shared`: that is the one place a render is
139
- handed from one visitor to another.
140
-
141
- **A change to a child is a change to its parent's list.** Renaming an app
142
- changes the app's own page and the team's list of apps. Say both where the
143
- write happens, rather than making either region watch the other's names:
108
+ Call it **after** the write commits. A tab asks for its section the moment it
109
+ hears, and a render that runs before the commit reads the old data. The tab is
110
+ then at the new version, so it won't ask again until the next change:
144
111
 
145
112
  ```ts
146
- await renameApp(app.id, name)
147
- await changed(`app:${app.id}`, `team:${app.teamId}:apps`)
148
- ```
113
+ await db.transaction(async (tx) => {
114
+ await tx.insert(conversations).values(row)
115
+ // not here: the transaction hasn't committed
116
+ })
149
117
 
150
- ```tsx
151
- // The app's page: refreshOn = ({ params }) => [`app:${params.app}`]
152
- // The team's list: refreshOn = ({ team }) => [`team:${team}:apps`]
118
+ await changed(`agent:${row.agentId}:conversations`) // here
153
119
  ```
154
120
 
155
- Each region names exactly what it shows, and the write - the one place that
156
- knows what it touched - names everything that did. A region that watched
157
- every child's name would hand the tab a name per row, and miss a child added
158
- after it rendered.
159
-
160
- **Not everything can announce itself.** A host's runtime logs, a third-party
161
- status page, anything nothing tells you about: there is no write to call
162
- `changed()` from, so poll it - `usePolling` - and keep `refreshOn` for data
163
- your own code changes.
164
-
165
- ## Testing what a page watches
121
+ In Laravel, `DB::afterCommit(fn () => Rsc::changed(...))` does this inside a
122
+ transaction.
166
123
 
167
- `createTestApp` renders the page as it is deployed, and `watched()` says what
168
- each region refreshes on for that url - `page` for the page's own, a
169
- section's name for each section's:
124
+ A change made where none of your code runs - in `psql`, a migration, another
125
+ application - says nothing, and open tabs stay stale. A database trigger can
126
+ say it for you: see [a change made straight in the database](/guides/live-data-in-production#a-change-made-straight-in-the-database).
170
127
 
171
- ```ts title="tests/live.test.ts"
172
- import { createTestApp } from '@rsc-kit/core/testing'
128
+ ## Naming the data
173
129
 
174
- const app = await createTestApp()
130
+ Use one name per thing that changes together, as narrow as the data:
131
+ `conversation:{id}`, `inbox:{userId}`, `team:{id}:repos`. Two things sharing a
132
+ name refresh too often, and one thing split across names refreshes too little.
175
133
 
176
- test('the team page watches the team and its apps', async () => {
177
- expect(await app.watched('/teams/acme')).toEqual({
178
- page: ['team:acme'],
179
- apps: ['team:acme:apps'],
180
- })
181
- })
182
- ```
134
+ Use ids, not emails or titles. A name is visible in the page, and its version
135
+ says when it last changed, so a name must not be something its visitor
136
+ shouldn't see. Never put a secret in a name.
183
137
 
184
- A region whose `refreshOn` gave no names is there with `[]` - and said in the
185
- server's log in development, since that is usually a param read under the
186
- wrong name. To check what a change does, say it - `changed()` in an app
187
- that keeps its own versions, `testChanges()` with a test backend - and fetch
188
- the section again: [What a page watches](/guides/testing#what-a-page-watches).
138
+ ### A name doesn't decide who sees what
189
139
 
190
- ## How a tab finds out
140
+ Hearing that `conversation:42` changed only tells a tab to ask for its section
141
+ again. The new render runs as that tab's visitor, through the same queries and
142
+ guards as the first one, so nobody sees another person's data through a name.
191
143
 
192
- Each name has a version, a number that moves when something says the name
193
- changed. Nothing else travels - not what changed, not the data.
194
-
195
- 1. The page renders, reads the version of each name it shows, and hands them
196
- to the tab, signed.
197
- 2. The tab opens one stream, `/_rsc/changes`, for every name on the page. Only
198
- a page with `refreshOn` opens one, and only while the tab is visible.
199
- 3. The server asks where the versions live - "which of these differ from what
200
- I hold?" - once for every open tab it is serving, and again on an interval.
201
- 4. When a version has moved, the stream says so in one line, and the tab asks
202
- for exactly the sections showing that name, the way `refresh('repos')` does.
144
+ ```tsx title="src/app/chats/[id]/messages.section.tsx"
145
+ export default section('messages', async function Messages({ params }) {
146
+ const { id } = await params
147
+ const messages = await rpc('Chats.messages', id) // the backend checks the viewer is in it
203
148
 
204
- A name belongs to the data, not to a section or a page. Any number of
205
- sections, on any number of pages, can refresh on the same name: one
206
- `changed('team:1:repos')` moves its version once, and every open tab showing
207
- any of them refreshes the ones it has. Section *names* are separate - two
208
- pages may both have a section called `stats`; each is resolved through its own
209
- page, and a shared render is never handed from one page to the other.
149
+ return <Thread messages={messages} />
150
+ }, { refreshOn: ({ params }) => [`conversation:${params.id}`] })
151
+ ```
210
152
 
211
- The data is never pushed: the section is rendered fresh, through its own
212
- queries and its own guards, as any refresh is. That is also why this runs
213
- on a Worker - the stream holds no state, and a version is a read.
153
+ ```go
154
+ // Ada sends Ben a message.
155
+ reg.Changed(ctx, "conversation:42", "inbox:"+ben.ID, "inbox:"+ada.ID)
156
+ ```
214
157
 
215
- ## Where the versions live
158
+ - Both have the conversation open, and each render asks `Chats.messages` as
159
+ its own visitor.
160
+ - Ben's inbox and Ada's refresh. Nobody else's does: their pages were rendered
161
+ with their own `inbox:` names.
162
+ - Someone outside the conversation can't open the page, so their tab never
163
+ gets the name. The renderer signs the names a page hands out, and refuses a
164
+ name a browser makes up.
216
165
 
217
- **One server, no backend:** in that server's memory. Nothing to set up - but
218
- in production rsc-kit says so in its log, once, because the same default
219
- fails silently the moment there are two instances. If the deploy really is
220
- one instance, say so and the warning goes:
166
+ ### Changing a child changes its parent's list
221
167
 
222
- ```ts title="src/instrumentation.ts"
223
- import { installVersionSource, memoryVersions } from '@rsc-kit/core/changed'
168
+ Renaming an app changes the app's page and the team's list of apps. Name both
169
+ where the write happens:
224
170
 
225
- export function register() {
226
- installVersionSource(memoryVersions()) // one instance, on purpose
227
- }
171
+ ```ts
172
+ await renameApp(app.id, name)
173
+ await changed(`app:${app.id}`, `team:${app.teamId}:apps`)
228
174
  ```
229
175
 
230
- **More than one instance, or a worker process:** this is the case to
231
- plan for. In-memory versions fail silently the moment a load balancer adds a
232
- second instance - a change made on one never reaches the tabs held by the
233
- other - and a job finishes in a process that serves no pages at all. Keep
234
- the versions somewhere they all share - any database you already have, through
235
- the client you already use. rsc-kit ships no driver; you hand it yours:
236
-
237
- | Your database | The store | Another instance's change arrives |
238
- | --- | --- | --- |
239
- | Postgres, with postgres.js or `Bun.sql` (Bun 1.4+) - or the one under Drizzle | `postgresVersions(sql)`, or `postgresVersions(db.$client)` | at once, through LISTEN/NOTIFY; one statement per change |
240
- | Postgres, with another client | `sqlVersions({ query, placeholder: (n) => '$' + n })` | within a second |
241
- | MySQL, MariaDB | `sqlVersions({ query, dialect: 'mysql' })` | within a second; one statement per change |
242
- | SQLite, libSQL, Turso, D1 | `sqlVersions({ query, dialect: 'sqlite' })` | within a second; one statement per change |
243
- | Redis | `createVersions({ read, bump, listen, notify })` | at once, through pub/sub |
244
- | An ORM: Drizzle, Prisma, Kysely, Knex | `createVersions` over its query builder, or `sqlVersions` over its raw query | as its database |
245
-
246
- `sqlVersions` takes your driver as one function of SQL text and parameters.
247
- Say which database with `dialect`, and a change is one upsert of every name it
248
- moves; leave it out and it uses only SQL every database has, a read and a
249
- write per name:
176
+ Each region names only what it shows: the app's page `app:{id}`, the team's
177
+ list `team:{id}:apps`. A list that watched every child's name would miss a
178
+ child added after it rendered.
250
179
 
251
- ```ts title="src/versions.ts"
252
- import { sqlVersions } from '@rsc-kit/core/changed'
180
+ Something nothing tells you about, such as a third-party status page, has no
181
+ write to call `changed()` from. Poll it with `usePolling`.
253
182
 
254
- // MySQL, mysql2
255
- export const versions = sqlVersions({ dialect: 'mysql', query: async (text, params) => (await pool.query(text, params))[0] })
256
-
257
- // SQLite, bun:sqlite or better-sqlite3
258
- export const versions = sqlVersions({ dialect: 'sqlite', query: async (text, params) => db.query(text).all(...params) })
259
-
260
- // libSQL / Turso
261
- export const versions = sqlVersions({ dialect: 'sqlite', query: async (sql, args) => (await client.execute({ sql, args })).rows })
262
- ```
183
+ ## Running more than one server
263
184
 
264
- and with postgres.js it is one line:
185
+ On one server, versions are kept in memory and there is nothing to set up.
186
+ With a second instance, or a worker process, a change made on one never
187
+ reaches the tabs held by another. Keep the versions in a database they all
188
+ share:
265
189
 
266
190
  ```ts title="src/versions.ts"
267
191
  import postgres from 'postgres'
268
192
  import { postgresVersions } from '@rsc-kit/core/changed'
269
193
 
270
- // A function, so the store - and its database client - is made on first use.
271
194
  export const versions = () => postgresVersions(postgres(process.env.DATABASE_URL!))
272
195
  ```
273
196
 
274
- A SQLite file is shared by the processes on one machine - a web server and a
275
- worker on the same box. Instances on several machines need a database they
276
- all reach over the network. The table every one of these reads is described
277
- [below](#the-table).
278
-
279
- postgres.js and `Bun.sql` both LISTEN, and `postgresVersions` uses it when the
280
- client has it: a change on one instance - or in a worker - reaches the tabs on
281
- every other at once. A listening server still reads the table now and then, in
282
- case its listening connection dropped without a word; it is not how changes
283
- normally arrive.
284
-
285
- **Any database, any ORM, or no SQL at all.** rsc-kit needs three things from
286
- your storage - read some versions, move some versions, and, if it can,
287
- say the moment one moved - and does the comparing, waiting and waking itself.
288
- `createVersions` takes exactly those:
289
-
290
- With Drizzle, use its query builder rather than raw SQL - the table is one
291
- more table in your schema:
292
-
293
- ```ts title="src/db/schema.ts"
294
- import { bigint, pgTable, text } from 'drizzle-orm/pg-core'
295
-
296
- export const rscVersions = pgTable('rsc_versions', {
297
- name: text('name').primaryKey(),
298
- version: bigint('version', { mode: 'number' }).notNull(),
299
- })
300
- ```
301
-
302
- ```ts title="src/versions.ts"
303
- import { inArray, sql } from 'drizzle-orm'
304
- import { createVersions } from '@rsc-kit/core/changed'
305
- import { db } from './db'
306
- import { rscVersions } from './db/schema'
307
-
308
- export const versions = createVersions({
309
- read: async (names) =>
310
- Object.fromEntries(
311
- (await db.select().from(rscVersions).where(inArray(rscVersions.name, names)))
312
- .map((row) => [row.name, Number(row.version)]),
313
- ),
314
- bump: async (names) => {
315
- await db.insert(rscVersions)
316
- .values(names.map((name) => ({ name, version: Date.now() })))
317
- .onConflictDoUpdate({
318
- target: rscVersions.name,
319
- set: { version: sql`GREATEST(${rscVersions.version} + 1, excluded.version)` },
320
- })
321
- },
322
- })
323
- ```
324
-
325
- ```ts title="Prisma"
326
- import { sqlVersions } from '@rsc-kit/core/changed'
327
-
328
- // Raw SQL through Prisma; the table is a model in its schema - see "The table" below.
329
- export const versions = sqlVersions({
330
- query: (text, params) => prisma.$queryRawUnsafe(text, ...params),
331
- placeholder: (n) => '$' + n, // Postgres; leave out for MySQL and SQLite
332
- })
333
- ```
334
-
335
- ```ts title="Redis"
336
- import { createVersions } from '@rsc-kit/core/changed'
337
-
338
- const key = (name: string) => 'rsc:' + name
339
- const BUMP = `local v = math.max(tonumber(redis.call('GET', KEYS[1]) or '0') + 1, tonumber(ARGV[1]))
340
- redis.call('SET', KEYS[1], v, 'EX', ARGV[2])
341
- return v`
342
-
343
- export const versions = createVersions({
344
- read: async (names) => {
345
- const values = await redis.mget(names.map(key))
346
- return Object.fromEntries(names.map((name, i) => [name, Number(values[i] ?? 0)]))
347
- },
348
- // One past where it was, or now if that is larger - see "Cleaning up".
349
- bump: async (names) => {
350
- await Promise.all(names.map((name) => redis.eval(BUMP, 1, key(name), Date.now(), 30 * 86400)))
351
- },
352
- // Instant across instances: a subscriber connection hears every bump.
353
- listen: (wake) => subscriber.subscribe('rsc:versions', wake),
354
- notify: () => redis.publish('rsc:versions', ''),
355
- })
356
- ```
357
-
358
- `sqlVersions({ query })` takes any SQL driver as a function of text and
359
- parameters - node-postgres, mysql2, Kysely, Knex, D1 - and `createVersions`
360
- takes anything else.
361
-
362
- Install it in every process - the web server once, before the first request.
363
- Pass the function, not a store: `register()` also runs during the build,
364
- usually without the database's settings, and a store made there makes its
365
- client there too. Given a function, rsc-kit makes the store the first time
366
- versions are read - which a build never does.
367
-
368
-
369
197
  ```ts title="src/instrumentation.ts"
370
198
  import { installVersionSource } from '@rsc-kit/core/changed'
371
199
  import { versions } from './versions'
@@ -375,508 +203,56 @@ export function register() {
375
203
  }
376
204
  ```
377
205
 
378
- and the worker, which then says what it finished:
379
-
380
- ```ts title="worker.ts"
381
- import { changed, installVersionSource } from '@rsc-kit/core/changed'
382
- import { versions } from './src/versions'
383
-
384
- installVersionSource(versions)
385
-
386
- queue.on('restoration.done', async (job) => {
387
- await changed(`restoration:${job.id}`)
388
- })
389
- ```
390
-
391
- Without `listen` and `notify` - MySQL, SQLite, or a driver that cannot listen -
392
- a waiting server reads the table every second instead (`poll` changes it).
393
-
394
- **From any process, without rsc-kit:** the table is the contract. A cron job,
395
- a service in another language, a database trigger - anything that can write
396
- to it can say a name changed:
397
-
398
- ```sql
399
- -- Postgres
400
- INSERT INTO rsc_versions (name, version)
401
- VALUES ('restoration:42', (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::bigint)
402
- ON CONFLICT (name) DO UPDATE SET version = GREATEST(rsc_versions.version + 1, EXCLUDED.version);
403
- NOTIFY rsc_versions; -- optional: wakes the listening servers at once
404
-
405
- -- MySQL, MariaDB
406
- INSERT INTO rsc_versions (name, version)
407
- VALUES ('restoration:42', FLOOR(UNIX_TIMESTAMP(NOW(3)) * 1000))
408
- ON DUPLICATE KEY UPDATE version = GREATEST(version + 1, VALUES(version));
409
-
410
- -- SQLite
411
- INSERT INTO rsc_versions (name, version)
412
- VALUES ('restoration:42', CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER))
413
- ON CONFLICT (name) DO UPDATE SET version = MAX(version + 1, excluded.version);
414
- ```
206
+ Every instance also needs the same `RSC_SIGNING_SECRET`.
207
+ [Live data in production](/guides/live-data-in-production) covers MySQL,
208
+ SQLite, Redis and ORMs, the table, connection poolers, Workers, and what it
209
+ costs. With a Go or Laravel backend, the backend keeps the versions and you
210
+ install nothing.
415
211
 
416
- The new version is one past the old, or the current time in milliseconds if
417
- that is larger - so a version never repeats, which is what makes it safe to
418
- delete old rows ([Cleaning up](#cleaning-up)). Every writer must bump this
419
- way; a plain `version + 1` is a counter, and a counter repeats once a row is
420
- deleted. Go's `SQLVersions` uses the same table, so a Go service and a
421
- JavaScript app can share one.
422
-
423
- **LISTEN through an ORM, or another driver.** An ORM builds queries; listening
424
- is its driver's job, so pass `listen` and `notify` from the client underneath -
425
- the one you handed the ORM:
426
-
427
- ```ts title="src/versions.ts"
428
- import { SQL } from 'bun'
429
- import { drizzle } from 'drizzle-orm/bun-sql'
430
-
431
- const client = new SQL(process.env.DATABASE_URL!)
432
- export const db = drizzle({ client })
433
-
434
- export const versions = createVersions({
435
- read, // the Drizzle read and bump above
436
- bump,
437
- listen: (wake) => client.listen('rsc_versions', wake),
438
- notify: () => client.notify('rsc_versions', ''),
439
- })
440
- ```
441
-
442
- On node-postgres (`pg`), keep one client for listening alone:
443
-
444
- ```ts
445
- const listener = new pg.Client(process.env.DATABASE_URL)
446
- await listener.connect()
447
-
448
- listen: async (wake) => {
449
- listener.on('notification', wake)
450
- await listener.query('LISTEN rsc_versions')
451
- },
452
- notify: () => pool.query('NOTIFY rsc_versions'),
453
- ```
454
-
455
- A `NOTIFY` sent inside a transaction is only delivered when it commits, so a
456
- listening tab is never woken before the data it will read is there - the
457
- [after-commit](#say-it-after-the-write-commits) rule, kept by the database.
458
- Redis has the same shape with SUBSCRIBE and PUBLISH (the example above).
459
-
460
- ## Connection poolers
461
-
462
- A pooler in **transaction mode** - PgBouncer, and the pooled connection
463
- DigitalOcean, Supabase and Neon offer - hands the database connection back
464
- after every statement. Reads and writes are fine; even sending a NOTIFY is.
465
- But a LISTEN lands on a connection the pooler takes back, and the listener
466
- hears nothing - silently. Changes from other instances would then wait for the
467
- thirty-second safety net.
468
-
469
- rsc-kit checks: as `postgresVersions` starts listening it sends itself a probe,
470
- and if the probe does not come back it says so in the log - naming the cause
471
- and the fix - and goes back to reading every second. The fix is to listen
472
- through a connection that keeps its session - a direct one, or a pool in
473
- session mode - and leave everything else on the pool:
474
-
475
- ```ts title="src/versions.ts"
476
- import { SQL } from 'bun'
477
- import { postgresVersions } from '@rsc-kit/core/changed'
478
-
479
- export const versions = () =>
480
- postgresVersions(new SQL(process.env.DATABASE_URL!), { // the pool: reads and writes
481
- listenWith: new SQL(process.env.DATABASE_LISTEN_URL!), // direct: listening only
482
- })
483
- ```
212
+ ## Sharing one render between tabs
484
213
 
485
- That is one extra connection per process. On DigitalOcean the direct port is
486
- 25060 and the pool's 25061; on Supabase, 5432 and 6543. Use the app's own
487
- database user for it, not the one migrations run as.
214
+ By default each tab renders its own refresh, since each can differ by who is
215
+ looking: 500 tabs on one board are 500 renders. A section that is the same for
216
+ everyone who may see the page can share one:
488
217
 
489
- If direct connections are too scarce to spend one per process, don't listen -
490
- say so, and rsc-kit reads every second instead, with no probe and no warning:
491
-
492
- ```ts
493
- postgresVersions(pool, { listen: false })
218
+ ```tsx title="src/app/status/board.section.tsx"
219
+ export default section('board', Board, { refreshOn: ['board'], shared: true })
494
220
  ```
495
221
 
496
- That is one small indexed read per second per process, however many tabs it
497
- holds. A change made in a process still reaches that process's tabs at once;
498
- one made elsewhere - another instance, the worker - within about a second.
222
+ The first tab's request renders it, and the others asking because of the same
223
+ change get the same bytes. Each tab's guards still run on its own request, and
224
+ a `refresh()` by hand or after an action always renders afresh.
499
225
 
500
- `await connection()` in a page is unrelated - despite the name, it is about
501
- rendering per request, not database connections.
226
+ Never set `shared` on a section that shows anything per visitor: their name,
227
+ their data, what they may do. Every tab is shown the first visitor's render,
228
+ and its `rpc()` calls ran with the first visitor's session.
502
229
 
503
- ## On Workers and serverless
504
-
505
- The stream needs nothing kept between requests - names are signed, not
506
- looked up - so it runs anywhere a response can stream. What differs is that
507
- there is no single long-lived process:
508
-
509
- - **Every isolate or instance watches for its own tabs.** Versions in memory
510
- belong to one isolate, so a `changed()` handled by one never reaches tabs
511
- held by another. Use a shared store - D1, Postgres, your backend - which the
512
- production warning asks for if there is none. On Workers, [one hub](#one-hub-on-workers)
513
- can hold every tab instead.
514
- - **Connections are cut.** Platforms bound how long a request may run; a
515
- stream that is cut reconnects on its own, and the tab catches up from its
516
- versions. On a platform that bills a function for every second it is open,
517
- each watching tab is billed for as long as it watches.
518
- - **Listening is unlikely.** Hyperdrive and serverless Postgres drivers go
519
- through poolers; the probe finds this and falls back to reading every second,
520
- or say `listen: false` up front.
230
+ ## Testing what a page watches
521
231
 
522
- On Workers, bindings come from `cloudflare:workers`, imported inside a
523
- request - when they exist, and never in the build:
232
+ `watched()` returns the names each region of a page refreshes on: `page` for
233
+ the page's own, and each section by its name:
524
234
 
525
- ```ts title="src/versions.ts"
526
- import { sqlVersions } from '@rsc-kit/core/changed'
235
+ ```ts title="tests/live.test.ts"
236
+ import { createTestApp } from '@rsc-kit/core/testing'
527
237
 
528
- // The binding, imported inside the request: the build prerenders in Node,
529
- // which runs register() and cannot load cloudflare:workers.
530
- const db = async () => (await import('cloudflare:workers')).env.DB
238
+ const app = await createTestApp()
531
239
 
532
- // D1: the table is the same as anywhere else.
533
- export const versions = () =>
534
- sqlVersions({
535
- dialect: 'sqlite',
536
- query: async (text, params) => (await (await db()).prepare(text).bind(...params).all()).results,
240
+ test('the team page watches the team and its apps', async () => {
241
+ expect(await app.watched('/teams/acme')).toEqual({
242
+ page: ['team:acme'],
243
+ apps: ['team:acme:apps'],
537
244
  })
538
- ```
539
-
540
- Then the binding, the table and the secret:
541
-
542
- ```jsonc title="wrangler.jsonc"
543
- {
544
- // Nitro merges this into the Worker's config.
545
- "d1_databases": [
546
- { "binding": "DB", "database_name": "my-app", "database_id": "<from wrangler d1 create>", "migrations_dir": "migrations" }
547
- ]
548
- }
549
- ```
550
-
551
- ```sql title="migrations/0001_rsc_versions.sql"
552
- CREATE TABLE IF NOT EXISTS rsc_versions (name TEXT PRIMARY KEY, version BIGINT NOT NULL);
553
- ```
554
-
555
- ```sh
556
- npx wrangler d1 create my-app # once; put its id in wrangler.jsonc
557
- npx wrangler d1 migrations apply DB --remote # --local for wrangler dev
558
- npx wrangler secret put RSC_SIGNING_SECRET # production; .dev.vars for wrangler dev
559
- ```
560
-
561
- and install it as anywhere else - `installVersionSource(versions)` in
562
- `instrumentation.ts`. A section the store serves needs `await connection()`
563
- when it reads D1 itself: the data is only there per request.
564
-
565
- The Cloudflare example's `/live` page is all of this, end to end, and was run
566
- on `wrangler dev`: a change from its webhook reaches an open tab, and the
567
- section refreshes with the new value.
568
-
569
- ### One hub on Workers
570
-
571
- Each isolate watches only the tabs it happens to hold, and on Workers that is
572
- often one. So by default every open tab costs its own ask of the store, every
573
- two seconds, and a `wakeOn` listener runs once per isolate. A Durable Object
574
- is one place every isolate can reach. Name it, and every tab's stream goes to
575
- one instance, which watches all of them:
576
-
577
- ```ts title="vite.config.ts"
578
- // cloudflare_module, plus the Durable Object class the hub runs in.
579
- nitro({ preset: 'cloudflare_durable', serveStatic: 'inline' })
580
- ```
581
-
582
- ```jsonc title="wrangler.jsonc"
583
- {
584
- "durable_objects": {
585
- "bindings": [{ "name": "$DurableObject", "class_name": "$DurableObject" }]
586
- },
587
- "migrations": [{ "tag": "v1", "new_sqlite_classes": ["$DurableObject"] }],
588
- "vars": { "RSC_CHANGES_HUB": "$DurableObject" }
589
- }
590
- ```
591
-
592
- Nothing changes in the app. `RSC_CHANGES_HUB` names the binding, and rsc-kit
593
- does not look for one on its own: without it, each isolate watches its own
594
- tabs as before. A name with no binding behind it is said once in the log, and
595
- the isolate falls back to that.
596
-
597
- What changes, against each isolate watching its own tabs:
598
-
599
- | | Each isolate (default) | One hub |
600
- | --- | --- | --- |
601
- | Asks of the store or backend | one per open tab, every 2s | one for every tab, every 2s |
602
- | A `changed()` reaches the tabs | at each isolate's next read, within a second or two | at once: `changed()` wakes the hub |
603
- | A `wakeOn` listener or broadcast | one connection per isolate | one connection |
604
- | Cost of a store with no LISTEN (D1) | grows with tabs | flat |
605
- | A Laravel backend | one PHP request per tab, every 2s | one, for every tab |
606
-
607
- - **Asks stop growing with tabs.** A thousand open tabs cost the store, or
608
- your backend, one ask every two seconds instead of a thousand. On a backend
609
- that answers each ask with a PHP request, this is the difference that
610
- matters.
611
- - **Changes arrive at once without LISTEN.** D1 cannot announce a change.
612
- With the hub, `changed()` in any isolate - a webhook, an action - pokes the
613
- hub after the write, and every tab hears it immediately instead of at the
614
- next read.
615
- - **One listener.** A broadcast server or `wakeOn` listener runs in the hub,
616
- one connection for the deployment, rather than one per isolate that
617
- happens to hold a tab.
618
-
619
- What it costs, and its limits:
620
-
621
- - **Durable Object time.** The hub stays active while any tab watches, and a
622
- Durable Object is billed for the time it is active - for one instance open
623
- all month, a few dollars on Cloudflare's paid plan. With no tab open it
624
- costs nothing.
625
- - **One location.** Every tab's stream goes to the one instance, wherever
626
- Cloudflare placed it. An event crosses one more hop, tens of milliseconds;
627
- the pages themselves are still rendered by the nearest isolate.
628
- - **One instance's limits.** A Durable Object runs on one thread, and
629
- Cloudflare documents a soft limit of about 1,000 requests a second for
630
- one. A site whose tabs connect faster than that should stay on the
631
- default flow, which spreads them across isolates.
632
- - **Versions still live in a shared store.** The hub holds the tabs, not the
633
- versions: D1, your database or your backend still keeps them, so a hub that
634
- restarts loses nothing.
635
-
636
- The forwarded requests carry a proof signed with `RSC_SIGNING_SECRET`, so a
637
- browser cannot reach the hub's side of the endpoint directly. The Cloudflare
638
- example runs this way, and was checked on `wrangler dev`: three tabs' streams
639
- held by the hub, one webhook, and all three hearing the change.
640
-
641
- Where a response cannot stream at all, use `usePolling` instead.
642
-
643
- ## The table
644
-
645
- A shared store keeps one row per name. Your app owns the table: rsc-kit never
646
- creates, alters or migrates it at runtime - make it with your own migrations,
647
- in your own schema, with whatever your ORM calls these types. (Laravel ships
648
- one you publish into your own migrations, `--tag=rsc-migrations`; after that
649
- it is yours too.)
650
-
651
- | Column | Type | |
652
- | --- | --- | --- |
653
- | `name` | text, `PRIMARY KEY` (or a unique index) | the name a section refreshes on |
654
- | `version` | `BIGINT NOT NULL` | when it last changed, in ms - or one past the last value, if that is larger |
655
-
656
- ```sql
657
- -- Postgres, SQLite
658
- CREATE TABLE rsc_versions (name TEXT PRIMARY KEY, version BIGINT NOT NULL);
659
- -- MySQL: an indexed TEXT needs a length
660
- CREATE TABLE rsc_versions (name VARCHAR(255) PRIMARY KEY, version BIGINT NOT NULL);
661
- ```
662
-
663
- - **Extra columns are fine** - an `updated_at`, say - as long as each has a
664
- default: rsc-kit and the documented upserts write only `name` and `version`.
665
- - **Another name is fine:** `sqlVersions({ table })`, `postgresVersions(sql,
666
- { table })`, Go's `SQLVersions{Table}`, Laravel's `RSC_VERSIONS_TABLE`.
667
- - **The NOTIFY channel** is `rsc_versions` whatever the table is called;
668
- `postgresVersions(sql, { channel })` changes it.
669
- - The same table works for Go's `SQLVersions` and Laravel's
670
- `RSC_VERSIONS=database`, so a JavaScript app, a Go service and a PHP job
671
- can share one.
672
-
673
- ## Cleaning up
674
-
675
- A row is kept for every name that ever changed. For a fixed set of names -
676
- `team:1:repos` - that is nothing; for one per order, job or restoration it
677
- grows for ever. Delete the old ones on a schedule:
678
-
679
- ```ts
680
- await versions.prune() // sqlVersions, postgresVersions: not changed in 30 days
681
- await versions.prune(7 * 86400_000) // or any age, in ms
682
- ```
683
-
684
- or from anything that can run SQL - the version is when the name last changed:
685
-
686
- ```sql
687
- DELETE FROM rsc_versions WHERE version < (EXTRACT(EPOCH FROM now() - interval '30 days') * 1000)::bigint;
688
- ```
689
-
690
- **Deleting is always safe.** A deleted name reads as 0, so a tab still
691
- holding it sees a different version and refreshes once; changed again, the
692
- name comes back at the current time - never at a value a tab is holding.
693
- That is why a bump moves to the time rather than counting: a counter
694
- restarted at 0 climbs back to values tabs still hold, and they would miss
695
- the change.
696
-
697
- The rest clean up on their own: `memoryVersions()` forgets a name not changed
698
- in 30 days (`{ forgetAfter }`), the Redis example's keys expire, and the
699
- server forgets every name the moment no open tab is watching it. Laravel and
700
- Go have the same: `php artisan rsc:prune-versions` and `SQLVersions.Prune`.
701
-
702
- A store of your own bumps with `nextVersion(current)` from
703
- `@rsc-kit/core/changed` - never `+ 1`.
704
-
705
- ## Say it after the write commits
706
-
707
- A tab that hears a name moved asks for its section at once. If the write
708
- that changed the data has not committed yet, that render reads the old data -
709
- and the tab is now at the new version, so it will not ask again until the
710
- next change. Inside a transaction, say it changed **after** the transaction,
711
- not inside it:
712
-
713
- ```ts
714
- await db.transaction(async (tx) => {
715
- await tx.insert(conversations).values(row)
716
- // not here: this transaction may still roll back, and has not committed
717
- })
718
-
719
- await changed(`agent:${row.agentId}:conversations`) // here
720
- ```
721
-
722
- The same goes for a worker writing the table directly: in the same
723
- transaction as the data, or after it - never before. In Laravel,
724
- `DB::afterCommit(fn () => Rsc::changed(...))` does this inside a transaction.
725
-
726
- **With a Go or Laravel backend:** the backend keeps them - a table in Go, the
727
- cache in Laravel - and you install nothing here. The backend owns the data,
728
- so it answers for its versions too: the renderer asks it which moved, once
729
- for every tab it is serving. Go holds that question until a version moves,
730
- so tabs hear at once. PHP cannot hold a request open, so Laravel answers at
731
- once and is asked again about every two seconds while any tab is watching:
732
- one small request - a cache read - per renderer process, however many tabs.
733
- For almost any app that is nothing, and a change reaches the tabs within
734
- about two seconds - or at once, with Laravel's [broadcasting](/hosts/laravel#saying-data-changed).
735
-
736
- ## A change made straight in the database
737
-
738
- Nothing watches a table. A section refreshes when a name's version moves, and a
739
- `psql` session, a migration, an admin tool or another application writing the
740
- same rows says nothing. The data is not wrong: any fresh render reads it as it
741
- is now. The tabs already open are stale, and stay so until something refreshes
742
- them, because no version moved.
743
-
744
- Three ways to cover it, in the order to reach for them:
745
-
746
- **Make the writer say it.** Whatever writes calls `changed()` after the write
747
- commits — a job, a webhook, a script you run for a manual fix. This is the one
748
- to prefer, because the name is then written by the code that knows what changed.
749
- It needs a [shared store](#where-the-versions-live) when the script is a different
750
- process from the server; in-memory versions are one process's.
751
-
752
- **Let the database say it.** For writes that never pass through your code, a
753
- trigger on the data table moves the version row, in the same transaction as the
754
- write. That is what `changed()` does, so it follows the same rules, and it
755
- moves with the commit: a write that rolls back moves nothing. Postgres:
756
-
757
- ```sql
758
- CREATE FUNCTION repos_moved() RETURNS trigger AS $$
759
- DECLARE team INT := COALESCE(NEW.team_id, OLD.team_id);
760
- BEGIN
761
- INSERT INTO rsc_versions (name, version)
762
- VALUES ('team:' || team || ':repos', (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::bigint)
763
- ON CONFLICT (name) DO UPDATE SET version = GREATEST(EXCLUDED.version, rsc_versions.version + 1);
764
- -- Delivered when the transaction commits, so a listener never wakes for a rolled-back write.
765
- PERFORM pg_notify('rsc_versions', '');
766
- RETURN NULL;
767
- END $$ LANGUAGE plpgsql;
768
-
769
- CREATE TRIGGER repos_moved AFTER INSERT OR UPDATE OR DELETE ON repos
770
- FOR EACH ROW EXECUTE FUNCTION repos_moved();
771
- ```
772
-
773
- The name must be the one the section lists in `refreshOn`, spelled the same.
774
- The `pg_notify` is what makes tabs hear at once: without it a store that
775
- listens still finds out, but only on its next check, up to 30 seconds later
776
- (a second, for a store that does not listen). The version is one past the last
777
- value when the clock has not moved, so two writes in the same millisecond are
778
- still two changes. SQLite has no `OR` in a trigger event, so it takes one
779
- trigger per statement, with `MAX` for `GREATEST` and no notify — the store
780
- checks every second. The table is [the one above](#the-table), and Go's and
781
- Laravel's stores read the same one.
782
-
783
- **Poll, when nothing can say it.** A value with no writer you control and no
784
- table you can put a trigger on is [`usePolling`](/guides/queries#live-data)'s.
785
- It re-asks on an interval, so it costs a request whether or not anything
786
- changed.
787
-
788
- Delete from the data table and the trigger fires on the old row, which is why
789
- the function reads `OLD` for a delete. Test the trigger the way you would any
790
- other, with a write from a second connection and a tab left open.
791
-
792
- ## Waking the renderer
793
-
794
- Whatever keeps the versions, the renderer has to learn *when* to ask which
795
- moved. Go holds the question until one does; a store that listens -
796
- Postgres's LISTEN, Redis's pub/sub - wakes it; otherwise it asks on a timer.
797
- Anything else that can say "something changed" can wake it too:
798
-
799
- ```ts title="src/instrumentation.ts"
800
- import { listenToBroadcast, wakeOn } from '@rsc-kit/core/changed'
801
-
802
- export function register() {
803
- // A broadcast server - anything speaking the Pusher protocol.
804
- wakeOn(listenToBroadcast({ url: process.env.RSC_BROADCAST_URL!, key: process.env.RSC_BROADCAST_KEY! }))
805
-
806
- // Or a Redis channel your backend publishes to.
807
- wakeOn((wake) => subscriber.subscribe('rsc:changed', wake))
808
- }
809
- ```
810
-
811
- `RSC_BROADCAST_URL` and `RSC_BROADCAST_KEY` in the renderer's environment do
812
- the first with no code. A wake carries nothing - no names, no data - so it
813
- can travel over a public channel: on a wake the renderer asks, as it always
814
- does, and the versions say which names moved for whom. With something to wake
815
- it, the renderer asks on its timer only every thirty seconds, as a safety net
816
- for a dropped connection. Listeners start with the first watching tab, never
817
- in a build.
818
-
819
- **Private data stays private.** A wake decides nothing about who sees what.
820
- On a wake the renderer asks which of *its tabs'* names moved - names each tab
821
- got, signed, from its own render - and a tab that has one refreshes its
822
- section through its own visitor's session and guards. Ada's `inbox:7` is never
823
- a name Ben's tab holds, so a change to it never refreshes his page, broadcast
824
- or not. All a public channel shows a subscriber is that the app changed and
825
- when; if even that timing is sensitive, keep the wake on a channel only the
826
- renderer can reach - a Redis channel, through `wakeOn` - rather than a
827
- broadcast.
828
-
829
- ## The signing secret
830
-
831
- The names a page hands the tab are signed, so a tab can only listen for the
832
- names its page was rendered with - a browser cannot make one up. Every
833
- instance has to sign with the same key, or a tab served by one is refused by
834
- the next and never refreshes:
835
-
836
- ```sh
837
- RSC_SIGNING_SECRET=… # the same on every instance: openssl rand -base64 32
838
- ```
839
-
840
- It is its own secret, with or without a backend - not the backend's
841
- `RSC_HOST_CALL_SECRET`, which authorises a different thing. In production, an
842
- app that uses `refreshOn` without it refuses to serve, saying what to set: a
843
- random key per instance would fail silently.
844
-
845
- That refusal comes on the first request, because on some platforms - Workers
846
- - the environment is only there once a request arrives. Under Kubernetes or
847
- any orchestrator with a readiness check, that is too late: the pod is already
848
- taking traffic. Make the deploy itself fail instead, by declaring the secret
849
- where every other variable is - in `env.ts`, which refuses a missing variable
850
- before the server starts:
851
-
852
- ```ts title="src/env.ts"
853
- export const env = createEnv({
854
- server: {
855
- // Signs refreshOn's names. Required in production; in development a
856
- // random key is fine, and what rsc-kit uses without one.
857
- RSC_SIGNING_SECRET:
858
- process.env.NODE_ENV === 'production' ? z.string().min(32) : z.string().optional(),
859
- // ...
860
- },
861
- // ...
862
245
  })
863
246
  ```
864
247
 
865
- An app without an `env.ts` gets the same from `assertSigningSecret()`, from
866
- `@rsc-kit/core/changed`, called in `register()`. In development a random key
867
- is fine, and is what you get.
868
-
869
- How to generate it, where to keep it, and what rotating it does:
870
- [Secrets](/hosts/deployment#secrets).
871
-
872
- Names are signed when the page is served, never at build: a page stored at
873
- build keeps everything else stored, and the part that carries the names is
874
- filled per request. So the build does not need the secret.
248
+ A region whose `refreshOn` gave no names appears with `[]`, which is usually a
249
+ param read under the wrong name. To check what a change does, see
250
+ [what a page watches](/guides/testing#what-a-page-watches).
875
251
 
876
252
  ## When nothing refreshes
877
253
 
878
- In development the browser console says what the page is watching, region
879
- by region, each time that changes:
254
+ In development the browser console lists what the page is watching, region by
255
+ region:
880
256
 
881
257
  ```
882
258
  [rsc-kit] refreshOn watching, by region:
@@ -884,67 +260,22 @@ by region, each time that changes:
884
260
  page: inbox:ada @0
885
261
  ```
886
262
 
887
- A region that declared `refreshOn` but is missing from that list rendered no
888
- names, and the server's log says why, once - including when its function
889
- returned none at all. And watching **stops while the
890
- tab is hidden** - a background tab holds no connection - which the console
891
- also says. Nothing is missed: shown again, the tab reconnects at the versions
892
- it holds and refreshes whatever moved meanwhile.
893
-
894
- ## When many tabs show the same thing
895
-
896
- When a name moves, every tab showing it asks for its sections again - 500 tabs
897
- on one team's board are 500 renders. Each tab's render can differ by who is
898
- looking, so by default each is its own. A section that is the same for
899
- everyone allowed to see the page can say so:
900
-
901
- ```tsx title="src/app/status/board.section.tsx"
902
- export default section('board', Board, { refreshOn: ['board'], shared: true })
903
- ```
904
-
905
- Then the tabs asking because of the same change get one render between them:
906
- the first tab's request renders it, and every other gets the same bytes.
907
- Each tab's guards still run on its own request - a visitor who may not see
908
- the page is still refused - and only a refresh a change triggered is shared,
909
- so `refresh()` by hand, or after an action, always renders afresh.
910
-
911
- Never set `shared` on a section that shows anything per visitor - their name,
912
- their data, what they may do. The first tab's render is what every other tab
913
- is shown, `rpc()` calls included: they run with the first visitor's session.
914
-
915
- ## What it costs
916
-
917
- - **Per tab:** one open connection while the page is visible, closed when the
918
- tab is hidden and reopened when it is seen again. Idle, it carries a
919
- keepalive line every eight seconds ([set it lower](/hosts/deployment#streams-and-idle-timeouts)
920
- under a shorter idle timeout); a change is one line of about forty
921
- bytes.
922
- - **Per change:** each tab showing the name asks for the sections that show
923
- it, once, however many names moved together. That request is the size of
924
- the section, not the page. A `shared` section renders once per change for
925
- every tab; any other renders once per tab.
926
- - **On the server:** one ask of wherever the versions live, covering every tab
927
- that server holds - a thousand open tabs are one query, not a thousand. The
928
- ask may wait up to five seconds for a change: a database with `listen`, or a
929
- Go backend, answers the moment a version moves; a table without it is read
930
- once a second while the ask waits; Laravel answers at once and is asked again
931
- two seconds later. Plus one small read when each tab opens its stream.
932
-
933
- Polling a section every two seconds instead costs a full render of it, per
934
- tab, every two seconds, whether anything changed or not. The trade is the open
935
- connection: cheap on Bun, Node and Workers; on a host that bills a function
936
- for every second it is open, it is a second billed for as long as the tab is.
263
+ - **A region is missing from the list.** Its `refreshOn` rendered no names,
264
+ and the server's log says why.
265
+ - **The tab is in the background.** A hidden tab stops watching and the
266
+ console says so. When it's shown again it catches up on whatever changed.
267
+ - **It works locally but not in production.** There is more than one instance;
268
+ see [running more than one server](#running-more-than-one-server).
269
+ - **The change was made outside your code.** See
270
+ [saying that data changed](#saying-that-data-changed).
937
271
 
938
272
  ## Coming from Next.js
939
273
 
940
- This is where `revalidateTag` was, and it is not the same thing. Next's tags
941
- label entries in its Data Cache and `revalidateTag()` throws them away, so the
942
- *next request* refetches; an open tab learns nothing until it navigates.
943
- There is no data cache here - every render is fresh - so `refreshOn` names
944
- what is *on screen*, and `changed()` refreshes every open tab showing it, now.
945
- A port keeps its names: `tags: ['posts']` on the fetch becomes
946
- `refreshOn: ['posts']` on the section, and `revalidateTag('posts')` becomes
947
- `changed('posts')`.
948
-
949
- A name's version reveals only that something with that name changed. Do not
950
- put a secret in a name.
274
+ `refreshOn` replaces fetch tags, and `changed()` replaces `revalidateTag()`.
275
+ `tags: ['posts']` on a fetch becomes `refreshOn: ['posts']` on the section, and
276
+ `revalidateTag('posts')` becomes `changed('posts')`.
277
+
278
+ They aren't the same thing. Next's `revalidateTag()` empties its Data Cache so
279
+ the *next request* refetches, and an open tab learns nothing until it
280
+ navigates. Here there is no data cache, and `changed()` refreshes every open
281
+ tab showing the name, now.