@rsc-kit/mcp 0.41.0 → 0.42.1

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 +18 -2
  2. package/dist/recipes.js.map +1 -1
  3. package/guides/admin-plugins.md +206 -6
  4. package/guides/api-routes.md +159 -215
  5. package/guides/authorization.md +103 -114
  6. package/guides/backend-answered-pages.md +301 -252
  7. package/guides/bap-vs-inertia.md +67 -25
  8. package/guides/blueprints.md +300 -169
  9. package/guides/bun.md +42 -25
  10. package/guides/caching.md +46 -49
  11. package/guides/coming-from-inertia.md +2 -2
  12. package/guides/commands.md +251 -200
  13. package/guides/connection.md +50 -54
  14. package/guides/content-security-policy.md +133 -84
  15. package/guides/domains.md +190 -149
  16. package/guides/edge-caching.md +242 -268
  17. package/guides/emails.md +96 -45
  18. package/guides/errors.md +116 -137
  19. package/guides/feature-flags.md +100 -30
  20. package/guides/file-uploads.md +101 -26
  21. package/guides/fonts.md +139 -110
  22. package/guides/forms.md +520 -542
  23. package/guides/images.md +87 -28
  24. package/guides/index.json +13 -33
  25. package/guides/instrumentation.md +134 -95
  26. package/guides/isr.md +3 -3
  27. package/guides/live-data-in-production.md +695 -0
  28. package/guides/live-data.md +170 -839
  29. package/guides/mcp.md +83 -59
  30. package/guides/metadata.md +124 -179
  31. package/guides/navigation.md +118 -147
  32. package/guides/no-javascript.md +49 -57
  33. package/guides/offline.md +118 -153
  34. package/guides/openapi.md +100 -35
  35. package/guides/pages.md +160 -50
  36. package/guides/ppr.md +178 -256
  37. package/guides/pwa.md +270 -216
  38. package/guides/queries.md +171 -300
  39. package/guides/react-compiler.md +90 -50
  40. package/guides/redirects.md +141 -177
  41. package/guides/response-headers.md +76 -74
  42. package/guides/route-interception.md +112 -111
  43. package/guides/routing.md +216 -322
  44. package/guides/sections.md +63 -66
  45. package/guides/seo-files.md +127 -65
  46. package/guides/server-actions.md +285 -357
  47. package/guides/static-generation.md +131 -199
  48. package/guides/testing.md +269 -147
  49. package/guides/third-party-scripts.md +94 -47
  50. package/guides/typed-routes.md +115 -113
  51. package/guides/url-validation.md +113 -61
  52. package/guides/validation.md +53 -62
  53. package/guides/view-transitions.md +159 -132
  54. package/guides/where-it-runs.md +226 -162
  55. package/package.json +2 -2
  56. package/guides/admin.md +0 -520
  57. package/guides/deployment.md +0 -598
  58. package/guides/go.md +0 -539
  59. package/guides/laravel.md +0 -787
  60. package/guides/your-own-backend.md +0 -602
