Skip to content
clientdb

Search the docs

Find a page or section

Guides

Permission recipes

Copy-paste read and write rules for the common shapes: team membership, roles, owner-only, inherited access, public and signed-in data, staff claims, restricted fields and deny lists.

Each recipe is a defineModelRules(schema, "model", { … }) call that lives in that model's file and is combined with the others by definePermissions(schema, [...]) (see Permissions). Read rules describe access through who the user is related to (see why some read rules are rejected); write rules can check anything.

The recipes share one app: teams with members, projects and issues. The conditions they reuse live in the team's file:

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

export const isMember = defineRule(
  schema,
  "team",
  (team, $) => {
    return team.members.some((member) => {
      return member.userId.is($.viewer.id);
    });
  },
  { name: "team.member" },
);

export const isAdmin = defineRule(
  schema,
  "team",
  (team, $) => {
    return team.members.some((member) => {
      return $.and(member.userId.is($.viewer.id), member.role.in(["owner", "admin"]));
    });
  },
  { name: "team.admin" },
);

Team membership

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

export const projectRules = defineModelRules(schema, "project", {
  read: (project) => {
    return isMember(project.team);
  },
  create: {
    when: (project) => {
      return isMember(project.team);
    },
  },
  update: {
    when: (project) => {
      return isMember(project.team);
    },
    fields: ["name"],
  },
});

Adding someone to a team (a new teamMember row) sends them the team's data; removing them takes it off their devices.

Roles, and fields only some roles may change

src/sync/permissions/issue.ts
import { defineModelRules } from "@clientdb/server";
import { schema } from "../schema";
import { isAdmin, isMember } from "./team";

export const issueRules = defineModelRules(schema, "issue", {
  read: (issue, $) => {
    return $.anyOf({
      visible: [issue.hidden.is(false), isMember(issue.team)],
      hidden: [issue.hidden, isAdmin(issue.team)],
    });
  },
  update: [
    {
      fields: ["title", "done"],
      when: (issue) => {
        return isMember(issue.team);
      },
    },
    {
      fields: ["hidden"],
      when: (issue) => {
        return isAdmin(issue.team);
      },
    },
  ],
});

update takes field groups, each with its own condition. An update passes when every field it changes belongs to a group whose when holds, before and after the change: a member may rename an issue, only an admin may hide it, and a member's update that touches hidden is refused as a whole.

When someone is promoted or demoted, admin-only rows appear on or disappear from their devices automatically. Use in([...]) for several roles inside one rule function, not $.or of two is.

Owner only

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

export const draftRules = defineModelRules(schema, "draft", {
  read: (draft, $) => {
    return draft.authorId.is($.viewer.id);
  },
  create: {
    when: (_draft, $) => {
      return $.authenticated;
    },
    enforce: ($) => ({ authorId: $.viewer.id }),
  },
  update: {
    when: (draft, $) => {
      return draft.authorId.is($.viewer.id);
    },
    fields: ["body"],
  },
  delete: {
    when: (draft, $) => {
      return draft.authorId.is($.viewer.id);
    },
  },
});

export const notificationRules = defineModelRules(schema, "notification", {
  read: (notification, $) => {
    return notification.userId.is($.viewer.id);
  },
});

enforce means "must equal": the client creates drafts with authorId: db.$session.viewerId, and a draft created with anyone else's id is rejected with Forbidden: draft.authorId must equal the viewer's id (got …). authorId isn't in any update group, so nobody can hand a draft to someone else either.

Children inherit their parent's access

A child that is readable whenever its parent is says so with $.canRead, whether or not it cascades from that parent. Nothing is readable implicitly, so every synced child has a read rule:

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

export const commentRules = defineModelRules(schema, "comment", {
  read: (comment, $) => {
    return $.canRead(comment.issue);
  },
  create: {
    when: (comment, $) => {
      return $.canRead(comment.issue);
    },
    enforce: ($) => ({ authorId: $.viewer.id }),
  },
});

// attachments are never written by clients: a read rule is all they need
export const attachmentRules = defineModelRules(schema, "attachment", {
  read: (attachment, $) => {
    return $.canRead(attachment.comment);
  },
});

When the parent is hidden or moved, its children follow it, re-tagged in bulk. Use $.canRead(comment.issue, { except: ["hidden"] }) to reuse a rule without some labeled branches (here, the admins-only branch of the issue rule); such a rule is routed row by row instead of re-tagged in bulk.

Users who share a team

src/sync/permissions/user.ts
import { defineModelRules } from "@clientdb/server";
import { schema } from "../schema";
import { isMember } from "./team";

