Skip to content
clientdb

Search the docs

Find a page or section

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

Type-safe, secure backend and frontend library replacing all your data endpoints and client queries

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

Four files, database to UI

How it works

Describe your data, say who may see it, add one endpoint, and use it in your components.

  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.

    generator clientdb {
      provider = "clientdb-prisma"
      output   = "../src/generated/clientdb"
    }
    
    model User {
      id           String   @id @default(uuid())
      name         String
      passwordHash String
      memberships  Member[]
      todos        Todo[]
      comments     Comment[]
    }
    
    model Project {
      id      String   @id @default(uuid())
      name    String
      members Member[]
      todos   Todo[]
    }
    
    model Member {
      id        String  @id @default(uuid())
      role      Role    @default(member)
      user      User    @relation(fields: [userId], references: [id])
      userId    String
      project   Project @relation(fields: [projectId], references: [id])
      projectId String
    }
    
    enum Role {
      member
      admin
    }
    
    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
      comments  Comment[]
    }
    
    model Comment {
      id       String @id @default(uuid())
      body     String
      todo     Todo   @relation(fields: [todoId], references: [id], onDelete: Cascade)
      todoId   String
      author   User   @relation(fields: [authorId], references: [id])
      authorId String
    }
  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.

    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);
      },
    });
  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);
        if (!session) {
          return null;
        }
        return { viewer: session.userId };
      },
    });
  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.

    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) => {
            return (
              <li key={todo.id}>
                <input type="checkbox" checked={todo.done} onChange={() => { todo.update({ done: !todo.done }); }} />
                {todo.title}
              </li>
            );
          })}
        </ul>
      );
    });
generator clientdb {
  provider = "clientdb-prisma"
  output   = "../src/generated/clientdb"
}

model User {
  id           String   @id @default(uuid())
  name         String
  passwordHash String
  memberships  Member[]
  todos        Todo[]
  comments     Comment[]
}

model Project {
  id      String   @id @default(uuid())
  name    String
  members Member[]
  todos   Todo[]
}

model Member {
  id        String  @id @default(uuid())
  role      Role    @default(member)
  user      User    @relation(fields: [userId], references: [id])
  userId    String
  project   Project @relation(fields: [projectId], references: [id])
  projectId String
}

enum Role {
  member
  admin
}

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
  comments  Comment[]
}

model Comment {
  id       String @id @default(uuid())
  body     String
  todo     Todo   @relation(fields: [todoId], references: [id], onDelete: Cascade)
  todoId   String
  author   User   @relation(fields: [authorId], references: [id])
  authorId String
}
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/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);
    if (!session) {
      return null;
    }
    return { viewer: session.userId };
  },
});
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) => {
        return (
          <li key={todo.id}>
            <input type="checkbox" checked={todo.done} onChange={() => { todo.update({ done: !todo.done }); }} />
            {todo.title}
          </li>
        );
      })}
    </ul>
  );
});

Permissions

Everyone sees exactly what they're allowed to.

Each person's device only receives what your rules allow. When their access changes, the right items appear or disappear on their screen, with no reload.

The rule in this demo: private todos are only visible to their author and to admins.read: (todo, $) => $.anyOf({ shared: [todo.isPrivate.is(false), isMember(todo.project)], author: todo.authorId.is($.viewer.id), admin: isAdmin(todo.project) })
Admin

Project members

Maya
YouAdmin

Switch Maya’s role and watch her screen.

Maya’s screenMember
  • Plan the launch event
  • Order the team T-shirts
  • Send the invitations

Less code

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

Every endpoint normally repeats the same checks: who is this user, which project are they in, are they an admin. clientdb replaces all of that code with one set of permission rules, one small file per model.

No endpoint to forget

There is no endpoint where someone can forget a check. Every read and every write, from every device, goes through the same rules.

Fetched once, used by every screen

Normally two screens that show the same todos each call the server and each show a spinner. With clientdb the data is fetched once, and every screen queries it on the device, instantly.

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.

src/app/api/projects/[id]/todos/route.ts
import { requireUser } from "@/lib/auth";
import { prisma } from "@/lib/prisma";

export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
  const user = await requireUser(request);
  const { id } = await params;
  const member = await prisma.member.findFirst({ where: { projectId: id, userId: user.id } });
  if (!member) return new Response("Forbidden", { status: 403 });

  const todos = await prisma.todo.findMany({
    where: { projectId: id, ...(member.role === "admin" ? {} : { isPrivate: false }) },
    orderBy: { createdAt: "asc" },
  });
  return Response.json(todos);
}

Local data

All accessible data, preloaded at once.

This is why apps built with clientdb feel instant. Here's the idea in four steps.

  1. Load everything once

    When Maya opens the app, her device downloads every project and todo she may see, and saves them. 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. No loading states, no await.

  4. Too big? Load it in parts

    Some data is too much to send up front, like the comments on every todo. Leave the model lazy, and each todo's comments load the first time they're needed.

In code

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" },
    Member: { load: "eager" },
    Todo: { load: "eager" },
  },
});

Your logic

Extend models with your own methods.

Models are plain classes. Add the methods and getters your app needs; getters stay reactive like any field, and relations return your classes everywhere.

import { Model } from "@clientdb/client";
import { schema } from "./schema";

export class Todo extends Model(schema, "todo") {
  toggle() {
    return this.update({ done: !this.done });
  }

  rename(title: string) {
    return this.update({ title: title.trim() });
  }
}

export class Project extends Model(schema, "project") {
  // Getters are reactive, like any field
  get openTodos() {
    return this.todos.where({ done: false });
  }

  get progress() {
    return this.todos.count ? 1 - this.openTodos.count / this.todos.count : 0;
  }
}

