Reference
WebSocket: realtime
Instant updates over a WebSocket, with catch-up on reconnect, sync tokens for a socket on another host, and sessions checked again while the socket is open.
Live updates are off by default; live: true on the client opens a WebSocket. Changes then reach every device the moment the server has ordered them: in the benchmark, a write shows on another device in about 2 ms (p50). The examples use the todo app from the quick start.
Server
The socket needs a long-running process: createSyncServer on Node.js. It serves the same HTTP endpoints as the Next.js handler plus WS /live, and starts the engine's background sequencer.
import { createServer } from "node:http";
import { createSyncServer, verifyJwt } from "@clientdb/server";
import { engine } from "./sync/engine";
const syncServer = createSyncServer(engine, {
session: verifyJwt({
jwks: "https://auth.example.com/.well-known/jwks.json",
issuer: "https://auth.example.com",
audience: "https://app.example.com", // the audience your app's tokens carry
session: (claims) => {
return claims.sub ? { viewer: claims.sub } : null; // or look up the user row by an external id
},
}),
});
const server = createServer();
syncServer.attach(server); // /api/sync/… and WS /api/sync/live
server.listen(4000);For Express, Fastify, Hono, CORS and graceful shutdown, see Node.js servers.
Client
"use client";
import { createDatabaseClient, indexedDb } from "@clientdb/client";
import { getToken } from "@/lib/auth-client"; // e.g. Clerk's getToken(), Supabase's session.access_token
import { schema } from "./schema";
export const db = createDatabaseClient({
schema,
url: "https://api.example.com/api/sync",
live: true,
token: () => {
return getToken(); // Authorization header over HTTP, ?token= on the socket
},
storage: indexedDb(),
});Browsers can't set headers on WebSockets, so the token travels as a query parameter there. The server reads ?token= on WebSocket upgrades only, never on plain HTTP requests, since URLs end up in logs. Keep query strings of the /live path out of your proxy's access logs, or use short-lived sync tokens (below) so a logged token expires within minutes.
Live updates on another host
Often the app keeps its session cookie and its Next.js route, and only the socket runs elsewhere. The route then hands out short-lived sync tokens: signed tokens carrying the whole session (the viewer, claims, read-only and tenant), so the socket server never asks your app who is signed in.
import { clientdbHandler } from "@clientdb/server/next";
import { getSyncSession } from "@/sync/session"; // the session callback from the HTTP page
import { engine } from "@/sync/engine";
export const { GET, POST } = clientdbHandler(engine, {
session: getSyncSession,
tokens: { secret: process.env.CLIENTDB_SECRET! }, // adds GET /api/sync/token
});import { createServer } from "node:http";
import { createSyncServer } from "@clientdb/server";
import { engine } from "./sync/engine";
// no session callback: every request carries a sync token signed with the same secret
const syncServer = createSyncServer(engine, { tokens: { secret: process.env.CLIENTDB_SECRET! } });
const server = createServer();
syncServer.attach(server);
server.listen(4000);export const db = createDatabaseClient({ schema, live: { url: "wss://live.example.com/api/sync" } });The client fetches a token from /api/sync/token (with the page's cookie) and opens the socket with it. Long-lived credentials never end up in WebSocket URLs.
Sessions are checked again while the socket is open
A socket can stay open for hours, longer than a sign-in or a claim lasts. So the server checks its session again every tokens.ttlSeconds (5 minutes by default):
- Opened with a sync token: the client fetches a new token before the current one expires and sends it over the socket; the server takes the new token's session. If the token expires without a new one, the server closes the socket.
- Opened otherwise (a cookie, or your auth provider's token): the server calls your
sessioncallback again with the original upgrade request.
When the claims or the read-only flag changed, the device receives the new session (db.$session updates) and the rows it gained or lost, as for any access change. When the user signed out, became someone else, or the token expired, the server closes the socket with code 4401 and the client reconnects with fresh credentials.
What happens on the socket
- The client sends
hellowith its protocol version, client id and the last sync id it has. - The server answers with its own
hello, the verified session, then the catch-up: changes to the user's groups, the rows of newly granted groups, and the log since the device's sync id, compacted to the latest change per row, plus confirmations of transactions it already applied. - From then on the server sends a
packetper batch of writes, and the client sendstransactionsas the user writes. Writes made while disconnected are sent again after reconnecting and applied once.
db.$sync() on a live client sends a barrier, { t: "sync", id }, instead of a pull. The server answers synced once the transactions the socket sent before it are applied and everything committed before it has been delivered, so $sync() and $action resolve with the server's changes on the device. If the socket closes first, the client pulls over HTTP instead.
Reconnects
The client reconnects with backoff (reconnect: { minDelayMs, maxDelayMs }, 250 ms up to 10 s). db.$reconnectNow() skips the wait. Catching up on 1,000 changes made while offline took 7 ms in the benchmark.
Swift on Linux
URLSession WebSockets on Linux need a libcurl built with WebSocket support (Ubuntu's isn't). Without one, the Swift client falls back to polling. See Swift.