Skip to content
clientdb

Search the docs

Find a page or section

Reference

Node.js servers: node:http, Express, Fastify and Hono

Run the sync endpoints and the realtime WebSocket on a plain Node.js server: node:http, Express, Fastify or Hono, with CORS, body limits and graceful shutdown.

On a long-running Node.js server, createSyncServer serves the same HTTP endpoints as the Next.js handler (/bootstrap, /pull, /push, /partial, /query, and /token with tokens) plus the WebSocket at /live, all under one base path (/api/sync by default, which is where clients look unless you set their url). It also starts the engine's background sequencer, which live clients need.

Every example below uses the same engine module and auth:

src/sync/engine.ts
import { createEngine } from "@clientdb/server";
import { permissions } from "./permissions";

export const engine = createEngine({ permissions });

The session callback reads who is signed in from the request headers, so it works on HTTP requests and on WebSocket upgrades alike. Express and Fastify middleware doesn't run for upgrades, so don't rely on what it adds to the request (req.user, req.session).

node:http

src/server.ts
import { createServer } from "node:http";
import { createSyncServer } from "@clientdb/server";
import { getSession } from "./auth"; // your auth library
import { engine } from "./sync/engine";

const syncServer = createSyncServer(engine, {
  session: async (request) => {
    const session = await getSession(request.headers);
    return session ? { viewer: session.userId } : null; // the id of the signed-in user's row, or null
  },
});

const server = createServer((request, response) => {
  if (request.url === "/health") {
    response.end("ok");
    return;
  }
  syncServer.middleware(request, response); // /api/sync/…, and 404 for anything else
});
syncServer.attachWebSocket(server); // WS /api/sync/live

server.listen(4000);

When the server does nothing else, syncServer.attach(server) does both lines at once.

Express

src/server.ts
import express from "express";
import { createSyncServer } from "@clientdb/server";
import { getSession } from "./auth"; // your auth library
import { engine } from "./sync/engine";

const syncServer = createSyncServer(engine, {
  session: async (request) => {
    const session = await getSession(request.headers);
    return session ? { viewer: session.userId } : null;
  },
});

const app = express();
app.use(syncServer.middleware); // before express.json(): clientdb reads the body itself
app.use(express.json());
// …your routes

const server = app.listen(4000);
syncServer.attachWebSocket(server);

The middleware answers requests under the base path and calls next() for everything else. Mounted as app.use("/api/sync", syncServer.middleware) it works the same. It also works with Connect and anything else that passes (request, response, next). A body parser that runs first is fine too, but its own size limit (100 KB for express.json()) then applies.

Fastify

src/server.ts
import Fastify from "fastify";
import { createSyncServer } from "@clientdb/server";
import { getSession } from "./auth"; // your auth library
import { engine } from "./sync/engine";

const syncServer = createSyncServer(engine, {
  session: async (request) => {
    const session = await getSession(request.headers);
    return session ? { viewer: session.userId } : null;
  },
});

const app = Fastify();
await app.register(syncServer.fastify); // /api/sync/*, WS /api/sync/live, closes with the app

await app.listen({ port: 4000 });

The plugin reads request bodies itself, but only in its own scope: the rest of your app keeps Fastify's parsers. Set the path with basePath, not with the prefix option of register.

Hono

On Node, Hono runs through the fetch handler; the WebSocket goes on the server serve() returns.

src/server.ts
import { serve } from "@hono/node-server";
import { Hono } from "hono";
import { createSyncServer } from "@clientdb/server";
import { getSession } from "./auth"; // your auth library
import { engine } from "./sync/engine";

const syncServer = createSyncServer(engine, {
  session: async (request) => {
    const session = await getSession(request.headers);
    return session ? { viewer: session.userId } : null;
  },
});

const app = new Hono();
app.all("/api/sync/*", (context) => {
  return syncServer.fetch(context.req.raw);
});

const server = serve({ fetch: app.fetch, port: 4000 });
syncServer.attachWebSocket(server);

syncServer.fetch is the same fetch-standard handler as createFetchHandler, so it also fits Bun and other fetch-style servers.

Options

createSyncServer takes the handler options (session, anonymous, readOnly, tokens, inlineSequencing, warnUntracked) and:

OptionDefaultMeaning
basePath"/api/sync"where the endpoints and /live are served; the same as the client's default url
corsoff{ origin, credentials? }: let browser pages on other origins call the endpoints
bodyLimit16 MiBlargest request body and WebSocket message; bigger ones get 413
starttruestart the engine's sequencer now and stop it in close(); false if you do both yourself

cors and bodyLimit work the same on createFetchHandler and the Next.js handler.

Clients on another origin

When the app's pages are served from another origin than the sync server, allow that origin:

src/server.ts
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", audience: "https://app.example.com" }), // reads the bearer token
  cors: { origin: ["https://app.example.com"] },
});
src/sync/db.ts
import { createDatabaseClient, indexedDb } from "@clientdb/client";
import { getToken } from "@/lib/auth-client"; // your auth library
import { schema } from "./schema";

export const db = createDatabaseClient({
  schema,
  url: "https://api.example.com/api/sync",
  live: true,
  token: () => {
    return getToken();
  },
  storage: indexedDb(),
});

origin takes one origin, a list, "*" or a function of the Origin header. Add credentials: true only if cross-origin requests carry cookies (it needs explicit origins). With cors set, WebSockets opened by pages on origins it doesn't allow are refused as well. Without it, a page on another origin may open the WebSocket only with a sync token, never on the viewer's cookies: browsers attach cookies to WebSockets any site opens.

Graceful shutdown

TypeScript
process.on("SIGTERM", async () => {
  await syncServer.close(); // closes live sockets; clients reconnect to another instance
  server.close();
  await engine.close();
});

close() closes every WebSocket with code 1001, refuses new ones, and stops the sequencer it started. With Fastify, await app.close() does this for you.

When session or the engine throws, the request answers 500 and the error is logged; the process keeps running.