Get started
Quick start: Next.js + Prisma
Add clientdb to the Next.js + Prisma app you already have. Everything runs inside your app; nothing else to host.
By the end of this page, your existing app's data will be available in the browser, instantly readable and writable, and kept in sync with Postgres. Nothing new to host: it all runs in a Next.js route handler, so it works on Vercel and Neon as is.
The examples come from a small todo app: users, projects, project members (with the role member or admin) and todos. Swap in your own models as you go.
Here's what you'll add, and why:
| Step | What | Why |
|---|---|---|
| 1 | A Prisma generator and a few bookkeeping tables | clientdb reads your models from schema.prisma and needs a place to track what it has synced |
| 2 | schema.ts | picks which models and columns go to browsers, and which load up front |
| 3 | a permissions/ folder, one file per model | says who may read and write what (this replaces your API checks) |
| 4 | the engine and a route handler | the one endpoint browsers talk to |
| 5 | a triggers migration | so changes your server makes with Prisma (or SQL) reach browsers too, without changing that code |
| 6 | a deploy step | lets clientdb pick up rows that existed before it |
| 7 | the client | reads and writes from React |
New to the idea? Read How it works, in 5 pictures first; it takes two minutes.
Tip
Install the packages first; see Installation.
1. Add the generator and clientdb's tables
Add the generator to prisma/schema.prisma:
generator clientdb {
provider = "clientdb-prisma"
output = "../src/generated/clientdb"
}Append the engine's own tables as Prisma models. Prisma then owns every table, and clientdb never runs DDL:
npx clientdb-prisma models >> prisma/schema.prisma # or a separate file in a multi-file schema
npx prisma migrate dev --name clientdb
npx prisma generate # writes src/generated/clientdb/index.tsThe generator fails with a clear message when the engine models are missing.
2. The schema, shared by server and browser
import { fromPrisma } from "@clientdb/prisma";
import { prismaModels } from "../generated/clientdb";
export const schema = fromPrisma(prismaModels, {
omit: { User: ["passwordHash"] }, // stays on the server
models: {
User: { load: "eager" },
Project: { load: "eager" },
Member: { load: "eager" },
Todo: { load: "eager" },
},
});
export type Schema = typeof schema;load: "eager": every row of the model this user may read arrives when the app starts, so reading it never waits. Use it for models that stay small per user.- Lazy, the default: the rest load when something reads them. Comments arrive per todo, the first time
todo.commentsis read. - Relations and
onDeletecome fromschema.prisma:Comment.todosaysonDelete: Cascadethere, so deleting a todo deletes its comments on every device too, and undo brings them back.
Everything is typed against your Prisma models: a misspelled field or relation is a compile error. schema also remembers which table and columns each model uses, so it's the only thing the rest of your code passes around. Auth models such as Session and Account never sync. A column whose name looks secret (token, secret, hash, password, salt, key) must be listed in omit (stays on the server) or notSecret (fine to send) before the schema builds, so a new apiToken column never reaches browsers by accident. See Prisma for the mapping.
3. Permissions, server only
Permissions live in one file per model. Each rule receives the row and $, the permission helpers: $.viewer.id is the signed-in user, and $.anyOf, $.and and the others combine conditions. Everything is typed against your schema.
Start with the project. Conditions you use in several models, such as "the viewer is a member of this project", are defined once with defineRule and imported where they're needed:
import { defineModelRules, defineRule } from "@clientdb/server";
import { schema } from "../schema";
export const isMember = defineRule(schema, "project", (project, $) => {
return project.members.some((member) => {
return member.userId.is($.viewer.id);
});
});
export const isAdmin = defineRule(
schema,
"project",
(project, $) => {
return project.members.some((member) => {
return $.and(member.userId.is($.viewer.id), member.role.is("admin"));
});
},
{ name: "project.admin" }, // optional: a stable, readable id for a widely shared condition
);
export const projectRules = defineModelRules(schema, "project", {
read: (project) => {
return isMember(project);
},
update: {
when: (project) => {
return isAdmin(project);
},
fields: ["name"],
},
});Then the todos:
import { defineModelRules } from "@clientdb/server";
import { schema } from "../schema";
import { isAdmin, isMember } from "./project";
export const todoRules = defineModelRules(schema, "todo", {
read: (todo, $) => {
return $.anyOf({
shared: [todo.isPrivate.is(false), isMember(todo.project)],
author: todo.authorId.is($.viewer.id),
admin: isAdmin(todo.project),
});
},
create: {
when: (todo) => {
return isMember(todo.project);
},
enforce: ($) => ({ authorId: $.viewer.id }),
},
update: {
when: (todo) => {
return isMember(todo.project);
},
fields: ["title", "done"],
},
delete: {
when: (todo, $) => {
return $.anyOf({
author: todo.authorId.is($.viewer.id),
admin: isAdmin(todo.project),
});
},
},
});$.anyOf passes when any one of its branches does. Each key is a short label for a branch, and an array means every condition in it must hold. The labels show up in errors, for example Forbidden: todo.delete (author: no, admin: no). enforce lists fields that must equal a value. Here every todo this user creates must have their own id as authorId, so nobody can create a todo in someone else's name. The browser sends authorId: db.$session.viewerId itself; a write with any other value is rejected with Forbidden: todo.authorId must equal the viewer's id. Rules only check, they never change data.
import { defineModelRules } from "@clientdb/server";
import { schema } from "../schema";
import { isAdmin, isMember } from "./project";
export const memberRules = defineModelRules(schema, "member", {
read: (member) => {
return isMember(member.project);
},
update: {
when: (member) => {
return isAdmin(member.project);
},
fields: ["role"], // promotion and demotion sync automatically
},
delete: {
when: (member, $) => {
return $.anyOf({
admin: isAdmin(member.project),
leaving: member.userId.is($.viewer.id),
});
},
},
});Comments are readable whenever their todo is, so their read rule says exactly that:
import { defineModelRules } from "@clientdb/server";
import { schema } from "../schema";
export const commentRules = defineModelRules(schema, "comment", {
read: (comment, $) => {
return $.canRead(comment.todo);
},
create: {
when: (comment, $) => {
return $.canRead(comment.todo);
},
enforce: ($) => ({ authorId: $.viewer.id }),
},
});$.canRead(comment.todo) holds when the viewer may read the comment's todo under the todo rule above. When a todo becomes private, its comments leave the devices that lose it, re-tagged in bulk.
import { defineModelRules } from "@clientdb/server";
import { schema } from "../schema";
import { isMember } from "./project";
export const userRules = defineModelRules(schema, "user", {
read: (user, $) => {
return $.anyOf({
self: user.id.is($.viewer.id),
teammate: user.memberships.some((membership) => {
return isMember(membership.project);
}),
});
},
});Finally, combine the files with definePermissions:
import { definePermissions } from "@clientdb/server";
import { schema } from "../schema";
import { commentRules } from "./comment";
import { memberRules } from "./member";
import { projectRules } from "./project";
import { todoRules } from "./todo";
import { userRules } from "./user";
export const permissions = definePermissions(schema, [userRules, projectRules, memberRules, todoRules, commentRules]);In development a model without a read rule is an error that names it; list models that should never reach devices in fromPrisma's serverOnly (or exclude). A missing write rule refuses that operation, and defining the same model in two files is an error. See Permissions.
4. The engine and the route handler
import { createEngine } from "@clientdb/server";
import { permissions } from "./permissions";
export const engine = createEngine({ permissions });import { clientdbHandler } from "@clientdb/server/next";
import { auth } from "@/lib/auth"; // e.g. Better Auth
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: the request is refused with 401
}
return { viewer: session.user.id }; // the id of the signed-in user's `User` row
},
});session(request) is the only place clientdb learns who is signed in: the browser never says who it is, your server does. It's called on every request, so signing out takes effect at once. It can also return readOnly: true for a user who may read but not write, and claims such as "staff" (see Permission recipes). Same-origin requests carry the session cookie.
The handler serves every endpoint the client uses: …/bootstrap (the first load), …/pull and …/push (sync), …/partial (lazy loads) and …/query (server queries).
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.
5. Install the change triggers
Your app keeps writing with Prisma in tRPC routers, server actions and webhooks. For browsers to see those changes, clientdb ships Postgres triggers that note which rows changed. They come as a regular Prisma migration:
npx clientdb-prisma triggers src/sync/schema.ts > prisma/migrations/20261202_clientdb_triggers/migration.sql
npx prisma migrate devtriggers reads your schema module and covers every model it syncs. After that, your write code needs no clientdb calls at all:
"use server";
import { prisma } from "@/lib/prisma";
export async function addTodo(projectId: string, authorId: string, title: string) {
await prisma.todo.create({ data: { projectId, authorId, title } }); // nothing else to add
}The triggers catch nested writes, createMany / updateMany / deleteMany, raw SQL, other services and rows removed by ON DELETE CASCADE. They are part of the same transaction as the write, so nothing is lost if it rolls back. The engine picks the changes up on the next pull or push. Run the command again, into a new migration, when you add or remove a synced model.
Other browsers see the change on their next sync: on focus, every 30 seconds while the tab is visible, or at once with live updates. The tab that called the action can wait for it with db.$action, which runs the function and then syncs:
"use client";
import { addTodo } from "./actions";
import { db } from "@/sync/db";
export function AddTodo({ projectId, userId }: { projectId: string; userId: string }) {
return (
<button
onClick={() => {
db.$action(() => {
return addTodo(projectId, userId, "New todo");
});
}}
>
Add
</button>
);
}As a safety net, await engine.reconcile() compares your tables with what clientdb last synced and sends any differences. engine.migrate() runs it too (next step), and you can also run it from a cron job. See Writes from your server.
6. Adopt existing rows, once per deploy
# after `prisma migrate deploy`, e.g. in your release step
npx clientdb migrate src/sync/engine.tsIt runs engine.migrate() on your engine, prints what it did and exits. Until it has run for the current schema and rules, the route handler refuses to serve (503 NotMigrated) and logs why.
Watch out
Migrations take a session-level advisory lock, so they need a direct (non-pooled) connection: set DIRECT_URL when DATABASE_URL goes through a pooler (a pooler URL is refused).
The first run adopts every row that existed before clientdb. Every later run also reconciles your tables with clientdb's copies, so anything written before the triggers were installed is picked up. See Untracked rows.
7. The client
"use client";
import { createDatabaseClient, indexedDb, type EntitiesOf } from "@clientdb/client";
import { schema, type Schema } from "./schema";
export const db = createDatabaseClient({
schema,
storage: indexedDb(), // keeps data and unsent changes on the device; tabs share one connection
});
/** Every model's entity type, by name: `DB["Todo"]`, `DB["Project"]`. */
export type DB = EntitiesOf<Schema>;
export type Todo = DB["Todo"];
export type Project = DB["Project"];That's all the configuration. The client syncs with /api/sync over plain HTTP: on load, when the window regains focus, after writes and on an interval. Creating it at module level is safe: it does nothing until it's first used in the browser. The local data is kept per signed-in user automatically.
Wrap your app in DatabaseProvider. With ready, it shows the fallback until the eager models are loaded, from IndexedDB or the network:
"use client";
import { DatabaseProvider } from "@clientdb/react";
import { Spinner } from "@/components/spinner";
import { db } from "@/sync/db";
export function Providers({ children }: { children: React.ReactNode }) {
return (
<DatabaseProvider db={db} ready fallback={<Spinner />}>
{children}
</DatabaseProvider>
);
}Then read models straight from db in any component:
"use client";
import { live, useLive } from "@clientdb/react";
import { db, type Todo } from "@/sync/db";
// live() tracks every field and relation read while rendering: the checkbox and author stay current.
const TodoRow = live(({ todo }: { todo: Todo }) => {
return (
<li>
<input
type="checkbox"
checked={todo.done}
onChange={() => {
todo.update({ done: !todo.done });
}}
/>
{todo.title} · {todo.author.name}
</li>
);
});
export function Todos({ projectId }: { projectId: string }) {
const todos = useLive(() => {
return db.todo.where({ projectId }).orderBy("createdAt", "desc").limit(50).all;
});
return (
<ul>
{todos.map((todo) => {
return <TodoRow key={todo.id} todo={todo} />;
})}
</ul>
);
}useLive tracks only what its function reads: here, which todos are in the list. Reading todo.done or todo.author.name in Todos itself would not be tracked, and the row would keep showing its first value. Read per-row data inside a live() component, or inside useLive. In development, such untracked reads during render log a warning. See Reactivity.
// writes: on screen at once, then confirmed by the server
await todo.update({ title: "Ship it" }).confirmed;Comments aren't eager, so the first read of todo.comments loads that todo's comments. Until they arrive, todo.comments.status is "loading"; see Reading data.
On sign-out, call await db.$clear() to delete the local data and unsent changes, so the next person on a shared computer doesn't see them.
What you have now
- When someone opens your app, their browser downloads the data they may see and saves it. The next visit starts from that copy, even offline, and fetches only what changed.
- Reads come from that copy, so your components render immediately.
- Writes show up at once and are checked against your permissions on your server before they're saved.
- Changes your server makes with Prisma or SQL reach browsers too, with no extra code, thanks to the triggers.
- When someone's access changes (promoted, removed from a project), the right data appears on or disappears from their devices.
Check it works: the two-browser test
- Sign in as one user in your normal browser and as a teammate in a private window.
- Open the same project in both.
- Rename a todo in one window. It changes there immediately, and in the other window on its next sync (switch to it: syncing on focus is on by default), or within milliseconds with live updates.
- Remove the teammate from the project in your database (Prisma Studio, psql or your admin UI). Their window loses the project's data on its next sync.
Next: write the rules for the rest of your models with the permission recipes, or learn how React components stay up to date.