Skip to content
clientdb

Search the docs

Find a page or section

Reference

HTTP: pull and push (no sockets)

Sync over plain HTTP: the Next.js route handler and its session callback, read-only routes, a fetch-standard handler for any runtime, the endpoints, and when the client syncs.

By default, clientdb syncs over plain HTTP: no long-running process and no WebSocket. The device pulls on load, on focus, after writes and every 30 seconds while the tab is visible; a pull also carries the device's unsent writes, so one round trip sends and receives. The server works out the order of writes inside the requests themselves, so any number of serverless instances can run at once.

Next.js App Router

The examples use the todo app from the quick start.

src/app/api/sync/[...path]/route.ts
import { clientdbHandler } from "@clientdb/server/next";
import { auth } from "@/lib/auth"; // e.g. Better Auth
import { getStaffLogin } from "@/lib/staff";
import { $support } from "@/sync/claims";
import { engine } from "@/sync/engine";

export const { GET, POST } = clientdbHandler(engine, {
  session: async (request) => {
    const session = await auth.api.getSession({ headers: request.headers });
    if (!session) {
      return null; // signed out: 401
    }
    return {
      viewer: session.user.id, // the id of the signed-in user's `User` row
      claims: [$support(Boolean(await getStaffLogin(session.user.id)))],
      readOnly: session.user.suspendedAt !== null, // suspended users still see their todos, but can't change them
    };
  },
});

No route segment config is needed: route handlers run on Node.js by default (Postgres needs TCP), and a handler that reads the request is always dynamic. Don't add export const runtime or export const dynamic: Next 16 rejects both when cacheComponents is on, which create-next-app enables by default.

The session

session(request) is the only place the server learns who is asking: the device never says who it is. It runs on every request, and every few minutes on an open WebSocket. Return null when nobody is signed in, or:

FieldMeaning
viewerthe id of the signed-in user's row in the viewer model
claimsclaims granted to this session: [$support(isOnShift)]; a grant made with false isn't granted
readOnlythe session may read but not write: its writes are refused with ReadOnly, and the client's write methods throw ReadOnlyError
tenantfor engine-owned tables split by tenant (see Postgres); Prisma tables have one

The device learns the outcome: db.$session.viewerId, db.$session.claims, db.$session.hasClaim($support) and db.$session.readOnly.

Options

OptionDefaultMeaning
sessionthe session callback above
anonymousfalsetrue: a null session gets an anonymous, read-only session that sees only $.public rows, instead of 401. In development the handler warns when this and the rules disagree
readOnlyfalseevery session on this route is read-only (below)
tokens{ secret, ttlSeconds? }: adds GET …/token, which hands out short-lived sync tokens carrying the session, for live updates on another host. The secret needs at least 32 characters (openssl rand -base64 32). See WebSocket
inlineSequencingtrueorder writes inside requests. Set false only when a background engine.start() runs elsewhere
warnUntrackedon unless NODE_ENV is productionon the first request, warn about rows written outside clientdb that devices never receive. With the change triggers installed there are none
corsoff{ origin, credentials? }: answer browser pages on other origins. See Node.js servers
bodyLimit16 MiBlarger request bodies get 413. A pull carries every write a device made offline, so keep it well above your largest backlog

createFetchHandler takes the same options. For a long-running Node.js server (node:http, Express, Fastify, Hono), see Node.js servers.

Read-only routes

A route with readOnly: true serves bootstraps, pulls, loads and queries, and refuses every write with ReadOnly, whatever the session says. Use it for a second endpoint, such as a wall display that shows a project's todos:

src/app/api/display-sync/[...path]/route.ts
import { clientdbHandler } from "@clientdb/server/next";
import { getSyncSession } from "@/sync/session";
import { engine } from "@/sync/engine";

export const { GET, POST } = clientdbHandler(engine, {
  session: getSyncSession,
  readOnly: true,
});

The client for it passes url: "/api/display-sync" and readOnly: true, so its types have no write methods (see Read-only clients).

Any fetch-standard runtime

createFetchHandler takes a Request and returns a Response. verifyJwt is a session callback that checks a bearer token from your auth provider:

src/worker.ts
import { createFetchHandler, verifyJwt } from "@clientdb/server";
import { engine } from "./sync/engine";

const handler = createFetchHandler(engine, {
  // reads the bearer token, checks its signature and expiry
  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;
    },
  }),
});

