Skip to Content
API ReferenceLive data & collaboration

Live data and collaboration

Foir has two live systems. They answer different questions, and they compose rather than compete:

  • GraphQL WebSocket subscriptions on api.foir.dev/graphql/ws — subscribe to record-change, operation-execution and event-log events with the same origin and API key as your queries and mutations. The event log is console-only: it needs an admin key holding events:read, and is reached through createEventsClient from @foir/sdk/server rather than the storefront data client.
  • The collaboration gateway on realtime.foir.io — Yjs-based collaborative record editing, authenticated with a user access token.

Choose by what you are doing, not by which credential you hold. Many writers editing one document, where edits have to merge — that is the collaboration gateway. One writer (a commit) and many readers, where order matters — those are subscriptions.

They meet at the write: a collaboration room auto-commits, which emits an event, so everyone outside the room learns about it through subscriptions.

Throughout these docs the two are called subscriptions and collaboration. “Realtime” is not used as the name of the category, because @foir/sdk/realtime is the collaboration helper specifically — one of the two — and using the word for both is most of why they blur.

GraphQL WebSocket Subscriptions

GraphQL subscriptions use the same origin as queries and mutations, so your client setup is straightforward.

There is an SDK equivalent. @foir/sdk/data speaks graphql-ws over this same endpoint, and every subscription below is reachable through the client you already have — foir.page.onChange(...), foir.ns.notifications.onNotification(...), foir.ns.operations.onExecution(...). It reconnects and resubscribes on its own, and it needs no graphql package. See Subscriptions for the typed path; the raw protocol below is for a document you wrote or a client you control.

Endpoint

wss://api.foir.dev/graphql/ws

Foir uses the graphql-ws  protocol for WebSocket subscriptions.

Connection Setup

Initialize the connection with your API key in the connection parameters:

import { createClient } from "graphql-ws"; const client = createClient({ url: "wss://api.foir.dev/graphql/ws", connectionParams: { apiKey: "foir_pub_your_publishable_key", }, });

If you are using user authentication, include the user token as well:

const client = createClient({ url: "wss://api.foir.dev/graphql/ws", connectionParams: { apiKey: "foir_pub_your_publishable_key", Authorization: `Bearer ${userAccessToken}`, }, });

Subscribing to Model Changes

Subscribe to real-time change events for specific models:

const unsubscribe = client.subscribe( { query: ` subscription OnRecordChange($modelKey: String!) { recordChanged(modelKey: $modelKey) { action recordId modelKey userId } } `, variables: { modelKey: "product" }, }, { next(data) { console.log("Record changed:", data); }, error(err) { console.error("Subscription error:", err); }, complete() { console.log("Subscription complete"); }, } ); // Later, to unsubscribe: unsubscribe();

The RecordChangedEvent payload is flat — there is no nested record object:

FieldTypeDescription
actionString!Change type (see below)
recordIdID!ID of the changed record
modelKeyString!Model the record belongs to
userIdStringActor that made the change, when a user made it. Absent for system, service and scoped callers
eventIdStringId of the durable event this message projects — the same id a webhook delivery for this change carries. This is what you join on
eventStringEvent family name, e.g. RECORD_UPDATED — the same name a hook subscribes to
seqFloatPlatform sequence, assigned in commit order and monotonic per project. Apply last-write-wins: keep the highest seq you have applied per record and discard anything at or below it

seq is a Float rather than an Int because it carries a bigint and GraphQL’s Int is 32-bit. A double represents every integer up to 2^53 exactly, which is what the JSON wire carries in any case; codegen maps both to number, so it costs you nothing and does not silently truncate once a stream passes 2^31.

recordChanged is the ergonomic front door over the event log, not a second source of truth. It is a typed contract seven keys wide, projected by the relay from a committed row in the same durable log events.subscribe() pages — the same fact, the same ordering, the same seq. So a webhook delivery, a log row and a recordChanged message for one write all name one event, and you can join them on eventId.