@@ -0,0 +1,695 @@
1
+ # Live data in production
2
+
3
+ > Where refreshOn's versions are kept, and running live data on several servers, Workers and poolers.
4
+
5
+ [Live data](/guides/live-data) works on one server with nothing to set up. This
6
+ page is for everything after that: more than one instance, a worker process,
7
+ Workers, a connection pooler, and the table the versions live in.
8
+
9
+ ## How a tab finds out
10
+
11
+ Each name has a version, a number that moves when something says the name
12
+ changed. Nothing else travels - not what changed, not the data.
13
+
14
+ 1. The page renders, reads the version of each name it shows, and hands them
15
+ to the tab, signed.
16
+ 2. The tab opens one stream, `/_rsc/changes`, for every name on the page. Only
17
+ a page with `refreshOn` opens one, and only while the tab is visible.
18
+ 3. The server asks where the versions live - "which of these differ from what
19
+ I hold?" - once for every open tab it is serving, and again on an interval.
20
+ 4. When a version has moved, the stream says so in one line, and the tab asks
21
+ for exactly the sections showing that name, the way `refresh('repos')` does.
22
+
23
+ A name belongs to the data, not to a section or a page. Any number of
24
+ sections, on any number of pages, can refresh on the same name: one
25
+ `changed('team:1:repos')` moves its version once, and every open tab showing
26
+ any of them refreshes the ones it has. Section *names* are separate - two
27
+ pages may both have a section called `stats`; each is resolved through its own
28
+ page, and a shared render is never handed from one page to the other.
29
+
30
+ The data is never pushed: the section is rendered fresh, through its own
31
+ queries and its own guards, as any refresh is. That is also why this runs
32
+ on a Worker - the stream holds no state, and a version is a read.
33
+
34
+ ## Where the versions live
35
+
36
+ **One server, no backend:** in that server's memory. Nothing to set up - but
37
+ in production rsc-kit says so in its log, once, because the same default
38
+ fails silently the moment there are two instances. If the deploy really is
39
+ one instance, say so and the warning goes:
40
+
41
+ ```ts title="src/instrumentation.ts"
42
+ import { installVersionSource, memoryVersions } from '@rsc-kit/core/changed'
43
+
44
+ export function register() {
45
+ installVersionSource(memoryVersions()) // one instance, on purpose
46
+ }
47
+ ```
48
+
49
+ **More than one instance, or a worker process:** this is the case to
50
+ plan for. In-memory versions fail silently the moment a load balancer adds a
51
+ second instance - a change made on one never reaches the tabs held by the
52
+ other - and a job finishes in a process that serves no pages at all. Keep
53
+ the versions somewhere they all share - any database you already have, through
54
+ the client you already use. rsc-kit ships no driver; you hand it yours:
55
+
56
+ | Your database | The store | Another instance's change arrives |
57
+ | --- | --- | --- |
58
+ | 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 |
59
+ | Postgres, with another client | `sqlVersions({ query, placeholder: (n) => '$' + n })` | within a second |
60
+ | MySQL, MariaDB | `sqlVersions({ query, dialect: 'mysql' })` | within a second; one statement per change |
61
+ | SQLite, libSQL, Turso, D1 | `sqlVersions({ query, dialect: 'sqlite' })` | within a second; one statement per change |
62
+ | Redis | `createVersions({ read, bump, listen, notify })` | at once, through pub/sub |
63
+ | An ORM: Drizzle, Prisma, Kysely, Knex | `createVersions` over its query builder, or `sqlVersions` over its raw query | as its database |
64
+
65
+ `sqlVersions` takes your driver as one function of SQL text and parameters.
66
+ Say which database with `dialect`, and a change is one upsert of every name it
67
+ moves; leave it out and it uses only SQL every database has, a read and a
68
+ write per name:
69
+
70
+ ```ts title="src/versions.ts"
71
+ import { sqlVersions } from '@rsc-kit/core/changed'
72
+
73
+ // MySQL, mysql2
74
+ export const versions = sqlVersions({ dialect: 'mysql', query: async (text, params) => (await pool.query(text, params))[0] })
75
+
76
+ // SQLite, bun:sqlite or better-sqlite3
77
+ export const versions = sqlVersions({ dialect: 'sqlite', query: async (text, params) => db.query(text).all(...params) })
78
+
79
+ // libSQL / Turso
80
+ export const versions = sqlVersions({ dialect: 'sqlite', query: async (sql, args) => (await client.execute({ sql, args })).rows })
81
+ ```
82
+
83
+ and with postgres.js it is one line:
84
+
85
+ ```ts title="src/versions.ts"
86
+ import postgres from 'postgres'
87
+ import { postgresVersions } from '@rsc-kit/core/changed'
88
+
89
+ // A function, so the store - and its database client - is made on first use.
90
+ export const versions = () => postgresVersions(postgres(process.env.DATABASE_URL!))
91
+ ```
92
+
93
+ A SQLite file is shared by the processes on one machine - a web server and a
94
+ worker on the same box. Instances on several machines need a database they
95
+ all reach over the network. The table every one of these reads is described
96
+ [below](#the-table).
97
+
98
+ postgres.js and `Bun.sql` both LISTEN, and `postgresVersions` uses it when the
99
+ client has it: a change on one instance - or in a worker - reaches the tabs on
100
+ every other at once. A listening server still reads the table now and then, in
101
+ case its listening connection dropped without a word; it is not how changes
102
+ normally arrive.
103
+
104
+ **Any database, any ORM, or no SQL at all.** rsc-kit needs three things from
105
+ your storage - read some versions, move some versions, and, if it can,
106
+ say the moment one moved - and does the comparing, waiting and waking itself.
107
+ `createVersions` takes exactly those:
108
+
109
+ With Drizzle, use its query builder rather than raw SQL - the table is one
110
+ more table in your schema:
111
+
112
+ ```ts title="src/db/schema.ts"
113
+ import { bigint, pgTable, text } from 'drizzle-orm/pg-core'
114
+
115
+ export const rscVersions = pgTable('rsc_versions', {
116
+ name: text('name').primaryKey(),
117
+ version: bigint('version', { mode: 'number' }).notNull(),
118
+ })
119
+ ```
120
+
121
+ ```ts title="src/versions.ts"
122
+ import { inArray, sql } from 'drizzle-orm'
123
+ import { createVersions } from '@rsc-kit/core/changed'
124
+ import { db } from './db'
125
+ import { rscVersions } from './db/schema'
126
+
127
+ export const versions = createVersions({
128
+ read: async (names) =>
129
+ Object.fromEntries(
130
+ (await db.select().from(rscVersions).where(inArray(rscVersions.name, names)))
131
+ .map((row) => [row.name, Number(row.version)]),
132
+ ),
133
+ bump: async (names) => {
134
+ await db.insert(rscVersions)
135
+ .values(names.map((name) => ({ name, version: Date.now() })))
136
+ .onConflictDoUpdate({
137
+ target: rscVersions.name,
138
+ set: { version: sql`GREATEST(${rscVersions.version} + 1, excluded.version)` },
139
+ })
140
+ },
141
+ })
142
+ ```
143
+
144
+ ```ts title="Prisma"
145
+ import { sqlVersions } from '@rsc-kit/core/changed'
146
+
147
+ // Raw SQL through Prisma; the table is a model in its schema - see "The table" below.
148
+ export const versions = sqlVersions({
149
+ query: (text, params) => prisma.$queryRawUnsafe(text, ...params),
150
+ placeholder: (n) => '$' + n, // Postgres; leave out for MySQL and SQLite
151
+ })
152
+ ```
153
+
154
+ ```ts title="Redis"
155
+ import { createVersions } from '@rsc-kit/core/changed'
156
+
157
+ const key = (name: string) => 'rsc:' + name
158
+ const BUMP = `local v = math.max(tonumber(redis.call('GET', KEYS[1]) or '0') + 1, tonumber(ARGV[1]))
159
+ redis.call('SET', KEYS[1], v, 'EX', ARGV[2])
160
+ return v`
161
+
162
+ export const versions = createVersions({
163
+ read: async (names) => {
164
+ const values = await redis.mget(names.map(key))
165
+ return Object.fromEntries(names.map((name, i) => [name, Number(values[i] ?? 0)]))
166
+ },
167
+ // One past where it was, or now if that is larger - see "Cleaning up".
168
+ bump: async (names) => {
169
+ await Promise.all(names.map((name) => redis.eval(BUMP, 1, key(name), Date.now(), 30 * 86400)))
170
+ },
171
+ // Instant across instances: a subscriber connection hears every bump.
172
+ listen: (wake) => subscriber.subscribe('rsc:versions', wake),
173
+ notify: () => redis.publish('rsc:versions', ''),
174
+ })
175
+ ```
176
+
177
+ `sqlVersions({ query })` takes any SQL driver as a function of text and
178
+ parameters - node-postgres, mysql2, Kysely, Knex, D1 - and `createVersions`
179
+ takes anything else.
180
+
181
+ Install it in every process - the web server once, before the first request.
182
+ Pass the function, not a store: `register()` also runs during the build,
183
+ usually without the database's settings, and a store made there makes its
184
+ client there too. Given a function, rsc-kit makes the store the first time
185
+ versions are read - which a build never does.
186
+
187
+
188
+ ```ts title="src/instrumentation.ts"
189
+ import { installVersionSource } from '@rsc-kit/core/changed'
190
+ import { versions } from './versions'
191
+
192
+ export function register() {
193
+ installVersionSource(versions)
194
+ }
195
+ ```
196
+
197
+ and the worker, which then says what it finished:
198
+
199
+ ```ts title="worker.ts"
200
+ import { changed, installVersionSource } from '@rsc-kit/core/changed'
201
+ import { versions } from './src/versions'
202
+
203
+ installVersionSource(versions)
204
+
205
+ queue.on('restoration.done', async (job) => {
206
+ await changed(`restoration:${job.id}`)
207
+ })
208
+ ```
209
+
210
+ Without `listen` and `notify` - MySQL, SQLite, or a driver that cannot listen -
211
+ a waiting server reads the table every second instead (`poll` changes it).
212
+
213
+ **From any process, without rsc-kit:** the table is the contract. A cron job,
214
+ a service in another language, a database trigger - anything that can write
215
+ to it can say a name changed:
216
+
217
+ ```sql
218
+ -- Postgres
219
+ INSERT INTO rsc_versions (name, version)
220
+ VALUES ('restoration:42', (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::bigint)
221
+ ON CONFLICT (name) DO UPDATE SET version = GREATEST(rsc_versions.version + 1, EXCLUDED.version);
222
+ NOTIFY rsc_versions; -- optional: wakes the listening servers at once
223
+
224
+ -- MySQL, MariaDB
225
+ INSERT INTO rsc_versions (name, version)
226
+ VALUES ('restoration:42', FLOOR(UNIX_TIMESTAMP(NOW(3)) * 1000))
227
+ ON DUPLICATE KEY UPDATE version = GREATEST(version + 1, VALUES(version));
228
+
229
+ -- SQLite
230
+ INSERT INTO rsc_versions (name, version)
231
+ VALUES ('restoration:42', CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER))
232
+ ON CONFLICT (name) DO UPDATE SET version = MAX(version + 1, excluded.version);
233
+ ```
234
+
235
+ The new version is one past the old, or the current time in milliseconds if
236
+ that is larger - so a version never repeats, which is what makes it safe to
237
+ delete old rows ([Cleaning up](#cleaning-up)). Every writer must bump this
238
+ way; a plain `version + 1` is a counter, and a counter repeats once a row is
239
+ deleted. Go's `SQLVersions` uses the same table, so a Go service and a
240
+ JavaScript app can share one.
241
+
242
+ **LISTEN through an ORM, or another driver.** An ORM builds queries; listening
243
+ is its driver's job, so pass `listen` and `notify` from the client underneath -
244
+ the one you handed the ORM:
245
+
246
+ ```ts title="src/versions.ts"
247
+ import { SQL } from 'bun'
248
+ import { drizzle } from 'drizzle-orm/bun-sql'
249
+
250
+ const client = new SQL(process.env.DATABASE_URL!)
251
+ export const db = drizzle({ client })
252
+
253
+ export const versions = createVersions({
254
+ read, // the Drizzle read and bump above
255
+ bump,
256
+ listen: (wake) => client.listen('rsc_versions', wake),
257
+ notify: () => client.notify('rsc_versions', ''),
258
+ })
259
+ ```
260
+
261
+ On node-postgres (`pg`), keep one client for listening alone:
262
+
263
+ ```ts
264
+ const listener = new pg.Client(process.env.DATABASE_URL)
265
+ await listener.connect()
266
+
267
+ listen: async (wake) => {
268
+ listener.on('notification', wake)
269
+ await listener.query('LISTEN rsc_versions')
270
+ },
271
+ notify: () => pool.query('NOTIFY rsc_versions'),
272
+ ```
273
+
274
+ A `NOTIFY` sent inside a transaction is only delivered when it commits, so a
275
+ listening tab is never woken before the data it will read is there - the
276
+ [after-commit](/guides/live-data#saying-that-data-changed) rule, kept by the database.
277
+ Redis has the same shape with SUBSCRIBE and PUBLISH (the example above).
278
+
279
+ **With a Go or Laravel backend:** the backend keeps them - a table in Go, the
280
+ cache in Laravel - and you install nothing here. The backend owns the data,
281
+ so it answers for its versions too: the renderer asks it which moved, once
282
+ for every tab it is serving. Go holds that question until a version moves,
283
+ so tabs hear at once. PHP cannot hold a request open, so Laravel answers at
284
+ once and is asked again about every two seconds while any tab is watching:
285
+ one small request - a cache read - per renderer process, however many tabs.
286
+ For almost any app that is nothing, and a change reaches the tabs within
287
+ about two seconds - or at once, with Laravel's [broadcasting](/hosts/laravel/data-changed).
288
+
289
+ ## Connection poolers
290
+
291
+ A pooler in **transaction mode** - PgBouncer, and the pooled connection
292
+ DigitalOcean, Supabase and Neon offer - hands the database connection back
293
+ after every statement. Reads and writes are fine; even sending a NOTIFY is.
294
+ But a LISTEN lands on a connection the pooler takes back, and the listener
295
+ hears nothing - silently. Changes from other instances would then wait for the
296
+ thirty-second safety net.
297
+
298
+ rsc-kit checks: as `postgresVersions` starts listening it sends itself a probe,
299
+ and if the probe does not come back it says so in the log - naming the cause
300
+ and the fix - and goes back to reading every second. The fix is to listen
301
+ through a connection that keeps its session - a direct one, or a pool in
302
+ session mode - and leave everything else on the pool:
303
+
304
+ ```ts title="src/versions.ts"
305
+ import { SQL } from 'bun'
306
+ import { postgresVersions } from '@rsc-kit/core/changed'
307
+
308
+ export const versions = () =>
309
+ postgresVersions(new SQL(process.env.DATABASE_URL!), { // the pool: reads and writes
310
+ listenWith: new SQL(process.env.DATABASE_LISTEN_URL!), // direct: listening only
311
+ })
312
+ ```
313
+
314
+ That is one extra connection per process. On DigitalOcean the direct port is
315
+ 25060 and the pool's 25061; on Supabase, 5432 and 6543. Use the app's own
316
+ database user for it, not the one migrations run as.
317
+
318
+ If direct connections are too scarce to spend one per process, don't listen -
319
+ say so, and rsc-kit reads every second instead, with no probe and no warning:
320
+
321
+ ```ts
322
+ postgresVersions(pool, { listen: false })
323
+ ```
324
+
325
+ That is one small indexed read per second per process, however many tabs it
326
+ holds. A change made in a process still reaches that process's tabs at once;
327
+ one made elsewhere - another instance, the worker - within about a second.
328
+
329
+ `await connection()` in a page is unrelated - despite the name, it is about
330
+ rendering per request, not database connections.
331
+
332
+ ## On Workers and serverless
333
+
334
+ The stream needs nothing kept between requests - names are signed, not
335
+ looked up - so it runs anywhere a response can stream. What differs is that
336
+ there is no single long-lived process:
337
+
338
+ - **Every isolate or instance watches for its own tabs.** Versions in memory
339
+ belong to one isolate, so a `changed()` handled by one never reaches tabs
340
+ held by another. Use a shared store - D1, Postgres, your backend - which the
341
+ production warning asks for if there is none. On Workers, [one hub](#one-hub-on-workers)
342
+ can hold every tab instead.
343
+ - **Connections are cut.** Platforms bound how long a request may run; a
344
+ stream that is cut reconnects on its own, and the tab catches up from its
345
+ versions. On a platform that bills a function for every second it is open,
346
+ each watching tab is billed for as long as it watches.
347
+ - **Listening is unlikely.** Hyperdrive and serverless Postgres drivers go
348
+ through poolers; the probe finds this and falls back to reading every second,
349
+ or say `listen: false` up front.
350
+
351
+ On Workers, bindings come from `cloudflare:workers`, imported inside a
352
+ request - when they exist, and never in the build:
353
+
354
+ ```ts title="src/versions.ts"
355
+ import { sqlVersions } from '@rsc-kit/core/changed'
356
+
357
+ // The binding, imported inside the request: the build prerenders in Node,
358
+ // which runs register() and cannot load cloudflare:workers.
359
+ const db = async () => (await import('cloudflare:workers')).env.DB
360
+
361
+ // D1: the table is the same as anywhere else.
362
+ export const versions = () =>
363
+ sqlVersions({
364
+ dialect: 'sqlite',
365
+ query: async (text, params) => (await (await db()).prepare(text).bind(...params).all()).results,
366
+ })
367
+ ```
368
+
369
+ Then the binding, the table and the secret:
370
+
371
+ ```jsonc title="wrangler.jsonc"
372
+ {
373
+ // Nitro merges this into the Worker's config.
374
+ "d1_databases": [
375
+ { "binding": "DB", "database_name": "my-app", "database_id": "<from wrangler d1 create>", "migrations_dir": "migrations" }
376
+ ]
377
+ }
378
+ ```
379
+
380
+ ```sql title="migrations/0001_rsc_versions.sql"
381
+ CREATE TABLE IF NOT EXISTS rsc_versions (name TEXT PRIMARY KEY, version BIGINT NOT NULL);
382
+ ```
383
+
384
+ ```sh
385
+ npx wrangler d1 create my-app # once; put its id in wrangler.jsonc
386
+ npx wrangler d1 migrations apply DB --remote # --local for wrangler dev
387
+ npx wrangler secret put RSC_SIGNING_SECRET # production; .dev.vars for wrangler dev
388
+ ```
389
+
390
+ and install it as anywhere else - `installVersionSource(versions)` in
391
+ `instrumentation.ts`. A section the store serves needs `await connection()`
392
+ when it reads D1 itself: the data is only there per request.
393
+
394
+ The Cloudflare example's `/live` page is all of this, end to end, and was run
395
+ on `wrangler dev`: a change from its webhook reaches an open tab, and the
396
+ section refreshes with the new value.
397
+
398
+ ### One hub on Workers
399
+
400
+ Each isolate watches only the tabs it happens to hold, and on Workers that is
401
+ often one. So by default every open tab costs its own ask of the store, every
402
+ two seconds, and a `wakeOn` listener runs once per isolate. A Durable Object
403
+ is one place every isolate can reach. Name it, and every tab's stream goes to
404
+ one instance, which watches all of them:
405
+
406
+ ```ts title="vite.config.ts"
407
+ // cloudflare_module, plus the Durable Object class the hub runs in.
408
+ nitro({ preset: 'cloudflare_durable', serveStatic: 'inline' })
409
+ ```
410
+
411
+ ```jsonc title="wrangler.jsonc"
412
+ {
413
+ "durable_objects": {
414
+ "bindings": [{ "name": "$DurableObject", "class_name": "$DurableObject" }]
415
+ },
416
+ "migrations": [{ "tag": "v1", "new_sqlite_classes": ["$DurableObject"] }],
417
+ "vars": { "RSC_CHANGES_HUB": "$DurableObject" }
418
+ }
419
+ ```
420
+
421
+ Nothing changes in the app. `RSC_CHANGES_HUB` names the binding, and rsc-kit
422
+ does not look for one on its own: without it, each isolate watches its own
423
+ tabs as before. A name with no binding behind it is said once in the log, and
424
+ the isolate falls back to that.
425
+
426
+ What changes, against each isolate watching its own tabs:
427
+
428
+ | | Each isolate (default) | One hub |
429
+ | --- | --- | --- |
430
+ | Asks of the store or backend | one per open tab, every 2s | one for every tab, every 2s |
431
+ | A `changed()` reaches the tabs | at each isolate's next read, within a second or two | at once: `changed()` wakes the hub |
432
+ | A `wakeOn` listener or broadcast | one connection per isolate | one connection |
433
+ | Cost of a store with no LISTEN (D1) | grows with tabs | flat |
434
+ | A Laravel backend | one PHP request per tab, every 2s | one, for every tab |
435
+
436
+ - **Asks stop growing with tabs.** A thousand open tabs cost the store, or
437
+ your backend, one ask every two seconds instead of a thousand. On a backend
438
+ that answers each ask with a PHP request, this is the difference that
439
+ matters.
440
+ - **Changes arrive at once without LISTEN.** D1 cannot announce a change.
441
+ With the hub, `changed()` in any isolate - a webhook, an action - pokes the
442
+ hub after the write, and every tab hears it immediately instead of at the
443
+ next read.
444
+ - **One listener.** A broadcast server or `wakeOn` listener runs in the hub,
445
+ one connection for the deployment, rather than one per isolate that
446
+ happens to hold a tab.
447
+
448
+ What it costs, and its limits:
449
+
450
+ - **Durable Object time.** The hub stays active while any tab watches, and a
451
+ Durable Object is billed for the time it is active - for one instance open
452
+ all month, a few dollars on Cloudflare's paid plan. With no tab open it
453
+ costs nothing.
454
+ - **One location.** Every tab's stream goes to the one instance, wherever
455
+ Cloudflare placed it. An event crosses one more hop, tens of milliseconds;
456
+ the pages themselves are still rendered by the nearest isolate.
457
+ - **One instance's limits.** A Durable Object runs on one thread, and
458
+ Cloudflare documents a soft limit of about 1,000 requests a second for
459
+ one. A site whose tabs connect faster than that should stay on the
460
+ default flow, which spreads them across isolates.
461
+ - **Versions still live in a shared store.** The hub holds the tabs, not the
462
+ versions: D1, your database or your backend still keeps them, so a hub that
463
+ restarts loses nothing.
464
+
465
+ The forwarded requests carry a proof signed with `RSC_SIGNING_SECRET`, so a
466
+ browser cannot reach the hub's side of the endpoint directly. The Cloudflare
467
+ example runs this way, and was checked on `wrangler dev`: three tabs' streams
468
+ held by the hub, one webhook, and all three hearing the change.
469
+
470
+ Where a response cannot stream at all, use `usePolling` instead.
471
+
472
+ ## The table
473
+
474
+ A shared store keeps one row per name. Your app owns the table: rsc-kit never
475
+ creates, alters or migrates it at runtime - make it with your own migrations,
476
+ in your own schema, with whatever your ORM calls these types. (Laravel ships
477
+ one you publish into your own migrations, `--tag=rsc-migrations`; after that
478
+ it is yours too.)
479
+
480
+ | Column | Type | |
481
+ | --- | --- | --- |
482
+ | `name` | text, `PRIMARY KEY` (or a unique index) | the name a section refreshes on |
483
+ | `version` | `BIGINT NOT NULL` | when it last changed, in ms - or one past the last value, if that is larger |
484
+
485
+ ```sql
486
+ -- Postgres, SQLite
487
+ CREATE TABLE rsc_versions (name TEXT PRIMARY KEY, version BIGINT NOT NULL);
488
+ -- MySQL: an indexed TEXT needs a length
489
+ CREATE TABLE rsc_versions (name VARCHAR(255) PRIMARY KEY, version BIGINT NOT NULL);
490
+ ```
491
+
492
+ - **Extra columns are fine** - an `updated_at`, say - as long as each has a
493
+ default: rsc-kit and the documented upserts write only `name` and `version`.
494
+ - **Another name is fine:** `sqlVersions({ table })`, `postgresVersions(sql,
495
+ { table })`, Go's `SQLVersions{Table}`, Laravel's `RSC_VERSIONS_TABLE`.
496
+ - **The NOTIFY channel** is `rsc_versions` whatever the table is called;
497
+ `postgresVersions(sql, { channel })` changes it.
498
+ - The same table works for Go's `SQLVersions` and Laravel's
499
+ `RSC_VERSIONS=database`, so a JavaScript app, a Go service and a PHP job
500
+ can share one.
501
+
502
+ ## Cleaning up
503
+
504
+ A row is kept for every name that ever changed. For a fixed set of names -
505
+ `team:1:repos` - that is nothing; for one per order, job or restoration it
506
+ grows for ever. Delete the old ones on a schedule:
507
+
508
+ ```ts
509
+ await versions.prune() // sqlVersions, postgresVersions: not changed in 30 days
510
+ await versions.prune(7 * 86400_000) // or any age, in ms
511
+ ```
512
+
513
+ or from anything that can run SQL - the version is when the name last changed:
514
+
515
+ ```sql
516
+ DELETE FROM rsc_versions WHERE version < (EXTRACT(EPOCH FROM now() - interval '30 days') * 1000)::bigint;
517
+ ```
518
+
519
+ **Deleting is always safe.** A deleted name reads as 0, so a tab still
520
+ holding it sees a different version and refreshes once; changed again, the
521
+ name comes back at the current time - never at a value a tab is holding.
522
+ That is why a bump moves to the time rather than counting: a counter
523
+ restarted at 0 climbs back to values tabs still hold, and they would miss
524
+ the change.
525
+
526
+ The rest clean up on their own: `memoryVersions()` forgets a name not changed
527
+ in 30 days (`{ forgetAfter }`), the Redis example's keys expire, and the
528
+ server forgets every name the moment no open tab is watching it. Laravel and
529
+ Go have the same: `php artisan rsc:prune-versions` and `SQLVersions.Prune`.
530
+
531
+ A store of your own bumps with `nextVersion(current)` from
532
+ `@rsc-kit/core/changed` - never `+ 1`.
533
+
534
+ ## A change made straight in the database
535
+
536
+ Nothing watches a table. A section refreshes when a name's version moves, and a
537
+ `psql` session, a migration, an admin tool or another application writing the
538
+ same rows says nothing. The data is not wrong: any fresh render reads it as it
539
+ is now. The tabs already open are stale, and stay so until something refreshes
540
+ them, because no version moved.
541
+
542
+ Three ways to cover it, in the order to reach for them:
543
+
544
+ **Make the writer say it.** Whatever writes calls `changed()` after the write
545
+ commits — a job, a webhook, a script you run for a manual fix. This is the one
546
+ to prefer, because the name is then written by the code that knows what changed.
547
+ It needs a [shared store](#where-the-versions-live) when the script is a different
548
+ process from the server; in-memory versions are one process's.
549
+
550
+ **Let the database say it.** For writes that never pass through your code, a
551
+ trigger on the data table moves the version row, in the same transaction as the
552
+ write. That is what `changed()` does, so it follows the same rules, and it
553
+ moves with the commit: a write that rolls back moves nothing. Postgres:
554
+
555
+ ```sql
556
+ CREATE FUNCTION repos_moved() RETURNS trigger AS $$
557
+ DECLARE team INT := COALESCE(NEW.team_id, OLD.team_id);
558
+ BEGIN
559
+ INSERT INTO rsc_versions (name, version)
560
+ VALUES ('team:' || team || ':repos', (EXTRACT(EPOCH FROM clock_timestamp()) * 1000)::bigint)
561
+ ON CONFLICT (name) DO UPDATE SET version = GREATEST(EXCLUDED.version, rsc_versions.version + 1);
562
+ -- Delivered when the transaction commits, so a listener never wakes for a rolled-back write.
563
+ PERFORM pg_notify('rsc_versions', '');
564
+ RETURN NULL;
565
+ END $$ LANGUAGE plpgsql;
566
+
567
+ CREATE TRIGGER repos_moved AFTER INSERT OR UPDATE OR DELETE ON repos
568
+ FOR EACH ROW EXECUTE FUNCTION repos_moved();
569
+ ```
570
+
571
+ The name must be the one the section lists in `refreshOn`, spelled the same.
572
+ The `pg_notify` is what makes tabs hear at once: without it a store that
573
+ listens still finds out, but only on its next check, up to 30 seconds later
574
+ (a second, for a store that does not listen). The version is one past the last
575
+ value when the clock has not moved, so two writes in the same millisecond are
576
+ still two changes. SQLite has no `OR` in a trigger event, so it takes one
577
+ trigger per statement, with `MAX` for `GREATEST` and no notify — the store
578
+ checks every second. The table is [the one above](#the-table), and Go's and
579
+ Laravel's stores read the same one.
580
+
581
+ **Poll, when nothing can say it.** A value with no writer you control and no
582
+ table you can put a trigger on is [`usePolling`](/guides/queries#live-data)'s.
583
+ It re-asks on an interval, so it costs a request whether or not anything
584
+ changed.
585
+
586
+ Delete from the data table and the trigger fires on the old row, which is why
587
+ the function reads `OLD` for a delete. Test the trigger the way you would any
588
+ other, with a write from a second connection and a tab left open.
589
+
590
+ ## Waking the renderer
591
+
592
+ Whatever keeps the versions, the renderer has to learn *when* to ask which
593
+ moved. Go holds the question until one does; a store that listens -
594
+ Postgres's LISTEN, Redis's pub/sub - wakes it; otherwise it asks on a timer.
595
+ Anything else that can say "something changed" can wake it too:
596
+
597
+ ```ts title="src/instrumentation.ts"
598
+ import { listenToBroadcast, wakeOn } from '@rsc-kit/core/changed'
599
+
600
+ export function register() {
601
+ // A broadcast server - anything speaking the Pusher protocol.
602
+ wakeOn(listenToBroadcast({ url: process.env.RSC_BROADCAST_URL!, key: process.env.RSC_BROADCAST_KEY! }))
603
+
604
+ // Or a Redis channel your backend publishes to.
605
+ wakeOn((wake) => subscriber.subscribe('rsc:changed', wake))
606
+ }
607
+ ```
608
+
609
+ `RSC_BROADCAST_URL` and `RSC_BROADCAST_KEY` in the renderer's environment do
610
+ the first with no code. A wake carries nothing - no names, no data - so it
611
+ can travel over a public channel: on a wake the renderer asks, as it always
612
+ does, and the versions say which names moved for whom. With something to wake
613
+ it, the renderer asks on its timer only every thirty seconds, as a safety net
614
+ for a dropped connection. Listeners start with the first watching tab, never
615
+ in a build.
616
+
617
+ **Private data stays private.** A wake decides nothing about who sees what.
618
+ On a wake the renderer asks which of *its tabs'* names moved - names each tab
619
+ got, signed, from its own render - and a tab that has one refreshes its
620
+ section through its own visitor's session and guards. Ada's `inbox:7` is never
621
+ a name Ben's tab holds, so a change to it never refreshes his page, broadcast
622
+ or not. All a public channel shows a subscriber is that the app changed and
623
+ when; if even that timing is sensitive, keep the wake on a channel only the
624
+ renderer can reach - a Redis channel, through `wakeOn` - rather than a
625
+ broadcast.
626
+
627
+ ## The signing secret
628
+
629
+ The names a page hands the tab are signed, so a tab can only listen for the
630
+ names its page was rendered with - a browser cannot make one up. Every
631
+ instance has to sign with the same key, or a tab served by one is refused by
632
+ the next and never refreshes:
633
+
634
+ ```sh
635
+ RSC_SIGNING_SECRET=… # the same on every instance: openssl rand -base64 32
636
+ ```
637
+
638
+ It is its own secret, with or without a backend - not the backend's
639
+ `RSC_HOST_CALL_SECRET`, which authorises a different thing. In production, an
640
+ app that uses `refreshOn` without it refuses to serve, saying what to set: a
641
+ random key per instance would fail silently.
642
+
643
+ That refusal comes on the first request, because on some platforms - Workers
644
+ - the environment is only there once a request arrives. Under Kubernetes or
645
+ any orchestrator with a readiness check, that is too late: the pod is already
646
+ taking traffic. Make the deploy itself fail instead, by declaring the secret
647
+ where every other variable is - in `env.ts`, which refuses a missing variable
648
+ before the server starts:
649
+
650
+ ```ts title="src/env.ts"
651
+ export const env = createEnv({
652
+ server: {
653
+ // Signs refreshOn's names. Required in production; in development a
654
+ // random key is fine, and what rsc-kit uses without one.
655
+ RSC_SIGNING_SECRET:
656
+ process.env.NODE_ENV === 'production' ? z.string().min(32) : z.string().optional(),
657
+ // ...
658
+ },
659
+ // ...
660
+ })
661
+ ```
662
+
663
+ An app without an `env.ts` gets the same from `assertSigningSecret()`, from
664
+ `@rsc-kit/core/changed`, called in `register()`. In development a random key
665
+ is fine, and is what you get.
666
+
667
+ How to generate it, where to keep it, and what rotating it does:
668
+ [Secrets](/hosts/deployment/secrets/).
669
+
670
+ Names are signed when the page is served, never at build: a page stored at
671
+ build keeps everything else stored, and the part that carries the names is
672
+ filled per request. So the build does not need the secret.
673
+
674
+ ## What it costs
675
+
676
+ - **Per tab:** one open connection while the page is visible, closed when the
677
+ tab is hidden and reopened when it is seen again. Idle, it carries a
678
+ keepalive line every eight seconds ([set it lower](/hosts/deployment#streams-and-idle-timeouts)
679
+ under a shorter idle timeout); a change is one line of about forty
680
+ bytes.
681
+ - **Per change:** each tab showing the name asks for the sections that show
682
+ it, once, however many names moved together. That request is the size of
683
+ the section, not the page. A `shared` section renders once per change for
684
+ every tab; any other renders once per tab.
685
+ - **On the server:** one ask of wherever the versions live, covering every tab
686
+ that server holds - a thousand open tabs are one query, not a thousand. The
687
+ ask may wait up to five seconds for a change: a database with `listen`, or a
688
+ Go backend, answers the moment a version moves; a table without it is read
689
+ once a second while the ask waits; Laravel answers at once and is asked again
690
+ two seconds later. Plus one small read when each tab opens its stream.
691
+
692
+ Polling a section every two seconds instead costs a full render of it, per
693
+ tab, every two seconds, whether anything changed or not. The trade is the open
694
+ connection: cheap on Bun, Node and Workers; on a host that bills a function
695
+ for every second it is open, it is a second billed for as long as the tab is.