Skip to content
المشاريع

حول

End-to-end database setup for apps you and your agent will love.

البيانات والتحليلات

كيف تُقاس هذه الأرقام

النمو المقاس للنجوم

خلال 24 ساعة
٠
خلال 7 أيام
+١
خلال 15 يومًا
+١
خلال شهر
جارٍ جمع السجل

تغيّر صافي النجوم خلال فترات متداخلة، وليس مجموعًا يوميًا. تبقى القياسات المفقودة فارغة. النجوم تقيس الاهتمام لا جودة البرمجيات.

README.md

الأصل

clientdb

End-to-end database setup for apps you and your agent will love.

A type-safe, secure backend and frontend library that replaces all your data endpoints and client queries.

Offline first · Optimistic updates · Realtime ready · No vendor lock-in · Works with any Node.js server · Undo built in

Documentation · Quick start · How it works


How it works

The examples on this page come from one small todo app: users, projects, project members (with the role member or admin) and todos, some of them private.

1. Data schema

Start from the Prisma schema you already have, or write one in TypeScript. It types everything that follows: queries, permissions and components.

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

model Todo {
  id        String   @id @default(uuid())
  title     String
  done      Boolean  @default(false)
  isPrivate Boolean  @default(false)
  createdAt DateTime @default(now())
  project   Project  @relation(fields: [projectId], references: [id])
  projectId String
  author    User     @relation(fields: [authorId], references: [id])
  authorId  String
}

// …and User, Project and Member, as you already have them
// src/sync/schema.ts
import { fromPrisma } from "@clientdb/prisma";
import { prismaModels } from "@/generated/clientdb"; // written by the generator above

// Auth models (Session, Account, …) never sync. Columns that look secret need a decision:
export const schema = fromPrisma(prismaModels, {
  omit: { User: ["passwordHash"] }, // stays on the server
});
export type Schema = typeof schema;

2. Permissions

A small rules file per model says who can see and change what. The rules run on your server, and each user's device only ever receives the rows they allow. Every rule gets the row and $, the permission helpers, with $.viewer as the signed-in user.

// src/sync/permissions/project.ts
import { defineModelRules, defineRule } from "@clientdb/server";
import { schema } from "../schema";

// Typed conditions, reused by the rules of other models. $.viewer is the signed-in user.
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"));
  });
});

export const projectRules = defineModelRules(schema, "project", {
  read: (project) => {
    return isMember(project);
  },
});
// src/sync/permissions/todo.ts
import { defineModelRules } from "@clientdb/server";
import { schema } from "../schema";
import { isAdmin, isMember } from "./project";

export const todoRules = defineModelRules(schema, "todo", {
  read: (todo, $) => {
    // Members see todos that aren't private; a private todo is seen by its author and by admins
    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 }), // must equal the signed-in user, or the write is rejected
  },
  update: {
    when: (todo) => {
      return isMember(todo.project);
    },
    fields: ["title", "done"],
  },
});

Some columns only some viewers may read, such as a project's billingEmail. Mark them restricted (fromPrisma(prismaModels, { models: { Project: { restricted: ["billingEmail"] } } }), or .restricted() on a hand-written field) and give them a field rule: the row reaches every member, the field only admins, and everyone else gets undefined:

export const projectRules = defineModelRules(schema, "project", {
  read: {
    when: (project) => {
      return isMember(project);
    },
    fields: {
      billingEmail: (project) => {
        return isAdmin(project);
      },
    },
  },
});

A comment is readable whenever its todo is. $.canRead reuses the todo's read rule, and when a todo turns private its comments leave the same devices:

// src/sync/permissions/comment.ts
export const commentRules = defineModelRules(schema, "comment", {
  read: (comment, $) => {
    return $.canRead(comment.todo);
  },
});
// src/sync/permissions/index.ts
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";

// A model without a read rule is an error in development; mark models devices never see `serverOnly` in the schema
export const permissions = definePermissions(schema, [userRules, projectRules, memberRules, todoRules, commentRules]);

3. Server endpoint

A single route serves every read and write, for every model. It runs inside your Next.js app or any Node.js server, on the Postgres you already use.

// src/app/api/sync/[...path]/route.ts
import { createEngine } from "@clientdb/server";
import { clientdbHandler } from "@clientdb/server/next";
import { getSession } from "@/lib/auth"; // your auth, e.g. Better Auth
import { permissions } from "@/sync/permissions";

const engine = createEngine({ permissions });

export const { GET, POST } = clientdbHandler(engine, {
  // Who is asking: the signed-in user, or null
  session: async (request) => {
    const session = await getSession(request);
    return session ? { viewer: session.userId } : null;
  },
});

4. Client

The data is already on the device, so reading it is a plain function call: no fetching and no loading state. A change shows immediately and is saved in the background.

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