It carries identifiers, never content, and that is deliberate rather than an omission. Reading events is plain tenant/project containment, while reading a record carries owner, access mode, grants, borrow and per-field stripping on top — so copying record data onto an event row would move those bytes from the second rule to the first, permanently. Take the id and read the record through the data path, where your reach is what decides what you see.

Change Event Types

action valueDescription
createdA new record was created
updatedAn existing record was modified
publishedA record version was published
unpublishedA record was unpublished
deletedA record was deleted

Subscribing to Operation Progress

A publishable or a server key must include a signed-in user token. The generic and per-operation streams show only that user’s own runs. Anonymous subscriptions are refused with a sign-in error.

operationExecution streams progress and terminal events for a single operation execution (the run’s id, which StartRun and the executeXxx mutations return). Each event carries the current status, so you can drive UI state from one field. On the socket status is the platform’s lowercase value; foir.ns.operations.onExecution in @foir/sdk hands it over as the OperationExecutionStatus enum name (RUNNING), the spelling the operationExecution query returns:

const unsubscribe = client.subscribe( { query: ` subscription OnExecution($id: String!) { operationExecution(id: $id) { id status # pending|dispatched|running|completed|failed|cancelled|timed_out progressPct # 0-100; null on terminal events progressMessage resultJson # present on status=completed errorJson # present on status=failed|timed_out } } `, variables: { id: "exec_abc123" }, }, { next(data) { console.log("Execution update:", data); }, error(err) { console.error("Subscription error:", err); }, complete() { console.log("Execution finished"); }, } );

Using with Apollo Client

import { ApolloClient, InMemoryCache, split, HttpLink } from "@apollo/client"; import { GraphQLWsLink } from "@apollo/client/link/subscriptions"; import { createClient } from "graphql-ws"; import { getMainDefinition } from "@apollo/client/utilities"; const httpLink = new HttpLink({ uri: "https://api.foir.dev/graphql", headers: { "x-api-key": "foir_pub_your_publishable_key", }, }); const wsLink = new GraphQLWsLink( createClient({ url: "wss://api.foir.dev/graphql/ws", connectionParams: { apiKey: "foir_pub_your_publishable_key", }, }) ); const splitLink = split( ({ query }) => { const definition = getMainDefinition(query); return ( definition.kind === "OperationDefinition" && definition.operation === "subscription" ); }, wsLink, httpLink ); const client = new ApolloClient({ link: splitLink, cache: new InMemoryCache(), });

Connection Lifecycle

The graphql-ws client handles reconnection automatically. You can configure retry behavior:

const client = createClient({ url: "wss://api.foir.dev/graphql/ws", connectionParams: { apiKey: "foir_pub_your_publishable_key", }, retryAttempts: 5, retryWait: async (retryCount) => { await new Promise((resolve) => setTimeout(resolve, Math.min(1000 * 2 ** retryCount, 16000)) ); }, on: { connected: () => console.log("WebSocket connected"), closed: () => console.log("WebSocket closed"), error: (err) => console.error("WebSocket error:", err), }, });

With @foir/sdk

Everything above is reachable through the typed data client, over the same endpoint and the same API key. Nothing extra is installed: the SDK speaks the graphql-transport-ws protocol itself, so there is no graphql-ws and no graphql package in your bundle, and it prints the subscription document for you from the same description your types were generated from.

// recordChanged — the model is the address, so the scope the server charges // is the one that put the model in your types. const live = foir.page.onChange({ onData: (event) => revalidate(event.recordId), onReconnect: () => refetchEverything(), }); // notification — scoped server-side to your own identity, no arguments. foir.ns.notifications.onNotification({ onData: show }); // jobProgress, and one operation execution until it reaches a terminal state. foir.ns.operations.onJobProgress({ onData: render }); foir.ns.operations.onExecution({ id: executionId, onData: render }); live.unsubscribe();