export default { fetch: (request: Request) => handler(request) };

Endpoints

All under the route's base URL (/api/sync above). The message shapes are in Wire protocol.

RequestResponse
GET /bootstrapNDJSON: meta, the rows of every eager model with their eager relations, end. ?models=a,b sends only those models; ?load=lazy only meta and end, for a client that loads every model when read
POST /pullNDJSON: meta, actions, then end with syncId, confirmed and rejected; or reset when the device must bootstrap again. Sends the device's unsent transactions first
POST /push{ results: [{ clientTransactionId, ok, duplicate?, rejection? }] }
POST /partial with { loads: [{ model, field, key }] }{ actions, covered }: the rows of every load (the client batches the reads of one tick) and the loads they cover completely
GET /partial?model=&field=&key=the same for one load
POST /queryone page of a server query: { actions, covered, ids, cursor }. Outside the model's query rules, 403
GET /token{ token, expiresAt }, with tokens set

A request without a session gets 401 (unless anonymous). On the client, a 401 or 403 surfaces as a SyncRequestError whose unauthorized is true.

The client

HTTP sync is the client's default; there's nothing to turn on.

src/sync/db.ts
"use client";
import { createDatabaseClient, indexedDb } from "@clientdb/client";
import { schema } from "./schema";

export const db = createDatabaseClient({
  schema,
  storage: indexedDb(), // url defaults to "/api/sync", resolved against the page
});
OptionDefaultMeaning
url"/api/sync"the sync endpoint; relative URLs resolve against the page, absolute ones are used as is
livefalsetrue adds a WebSocket for instant updates; { url } puts it on another host
networkonfalse: a local database with no server (tests, previews)
readOnlyfalsea client without write methods
load"lazy": treat every model as lazy, for a client that loads only what it reads
syncOnLoadtruepull right after start
syncOnFocus!livepull when the window regains focus, becomes visible or comes back online
syncIntervalMs30_000 without livepull every N ms while the tab is visible (hidden tabs catch up on focus); false turns it off
pushOnWritetruesync right after local writes
token() => token, sent as Authorization: Bearer …, for other origins and native apps. Same-origin cookies need nothing
reconnect250 ms to 10 s{ minDelayMs, maxDelayMs }: backoff between retries
onErrornetwork and storage errors; the client keeps retrying

Syncing on demand

src/app/projects/AddTodo.tsx
"use client";
import { db } from "@/sync/db";
import { addTodo } from "./actions"; // a server action that writes with Prisma

export function AddTodo({ projectId }: { projectId: string }) {
  return (
    <button
      onClick={async () => {
        await db.$action(() => {
          return addTodo(projectId, db.$session.viewerId!, "Write the launch post");
        });
        // the todo the server action wrote is on this device now
      }}
    >
      Add
    </button>
  );
}
  • db.$sync() sends unsent writes and resolves once this device has everything the server committed before the call: it waits for a pull that started after the call (with a live socket, a barrier on the socket instead). Calls made meanwhile share one pull; other tabs ask the tab that holds the connection.
  • db.$action(fn) runs your server action (or tRPC mutation, or fetch), then does the same, so what it wrote is on this device when the promise resolves. It resolves to fn's result. See Server logic with $action.

Status and lifecycle

TypeScript
import { db } from "@/sync/db";

db.$status; // "idle" | "loading" | "bootstrapping" | "connecting" | "online" | "offline" | "outdated" | "closed"
await db.$ready(); // eager models usable, from storage or the network; starts the client
db.$role; // "leader" | "follower": which tab holds the connection
await db.$close();

"outdated" means the server runs another protocol or schema version: reload the app. $ready() rejects then, and when the server refuses the session.

Performance

Through the fetch handler (the same code the Next.js route uses), without network latency:

MetricResult
Push of one transaction incl. inline sequencing, p50 / p992.21 / 4.23 ms
Pull with nothing new, p50 / p990.76 / 2.47 ms
Push + pull in one request, p50 / p992.78 / 6.45 ms
Pull after 1,000 changes (compacted, streamed)12.6 ms, 274 KB
Throughput, 8 concurrent serverless instances1,184 tx/s

Mixing modes

Both modes share the same log. A WebSocket server for live clients and serverless route handlers can run side by side, and db.$sync() works with live: true too.