Skip to content
clientdb

Search the docs

Find a page or section

Reference

Prisma as the source of truth

Build a fully typed clientdb schema from schema.prisma with fromPrisma, run on Prisma's tables, and sync the writes your app makes with Prisma Client.

If your app already uses Prisma, schema.prisma stays the source of truth. Models, fields, nullability, defaults, ids and relations come from it, and the tables stay Prisma's: clientdb never runs DDL on them. You only add what Prisma can't say, such as which models load at startup.

The examples use the todo app from the quick start: users, projects, members and todos, with comments on todos.

The generator

prisma/schema.prisma
generator clientdb {
  provider = "clientdb-prisma"
  output   = "../src/generated/clientdb"
}

prisma generate now also writes src/generated/clientdb/index.ts: your Prisma models as plain as const data. It has literal types, so fromPrisma can type every model and field from it, and it is safe to import in the browser. Nothing else is generated: entity classes are built at runtime.

The generator fails with a clear message until clientdb's own tables are in schema.prisma (see below).

fromPrisma(prismaModels, options)

src/sync/schema.ts
import { fromPrisma } from "@clientdb/prisma";
import { prismaModels } from "../generated/clientdb";

export const schema = fromPrisma(prismaModels, {
  omit: { User: ["passwordHash"] }, // never leaves the server
  models: {
    User: { load: "eager" },
    Project: { load: "eager", archivable: true },
    Member: { load: "eager" },
    Todo: { load: "eager" },
    Comment: { relations: { todo: { eager: true } } }, // comments arrive with their todo
  },
});
export type Schema = typeof schema;

prismaModels is the generator's output, and this file is the only place that uses it. The schema also remembers which table and columns each model uses, so the rest of your code, server and client, only passes schema around.

Everything is typed against your Prisma models: a misspelled model (in models, omit, notSecret or a model list), field or relation is a type error on that key, and a runtime error that names it. To keep options in their own constant, check it with satisfies FromPrismaOptions<typeof prismaModels>.

Top-level options

OptionMeaning
modelsper-model options, keyed by Prisma model name (below). A model you don't list syncs lazily, with no extra options
omitcolumns that never leave the server, per model. When clients create a row, omitted columns take their database defaults; a required omitted column without a default (User.passwordHash) means clients can read the model but not create it. A /// @clientdb.omit comment above a field in schema.prisma does the same
notSecretcolumns whose names look secret but are fine to send (see secret-looking columns)
serverOnlymodels that stay on the server: rules can read them, your backend writes them, clients get no API for them. They need no rules
excludemodels left out entirely. Relations into them are dropped, and their foreign keys stay plain fields
includeauth models to sync anyway. Session, Account, Verification and VerificationToken are excluded by default
viewerthe model whose rows are the signed-in users (default User); it types db.$viewer and $.viewer

Per-model options: models

OptionMeaning
load: "eager"every row of the model the user may read arrives when the client starts. Default "lazy": rows load when something reads them. See load modes
relationsoptions of the relations that hold a foreign key, by relation field name. The one option is eager: true, as on t.belongsTo; onDelete comes from schema.prisma
restricted: ["inviteCode"]fields only some viewers receive, each with its own field read rule
archivable: trueenables archive() and unarchive(). Needs nullable archivedAt DateTime? and archivedBy String? columns
id: { prefix: "todo" }ids created on devices are todo_<UUIDv7>. Needs a single String id column (not @db.Uuid)

The checks behind these options:

  • relations only takes the side that holds the key: Todo.project, not Project.todos. Putting options on the list side is a type error that names the right field.
  • onDelete is never an option: it is the relation's referential action in schema.prisma, so deleting a todo with Prisma Client and with clientdb removes the same rows. onDelete: Cascade on Comment.todo deletes a todo's comments on devices too, restores them on undo, and counts them as archived while their todo is, like onDelete: "cascade" in a TypeScript schema.
  • archivable: true on a model without both archive columns is a type error that names the missing ones, for example archivable needs archivedBy String? in schema.prisma.

An archivable model keeps its archive state in its own columns:

prisma/schema.prisma
model Project {
  id         String    @id @default(uuid(7))
  name       String
  archivedAt DateTime?
  archivedBy String?
  members    Member[]
  todos      Todo[]
}

project.archive() on a device sets both, and so does any write of your own (prisma.project.update({ data: { archivedAt: new Date() } })). Either way the project is hidden on every device. With retention.archived, the engine deletes projects archived longer than that; see Archive and delete.

Secret-looking columns