It reconnects with backoff and resubscribes, answers keepalive pings, and opens the socket lazily so a client used only for queries never has one.

Subscriptions is the full reference — every event payload, the handler contract, the reconnect policy, and what to do on Node 18 and 20 where there is no global WebSocket.

If what you actually want is for the queries you already made to stop being wrong, rather than to handle each event yourself, see Live reads below — the same stream, wired to your query cache by the server’s own dependency graph.

Live reads

A subscription tells you a record changed. What you usually want is for the queries you already made to stop being wrong — and that needs to know which of them depended on that record.

Foir already computes exactly that. Every cacheable response carries the set of records and collections it was built from, because the API needs it to invalidate its own cache; recordChanged streams the events that make those dependencies stale, each with the project’s monotonic seq. @foir/sdk/live is the join.

That is a different thing from what a client cache normally does. Query-key conventions and normalised-cache heuristics both guess at the dependency graph. Here it is computed by the process that actually resolved the query, so invalidation is exact and does not know or care what your schema looks like.

import { FoirLive, useFoirLive, useFoirLiveStatus } from '@foir/sdk/live/react'; <FoirLive queryClient={queryClient} subscribe={(model, options, handlers) => foir[model].onChange({ ...handlers, ...options })} > <ProductList /> </FoirLive>; function ProductList() { useFoirLive('product'); // watch, while this is mounted const { newCounts } = useFoirLiveStatus(); // "3 new products — show" }

It is an adapter, not a store. You keep the query library you already have and it keeps owning your data. What this owns is which entries a change invalidates.

What it does per action, and why the three differ

An edit is matched on the record, not the model — a list response already carries a tag for every member it served, so one edit refetches the queries holding that record and nothing else. Invalidating the model instead would refetch every list on it, which is a refetch storm standing in for an update.

A create cannot be spliced into a page you have loaded: the event carries no record body, and even with one, placing the row would need to know the query’s sort. So it reports a count and lets you decide — refetching the head page instead prepends under a reader mid-scroll, which is the disruption this avoids.

A delete is applied in memory with no fetch at all, because the event carries the id.

totalCount is flagged approximate rather than adjusted: it is the server’s count under your filter, and guessing at it turns a stale number into a wrong one.

Opt in per model

Nothing subscribes because the provider is mounted. A component asks for a model and the stream lives as long as something is asking.

That default is deliberate. Reads on a publishable key take a shared CDN lane, and that lane is most of why anonymous reads are cheap — making everything live pushes that traffic onto the origin. Ask for liveness on the models where it earns the connection.

Bursts, drift, and the two refusals

A bulk import fires a burst. Fifty invalidations of one query inside a short window are one refetch, at most four refetches run at once, and a query invalidated again mid-refetch is owed exactly one more.

A deploy is the case nothing else catches: it leaves every cached entry perfectly current and quietly wrong, because no record changed and nothing is out of order — the bytes simply describe a schema that no longer exists. Wire createFoirDriftHandler into onSchemaDrift once and the whole class goes away.

Pass the highest seq you have applied as after and the stream replays what came after it from the durable log before continuing live, so a message lost in transit is repaired by the next connect rather than left as a permanently stale entry. Two refusals end that stream and both mean throw the cache away: cursor_expired (older than the log’s retention window) and backlog_too_large (further behind than this surface will page). They are refusals rather than partial replays on purpose — a cache handed half a backlog believes it is caught up.

What it is not

No local mutation log, no offline mode, no conflict resolution, no optimistic rollback. The server is authoritative: mutations go over the wire and the invalidation comes back.

That is a product boundary, not a phase we have not reached. And one known limitation to design around: a query ordered by a mutable sort key — updatedAt, or a position someone drags — can have a record move between pages when it is updated, so it may appear twice or vanish until the next full refetch.

Collaboration Gateway

The gateway at realtime.foir.io runs collaborative record editing (Yjs). Discover the gateway URL and a record’s room at runtime by selecting the collab field, which every record type carries:

query GetCollabInfo { product(id: "rec_123") { collab { enabled wsUrl roomName } } }
{ "data": { "product": { "collab": { "enabled": true, "wsUrl": "wss://realtime.foir.io", "roomName": "product:rec_123:default" } } } }

roomName is {modelKey}:{recordId}:{variant}. The variant segment is the one that record resolved onto for your request, so the room you’re handed always holds the content you just read — a record served on the vip variant returns product:rec_123:vip. Records that resolved onto no variant get default.

The same read through the data client:

const product = await foir.product.findUnique({ id: 'rec_123' }); product.collab?.roomName; // 'product:rec_123:default'

collab is a composite value and arrives whole without being asked for, on every read of the model. It is cheap — the server builds it from values it already has, with no lookup of any kind, and because wsUrl is identical on every record in a response, compression removes almost all of it: a 100-item list carries about 2 bytes per record on the wire. omit: ['collab'] if you want it out of your result type on reads that are not opening a room; do not omit it for speed. See Selection & Responses.

Discovering the room is the only part of this the data client has a form for. Opening it, and every stream on this page, is a persistent connection rather than an operation.

Finding out what is available

Both systems answer this the same way, and it is worth seeing them side by side:

QuestionAnswerWhere it comes from
Can I collaborate on this record?collab.enabled on the recordA field, at runtime
Can I subscribe to this model?Whether the model is in FoirSchemaYour generated types, at compile time

A model you may not watch is a model you may not read — recordChanged charges records:read:<modelKey>, which is the same scope that put the model in your types at all. So the refusal is a type error before it is a runtime one, and there is no “subscribe and find out”.

Authentication

The gateway authenticates with a user access token passed as a ?token= query parameter — browser WebSocket clients can’t set headers, so the token rides on the URL. Use the EdDSA access token your app already holds from hosted sign-in (the same token you send as Authorization: Bearer to the public API). Tokens are verified against https://api.foir.dev/.well-known/jwks.json.

Looking for per-user event channels?

They are not part of this gateway. Per-user notifications, job progress and record changes are GraphQL WebSocket subscriptions on api.foir.dev/graphql/ws — see GraphQL WebSocket Subscriptions above.

connectionParams need both credentials: an apiKey (a publishable key is the intended browser credential) and Authorization: Bearer <userAccessToken> for the person. Name the organization the person stands at as X-Org-Id, as a request names it; the SDK sends the client’s orgId there. A person who is no member of the organization named is refused with close code 4403, and a socket whose token is no longer honoured is closed with 4402, after which the SDK renews the bearer through refreshBearer and reconnects. Each subscription charges a scope on the key:

SubscriptionScope on the keyFiltered to
notificationnotifications:readthe bearer’s own user id
operationExecutionoperations:readthe execution you name
jobProgressoperations:readyour project’s background jobs
recordChangedrecords:read:<modelKey>the model you name

Collaborative Editing

The gateway runs a Yjs  collaboration server so several users can edit the same record live, with shared cursors and presence. Open one room per record:

wss://realtime.foir.io/record/{modelKey}:{recordId}:{variantKey}?token={userAccessToken}

The canonical room address is {namespace}/{roomId}; for a record that is record/{modelKey}:{recordId}:{variantKey}. The third segment is the variant’s human key — default, or one of your variant keys such as vip, or the reserved live — and never a variant row’s id. Use the literal default when the record resolved onto no variant. Sending a row id addresses a different room: both sides connect, neither sees the other’s edits, and nothing errors. (The bare {modelKey}:{recordId}:{variantKey} triple without the record/ prefix is still accepted for backward compatibility.) Connect any standard Yjs WebSocket provider; the shared document’s content map holds the record’s field values, and Yjs awareness carries presence — who’s editing and where their cursor is.

There is an SDK helper, and it gets the addressing right for you. @foir/sdk/realtime is a thin wrapper over y-websocket that adds the three things the raw provider does not: the canonical {namespace}/{roomId} path, the presence payload shape, and token refresh the next reconnect picks up (tokens are short-lived and the gateway re-validates on every upgrade, so a live socket outlives its token but a reconnect does not).

import { createCollabSession } from '@foir/sdk/realtime'; const session = createCollabSession({ url: collab.wsUrl, room: { namespace: 'record', id: collab.roomName }, doc, // your Y.Doc — the SDK never owns it getToken: () => auth.accessToken(), orgId: currentOrgId, // where the user stands; omit for the project presence: { id: user.id, name: user.name }, });

A room join stands where it names, as a request does: orgId is sent as the connection’s org, and the user joins there only as a member of it.

yjs and y-websocket are optional peer dependencies gated to this subpath, so importing anything else from @foir/sdk pulls no Yjs. Use the wsUrl and roomName the collab field returns rather than building the address yourself — that is the whole point of the helper.

Access control. Nobody joins a room by being signed in. Joining is a permission a role gives, and the record’s own access then says which records’ rooms.

PermissionWhat it opens
rooms:readJoining a record’s room: receiving the shared document live, seeing who is in it, and being seen.
rooms:writeChanging the shared document. It needs rooms:read as well, because a read and a write are separate permissions.

Give them to a role for every model (rooms:read) or for one (rooms:read:page), in the role editor or with foir roles update <roleId> --grants "records:read:page,rooms:read:page,rooms:write:page". No role holds them until you do. A room’s shared document is the working copy, including text nobody has saved, so being able to read a published record does not open its room.

There are two kinds of join, and they ask for different things.

A write join, which is the default and what a co-editor needs, asks for rooms:read and rooms:write on the record’s model, and for edit access on the record: the user owns it, or holds an accepted edit or the console share. A read join asks for rooms:read on the model, and that the user can see the record, which a read share is enough for. A read-joined connection receives the document and presence but its own document updates are dropped, so it watches the room without being able to change it.

Declare a read join by adding ?capability=read to the gateway URL. createCollabSession has no capability option of its own, so reach it through the params escape hatch:

const session = createCollabSession({ url: collab.wsUrl, room: { namespace: 'record', id: collab.roomName }, doc, getToken: () => auth.accessToken(), params: { capability: 'read' }, });

A console user is asked for the same permissions, which project:manage carries. Either join failing is rejected with 403. The answer is read again while a connection is open: when a role loses the permission, or a person loses the role, their connections are closed with code 4403 within about thirty seconds. If your token was issued for fewer scopes than the role holds, add the room permissions to the scopes your application asks for, since a token opens nothing it was not authorised for. Each identity may hold up to 10 open rooms at once by default; exceeding that rejects the connection with 429 (a Retry-After header and a JSON body { "error": "room_limit_exceeded", "limit", "held" }). Reconnecting to a room you already hold does not count against the limit.

How edits are saved depends on whether the model is versioned:

  • Unversioned models — auto-commit. Edits are debounced and persisted to the record automatically, attributed to the last editor, with a final flush when the last editor disconnects. There’s nothing extra to call — collaborative edits just save themselves.
  • Versioned models — collaborate, then save. Live edits are shared across all participants (and recovered if everyone disconnects), but they are not auto-persisted. Committing is an explicit step your app drives through the normal record APIs — save the draft, then publish a version (update<Model> + publish<Model>Version, or foir records save + foir records publish). This keeps each published version an intentional, reviewable snapshot.

Gateway status

EndpointReturns
GET https://realtime.foir.io/health{ "status": "ok" }
GET https://realtime.foir.io/api/collab/room-status/{room}{ exists, clients } for a collab room. Internal control endpoint — requires X-Internal-Token, not reachable with a user access token.
Last updated on