Declarative Permissions
Learn how to write declarative permissions, from simple ownership to relationship-based access, and how to test them.Declarative permissions control who can read, insert, update, and delete rows. You declare them as policies in schema.ts, next to your tables, and Jazz enforces them server-side. Clients that fail a policy check have their writes rejected and their reads filtered.
If you know Postgres row-level security (RLS), declarative permissions are similar: rules over rows and the signed-in user. In Jazz they are typed TypeScript next to your schema, every operation is denied until a policy grants it, and you test them like the rest of your app.
Jazz decides permissions per table:
- every read, insert, update, and delete requires an explicit grant
- every omitted operation is denied, including on tables with no policy declarations
For example, declaring read without insert, update, or delete makes that table
read-only. A table without any grants returns no
rows to permission-scoped reads and rejects writes on the server. Optimistic
local writes can still appear before the server accepts or rejects them.
Authoring workflow
Permissions live in schema.ts, after your tables. The tools for writing them are properties of
the schema, so they know your tables, columns and relations. If we have the following schema:
schema.tsimport { schema as s } from "jazz-tools";export const schema = s.defineSchema({projects: s.table({ name: s.string(), owner_id: s.uuid() },{todos: s.reverse("todos", "project"),},),todos: s.table({title: s.string(),done: s.boolean(),parentId: s.uuid().optional(),projectId: s.uuid().optional(),owner_id: s.uuid(),},{parent: s.rel("todos", "parentId"),children: s.reverse("todos", "parent"),project: s.rel("projects", "projectId"),shares: s.reverse("todoShares", "todo"),},),todoShares: s.table({ todoId: s.uuid(), user_id: s.uuid(), can_read: s.boolean() },{todo: s.rel("todos", "todoId"),},),});
We can define permissions below it, in the same file:
schema.tsconst { definePermissions, session } = schema;export const permissions = definePermissions({projects: {read: true,insert: true,},todos: {read: { owner_id: session.user },insert: { owner_id: session.user },update: { owner_id: session.user },delete: { owner_id: session.user },},todoShares: {},});
jazz.permissions.json{"$schema": "https://jazz.tools/schemas/jazz.permissions.v1.json","tables": {"projects": {"read": "true","insert": "true"},"todos": {"read": "owner_id = session.user","insert": "owner_id = session.user","update": "owner_id = session.user","delete": "owner_id = session.user"}}}
npx jazz-tools generate reads the permissions export and writes the second tab,
jazz.permissions.json, which is what your backend loads. You don't edit it, but it's worth a
look: it shows exactly what each rule means. Every example on this page shows both. (The generated
file also starts with a $generated marker, left out here.)
Rules
definePermissions takes one entry per table, and TypeScript requires every table of the schema.
{} grants nothing, so every operation on that table is denied. A table's rules are its
operations:
| Key | Checks |
|---|---|
read | Rows a session may read |
insert | Rows a session may create |
update | Rows a session may change, checked before and after the change |
updateIf / updateTo | An update with different checks before and after it (always together) |
delete | Rows a session may delete |
An operation without a key is denied. Each rule is one of:
- a condition such as
{ owner_id: session.user }, which applies to the row being checked; trueorfalse;- a function of the row,
(todo) => …, for conditions that refer to the row's columns or relations, such asallowedTo.read(todo.project).updateToalso receives the row as it was before the update:(todo, old) => ….
Apps that do not need user-scoped filtering must still declare every required operation explicitly,
with rules such as read: true and insert: true.
Basic policies
Simple conditions
A plain object is a condition on the row: each key is a column, and every key must match. A value
on its own means =, an array means "one of", and null matches an empty optional column.
ne, gt, gte, lt, lte and contains compare in other ways, for example
{ priority: gte(3) }, { parentId: ne(null) } or { tags: contains("urgent") }. A session value
such as session.user can stand where a value does.
Policies decide which rows a user may read or write, not which columns. To keep a column from some users, move it to its own table with a one-to-one relation to the row, and give that table its own policies.
schema.tsconst { definePermissions, session } = schema;export const permissions = definePermissions({todos: {read: { owner_id: session.user },// Users cannot create todos with different owners.insert: { owner_id: session.user },// Users can update their own todos, but only if not already done.updateIf: { owner_id: session.user, done: false },updateTo: { owner_id: session.user },// Users can only delete their own todos.delete: { owner_id: session.user },},// ...});
jazz.permissions.json{"tables": {"todos": {"read": "owner_id = session.user","insert": "owner_id = session.user","update": {"old": {"allOf": ["owner_id = session.user", "done = false"]},"new": "owner_id = session.user"},"delete": "owner_id = session.user"}}}
updateIf and updateTo are explained in Update policies.
Examples on this page leave out the other tables with // ...; in your file, list them all.
true
Use true when an operation should always be permitted.
schema.tsexport const permissions = definePermissions({todos: {read: true,insert: true,update: true,delete: true,},// ...});
jazz.permissions.json{"tables": {"todos": {"read": "true","insert": "true","update": "true","delete": "true"}}}
false
Use false when an operation should be impossible. Leaving the operation out denies it too;
false says it's on purpose, and stays in the generated file.
schema.tsexport const permissions = definePermissions({todos: {read: false,insert: false,update: false,delete: false,},// ...});
jazz.permissions.json{"tables": {"todos": {"read": "false","insert": "false","update": "false","delete": "false"}}}
Tables only your backend writes
A table your users read but only your backend writes (an audit log, imported data, counters a job
keeps) needs no write grants: your backend isn't checked when it acts as the system (see
System-authored rows). npx jazz-tools generate
warns about each operation without a policy, so say it's on purpose with false rather than
adding an allow rule to silence the warning:
schema.tsexport const schema = s.defineSchema({auditLog: s.table({ownerId: s.uuid(),action: s.string(),}),});const { definePermissions, session } = schema;export const permissions = definePermissions({auditLog: {read: { ownerId: session.user },insert: false,update: false,delete: false,},});
jazz.permissions.json{"tables": {"auditLog": {"read": "ownerId = session.user","insert": "false","update": "false","delete": "false"}}}
Composing policies
Combining conditions (allOf / anyOf)
Combine conditions with allOf (all must match), anyOf (any can match) and not:
schema.tsconst { definePermissions, session, anyOf, allOf, allowedTo } = schema;export const permissions = definePermissions({projects: {read: { owner_id: session.user },},todos: {// Users can read a todo if they own it, or if it's not done and they can read its project.read: (todo) =>anyOf({ owner_id: session.user }, allOf({ done: false }, allowedTo.read(todo.project))),},// ...});
jazz.permissions.json{"tables": {"projects": {"read": "owner_id = session.user"},"todos": {"read": {"anyOf": ["owner_id = session.user",{"allOf": ["done = false", "allowedTo.read(project)"]}]}}}}
anyOf() with no conditions matches nothing, and allOf() everything.
Helpers
When several policies repeat a condition, give it a name. A helper is an ordinary TypeScript
value or function: generate writes out its result wherever you use it, so helpers cost nothing
at runtime and can take any parameters, call each other and live in other modules.
schema.tsconst { definePermissions, exists, session, anyOf } = schema;const mine = { owner_id: session.user };const isSharedWithMe = (todoId: s.Uuid) =>exists.todoShares({ todoId, user_id: session.user, can_read: true });export const permissions = definePermissions({todos: {read: (todo) => anyOf(mine, isSharedWithMe(todo.id)),update: mine,delete: mine,},todoShares: {read: (share) => anyOf({ user_id: session.user }, share.todo.where(mine)),insert: (share) => share.todo.where(mine),},// ...});
jazz.permissions.json{"tables": {"todoShares": {"read": {"anyOf": ["user_id = session.user","exists todos(id = this.todoId, owner_id = session.user)"]},"insert": "exists todos(id = this.todoId, owner_id = session.user)"},"todos": {"read": {"anyOf": ["owner_id = session.user","exists todoShares(todoId = this.id, user_id = session.user, can_read = true)"]},"update": "owner_id = session.user","delete": "owner_id = session.user"}}}
A helper's parameters are typed with the schema's value types: s.Uuid for a UUID column or
id, s.Value<"string"> for a string column, and so on. Pass a column of the row (todo.projectId)
and the helper's condition follows that row. A condition object such as mine works on any table
with those columns, and inside .where(...).
Session claims
When your backend's authenticate returns claims, session.claims.<path> lets you check them
directly in permissions without mapping them onto row columns first. Compare a claim with a value
using eq, ne, gt and the other comparisons, or isIn for a list:
schema.tsconst { definePermissions, session, anyOf, eq } = schema;export const permissions = definePermissions({todos: {read: anyOf({ owner_id: session.user }, eq(session.claims.role, "manager")),},// ...});
jazz.permissions.json{"tables": {"todos": {"read": {"anyOf": ["owner_id = session.user", "session.claims.role = 'manager'"]}}}}
A claim can also be the value a row is compared with, for example rows of the user's organization
({ orgId: session.claims.org }), or a list to test membership in
({ teamId: isIn(session.claims.teams) }).
Claims are JSON, so a claim is compared as the type of the column it meets, the same way in every
policy form: a s.uuid() column (or id) reads a string claim as the UUID it spells, a text column
compares the claim's text exactly, and an integer column accepts a JSON number or a string such as
"42". A claim the column can't hold matches no rows.
Untyped claims accept any path. To have TypeScript check them, declare their shape:
schema.tsexport const schema = s.defineSchema({projects: s.table({name: s.string(),orgId: s.string(),teamId: s.string(),}),},{ claims: s.claims<{ role: "manager" | "member"; org: string; teams: string[] }>() },);
Inherited access (allowedTo.*)
A row can inherit its access from a related row. Use
allowedTo.read/insert/update/delete(row.relation) to express that inheritance.
The argument is a relation declared on the protected table. For
writer: s.rel("users", "authorId"), write allowedTo.update(post.writer).
Reverse relations work the same way. Given authored: s.reverse("posts", "writer") on users,
allowedTo.delete(user.authored) grants deletion only when at least one referencing
post permits deletion for the current identity. Readability or mere existence
of a referencing post does not grant deletion. No matching reference means no
grant; nullable references contribute no match, and UUID arrays use membership.
For a link no relation names, pass a column instead: allowedTo.read(post.authorId) follows the
forward column itself, and allowedTo.delete(schema.tables.posts.writer) the rows of posts whose
writer column points here.
Inheritance keeps each operation's own policy, and each update rule's before and after checks.
TypeScript only offers relations of the rule's table, and jazz-tools generate checks their
direction and target.
allowedTo can't be used inside an exists yet (in its conditions, a .hop, a relation's
.where or a relation query), nor under not: it is only a rule's own check, alone or in anyOf
and allOf. TypeScript rejects it in both places, and jazz-tools generate refuses a file that
has it, with "allowedTo.read(…) inside exists is not supported yet" or "not allowedTo.read(…)
is not supported yet". Write a rule that would negate inheritance without it (not works on the
row's own columns and session values). Inside an exists, repeat the other table's rule instead,
sharing it as a helper:
schema.ts// Who may read a project, shared by the rules that need it.const readableProject = { owner_id: session.user };export const permissions = definePermissions({projects: { read: readableProject },todos: { read: (todo) => allowedTo.read(todo.project) },todoShares: {// Not `exists.todos({ id: share.todoId }, (todo) => allowedTo.read(todo.project))`:read: (share) => exists.todos({ id: share.todoId }).hop("project", readableProject),},});
schema.tsconst { definePermissions, session, anyOf, allOf, allowedTo } = schema;export const permissions = definePermissions({projects: {read: { owner_id: session.user },update: { owner_id: session.user },},todos: {// Users can read a todo if it's not done, or if they can read its project.read: (todo) => anyOf({ done: false }, allowedTo.read(todo.project)),// Users can update a todo if they can update its project and it's not done.updateIf: (todo) => allOf(allowedTo.update(todo.project), { done: false }),updateTo: (todo) => allowedTo.update(todo.project),},// ...});
jazz.permissions.json{"tables": {"projects": {"read": "owner_id = session.user","update": "owner_id = session.user"},"todos": {"read": {"anyOf": ["done = false", "allowedTo.read(project)"]},"update": {"old": {"allOf": ["allowedTo.update(project)", "done = false"]},"new": "allowedTo.update(project)"}}}}
Share-based access
Sometimes access isn't determined by ownership or a parent relationship, but by a separate "shares"
table. Use exists.<table>({ … }) to check whether a matching row exists in another table.
schema.tsconst { definePermissions, session, anyOf, exists } = schema;export const permissions = definePermissions({todos: {// Users can read a todo if they own it, or if someone shared it with them.read: (todo) =>anyOf({ owner_id: session.user },exists.todoShares({ todoId: todo.id, user_id: session.user, can_read: true }),),},// ...});
jazz.permissions.json{"tables": {"todos": {"read": {"anyOf": ["owner_id = session.user","exists todoShares(todoId = this.id, user_id = session.user, can_read = true)"]}}}}
Inside exists.todoShares({ … }), the keys are columns of todoShares, and todo.id is the
current row, so you can correlate it with rows in other tables. Every key must match. Pass more
conditions after the object for what an object can't say, such as
exists.todoShares({ todoId: todo.id }, anyOf({ can_read: true }, { user_id: session.user })).
A relation of the row gives a shorter form: todo.shares.where({ user_id: session.user }) checks
the rows shares leads to, here the same todoShares rows. It works for forward relations too:
todo.project.where({ owner_id: session.user }).
An exists can also follow a relation from the row it finds, with .hop:
exists.docs({ id: doc.id }).hop("author", { uid: session.identity.subject }) reads uid on the
row author leads to.
One correlation links the two rows: the one on the other table's id, if there is one. It must
follow a relation, either id against a column declared with an s.rel to that table, or two
columns that are relations to the same table; otherwise validation fails with
JoinNotRefCompatible. Further correlations, such as authUserId: row.authUserId, only need
comparable column types.
To match the userId your authenticate returned (for example an assignee text column holding
your auth's user ids), compare with session.identity.subject: session.user is the Jazz account,
not your user id.
Inside a transaction, exists also sees the transaction's own writes, so a row can be written in
the same transaction as the row that grants it access, such as a task inserted together with its
project. A row that already existed still counts if the same transaction deletes it, so you can,
for example, admit a member and remove their join request together. A row the transaction both
creates and deletes never counts, and neither do writes from other transactions that the server
has not accepted yet. Rows a transaction writes cannot grant each other access in a cycle:
each one has to be allowed by rows that already exist or that the transaction writes and are
themselves allowed. Every write must also still be allowed by the state the whole transaction
leaves behind, so demoting your own membership from admin in the same transaction as creating a
document that requires admin is rejected. The order in which you make the writes doesn't matter. See
Know when permissions are checked
for when a transaction's writes are checked and more examples.
Importing many rows whose permissions rest on rows that already exist (for example, thousands of
folders under existing parents) is checked once per row. A transaction whose rows mostly depend on
each other (for example, thousands of folders nested inside one another in the same transaction)
is rejected with the write_rejected code and a reason ending in "is not supported yet" once its
checks would have to read more than 262,144 of its own rows. Split such an import into smaller
transactions.
Access through related rows
When access depends on rows in another table, check that a matching path exists: start from a
table with exists.<table>, filter it, follow a relation with .hop("relation", { … }), and
filter again. For example, a doctor may read the patients they have an appointment with:
schema.tsexport const schema = s.defineSchema({doctors: s.table({userId: s.string(),name: s.string(),}),patients: s.table({name: s.string(),}),appointments: s.table({ doctorId: s.uuid(), patientId: s.uuid(), at: s.timestamp() },{doctor: s.rel("doctors", "doctorId"),patient: s.rel("patients", "patientId"),},),});
schema.tsconst { definePermissions, session, exists } = schema;export const permissions = definePermissions({doctors: {// A doctor reads their own record.read: { userId: session.identity.subject },},patients: {// Patients with an appointment whose doctor is the signed-in user.read: (patient) =>exists.appointments({ patientId: patient.id }).hop("doctor", { userId: session.identity.subject }),},appointments: {// A doctor's own appointments.read: (appointment) => appointment.doctor.where({ userId: session.identity.subject }),},});
jazz.permissions.json{"tables": {"appointments": {"read": "exists doctors(id = this.doctorId, userId = session.identity.subject)"},"doctors": {"read": "userId = session.identity.subject"},"patients": {"read": "exists appointments(patientId = this.id).doctor(userId = session.identity.subject)"}}}
These are read rules only: who may book or change appointments needs insert and update policies
too. A hop takes a relation declared with s.rel or s.reverse, and the conditions after it
filter the rows it reaches. An exists takes one hop: chaining a second one is not supported yet;
for longer paths, see Relation queries.
If a table references itself (e.g. a comment that can have sub-comments), you can inherit access recursively up to a fixed depth.
schema.tsexport const permissions = definePermissions({todos: {// Users can read a todo if they can read its parent (follows the chain upward).read: (todo) => allowedTo.read(todo.parent),// Users can update a todo if they can update its parent, up to 5 levels deep.update: (todo) => allowedTo.update(todo.parent, { maxDepth: 5 }),},// ...});
jazz.permissions.json{"tables": {"todos": {"read": "allowedTo.read(parent)","update": "allowedTo.update(parent, maxDepth: 5)"}}}
maxDepth must be a non-negative integer. A value of 0 performs no inheritance
hop, so the inheritance condition cannot grant access; 1 checks only the
directly referenced row. These bounds apply to forward relationships. Reverse
inheritance currently rejects maxDepth rather than ignoring it; cyclic reverse
policy expansion is rejected during schema validation.
Update policies: old row vs new row
An update policy can check both the row before the update and the row after it. update
applies the same condition to both. To check them differently, use updateIf for the row before the
update (may this user change it?) and updateTo for the row after it (is the result valid?). They
always come together, and replace update.
schema.tsexport const permissions = definePermissions({todos: {// Users can only update their own rows, and the result must still be owned by them.update: { owner_id: session.user },},// ...});
jazz.permissions.json{"tables": {"todos": {"update": "owner_id = session.user"}}}
updateTo also receives the row as it was before the update, as its second argument. Compare a
column of the new row with the old one to say what an update may not change, or how it may change
it:
schema.tsconst { definePermissions, session, allOf } = schema;export const permissions = definePermissions({todos: {updateIf: { owner_id: session.user },// parentId and projectId cannot be updated.updateTo: (todo, old) =>allOf({ owner_id: session.user }, { parentId: old.parentId, projectId: old.projectId }),},// ...});
jazz.permissions.json{"tables": {"todos": {"update": {"old": "owner_id = session.user","new": {"allOf": ["owner_id = session.user","exists todos(id = this.id, parentId = this.parentId, projectId = this.projectId)"]}}}}}
old works in direct comparisons with the row's own columns: { status: old.status },
{ ownerId: ne(old.ownerId) }, { version: gt(old.version) }. As the generated JSON shows, the
comparisons of one object become one exists on the same table: while the update is checked, the
stored row is still the old version, also inside a transaction that wrote the row before. old
can't be used inside another exists, and TypeScript rejects it there.
Relation queries
Everything a policy can express has a form in TypeScript. Most policies need only the forms
above. For the rest, such as a path of several hops, a join, or a walk up a tree of any depth,
exists(...) takes a relation query built from the schema's from, with SQL-like steps:
from.<table>(alias?)starts from a table, andfrom(query, alias?)from another query;.join(other, { on: [["a.x", "b.y"]], left? })joins another, and.where({ "alias.col": value })filters;.select({ id: "a.id" }),.distinctOn(...),.orderBy(...),.limit(n)and.offset(n)shape the result;union({ label: query, … })combines queries, andfrom(recursive({ seed, step, frontier, dedupe, maxDepth }))repeats a step from a starting set, up tomaxDepthtimes or"fixpoint";- inside them,
outer("col")is a column of the row being checked,frontier("col")one of the rows a recursive step starts from, androwId("row")a row's identity.
Column references in these queries are strings such as "f.ownerId", so TypeScript doesn't check
them; generate does. For example, with folders and files:
schema.tsexport const schema = s.defineSchema({folders: s.table({name: s.string(),ownerId: s.uuid(),}),files: s.table({ name: s.string(), folderId: s.uuid() },{folder: s.rel("folders", "folderId"),},),});
a user may read a file in a folder they own:
schema.tsconst { definePermissions, session, exists, from } = schema;export const permissions = definePermissions({files: {read: exists(from.files().join(from.folders("f"), { on: [["files.folderId", "f.id"]] }).where({ "f.ownerId": session.user }).select({ id: "files.id" }),),},folders: {read: { ownerId: session.user },},});
jazz.permissions.json{"tables": {"files": {"read": "exists (from files join folders as f on files.folderId = f.id where f.ownerId = session.user select files.id as id)"},"folders": {"read": "ownerId = session.user"}}}
(The same rule is shorter as file.folder.where({ ownerId: session.user }); the query form is for
what the shorter forms can't say.) The engine supports recursive queries in policies only when they
walk from the row being checked; to inherit access up a tree, use
allowedTo with maxDepth instead.
Values in policies are plain JavaScript values, typed by the column they meet. Where a value has no
column to take its type from, typed.int(5), typed.text("5"), typed.uuid(…),
typed.timestamp(…) and the like give it one. The full expression grammar is in
App files.
Policy enforcement and request context
Every policy is evaluated against a session. On the frontend, this is the authenticated user's session. In a backend handler, create a scoped session per request so queries run with the right identity.
handler.tsexport async function listTodosForRequester(request: Request): Promise<Response> {try {const requester = await jazz.forReqUser(request);const rows = await requester.all(schemaApp.todos.where({ done: true }));return Response.json(rows);} catch {return queryError();}}
handler.ts// Written against `Jazz` only, so the same code runs in a browser, in a test// against an in-memory database, or here as the requesting user.export const listDoneTodos = Effect.gen(function* () {const jazz = yield* Jazz;return yield* jazz.all(schemaApp.todos.where({ done: true }));});// A standalone route: mount it with the quickstart routes below if you want it served.export const listDoneTodosRoute = HttpRouter.add("GET","/api/todos/done",listDoneTodos.pipe(Effect.flatMap((rows) => HttpServerResponse.json(rows)),JazzBackend.forCurrentReqUser(),Effect.catchTag("JazzError", () =>HttpServerResponse.json({ error: "Failed to query todos" }, { status: 500 }),),),);
See Main Backend for setting up your backend.
Check permissions before an action
Use db.canInsert(), db.canRead(), db.canUpdate(), or db.canDelete() when your app needs to
check an action before showing it to the user. Each method returns "allowed", "denied", or
"unknown".
These results are advice, not permission enforcement. A result can become stale, and "unknown"
means Jazz could not give a definite answer. The authority still makes the final decision when the
read or write reaches it.
app.tsexport async function canReadTodo(db: Db, todoId: string) {return db.canRead(app.todos, todoId);}export async function readTodosWithDeletePermission(db: Db) {const todos = await db.all(app.todos.select("id", "title").orderBy("title", "asc"));const advice = await Promise.all(todos.map((todo) => db.canDelete(app.todos, todo.id)));return todos.filter((_, index) => advice[index] === "allowed");}export async function readEditableTodos(db: Db) {const todos = await db.all(app.todos.select("id", "title").orderBy("title", "asc"));const advice = await Promise.all(todos.map((todo) => db.canUpdate(app.todos, todo.id, { title: todo.title })),);return todos.filter((_, index) => advice[index] === "allowed");}export async function canCreateTodo(db: Db, title: string) {return db.canInsert(app.todos, { title, done: false });}
app.tsexport const canReadTodo = (todoId: string) => Jazz.use((jazz) => jazz.canRead(app.todos, todoId));export const readTodosWithDeletePermission = Effect.gen(function* () {const jazz = yield* Jazz;const todos = yield* jazz.all(app.todos.select("id", "title").orderBy("title", "asc"));return yield* Effect.filter(todos,(todo) => Effect.map(jazz.canDelete(app.todos, todo.id), (advice) => advice === "allowed"),{ concurrency: "unbounded" },);});export const readEditableTodos = Effect.gen(function* () {const jazz = yield* Jazz;const todos = yield* jazz.all(app.todos.select("id", "title").orderBy("title", "asc"));return yield* Effect.filter(todos,(todo) =>Effect.map(jazz.canUpdate(app.todos, todo.id, { title: todo.title }),(advice) => advice === "allowed",),{ concurrency: "unbounded" },);});export const canCreateTodo = (title: string) =>Jazz.use((jazz) => jazz.canInsert(app.todos, { title, done: false }));
pub async fn can_read_todo(jazz: &Jazz, todo_id: ObjectId) -> jazz_app::Result<Advice> {jazz.can_read::<Todo>(todo_id).await}pub async fn read_todos_with_delete_permission(jazz: &Jazz) -> jazz_app::Result<Vec<Todo>> {let todos = jazz.all(todos::query().order_by(todos::title(), Order::Asc)).await?;let mut deletable = Vec::new();for todo in todos {if jazz.can_delete::<Todo>(todo.id).await? == Advice::Allowed {deletable.push(todo);}}Ok(deletable)}pub async fn read_editable_todos(jazz: &Jazz) -> jazz_app::Result<Vec<Todo>> {let todos = jazz.all(todos::query().order_by(todos::title(), Order::Asc)).await?;let mut editable = Vec::new();for todo in todos {let update = TodoUpdate {title: Some(todo.title.clone()),..Default::default()};if jazz.can_update(todo.id, update).await? == Advice::Allowed {editable.push(todo);}}Ok(editable)}pub async fn can_create_todo(jazz: &Jazz, title: &str) -> jazz_app::Result<Advice> {jazz.can_insert(NewTodo::new(title, false)).await}
// Each answer is `true`, `false` or `nil` (unknown: no server to ask, say).public func canReadTodo(_ jazz: Jazz.Client, todoId: Jazz.ID) async throws -> Bool? {try await jazz.canRead(JazzApp.Todo.self, id: todoId)}public struct TodoSummary: Decodable, Sendable, Equatable {public var id: Jazz.IDpublic var title: String}public func readTodosWithDeletePermission(_ jazz: Jazz.Client) async throws -> [TodoSummary] {let todos = JazzApp.todos.selfvar deletable: [TodoSummary] = []let all = try await jazz.all(todos.query().orderBy(todos.title.asc).select(todos.title), as: TodoSummary.self)for todo in all {if try await jazz.canDelete(JazzApp.Todo.self, id: todo.id) == true { deletable.append(todo) }}return deletable}public func readEditableTodos(_ jazz: Jazz.Client) async throws -> [TodoSummary] {let todos = JazzApp.todos.selfvar editable: [TodoSummary] = []let all = try await jazz.all(todos.query().orderBy(todos.title.asc).select(todos.title), as: TodoSummary.self)for todo in all {let patch = JazzApp.TodoPatch(title: .set(todo.title))if try await jazz.canUpdate(todo.id, patch) == true { editable.append(todo) }}return editable}public func canCreateTodo(_ jazz: Jazz.Client, title: String) async throws -> Bool? {try await jazz.canInsert(JazzApp.NewTodo(title: title, done: false))}
// Each answer is true (allowed), false (denied), or null when no server can say.suspend fun canReadTodo(jazz: Jazz, todoId: String): Boolean? =jazz.canRead(Todos, todoId)suspend fun readTodosWithDeletePermission(jazz: Jazz): List<JazzRow<Todo>> {val todos = jazz.all(Todos.orderBy(Todos.title.asc()).select(Todos.title))return todos.filter { todo -> jazz.canDelete(Todos, todo.id) == true }}suspend fun readEditableTodos(jazz: Jazz): List<JazzRow<Todo>> {val todos = jazz.all(Todos.orderBy(Todos.title.asc()).select(Todos.title))return todos.filter { todo -> jazz.canUpdate(Todos, todo.id) { title(todo[Todos.title]) } == true }}suspend fun canCreateTodo(jazz: Jazz, title: String): Boolean? =jazz.canInsert(Todos, NewTodo(title = title, done = false))
// Advice, not enforcement: jazz.Allowed, jazz.Denied, or jazz.Unknown// (e.g. offline).func CanReadTodo(ctx context.Context, db *jazz.DB, todoID string) (jazz.Advice, error) {return jazzapp.Todos.CanRead(ctx, db, todoID)}func TodosYouMayDelete(ctx context.Context, db *jazz.DB) ([]jazzapp.Todo, error) {todos, err := jazzapp.Todos.Query().OrderBy(jazzapp.Todos.Title.Asc()).All(ctx, db)if err != nil {return nil, err}var allowed []jazzapp.Todofor _, todo := range todos {advice, err := jazzapp.Todos.CanDelete(ctx, db, todo.ID)if err != nil {return nil, err}if advice == jazz.Allowed {allowed = append(allowed, todo)}}return allowed, nil}func TodosYouMayEdit(ctx context.Context, db *jazz.DB) ([]jazzapp.Todo, error) {todos, err := jazzapp.Todos.Query().OrderBy(jazzapp.Todos.Title.Asc()).All(ctx, db)if err != nil {return nil, err}var allowed []jazzapp.Todofor _, todo := range todos {advice, err := jazzapp.Todos.CanUpdate(ctx, db, todo.ID, jazzapp.TodoPatch{Title: jazz.Set(todo.Title)})if err != nil {return nil, err}if advice == jazz.Allowed {allowed = append(allowed, todo)}}return allowed, nil}func CanCreateTodo(ctx context.Context, db *jazz.DB, title string) (jazz.Advice, error) {return jazzapp.Todos.CanInsert(ctx, db, jazzapp.NewTodo{Title: title, Done: false})}
Magic columns
Jazz exposes a small set of system-provided magic columns at query time. They do not exist in your
schema, and they are omitted from select("*"), so opt in explicitly when you want them.
Edit metadata columns
Jazz also tracks row authorship and timestamps automatically:
$createdBy— the Jazz principal that created the row$createdAt— when the row was first created$updatedBy— the Jazz principal that last updated the row$updatedAt— when the row was last updated
Jazz always tracks this metadata; select the columns explicitly to include them in query results. Backend writes that are not attributed to a user use the reserved system account and an internal system identity. See System-authored rows for their account, issuer, and originating-node subject.
Authorship-based policies
You can use these edit metadata magic columns directly in permissions. This is useful for simple
"creator can read/edit/delete their own rows" policies without adding explicit owner_id columns.
Compare $createdBy with session.user to scope a rule to the row's creator. session.user is
the account, so the rule matches rows written through any identity linked to it, including
alpha.59 rows whose author was imported with an account. To match only the exact login that wrote
the row, compare { "$createdBy.identity": session.identity } (its issuer and subject).
session.claims holds the claims your authenticate returned, not a raw JWT payload; with
fromJWT(), session.identity is
{ issuer: "jazz:backend", subject }, not your provider's iss. Claims never replace the
canonical author identity.
schema.tsconst { definePermissions, session } = schema;// Only the row's creator can read, create, update, or delete it.const createdByMe = { $createdBy: session.user };export const permissions = definePermissions({todos: {read: createdByMe,insert: createdByMe,update: createdByMe,delete: createdByMe,},// ...});
jazz.permissions.json{"tables": {"todos": {"read": "$createdBy = session.user","insert": "$createdBy = session.user","update": "$createdBy = session.user","delete": "$createdBy = session.user"}}}
The creator condition is a plain condition, so it composes inside larger rules:
schema.tsexport const permissions = definePermissions({todos: {read: anyOf({ $createdBy: session.user }, { done: true }),},// ...});
jazz.permissions.json{"tables": {"todos": {"read": {"anyOf": ["$createdBy = session.user", "done = true"]}}}}
For more dynamic sharing or ownership models, prefer explicit tables and relations rather than encoding extra meaning into authorship alone.
Changing permissions in production
Each deployment of your backend serves the permissions it was built with, and every client is checked by the permissions of the deployment it connected through. When a deployment with new permissions starts, every connected client reconnects, including clients of your other deployments (previews too), and each is checked again by the permissions of the deployment it now reaches. Deploying permissions that have been deployed before, such as a rollback, reconnects no one.
To retire permissions that grant too much, deploy fixed ones and delete every deployment that still serves the old ones, including older production and preview deployments that are still reachable. Until it is gone, any client that connects through such a deployment is checked by its permissions.
Testing permissions
Jazz provides utilities to test permissions in isolation without testing your whole app's logic. See Testing permissions.
Troubleshooting denied access
If a write appears locally but does not persist, wait for
server durability and handle the rejection.
The local-first client rejects with PersistedWriteRejectedError, code permission_denied. The
thin client rejects with a ThinRemoteError whose code is WriteRejected and whose message
starts with the reason, such as authorization_denied: …. Use
db.onMutationError(...) as a fallback for rejections without an active wait;
see Handling mutation errors.
A backend connected to Jazz Cloud (deprecated) doesn't refuse a session's write up front either: the cloud
decides it, and a denial arrives through wait(...) with the same permission_denied code. A store
with no authority above it, such as a client with serverUrl: null or a backend on its own
storage, refuses some denied writes at once (the write call throws), and accepts others, such as a
denied update of a row it holds, then rejects them through wait(...). So in backend code, await every write
and handle both:
try {await db.update(app.deals, dealId, { stage: "won" }).wait({ tier: "global" });} catch (error) {// permission_denied, thrown by update() or by wait()}
In Node, a write's rejected wait() that nothing awaits or catches is an unhandled rejection, which
ends the process.
An empty query result can also mean that read permissions filtered out rows.
As the app developer, check your own configuration:
- Run
npx jazz-tools generateand check that every required table and operation has an explicit grant. For updates and upserts that update an existing row, also check the required read permission. - Check that the grants match the authenticated session and the relevant row values, including both old and new values for updates. Test these cases with permission tests.
- Deploy your main backend with the intended policies
and verify the app ID and deployed configuration. Changing
schema.tsand runninggeneratelocally does not update the server's policies.
Treat permission_denied as a generic rejection: it does not tell the caller
whether a policy is missing, a predicate failed, or a protected row exists.
Keep these configuration checks in developer tooling and tests; do not expose
protected policies, row values, or row-existence details in client-facing errors.