export const userRules = defineModelRules(schema, "user", {
  read: (user, $) => {
    return $.anyOf({
      self: user.id.is($.viewer.id),
      teammate: user.memberships.some((membership) => {
        return isMember(membership.team);
      }),
    });
  },
});

Every signed-in user

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

export const announcementRules = defineModelRules(schema, "announcement", {
  read: (announcement, $) => {
    return $.and($.authenticated, announcement.draft.is(false));
  },
});

A branch with no viewer condition, like announcement.draft.is(false) alone, is a compile error; $.authenticated makes the intent explicit.

Public, including anonymous visitors

src/sync/permissions/post.ts
import { defineModelRules } from "@clientdb/server";
import { schema } from "../schema";
import { isMember } from "./team";

export const postRules = defineModelRules(schema, "post", {
  read: (post, $) => {
    return $.anyOf({
      published: [post.published, $.public],
      team: isMember(post.team),
    });
  },
});

Anonymous sessions (your session(request) callback returns null and the handler sets anonymous: true) are read-only and see only $.public rows.

Staff and other facts about the session

Some access depends on the login, not on rows: an active staff session, a verified email, a paid plan your auth provider knows about. Declare each such fact once as a claim, in a file both server and client import:

src/sync/claims.ts
import { declareClaim } from "@clientdb/schema";

export const $staff = declareClaim("staff");

Your session() callback grants it, per request:

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

export const { GET, POST } = clientdbHandler(engine, {
  session: async (request) => {
    const session = await getSession(request);
    if (!session) {
      return null;
    }
    return { viewer: session.userId, claims: [$staff(session.isStaff)] };
  },
});

Rules use it like any other condition:

src/sync/permissions/ticket.ts
import { defineModelRules } from "@clientdb/server";
import { $staff } from "../claims";
import { schema } from "../schema";
import { isMember } from "./team";

export const ticketRules = defineModelRules(schema, "ticket", {
  read: (ticket, $) => {
    return $.anyOf({
      team: isMember(ticket.team),
      staff: $staff,
    });
  },
});

On the client, db.$session.hasClaim($staff) tells the UI whether to show the staff tools. A claim can't be negated or combined with viewer conditions in one branch; give it its own branch, as above. When a session loses a claim, the rows it granted leave the device on the next sync.

A fact that is a column of the user's own row works too: $.viewer.row.role.in(["support"]) compares the viewer's row with fixed values, and changing the column updates what they see.

Fields only some users may see

Mark the field .restricted() in the schema (or list it under restricted in fromPrisma). The model's read rule then becomes { when, fields }: everyone when allows receives the row, and each restricted field reaches only the people its own rule allows. Others get the row without it.

src/sync/permissions/user.ts
import { defineModelRules } from "@clientdb/server";
import { $staff } from "../claims";
import { schema } from "../schema";
import { isMember } from "./team";

// in the schema: email: t.string().unique().restricted()
export const userRules = defineModelRules(schema, "user", {
  read: {
    when: (user, $) => {
      return $.anyOf({
        self: user.id.is($.viewer.id),
        teammate: user.memberships.some((membership) => {
          return isMember(membership.team);
        }),
      });
    },
    fields: {
      email: (user, $) => {
        return $.anyOf({
          self: user.id.is($.viewer.id),
          staff: $staff,
        });
      },
    },
  },
});

On a device without access, user.email is undefined (the type says so), and a restricted field can't be a load key or a server-query filter. A restricted field with no rule in fields is an error from definePermissions outside production, and reaches nobody in it.

Deny lists

src/sync/permissions/document.ts
import { defineModelRules } from "@clientdb/server";
import { schema } from "../schema";
import { isMember } from "./team";

export const documentRules = defineModelRules(schema, "document", {
  read: (document, $) => {
    const blocked = document.blocks.some((block) => {
      return block.userId.is($.viewer.id);
    });
    return $.and($.not(blocked), isMember(document.team));
  },
});

A whole-rule deny withholds the row from blocked users even when another branch allows it. Blocking and unblocking move the row out and back in for that user. This is the one place to use $.not; elsewhere, negate a field with .is(false).

Rules that need data the router can't see

Use an explicit group with your own membership function, or a validate function for write-side checks such as uniqueness or quotas:

src/sync/permissions/inviteLink.ts
import { defineModelRules } from "@clientdb/server";
import { schema } from "../schema";
import { isMember } from "./team";

export const inviteLinkRules = defineModelRules(schema, "inviteLink", {
  create: {
    when: (link) => {
      return isMember(link.team);
    },
  },
  validate: async ({ operation, after, db }) => {
    if (operation !== "create") {
      return null;
    }
    const links = await db.find("inviteLink", "teamId", after!.teamId);
    return links.length >= 50 ? "Link limit reached" : null;
  },
});