# Live data

> Keep what a page shows current as the data changes - refreshOn, events, polling.

A page shows its data as it was when it rendered. When the data changes while
someone is looking - a teammate edits it, a webhook lands, a job finishes - a
section can refresh itself in every open tab.

```tsx title="src/app/t/[team]/repos.section.tsx"
export default section('repos', Repos, {
  refreshOn: ({ params }) => [`team:${params.team}:repos`],
})
```

```ts
await changed(`team:${team}:repos`)   // every open tab showing it refreshes
```

Inside the tab that made the change you don't need this: an action says what
it changed, and its answer brings those sections back. See
[revalidate](/guides/sections#refreshing-it).

| The change comes from | Use |
| --- | --- |
| your own code: a webhook, a job, another visitor's action | [`refreshOn`](#refreshing-a-section-when-its-data-changes) |
| a stream of values: prices, progress, logs | [`events()` and `useEvents`](/guides/api-routes#a-route-that-streams) |
| somewhere you can't hook into, such as a third-party API | [`usePolling`](/guides/queries#live-data) |

## Refreshing a section when its data changes

Give a [section](/guides/sections) a `refreshOn` list of names. A name stands
for a piece of data:

```tsx title="src/app/status/board.section.tsx"
export default section('board', Board, { refreshOn: ['board'] })
```

When the names depend on the URL, pass a function. It receives the page's
`params` and `searchParams`, already awaited:

```tsx title="src/app/t/[team]/repos.section.tsx"
export default section('repos', Repos, {
  refreshOn: ({ params }) => [`team:${params.team}:repos`],
})
```

The function runs on each request, so it can read the request too:

```tsx
import { cookies } from '@rsc-kit/core/request'

refreshOn: async () => [`inbox:${(await cookies()).get('agent')?.value}`]
```

When a name changes, every open tab showing the section renders it again
through its own queries and guards. Nothing polls, and you write no client
code.

### Refreshing a whole page

A page can export its own `refreshOn`. A change then refreshes the page, as
`refresh('page')` does:

```tsx title="src/app/dashboard/page.tsx"
export const refreshOn = async () => [`inbox:${await currentUserId()}`]
```

With [URL schemas](/guides/url-validation), type it from the schema so `params`
arrives parsed:

```tsx title="src/app/teams/[team]/page.tsx"
import type { PageRefreshOn } from '@rsc-kit/core/section'

export const params = z.object({ team: z.string() })
export const refreshOn: PageRefreshOn<typeof params> = ({ params }) => [`team:${params.team}`]
```

Without a schema, name the route's pattern. A misspelt param, or a pattern
that isn't a page, fails the typecheck:

```tsx title="src/app/[team]/[app]/[env]/page.tsx"
export const refreshOn: PageRefreshOn<'/[team]/[app]/[env]'> = ({ params }) => [`app:${params.app}:${params.env}`]
```

`export const refreshOn`, `export function refreshOn` and
`export { refreshOn } from './names'` all work. `export * from` does not: the
build reads the page, not what it re-exports wholesale, so name it in a list.

## Saying that data changed

Call `changed()` with the names, wherever the write happens:

```ts title="src/app/api/github/webhook/route.ts"
import { changed } from '@rsc-kit/core/changed'

export async function POST(request: Request) {
  const { team, repos } = await request.json()
  await saveRepos(team, repos)
  await changed(`team:${team}:repos`)
  return new Response(null, { status: 204 })
}
```

With a Go or Laravel backend, the backend says it instead:
[`reg.Changed(ctx, …)`](/hosts/go/data-changed) or
[`Rsc::changed(…)`](/hosts/laravel/data-changed). The page is the same.

Call it **after** the write commits. A tab asks for its section the moment it
hears, and a render that runs before the commit reads the old data. The tab is
then at the new version, so it won't ask again until the next change:

```ts
await db.transaction(async (tx) => {
  await tx.insert(conversations).values(row)
  // not here: the transaction hasn't committed
})

await changed(`agent:${row.agentId}:conversations`)   // here
```

In Laravel, `DB::afterCommit(fn () => Rsc::changed(...))` does this inside a
transaction.

A change made where none of your code runs - in `psql`, a migration, another
application - says nothing, and open tabs stay stale. A database trigger can
say it for you: see [a change made straight in the database](/guides/live-data-in-production#a-change-made-straight-in-the-database).

## Naming the data

Use one name per thing that changes together, as narrow as the data:
`conversation:{id}`, `inbox:{userId}`, `team:{id}:repos`. Two things sharing a
name refresh too often, and one thing split across names refreshes too little.

Use ids, not emails or titles. A name is visible in the page, and its version
says when it last changed, so a name must not be something its visitor
shouldn't see. Never put a secret in a name.

### A name doesn't decide who sees what

Hearing that `conversation:42` changed only tells a tab to ask for its section
again. The new render runs as that tab's visitor, through the same queries and
guards as the first one, so nobody sees another person's data through a name.

```tsx title="src/app/chats/[id]/messages.section.tsx"
export default section('messages', async function Messages({ params }) {
  const { id } = await params
  const messages = await rpc('Chats.messages', id)   // the backend checks the viewer is in it

  return <Thread messages={messages} />
}, { refreshOn: ({ params }) => [`conversation:${params.id}`] })
```

```go
// Ada sends Ben a message.
reg.Changed(ctx, "conversation:42", "inbox:"+ben.ID, "inbox:"+ada.ID)
```

- Both have the conversation open, and each render asks `Chats.messages` as
  its own visitor.
- Ben's inbox and Ada's refresh. Nobody else's does: their pages were rendered
  with their own `inbox:` names.
- Someone outside the conversation can't open the page, so their tab never
  gets the name. The renderer signs the names a page hands out, and refuses a
  name a browser makes up.

A signed name expires after a day. A tab still open then renders its regions
again, as its visitor, and is handed fresh names - nobody notices. Someone who
has since lost access, removed from the team, is refused that render, and
their tab stops hearing; a name copied out of the page stops working with it.

A page or section that ends in `notFound()` hands out no names, so a name made
from the url, `build:${params.build}`, is not signed for a build that isn't
there. Only its own `notFound()` counts: a record looked up in a child
component is past what the engine can see, so look it up in `refreshOn` or in
the page itself.

### Changing a child changes its parent's list

Renaming an app changes the app's page and the team's list of apps. Name both
where the write happens:

```ts
await renameApp(app.id, name)
await changed(`app:${app.id}`, `team:${app.teamId}:apps`)
```

Each region names only what it shows: the app's page `app:{id}`, the team's
list `team:{id}:apps`. A list that watched every child's name would miss a
child added after it rendered.

Something nothing tells you about, such as a third-party status page, has no
write to call `changed()` from. Poll it with `usePolling`.

## Running more than one server

On one server, versions are kept in memory and there is nothing to set up.
With a second instance, or a worker process, a change made on one never
reaches the tabs held by another. Keep the versions in a database they all
share:

```ts title="src/versions.ts"
import postgres from 'postgres'
import { postgresVersions } from '@rsc-kit/core/changed'

export const versions = () => postgresVersions(postgres(process.env.DATABASE_URL!))
```

```ts title="src/instrumentation.ts"
import { installVersionSource } from '@rsc-kit/core/changed'
import { versions } from './versions'

export function register() {
  installVersionSource(versions)
}
```

Every instance also needs the same `RSC_SIGNING_SECRET`.
[Live data in production](/guides/live-data-in-production) covers MySQL,
SQLite, Redis and ORMs, the table, connection poolers, Workers, and what it
costs. With a Go or Laravel backend, the backend keeps the versions and you
install nothing.

## Sharing one render between tabs

By default each tab renders its own refresh, since each can differ by who is
looking: 500 tabs on one board are 500 renders. A section that is the same for
everyone who may see the page can share one:

```tsx title="src/app/status/board.section.tsx"
export default section('board', Board, { refreshOn: ['board'], shared: true })
```

The first tab's request renders it, and the others asking because of the same
change get the same bytes. Each tab's guards still run on its own request, and
a `refresh()` by hand or after an action always renders afresh.

The shared render is nobody's, the way a [kept page](/guides/caching) is: its
`rpc()` calls go to the backend with no cookie, so `auth()->user()` is null
there, and a section that should show something to a signed-in visitor only
should not be shared. One that reads the visitor anyway - `cookies()`,
`headers()` - is not shared: each tab renders its own, as if `shared` were
not set, and the dev server says which read did it.

The change a tab names is checked against the versions the engine reads, so
a tab cannot name a version that has not happened yet and have its render
answer the tabs that later ask about it: that tab renders alone.

## Testing what a page watches

`watched()` returns the names each region of a page refreshes on: `page` for
the page's own, and each section by its name:

```ts title="tests/live.test.ts"
import { createTestApp } from '@rsc-kit/core/testing'

const app = await createTestApp()

test('the team page watches the team and its apps', async () => {
  expect(await app.watched('/teams/acme')).toEqual({
    page: ['team:acme'],
    apps: ['team:acme:apps'],
  })
})
```

A region whose `refreshOn` gave no names appears with `[]`, which is usually a
param read under the wrong name. To check what a change does, see
[what a page watches](/guides/testing#what-a-page-watches).

## When nothing refreshes

In development the browser console lists what the page is watching, region by
region:

```
[rsc-kit] refreshOn watching, by region:
  repos: team:1:repos @3
  page: inbox:ada @0
```

- **A region is missing from the list.** Its `refreshOn` rendered no names,
  and the server's log says why.
- **The tab is in the background.** A hidden tab stops watching and the
  console says so. When it's shown again it catches up on whatever changed.
- **It works locally but not in production.** There is more than one instance;
  see [running more than one server](#running-more-than-one-server).
- **The change was made outside your code.** See
  [saying that data changed](#saying-that-data-changed).

## Coming from Next.js

`refreshOn` replaces fetch tags, and `changed()` replaces `revalidateTag()`.
`tags: ['posts']` on a fetch becomes `refreshOn: ['posts']` on the section, and
`revalidateTag('posts')` becomes `changed('posts')`.

They aren't the same thing. Next's `revalidateTag()` empties its Data Cache so
the *next request* refetches, and an open tab learns nothing until it
navigates. Here there is no data cache, and `changed()` refreshes every open
tab showing the name, now.