Your stack

Plugs into the libraries you already use.

Every field, relation and query is reactive: when data changes, whatever reads it updates. Use the built-in React hooks, or plug in MobX and keep writing the stores and computed values you know.

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

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

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

You own your data

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

clientdb is a library, not a platform. All your data lives in normal tables in your own Postgres database, and you keep your hosting.

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. No hosted backend to sign up for, 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.

A note on bookkeeping tables. clientdb adds a few tables of its own to your database. They record what each device has already received and power realtime updates. It also adds small triggers to your synced tables that note which rows changed. Only the sync engine reads and writes its tables; your own tables, rows and columns are never changed.

Live updates

Realtime: every change shows up on every screen.

When someone changes something, everyone who can see it gets the change, without refreshing. Nothing to build: it's how clientdb syncs.

Try it: this is the real clientdb client running in your browser. Check a task on one device and watch the other.

Your laptopAll changes synced
  • Design the onboarding flow
  • Write the launch post
  • Invite the beta testers
Teammate's phoneAll changes synced
  • Design the onboarding flow
  • Write the launch post
  • Invite the beta testers
Network between the devices and the server:
  • Pushed as it happens

    With realtime on, changes travel over a WebSocket. A saved change reaches other open apps in about 2 ms, plus network time.

  • Or no sockets at all

    On serverless hosts like Vercel, apps sync over plain HTTP: on load, when the tab gets focus, and after each change.

  • Catches up on its own

    After a lost connection or a closed laptop, the app fetches only what it missed, then carries on.

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
});

Performance

It's really fast.

Lists, filters, sorting and search run in the browser, on data that's already there, so they don't wait for the network. Try it below on 100,000 issues.

~1 msfor the server to check and save a change
~2 msuntil a teammate's open app shows it
0.15 sto load 25,000 rows on a fresh device
177 bytesof memory per row in the browser

Generating 100,000 issues in your browser…

Server numbers are measured on one machine with local Postgres, so they exclude network time. Full benchmarks

Every platform

Multi-platform: web, iPhone, Mac and more.

Build your web app and your native apps on the same data. Each one keeps its own copy on the device, so all of them are instant and work offline, and a change in one shows up in the others.

src/app/TodoRow.tsx
// React in the browser. Data is kept in IndexedDB.
import { live, useLive } from "@clientdb/react";
import type { Todo } from "@/sync/db";

// With live()
export const TodoRow = live(({ todo }: { todo: Todo }) => {
  return (
    <label>
      <input type="checkbox" checked={todo.done} onChange={() => { todo.update({ done: !todo.done }); }} />
      {todo.title}
    </label>
  );
});

// Or with the useLive() hook
export function TodoRowWithHook({ todo }: { todo: Todo }) {
  const { done, title } = useLive(() => {
    return { done: todo.done, title: todo.title };
  });
  return (
    <label>
      <input type="checkbox" checked={done} onChange={() => { todo.update({ done: !done }); }} />
      {title}
    </label>
  );
}

No connection needed

Offline first, with nothing to build.

Your app reads and writes data on the device, so losing the network changes nothing for the user. Changes wait on the device and are sent when the connection is back.

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.

Your edits stay on top

Teammates' changes keep arriving while yours wait to be sent. Yours are re-applied on top, so the screen never jumps back.

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. Close it, and another takes over without losing anything.

Questions

Frequently asked questions

Can I directly update data in my database?
Yes. Your tables stay normal Postgres tables. clientdb installs small Postgres triggers that note which rows changed, so a write from a SQL console, a script, another service or your own server code reaches devices on its own, with no extra code. engine.reconcile() is there as a safety net. Writes made outside clientdb
Can a device ever see data it shouldn't, even for a moment?
No. The server never sends a row to someone whose permissions don’t allow it. When access is removed, the device gets only the ids of the rows to delete, never their content. This is checked by automated tests that compare every step against your rules.
What if someone loses access while they're offline?
When they reconnect, their device removes the rows they can no longer see. Any changes they made to those rows while offline are refused, removed from the screen, and reported to your app so you can tell them.
What happens when two people edit the same thing?
Edits to different fields never conflict. If both change the same field, the change saved last wins, and every device ends up showing the same value. Conflicts
What if a user has too much data to load up front?
Only models marked eager load up front. The others, like comments or an audit log, load per parent (a todo’s comments, an author’s comments), or all at once, the first time they’re needed, and stay up to date after that. Server queries search rows that aren’t on the device, and eviction caps how many stay in memory. Lazy loading
Can I still run logic only on my server?
Yes. Your existing routes and server actions keep working for things like aggregates, emails or payments, and their writes reach devices through the triggers. db.$action calls one and waits until its changes are on the device, optionally showing the outcome at once. Server logic
How do I change my schema later?
Change your Prisma schema and migrate as usual, then run clientdb migrate when you deploy. When you add or remove a synced model, generate the triggers migration again too. Devices running an older version of your app notice the change and reload, so nobody is ever on an outdated schema. Migrations
Can I hide one column, like an email or a password hash?
Yes. Columns listed in omit never leave your server. A column marked restricted reaches only the users its own read rule allows; everyone else gets the row without it. Restricted fields
Do I need WebSockets, or a separate server?
No. A single Next.js route handler syncs over plain HTTP, and works on Vercel with Neon. When you want instant updates, add the WebSocket server; both use the same data. HTTP and Next.js
Will my coding agent get it right?
That’s the goal. There’s one small client API and one set of permission rules instead of dozens of endpoints, everything is typed against your schema, and the docs ship as llms.txt.

Give your users an app that feels instant.

Start from the app you already have. The quick start takes an existing Next.js and Prisma project step by step.