Subscriptions
Live data is part of the data client, not a separate product. The same foir object that reads records also opens streams, over the same credential, with no extra package: @foir/sdk/data speaks the graphql-transport-ws protocol itself, so there is no graphql-ws and no graphql in your bundle.
const live = foir.page.onChange({
onData: (event) => revalidate(event.recordId),
});
// later
live.unsubscribe();The six streams
| Call | What it streams |
|---|---|
foir.<model>.onChange(…) | Records of that model being created, updated, published, unpublished or deleted |
foir.ns.notifications.onNotification(…) | Notifications for the subscribing identity |
foir.ns.operations.onJobProgress(…) | Background job lifecycle for the project |
foir.ns.operations.onExecution({ id, … }) | One operation execution, until it reaches a terminal state |
foir.ns.operations.onExecution({ id, operation, … }) | The same, on that operation’s typed stream |
events.subscribe(…) from @foir/sdk/server | The project’s durable event log, pushed from a cursor — see events |
Handling events one at a time is the low-level path. If the reason you want the stream is to keep already-fetched queries from going stale,
@foir/sdk/livedoes that from the dependency set the API ships on every response — see Live reads. Reach foronChangedirectly when you want the event itself: an audit trail, a toast, a webhook you are mirroring.
Which of them your key can open is a projection, exactly as it is for operations — a publishable key holding only records:read: scopes is published recordChanged and nothing else. See scopes.
Every subscription method is named on…, which keeps them distinguishable at a glance from operations that await a value — and means no generated operation name can collide with one.
onChange hangs off the model because the model is its argument: foir.page already carries modelKey: 'page', so the one thing the server gates on is supplied by the address rather than by you. The other four are project-independent platform surfaces, so they hang off the namespace that owns them.
The event log is the exception to the shape of this page: it is a user surface an admin key reaches, never a user token, and its live stream is not on the data client. Build it with createEventsClient from @foir/sdk/server, which also reads the log page by page.
Record changes
const live = foir.page.onChange({
onData: (event) => {
if (event.action === 'deleted') dropFromCache(event.recordId);
else revalidate(event.recordId);
},
onReconnect: () => refetchEverything(),
onError: (err) => report(err),
});One event, as it arrives:
{
"recordId": "y5nwq2rk8vd1t0jc6phaz3xe",
"modelKey": "page",
"action": "published",
"userId": "usr_8fbd21c0",
"eventId": "btjl746n07wqygmg1hbwc4v7",
"event": "RECORD_PUBLISHED",
"seq": 48213
}| Field | |
|---|---|
recordId | The record that changed |
modelKey | The model it belongs to — the one you addressed |
action | created, updated, published, unpublished or deleted |
userId | Actor, when a user made the change. Absent for system and service callers |
eventId | The durable event this projects — the same id a webhook delivery carries |
event | Event family name, e.g. RECORD_PUBLISHED. The name a hook subscribes to |
seq | Platform sequence, assigned in commit order and monotonic per project |
seq is what makes an out-of-order delivery survivable. Apply last-write-wins: keep the highest seq you have applied per record and discard anything at or below it.
Resuming after a disconnect
Pass after — the highest seq you have applied — and the server replays what came after it from the durable log before continuing live. A message lost anywhere upstream is then repaired by the next connect, rather than left as a permanently stale cache entry.
foir.page.onChange({
after: lastAppliedSeq,
onData: apply,
});Two refusals can come back on onError, and both mean the cache must be thrown away rather than partially repaired: cursor_expired (your cursor is older than the retention window) and backlog_too_large (it is further behind than this surface will page). Branch on extensions.code, never on the message — the sentence is documentation, the code is the contract. @foir/sdk/live classifies them for you with foirRequiresResync.
Private models: reconcile on reconnect, or you will never see deletes
If a model’s records are partitioned per caller — each user sees only their own — its change stream is filtered to you. You receive changes to your own records and nothing about anyone else’s.
That filtering has one consequence you must design for:
A delete produces no event on a partitioned model. Neither does losing access to a record. Resuming the cursor cannot recover either one, because there was never an event to replay.
The filter is a join against the records you can currently read. Records are deleted outright rather than flagged, so by the time the server evaluates that join for a deletion there is no row left to match — and a record that moved to another owner stops matching for the same reason. Both go silent.
So a client on a partitioned model has to ask a second question on reconnect, alongside resuming the cursor. They are not alternatives:
- the cursor replays what changed while you were away;
- reconciling reports what vanished.
Re-read the ids you are holding. Anything that does not come back is gone:
import { createFoirReconciler, foirTagsForGoneRecords } from '@foir/sdk/live';
const reconciler = createFoirReconciler({
// Which of these ids can I still see? The call discloses nothing, because
// YOU supply the ids — an id you name is one you already held.
resolve: async (modelKey, ids) => {
const found = await foir[modelKey].findMany({
where: { id: { in: [...ids] } },
first: ids.length,
});
return found.edges.map((e) => e.node._id);
},
heldIds: (modelKey) => cachedRecordIdsFor(modelKey),
onGone: (modelKey, goneIds) => {
dropFromCache(goneIds);
invalidate(foirTagsForGoneRecords(modelKey, goneIds));
},
});
foir.page.onChange({
after: lastAppliedSeq,
onData: apply,
onReconnect: () => reconciler.reconcile('page'),
});With <FoirLive> this is the reconcile prop, and the provider calls it on every reconnect for you:
<FoirLive
subscribe={subscribe}
queryClient={queryClient}
reconcile={(modelKey) => reconciler.reconcile(modelKey)}
>
{children}
</FoirLive>A few properties worth knowing:
- It cannot leak. You name the ids, so the answer only ever concerns records you already had.
- It fails closed in the direction that keeps data. If the resolve throws, the reconcile is abandoned rather than treated as “everything is gone” — a network blink must not evict a working cache.
- It is batched and deduplicated, and concurrent reconciles for one model collapse onto a single read, so a reconnect storm does not multiply it.
- Running it on a public model is harmless — it reports nothing. You do not have to know which models are partitioned.
userId is absent on a partitioned model
A record you own may still have been changed by somebody else — a manager, a support agent, a previous owner. The filter cannot help there, because those are changes to records you are entitled to see. So the filtered stream omits userId entirely rather than naming who acted.
Notifications
Scoped server-side to the subscribing identity, so it takes no arguments — there is no one else’s inbox to ask for.
foir.ns.notifications.onNotification({
onData: (event) => toast(event.title ?? 'New notification'),
});{ "userId": "usr_8fbd21c0", "type": "mention", "title": "Ana mentioned you" }type is notification, announcement or mention.
Operation executions
execute<Op> returns the execution row. Subscribe to its id and drive your UI from status, which every event carries:
const { execution } = (await foir.ns.operations['execute.contact-form-handler']({
input: { name: 'Ana', email: 'ana@example.com' },
mode: 'ASYNC',
})) as { execution: { id: string } };
foir.ns.operations.onExecution({
id: execution.id,
onData: (event) => setProgress(event.status, event.progressPct),
onComplete: () => setProgress('done', 100),
});{
"id": "exec_abc123",
"status": "RUNNING",
"progressPct": 40,
"progressMessage": "Rendering 2 of 5",
"progressUpdatedAt": "2026-08-11T09:22:41.019Z",
"progressMetadata": null,
"resultJson": null,
"errorJson": null
}status is PENDING, DISPATCHED, RUNNING, COMPLETED, FAILED, CANCELLED or TIMED_OUT, the same spelling operationExecution returns for the run, so one comparison serves a read and an event. The socket itself carries the lowercase platform value, and a raw graphql-ws client sees that (see Real-time and Subscriptions). resultJson is present on COMPLETED; errorJson on FAILED and TIMED_OUT; progressPct is null on terminal events. The server ends the stream on a terminal event, which is what fires onComplete.
Pass operation as well to take that operation’s typed stream instead of the generic one:
foir.ns.operations.onExecution({ id, operation: 'contact-form-handler', onData: render });The key is matched against the field names your manifest publishes, never converted into one. An operation with no typed stream fails naming the ones that exist, rather than quietly opening the generic stream under a name you did not ask for.
Project-wide job lifecycle, rather than one execution:
foir.ns.operations.onJobProgress({ onData: (event) => log(event.jobId, event.status) });{ "jobId": "job_7c1e", "queue": "media", "status": "progress", "progress": 60, "error": null }The handle
Every subscription call returns synchronously with a handle carrying unsubscribe():
const live = foir.page.onChange({ onData: apply });
live.unsubscribe();The document is resolved behind that handle, so cancelling before it is ready is honoured and no stream is ever opened. unsubscribe() is idempotent.
The socket is lazy and self-closing: it opens on the first subscription and closes when the last one is cancelled. A client used only for queries never opens one, and never needs tearing down. A long-lived process that discards a client can call foir.dispose() to close the socket and drop every live subscription at once; a browser tab or an edge invocation just goes away.
Handlers
foir.page.onChange({
onData: (event) => {}, // one event, per `next` frame
onError: (err) => {}, // terminal for THIS subscription
onComplete: () => {}, // the server ended the stream
onReconnect: () => {}, // the socket dropped and this stream is back
});onData is the only required one.
onReconnect is worth handling. If the socket drops, the client reconnects with exponential backoff and re-sends every live subscription, and onReconnect fires when yours is running again. That is not merely informational: a subscription is not a durable log, and events published while the socket was down were not buffered anywhere. A view that must not miss one refetches there.
onError fires only when the stream is over — the server refused it, or the transport gave up reconnecting. A drop the transport recovers from reaches onReconnect, not onError.
Reconnection
Retries forever by default, which is the right behaviour for a stream in a browser tab. Tune it per client:
const foir = createFoirClient({
apiUrl,
apiKey,
generated,
reconnect: {
maxAttempts: 10, // default: Infinity
initialDelayMs: 500, // doubles, capped at maxDelayMs
maxDelayMs: 15_000,
jitter: 0.25, // random fraction added per attempt
},
});Jitter is on by default and worth leaving on: without it, a server restart brings every client back at the same instant.
Server pings are answered and the client pings on its own timer, so an idle stream is not reaped by a proxy in between.
Credentials and scopes
The connection carries the same credentials the HTTP requests do, built by the same code — including a user bearer token when you set bearerToken. A WebSocket handshake carries no headers a browser will let you set, so they travel in the connection_init payload, which is what the protocol is for.
A subscription your key cannot open is not published to it. Your manifest lists the streams the socket will accept for that credential and nothing else, so a missing scope is an absence naming what you do have rather than a stream that silently delivers nothing:
[foir] `notification` is not available to this credential. Available: recordChanged.recordChanged goes one further and names the models: its manifest entry carries the set of model keys your key holds records:read: for, which is exactly the set the socket will accept as modelKey.
onChange is offered on every model in your generated schema, and that is exact rather than lax: watching a model charges the same read scope that put the model in your types at all, so a model you cannot watch is a model you cannot read, and the accessor does not exist to be called.
Endpoint and runtimes
The socket goes to your apiUrl with the scheme swapped to ws and /graphql/ws appended — wss://api.foir.dev/graphql/ws. Override it with wsUrl only for a proxy or a test server.
globalThis.WebSocket is used by default, which browsers, Deno, Bun, Cloudflare Workers and Node 22+ all provide. On Node 18 and 20 there is none, so pass one:
import WebSocket from 'ws';
const foir = createFoirClient({
apiUrl,
apiKey,
generated,
webSocketImpl: (url, protocols) => new WebSocket(url, protocols),
});Writing your own subscription
The transport is exported, so you can open the socket with a document of your own without forking the client — the same escape hatch foir.raw() is for the HTTP side:
import { FoirSocketTransport } from '@foir/sdk/data';The wire is the standard graphql-transport-ws subprotocol either way, so a consumer who would rather use the graphql-ws package can point it at the same endpoint. Real-time and Subscriptions covers that path, plus the collaboration gateway for Yjs-based record editing.