// Talks to /api/sync, the endpoint from step 3. Who the user is comes from the server.
export const db = createDatabaseClient({
  schema,
  storage: indexedDb(), // keeps the data on the device
});

export type DB = EntitiesOf<Schema>;
export type Todo = DB["Todo"];
export type Project = DB["Project"];
// src/app/Todos.tsx
import { live } from "@clientdb/react";
import { db } from "@/sync/db";

// live() re-renders the component when anything it read changes
export const Todos = live(({ projectId }: { projectId: string }) => {
  const todos = db.todo.where({ projectId }).orderBy("createdAt").all;
  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>
          <input type="checkbox" checked={todo.done} onChange={() => todo.update({ done: !todo.done })} />
          {todo.title}
        </li>
      ))}
    </ul>
  );
});

The quick start walks through the same steps in an existing Next.js + Prisma app, including the one-time setup: clientdb's bookkeeping tables, the triggers that pick up writes your server makes with Prisma, and the deploy step.


Remove all your endpoints

Normally, every endpoint checks permissions on its own, and every screen fetches, waits and refetches. With clientdb, permissions are defined once, and screens read data that's already on the device.

  • One set of rules instead of many endpoints. The checks every endpoint repeats (who is this user, which project are they in, are they an admin) become one small rules file per model.
  • No endpoint to forget. Every read and every write, from every device, goes through the same rules.
  • Fetched once, used by every screen. Two screens showing the same todos don't each call the server and show a spinner: the data is fetched once, and every screen queries it on the device.
  • Feels like raw data, secure by design. Your code reads and changes data like plain objects, yet a device only ever holds the rows its user may see, and the server checks every change.

Changes your server makes elsewhere, in server actions, webhooks or scripts, keep using Prisma as before. Postgres triggers pick them up and send them to every device that may see them.

All accessible data, preloaded at once

This is why apps built with clientdb feel instant.

  1. Load everything once. When Maya opens the app, her device downloads every row she may see and saves it. Next time it starts from that copy, and only fetches what changed.
  2. It usually fits. A team's tasks, a company's customers, a project's issues: thousands of rows, not billions. Even 100,000 rows take only about 17 MB in the browser.
  3. Then everything is instant. Reading data is a plain function call, and a change shows on screen in the same frame.
  4. Too big? Load it in parts. Some data is too much to send up front, like the comments on every todo. Leave that model lazy (the default) and only list the rest as eager: each todo's comments load the first time they're needed.
// src/sync/schema.ts
import { fromPrisma } from "@clientdb/prisma";
import { prismaModels } from "@/generated/clientdb";

export const schema = fromPrisma(prismaModels, {
  omit: { User: ["passwordHash"] },
  models: {
    User: { load: "eager" },
    Project: { load: "eager" },
    Todo: { load: "eager" },
    // Comment stays lazy. Its relation says onDelete: Cascade in schema.prisma, so a todo's comments are deleted with it.
  },
});
// src/app/actions.ts
import { db } from "@/sync/db";

const todo = db.todo.get(todoId)!;        // an object, not a promise
todo.update({ done: true });              // on screen now, saved in the background
todo.project.todos.where({ done: false }).count; // already counts the change

db.$transaction(() => {                   // several changes, saved together
  db.todo.create({ projectId: todo.projectId, authorId: db.$session.viewerId!, title: "Write release notes" });
  todo.update({ title: "Ship v2" });
});

db.$undo();                               // undo is built in

Offline first, with nothing to build

Your app reads and writes data on the device, so losing the network changes nothing for the user.

  • Opens instantly, even offline. Data is saved on the device (IndexedDB in browsers, SQLite on iPhone and Mac), so the app starts from it before any request.
  • Changes wait in a queue. Each change is saved on the device right away, so it survives closing the tab. When the connection is back, the queue is sent in order, and the server applies each change exactly once.
  • Conflicts resolve per field. Two people editing different fields of the same todo never conflict. If both change the same field, the last one saved wins, and every device ends up with the same result.
  • Refused changes roll back. If the server refuses a change, for example because the user lost access while offline, it disappears from the screen and you get a callback to tell the user.
  • Tabs share one connection. With several tabs open, one syncs for all of them.

Realtime: every change shows up on every screen

When someone changes something, everyone who can see it gets the change, without refreshing.

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

export const db = createDatabaseClient({
  schema,
  storage: indexedDb(),
  live: true, // push over a WebSocket; without it, syncs on load, on focus and after writes
});

On serverless hosts like Vercel, apps sync over plain HTTP instead: on load, when the tab gets focus, and after each change. After a lost connection, the app fetches only what it missed.

Web, iPhone and Mac

Build your web app and your native apps on the same data. Each keeps its own copy on the device, so all of them are instant and work offline. The Swift client generates typed models from your schema and keeps data in SQLite; see swift/README.md.

