Collaboration
State that several people share and that merges after time offline; loads the server keeps current; and changes you try before you make them. Everything here is opt-in, and nothing in it sends data anywhere but your own server.
Shared documents: @qatjs/core/sync
shared(initial, { room }) is a deep store that everyone in room shares. You read and write it
as you would a deep state:
// src/todos.js
import { shared } from '@qatjs/core/sync'
export const todos = shared([], { room: 'todos' })// src/app.qx
import { room } from '@qatjs/core/sync'
import { todos } from './todos.js'
export default function App() {
let text = state('')
const r = room(todos)
return (
<main>
<p class="status">{r.status()}{r.pending() ? ` · ${r.pending()} to send` : ''}</p>
<form on:submit|prevent={() => todos.push({ text, done: false })}>
<input aria-label="New todo" bind:value={text} />
</form>
<ul>
{for (const t of todos)}
<li key={t}><input type="checkbox" checked={t.done} on:change={(e) => (t.done = e.currentTarget.checked)} /> {t.text}</li>
{/for}
</ul>
</main>
)
}
<style>
.status { color: #555; }
</style>text stateEach write is an operation. Your app's relay passes it to everyone in the room. Writes made offline
queue up (r.pending()); on reconnect they are sent, and what others wrote meanwhile comes in.
Every client ends with the same document.
It covers lists and maps. For rich text, which several people edit at once, use the Yjs adapter,
@qatjs/sync-yjs: it carries a Yjs document through the same relay, its texts and maps as signals.
// src/notes.js
import { yjs } from '@qatjs/sync-yjs'
export const notes = yjs('notes-7')
export const body = notes.text('body') // body.y.insert(0, 'Hi'); body.value() is the textHow concurrent writes merge:
- An object is a map of last-writer-wins registers. If two people write one key at once, the
later write wins.
deleteis a write too. Keys keep the order they arrived in, which can differ between clients; when order matters, use an array. - An array is a sequence. An insert lands right after the element it was made after;
concurrent inserts at the same place come newest first. A removed element leaves a tombstone, so
an insert made after it keeps its place.
a[i] = vreplaces that element, and a concurrent removal wins over it. - A value you write is copied in. Its objects and arrays become parts of the document, so editing your original afterwards changes nothing.
The CRDT is Qat's own. Yjs 13.6.33 is 28.1 kB gzip, minified and bundled whole; Loro and
Automerge ship their CRDT as WASM, over 1 MB. @qatjs/core/sync is 2.85 kB gzip with its CRDT
(918 B of that; pnpm size).
A document made in a component leaves with it: its connection closes when the component is
disposed. One made in a module lives as long as the page. A list takes a write at an index or to
its length; any other property (list.total = 1) is a TypeError.
Options
| Option | |
|---|---|
room |
the room's name: everyone who opens it shares one document |
version |
the document's version (default 1); see below |
migrate |
{ 2: (doc) => … }: run by one client of that version, its writes sent as one migration |
persist: 'local' |
keep the document and its queued writes in localStorage, so a reload offline keeps them. The room open in two tabs shares that record: each tab holds the other's unsent writes too, and they see each other offline. A storage that is full or refused is not written to; the document goes on |
url |
the relay, if not this origin's /__qat/sync |
Versions
A room has a version. The first client of a newer version raises it, and one client of that
version runs its migrate steps: the relay asks the first one to join, and the next one if that
client leaves before it has migrated. The steps' writes travel as one migration, and the relay
keeps the first migration of a version. Two clients that migrated at once (one of them offline,
say, while the relay restarted) do not both count: the later one is refused, and its client undoes
it. A step runs once per room, so it does not need to check whether it ran already. Clients of an
older version, and any that join later, are outdated: they stop merging, so an old shape never
mixes with a new one.
A restarted relay keeps what it saved, which can be less than it had. Each client then sends back the whole log it holds, so what the relay lost comes back from the clients that have it.
// src/board.js
import { shared } from '@qatjs/core/sync'
export const board = shared({ title: '', cards: [] }, {
room: 'board',
version: 2,
migrate: { 2: (doc) => (doc.archived = []) },
})Who else is here
room(doc) tells you where the room stands and who else is in it:
status() |
'connecting', 'open', 'offline' (writes queue up), 'outdated', 'denied' |
pending() |
your writes the relay has not confirmed yet |
present(state) |
send your presence to the others (a name, a cursor); null to leave |
others() |
the others' presence, by client |
me |
this client's id in the room |
Presence is opt-in: nothing is sent until you call present(). It is never stored.
Server rendering
On a server-rendered route, shared() renders the relay's latest state, and the page carries it so
the browser starts from the same state. Such a page is sent as Cache-Control: private, no-store,
so it never lands in a shared cache. A static route cannot use @qatjs/core/sync (QX-SYNC-STATIC): its
page is built once, and a shared document changes after that.
The relay
qatjs dev and qatjs preview serve a relay at /__qat/sync, with rooms kept in
node_modules/.qat/sync. In production, @qatjs/sync-server is the reference relay. Attach it to
your own server:
// server.js
import { createServer } from 'node:http'
import { attach, file, relay } from '@qatjs/sync-server'
const rooms = relay({ store: file('./rooms'), cap: 5e6, version: 2 })
const server = createServer((req, res) => res.writeHead(404).end())
attach(server, rooms, { onJoin: (req, room) => req.headers.cookie?.includes('session=') ?? false })
server.listen(3000)onJoin(req, room)decides who may join. It reads the request's own auth (its cookies, its headers); a refused join closes the socket, and the client's status becomes'denied'. It is required: without it,attachlets nobody join. (qatjs devandqatjs preview, on your machine, let everyone in.)versionis the highest store version your deploy has. A client that claims a higher one, in its join or in a migration, is closed (4008). Without it, any member could raise a room past every real client and close it for all of them: set it in production. The cookie check above shows the shape; check the room against the user too (a member is trusted with the content, not with every room).caplimits a room's size, in bytes of operations (default 5 MB). A write past it closes that client's socket (4013, "the room is full"): its status becomes'denied'for the whole room, and its queued writes staypending, kept on the device. Rooms do not shrink, so sizecapfor a room's whole life: near it, every write that does not fit closes its writer.- Stores:
memory(),file(dir), orpostgres(client)(any client withquery(text, values), such aspg's). - It never reads content. It keeps an operation or not by its id, and counts bytes. Each
client drops an operation whose id holds no valid clock, and a key
__proto__. - The inspector:
qatjs-sync-server --room board --store file:./roomsprints a room's version, size and clients, never its content. - Server rendering:
withSync(handler, rooms)wraps your server's handler. It seeds a page that read a room, and keeps that page out of shared caches.
The devtools' Sync tab lists the page's rooms: status, version, operations, pending writes, and who else is here.
Live loads: the server keeps them current
load(fn, { live: true, key }) is a load the server keeps current. It loads like any other. While
it is in use, the page's one session with your server subscribes to its key, and the key names
what the server pushes. When that changes on the server, the new value becomes the load's data, as
mutate would set it, so only the nodes bound to it change.
// src/pages/product.qx
export default function Product({ id }) {
let stock = load(({ signal }) => fetch('/__qat/live?k=' + encodeURIComponent(JSON.stringify(['stock', id])), { signal }).then((r) => r.json()), { live: true, key: ['stock', id] })
return <p class="stock">{stock.data} in stock</p>
}
<style>
.stock { color: #2a6; }
</style>stock loadA live load needs a key (QX-LIVE-KEY), unless an api operation keys it, as
load(() => api.stock.get({ id }), { live: true }) does.
On the server, a hub from @qatjs/server/live resolves each key with the session's own request, so
the auth is the request's. Put it in server/live.js: qatjs dev and qatjs preview serve it at
/__qat/live. The example's node:sqlite needs Node 22.13 or later (on 22.12, Qat's minimum, it
is behind --experimental-sqlite). sqlite() takes any connection with the same prepare and
exec, so better-sqlite3's works too.
// server/live.js
import { DatabaseSync } from 'node:sqlite'
import { live, sqlite } from '@qatjs/server/live'
const db = new DatabaseSync('stock.db')
const count = db.prepare('select n from stock where id = ?')
const hub = live({ resolve: { stock: ([id]) => count.get(String(id))?.n ?? 0 } })
sqlite(hub, db)
export default hub- A change:
hub.changed('stock', '5')resolves again every subscribed key that starts with those parts (hub.changed(): every key), in each session, and pushes the ones whose value differs. - Coalescing: changes within 50 ms (
every) go out as one push per session. - A key that fails to resolve (its database locked by another writer, a service down) is not
dropped: it is resolved again after 100 ms, doubling to 1 s, until it resolves, and its error is
logged once. No change is lost, but changes made while it fails coalesce: the page gets the value
as it is once the key resolves, not each value in between. After a lock is released, the push
comes within 1.05 s (the retry's 1 s cap and the 50 ms window); a write the lock's holder made
moves
data_versionand reaches the page within the adapter's 200 ms and the window. - Cap: a session holds at most 50 keys (
cap); the rest are left out. - One read:
GET /__qat/live?k=<key>returns a key's value once. A live load can read its first value there, and so can the server render, in process, throughwithLive(handler, hub). - Disconnects: with no session,
stale(from@qatjs/core/live) is true and the loads keep what they had. When the session comes back, every live load fetches again, as any load does. - Transport: Server-Sent Events by default.
import '@qatjs/core/live/ws'uses a WebSocket to the same path instead;@qatjs/sync-server'sattach(server, relay, { live: hub })serves it beside the relay.
Adapters turn your database's changes into changed():
| Adapter | |
|---|---|
postgres(hub, client, { channel }) |
LISTEN qat_live; NOTIFY qat_live, '["stock","5"]' is hub.changed('stock', '5') |
poll(hub, { every }) |
poll and diff: every key resolved again every every ms (1000), pushed when it changed |
sqlite(hub, db, { every }) |
a write by another connection or process moves PRAGMA data_version; checked every 200 ms. After a write through the same connection, call hub.changed() yourself. A check that meets a locked database is made again at the next tick |
Where it runs:
- Node: in process (
withLive), asqatjs previewruns it. - workerd (Cloudflare): one request cannot write to a stream that another request opened. Keep
the hub in a Durable Object, which all its requests share, and pass
/__qat/liveto it.examples/workerd/test/live.test.tsruns it this way. - Vercel Edge: not run here. Its isolates share no memory and hold a stream for a limited time.
Run the hub on a Node server, or feed it from a shared bus (Postgres
NOTIFY). When a stream closes, the page's EventSource reconnects and its live loads fetch again.
examples/shop shows a product's stock count, live. examples/admin shows each order's status
pushed from the backend, so a change made in another session appears in the open list.
Scenarios: try a change before making it
A scenario is a branch of the page's state. You make the change in the branch, look at the page as the change would leave it, and then commit it or discard it.
// src/pages/orders.qx
import { Compare, scenario, scoped } from '@qatjs/core/scenario'
import { setStatus } from '../api.js'
export default function Orders({ data }) {
let orders = state(data)
let trial = state(null)
let seen = derived(trial ? trial.of(orders, 'orders') : orders)
const tryMove = (ids) => {
const s = scenario({ name: 'Move to courier' })
for (const o of orders) if (ids.includes(o.id)) s.mutate(o, (d) => (d.status = 'On the way'), () => setStatus(o.id, 'On the way'))
trial = s
}
const onTheWay = (list) => list.filter((o) => o.status === 'On the way').length
return (
<main>
<button on:click={() => tryMove(['10479'])}>Try</button>
{if (trial)}
<Compare scope={trial}>{(side) => <p class="kpi">{side}: {onTheWay(scoped(orders))} on the way</p>}</Compare>
<button on:click={() => trial.commit()}>Commit</button>
{/if}
<ul>
{for (const o of seen)}<li key={o.id}>{o.id}: {o.status}</li>{/for}
</ul>
</main>
)
}
<style>
.kpi { font-weight: 600; }
</style>orders statetrial stateseen deriveds.of(x, name)isxas the branch sees it. A read falls through to the real value until the branch writes one; an object is copied by key, an array whole. Something derived over the branch runs on the branch.nameis what the diff calls the value.s.mutate(target, apply, commit)is a change the backend must accept.applyruns on the branch now;commit, the request, waits fors.commit().<App scope={s} />renders a component under the scenario. There,scoped(x)is the branch's view ofx, and loads use a cache of the scenario's own, so nothing reaches the page's cache.<Compare scope={s}>renders its children twice: the page as it is, and as the scenario would make it.s.diff()lists each changed field:orders[10479].status, before and after. An element is named by itsid, else by its index.s.commit()is ordered, not atomic:- first it checks for conflicts. If a field the branch wrote has changed meanwhile, say through a
live push from another session, it returns
QX-SCENARIO-CONFLICTwith those fields and commits nothing. A field of a shared document (@qatjs/core/sync) is merged instead; - then it runs each step in order, a mutate through its own request, which the server checks again;
- the first step that fails stops the commit. That step is put back, the report says which one it was, and the branch stays open with the steps left.
commit({ transaction })is reserved.
- first it checks for conflicts. If a field the branch wrote has changed meanwhile, say through a
live push from another session, it returns
s.discard()drops the branch.- QX-SCENARIO-UNTRACKED (a warning; an error with
qatjs check --strict):s.run(fn)or a mutate'sapplycalls something that acts on the world (a request, storage, a socket), followed through the file's own functions. That call runs at once, for real. Put it in the mutate'scommit. - QX-SCENARIO-STATIC: a static route cannot use a scenario.
examples/admin has "Try: move to courier": pick orders, see the table, the side sheet and the
count on the way under the scenario, then commit or discard. If another session moves one of those
orders meanwhile, the commit stops with the conflict.
Try it
examples/sync is a shared todo list: run qatjs dev and open it in two windows. Its Playwright
tests use two browser contexts, one of which goes offline and merges on reconnect.