A column whose name contains token, secret, hash, password, salt or key must be listed in omit, in models.<Model>.restricted, or in notSecret; otherwise fromPrisma is a type error and a runtime error that name it. So an apiToken column added in a later migration can't reach browsers by accident:

TypeScript
notSecret: { Attachment: ["storageKey"] }, // an object storage path, fine to send

How Prisma maps

Prismaclientdb
model TeamMembermodel teamMember (camelCase, like Prisma Client)
String, String @db.Uuidt.string(), t.uuid()
Int, Float, BigIntt.number() (BigInt is exact up to 2^53)
Decimalt.decimal(): exact, sent and typed as a string such as "49.00"
DateTimet.timestamp(): milliseconds since 1970. A timestamp column without time zone is read as UTC, as Prisma writes it
Boolean, Jsont.boolean(), t.json()
enumst.enum([…])
String[] and other listsarrays (a json field)
?.nullable()
@unique.unique(): a lazy read by it (where({ email })) loads that row
@default(now()), literalsthe same default, applied on the device
@default(uuid()), uuid(7), cuid(), ulid(), nanoid()a UUIDv7 generated on the device
@default(autoincrement()), sequence(), dbgenerated(…).generated(): Postgres fills it in, clients never send it
@updatedAt.updatedAt(): set on create and on every update
@id on idthe model's id
@@id([a, b]), or @id on another fielda derived id: the key fields joined with |. Key fields can't be updated
a relation with fields: [projectId]a belongsTo relation; the back-relation (Project.todos) is its inverse
onDelete: Cascade, SetNull, other (Restrict, NoAction, SetDefault)"cascade", "setNull", "restrict"; without one, Prisma's defaults (SetNull for optional relations, Restrict for required ones)

Give every foreign key of a lazy model an index (@@index([todoId])): lazy reads load by foreign key, and Postgres doesn't index them on its own.

clientdb's tables as Prisma models

clientdb keeps its bookkeeping (the sync log, row metadata, the triggers' queue) in a few tables. Add them to schema.prisma, so Prisma creates and migrates every table:

Terminal
npx clientdb-prisma models >> prisma/schema.prisma   # or a separate file in a multi-file schema
npx prisma migrate dev --name clientdb

The engine runs no DDL, and prisma migrate diff reports no drift after it has run.

When you upgrade clientdb, replace that block with the current npx clientdb-prisma models and run prisma migrate dev: newer versions add columns (such as clientdb_row.field_readers and clientdb_log.created_at). Until then, clientdb migrate stops with an error that names the missing column.

Writes your app makes with Prisma

The engine writes clients' changes straight into your tables. Writes your own code makes, with Prisma Client, raw SQL, scripts or other services, are picked up by Postgres triggers, which ship as a Prisma migration:

Terminal
npx clientdb-prisma triggers src/sync/schema.ts > prisma/migrations/20261202_clientdb_triggers/migration.sql
npx prisma migrate dev

triggers <module> imports your schema module (--export name when the schema isn't exported as schema) and prints the triggers for every model it maps, serverOnly ones included, since rules read them. It also drops the triggers of tables that no longer sync. Run it again, into a new migration, when you add or remove a model.

Your write code then needs no clientdb calls:

src/app/projects/actions.ts
"use server";
import { prisma } from "@/lib/prisma";

export async function promote(memberId: string) {
  await prisma.member.update({ where: { id: memberId }, data: { role: "admin" } }); // syncs on its own
}

The triggers record each changed row in the same transaction as your write, and catch nested writes, createMany / updateMany / deleteMany, raw SQL and rows Postgres changed by cascade. See Writes from your server for the details, the safety net engine.reconcile(), and engine.changed() for apps that can't install triggers.

Deploying

Run clientdb migrate after Prisma's own migrations:

Terminal
npx prisma migrate deploy
npx clientdb migrate src/sync/engine.ts
  • The first run adopts every row that existed before clientdb (about 2 seconds for 20,000 rows). Later runs sync rows written outside clientdb that no trigger caught, such as seeds run before the triggers existed.
  • When a prisma migrate changed a model's fields, or your rules changed, it re-routes that model's rows to the right devices.
  • Until it has run for the current schema and rules, the sync routes answer 503 NotMigrated.

See Migrations.

Limits

  • One engine tenant on Prisma's tables: tenancy inside your app comes from your rules.
  • fromPrisma refuses, with an error that names the field: ids that aren't String, composite foreign keys, @map on enum values, Bytes and other unsupported types, and @default functions it doesn't know. Omit the field, or exclude the model.
  • BigInt values beyond 2^53 lose precision on clients.