// TodosView.swift
import ClientDB
import SwiftUI

struct TodosView: View {
  @Live(.sorted(by: \.createdAt)) var todos: [Todo]

  var body: some View {
    List(todos) { todo in
      Toggle(todo.title, isOn: Binding(
        get: { todo.done },
        set: { done in try? todo.update { $0.done = done } }
      ))
    }
  }
}

To add it to an app in Xcode: File → Add Package Dependencies…, paste https://github.com/pie6k/clientdb, pick version 0.6.0 or later, and add the ClientDB and ClientDBSQLite products. Put your clientdb.schema.json in the target and enable ClientDBPlugin under Build Phases → Run Build Tool Plug-ins; Xcode asks once to trust the plugin (on CI, pass -skipPackagePluginValidation to xcodebuild). Details in swift/README.md.

Plugs into the libraries you already use

Every field, relation and query is reactive: when data changes, whatever reads it updates. Use the React hooks from @clientdb/react, plug in MobX with @clientdb/mobx, or use computed() and effect() without any UI library.

// src/app/Progress.tsx
import { useLive } from "@clientdb/react";
import type { Project } from "@/sync/db";

// useLive() re-renders the component when the returned value changes
export function Progress({ project }: { project: Project }) {
  const done = useLive(() => project.todos.where({ done: true }).count);
  const total = useLive(() => project.todos.count);
  return <progress value={done} max={total} />;
}

Models are plain classes too: extend them with your own methods and getters (class Todo extends Model(schema, "todo")), and relations return your classes everywhere.

No vendor lock-in: it's just your Postgres

clientdb is a library, not a platform.

  • Your tables, your schema. Data stays in your Postgres tables, shaped by your Prisma schema. clientdb doesn't copy it anywhere else and never changes your tables.
  • No extra service. It runs inside your Next.js app or Node.js server. No hosted backend, no separate sync server, no database extensions.
  • Any Postgres. Neon, Supabase, RDS, or Postgres on your laptop. It works on serverless hosts like Vercel without a background process.
  • Easy to leave. Remove the route, the triggers and the small bookkeeping tables clientdb adds, and your app's data is exactly where it always was.

It's really fast

Lists, filters, sorting and search run on the device, on data that's already there.

~1 ms for the server to check and save a change
~2 ms until a teammate's open app shows it
0.15 s to load 25,000 rows on a fresh device
177 bytes of memory per row in the browser

Measured on one machine with local Postgres, so network time is excluded. Details in bench/RESULTS.md.


Packages

Package What it is
@clientdb/server Permission rules, the sync engine and the endpoint (Next.js, fetch or Node.js), migrations
@clientdb/client The database on the device: live queries, optimistic writes, undo, offline storage, sync
@clientdb/react live(), useLive() and DatabaseProvider for React
@clientdb/mobx Makes every entity and query MobX-observable
@clientdb/prisma Builds the schema from your Prisma models; the generator and triggers
@clientdb/schema Models, fields and relations in TypeScript, shared by server and clients
@clientdb/core The platform-neutral sync core and protocol types that the clients build on
Swift ClientDB for iPhone and Mac: generated models, SwiftUI, SQLite

Install them from npm, for example npm install @clientdb/schema @clientdb/client @clientdb/server @clientdb/prisma @clientdb/react; Installation has the details. Requirements: Node 22+, Postgres 14+, TypeScript 5.5+, and Prisma 7 for the Prisma integration.

Working on clientdb

corepack enable                            # once; uses the Yarn version pinned in package.json
yarn install
yarn workspace @clientdb/prisma generate   # Prisma fixture client (needed by typecheck and Prisma tests)
yarn typecheck
yarn test                                  # server and Prisma tests need CLIENTDB_TEST_PG=postgres://… (skipped when unset)
yarn spec:generate                         # regenerate spec/schemas and spec/vectors (CI checks they are current)
yarn bench                                 # client benchmarks; bench:server and bench:prisma need Postgres
yarn web dev                               # the website and docs (web/), on http://localhost:3000
  • spec/: the protocol and replica semantics every client implements, with conformance vectors (spec/README.md).
  • swift/: the Swift client; swift test, and swift/E2E/run.sh against the real server.
  • web/: the website and documentation. The docs are MDX files in web/content/docs/.
  • packages/fixtures: test schemas shared by the test suites.

License

The client side is Apache-2.0: @clientdb/client, @clientdb/react, @clientdb/mobx, @clientdb/schema, @clientdb/core and the Swift package. The server engine, @clientdb/server and @clientdb/prisma with their commands, is FSL-1.1-ALv2: you can run it as the backend of your own apps, commercial or not, but not offer it to others as a competing product, and each version becomes Apache-2.0 two years after its release. Details in LICENSE.md.

استكشف مشاريع مشابهة ومرتبطة

جارٍ التحميل…