Data config
A resource describes one table of a database you already have: its columns as fields, its key, and the rules around it. It is plain TypeScript in config/<resource>/data.ts, exported from config/index.ts; protobase scaffold writes a first version from the database. Every example on this page is a file in the repository that CI typechecks and tests.
import { f, resource } from '@protobase/schema'
// Pip's bike shop: customers bring bikes in, the workshop repairs them. Two tables of a Postgres database the// shop already has, described as they are.
/** shop.customers */export const customers = resource('customers') .table('shop.customers') .fields({ id: f.integer().readOnly().filterable().sortable().dbDefault(), name: f.text().min(2).filterable().sortable(), phone: f.text().regex(/^\+?[0-9 ]{6,}$/, 'Use digits, spaces and an optional +').optional(), email: f.text().optional().filterable(), country: f.country().default('NL'), created_at: f.timestamp().readOnly().filterable().sortable().dbDefault(), }) .primaryKey((r) => r.id) .search((r) => [r.name, r.email])
/** shop.repairs */export const repairs = resource('repairs') .table('shop.repairs') .fields({ id: f.integer().readOnly().filterable().sortable().dbDefault(), number: f.text().readOnly().filterable().sortable().dbDefault(), customer_id: f.relation('customers').filterable().sortable(), bike: f.text(), problem: f.text(), status: f.enum(['booked', 'waiting', 'working', 'ready', 'collected']).default('booked').filterable().sortable(), mechanic: f.text().optional().filterable().sortable(), estimate: f.decimal({ precision: 8, scale: 2 }).filterable().sortable(), currency: f.currency().default('EUR'), paid: f.boolean().default(false).filterable(), booked_on: f.date().filterable().sortable(), notes: f.text().optional().column('internal_notes'), legacy_ref: null, updated_at: f.timestamp().readOnly().dbDefault(), }) .primaryKey((r) => r.id) .search((r) => [r.number, r.bike, r.problem]) .validate((repair) => (repair.status === 'collected' && !repair.paid ? [{ field: 'paid', message: 'A bike leaves the shop paid' }] : undefined))resource()
Section titled “resource()”resource(name) |
The name is the resource’s address (/api/v1/<name>, /<name> in the admin) and how other config refers to it. It may not contain /, :, ? or #, and must be unique. |
.table('schema.table') |
The table, with or without its schema. Required. |
.fields({ ... }) |
The columns, by field name. name: null ignores a column on purpose (scaffold writes it, so it does not offer the column again). Required. |
.primaryKey((r) => r.id) |
The key, one field or a list ((r) => [r.order_id, r.line_no]). Required; records are addressed by it. |
.softDelete((r) => r.deleted_at) |
A nullable timestamp or date: deleting sets it, lists leave such rows out, :undelete clears it. See REST API. |
.tenant((r) => r.organization_id, { across? }) |
The column that separates tenants: every query is limited to the caller’s tenant, creates set it, and a request body may not. With across: 'memberships', lists read every organization the person is a member of, each with their role there; see Lists across organizations. |
.owner((r) => r.owner_id) |
The field holding the owning user’s id, which .own and .team capabilities filter on (see Access). The server does not start when its column cannot hold the signed-in users’ ids, such as an integer column with Better Auth’s text ids; see user ids. |
.author((r) => r.author_id) |
The field holding the id of the user who created the record, such as a chat message’s sender: every create sets it to the signed-in user’s id, and no request may write it, so a body that names it is refused as read-only. A create by no one signed in, through a public form, leaves it empty. Its column is checked at startup as an owner’s is. |
.search((r) => [r.number, r.name]) |
The fields that search("...") and bare words in a filter match, and what the admin’s global search looks in. Every word of the text must appear in one of them, ignoring case, and part of a word is enough: port finds “Portfolio”. r.phone.digitsEnd() matches only the end of a field’s digits instead, ignoring spaces, + and dashes, and only words written like phone numbers: 9623, 47069623 and +31 6 47069623 find “+31 6 47069623”, 4706 and +316 do not. Each field needs a pg_trgm index (using gin (name gin_trgm_ops)), a digitsEnd one on regexp_replace(phone, '[^0-9]', '', 'g'), or the API refuses the search. |
.position((r) => r.position, { within?, after? }) |
The integer field holding the records’ order by hand, 1 the first, which a list’s Reorder button changes by dragging; with within: (r) => r.invoice_id, a filterable relation, each parent’s records have an order of their own, sorted in its related section; with after, a record never ranks above the records it depends on. The field must be sortable. See Reordering by hand and Ranked after what they depend on. |
.parent((r) => r.vm_id, 'update') |
The relation whose record each record belongs to, and the access on it ('read' or 'update') that creating, changing, deleting and undeleting a record needs, checked with the caller’s own rules on that resource. With 'read', every read of its records also keeps to those whose parent the caller reads. The relation is one column, to a resource with a key of one field. See Records that belong to another. |
.links((r) => [r.objective_id, r.task_id]) |
Its records link records of two resources, so each side lists the other, and what points at it, at /{parent}/{key}/{resource}. Two different filterable relations of one column. protobase doctor asks for the indexes reading either side needs. |
.checks({ tasks_parked_by_hand: { label: '{title} waits for a day.' } }) |
The database checks whose refusal the API names, each by its constraint name, with the label the app shows. See Checks the database makes. |
.openExisting((r) => [r.organization_id, r.member_key]) |
A unique key of the table whose conflict on create opens the record already holding those values, such as a direct message with the same members. See Opening an existing record. |
.validate((record) => issues) |
A rule over the whole record, run after the field checks on every create and update. It returns [{ field, message }] or undefined; issues answer 400 with the field named. |
.prepare((values, context) => values) |
Fills in or rewrites a create’s or update’s values on the server before they are written, inside the write’s transaction, such as a generated key or a normalised name. See Preparing a record. |
.access({ ... }) |
Rules per operation. See Access. |
.events((e, r) => [...]) |
What changes of its records mean, such as orders.created, captured in the database for every write. See Events. |
.explicitGrants() |
Leaves the resource out of role wildcards such as *.read: only * and capabilities that name it grant it. For resources whose records hold secrets. See Resources that need named grants. |
.history() |
Keeps every change of its records with who made it, shown on the record page and listed for admins as Activity. See Record history. |
.comments() |
Lets whoever may read a record comment on it and @mention others who may, who are emailed; shown on the record page and listed for admins. See Record comments. |
Field and resource names are snake_case by convention, like the columns: they are the names in URLs, the API, filters and sorts as written (/stock_moves?order_by=moved_at desc). The column is the snake_case of the name unless .column() says otherwise, so a camelCase name such as movedAt maps to moved_at too. protobase scaffold writes snake_case names, and the built-in resources, such as failed_jobs and webhook_subscriptions, have them too. Nothing checks the convention: a resource or field may have any name.
Field types
Section titled “Field types”| Builder | Column types | API value | Options |
|---|---|---|---|
f.text() |
text, varchar, bpchar |
string | .min(n), .max(n) (length), .regex(re, message); a text of several lines, such as a description, takes the view’s .multiline(), and markdown its .markdown() |
f.integer() |
int2, int4 |
number | .min(n), .max(n) |
f.bigint() |
int8 |
string (all 64 bits) | |
f.decimal({ precision, scale }) |
numeric |
string (exact) | |
f.boolean() |
bool |
boolean | |
f.date() |
date |
2026-10-08 |
a day with no time zone, shown as it is |
f.timestamp() |
timestamp, timestamptz |
ISO 8601 with offset | an instant, shown on the viewer’s clock, in their browser’s time zone, which hovering over it names |
f.uuid() |
uuid |
string | |
f.enum(['a', 'b']) |
Postgres enum, or text with a CHECK (... IN ...) |
one of the values | |
f.json() |
json, jsonb |
any JSON | nested at most 256 levels deep (each array or object is a level); a deeper value is refused |
f.relation('resource') |
the key column(s) of another resource | its key | .columns([...]) |
f.currency() |
text |
ISO 4217 code (EUR) |
|
f.country() |
text |
ISO 3166-1 alpha-2 code (NL) |
|
f.mailSender() |
text |
a From address the saver may send from ([email protected]) |
the form offers the saver’s addresses as a dropdown; see A From address on a record |
f.file() |
text |
{ uri, name, type, size, url }; written with a ticket from :upload |
.accept([...]), .maxSize(size), .public(), .storage(name), .derive({...}); see Files |
A constraint a type does not support (f.boolean().min(1)) throws when the config loads. The builders are the members of f.
Field options
Section titled “Field options”Every option returns a new field, so they chain in any order.
| Option | Effect |
|---|---|
.optional() |
The column is nullable; the value may be null. |
.readOnly() |
Never written through the API: ids, computed columns, audit timestamps. |
.default(value) |
The value a create uses when none is given; the admin’s create form shows it. |
.dbDefault() |
The database supplies a value when none is given (identity, now(), a sequence). |
.filterable() |
May appear in filter, in filter widgets and in Stat/Table filters. It needs an index: the API refuses a filter on a column no index serves (see the scan guard), and protobase doctor fails without one. |
.sortable() |
May appear in order_by and in sorts. It needs a btree index that serves it alone, as a filterable field does, since a list may be sorted by it. A list’s header of a field without it is no button and says “This column can’t be sorted” on hover and in its menu. |
.alias(...names) |
Other names filters may use for the field. |
.column('name') |
The column, when it is not the snake_case of the field name ('EMP_NAME'). |
.access({ read, create, update }) |
Role rules for this column. See Access. |
.sensitive() |
Hidden like a password: no response carries it, and a caller who may read it reveals one record’s value at a time. See Sensitive fields. |
.encrypted() |
Sensitive, and stored encrypted with the app’s own key, so the database only ever holds ciphertext. Text only. See Encrypted fields. |
.strongSignIn({ minutes }) |
Sensitive, and revealed only after a passkey or a second step in the last minutes (15 by default). See Recent strong sign-in. |
.ai({ prompt }) |
A job fills the field from prompt, {{field}} replaced by the record’s values, after a create and after an update of a field the prompt reads, as the user who wrote. Text or enum, optional. See AI fields and actions. |
.rollup({ from, via, fn, field }) |
The database keeps the field from the records of another resource: their count, sum, average, least or greatest value. Read-only. See Rollups and formulas. |
.formula(expression) |
The database computes the field from the record’s other number fields, as a generated column. Read-only. See Rollups and formulas. |
.lookup({ via, field, from? }) |
Shows a field of the record this one is linked to, read with the record. Read-only. See Lookups. |
The ERP’s products show most of them, together with soft delete and a tenant:
import { f, resource } from '@protobase/schema'import { erpAccess } from '../roles'
/** catalog.products. Unique: (organization_id, sku) */export const products = resource('products') .table('catalog.products') .fields({ id: f.bigint().readOnly().filterable().sortable().dbDefault(), organization_id: f.relation('organizations').filterable().sortable(), category_id: f.relation('categories').filterable().sortable(), sku: f.text().filterable().sortable(), name: f.text().filterable(), description: f.text().optional(), price: f.decimal({ precision: 12, scale: 2 }), currency_code: f.relation('currencies'), attributes: f.json().dbDefault(), active: f.boolean().default(true), deleted_at: f.timestamp().optional(), created_at: f.timestamp().readOnly().filterable().sortable().dbDefault(), updated_at: f.timestamp().readOnly().dbDefault(), }) .primaryKey((r) => r.id) .softDelete((r) => r.deleted_at) .tenant((r) => r.organization_id) .access(erpAccess('products'))Rollups and formulas
Section titled “Rollups and formulas”A rollup is a value of the other records that point at a record, such as an order’s total of its lines. A formula is a value computed from the record’s own fields, such as a line’s amount. Neither needs SQL: you declare the field, and protobase migration writes its column into the project’s next migration (NNN_computed.sql). Both are real columns, kept by the database in the transaction that writes, so they are right for writes from psql or other services too, and they filter and sort like any column once they have an index.
import { f, resource } from '@protobase/schema'
// An order's total and line count kept from its lines, and each line's amount computed from its own fields.
/** shop.orders: one row per order. */export const orders = resource('orders') .table('shop.orders') .fields({ id: f.integer().readOnly().filterable().sortable().dbDefault(), customer: f.text(), // The sum of its lines' amounts; 0 for an order without lines. total: f.decimal({ precision: 12, scale: 2 }).rollup({ from: 'order_lines', via: 'order_id', fn: 'sum', field: 'amount' }).filterable().sortable(), line_count: f.integer().rollup({ from: 'order_lines', via: 'order_id', fn: 'count' }), // The largest line; empty for an order without lines. largest_line: f.decimal({ precision: 12, scale: 2 }).optional().rollup({ from: 'order_lines', via: 'order_id', fn: 'max', field: 'amount' }), }) .primaryKey((r) => r.id)
/** shop.order_lines: what each order is for. */export const orderLines = resource('order_lines') .table('shop.order_lines') .fields({ id: f.integer().readOnly().filterable().dbDefault(), order_id: f.relation('orders').filterable(), quantity: f.integer().min(1), unit_price: f.decimal({ precision: 10, scale: 2 }), discount: f.decimal({ precision: 10, scale: 2 }).optional(), amount: f.decimal({ precision: 12, scale: 2 }).formula('round(quantity * unit_price - coalesce(discount, 0), 2)'), }) .primaryKey((r) => r.id).rollup({ from, via, fn, field }) reads the records of resource from whose relation field via points at the record. They are the records that are not soft deleted, when from has soft delete.
fn |
Value | Field |
|---|---|---|
count |
How many records there are; with field, how many have a value for it. 0 without records. |
f.integer() or f.bigint() |
sum |
The sum of field. 0 without records. |
a number field |
avg |
The average of field. Empty without records. |
f.decimal(), .optional() |
min, max |
The least or greatest value of field. Empty without records. |
a number field, .optional() |
Empty values of field are left out, as in SQL. The migration adds the column, a function in the rollups schema and a trigger on from’s table that sets the value after every insert, delete and update of the columns it reads, and then sets every record’s value once.
.formula(expression) is a Postgres generated column. The expression reads the record’s number fields, and takes numbers, + - * /, parentheses, coalesce(a, b, ...) and round(x) or round(x, digits). It is computed exactly as decimals, so 7 / 2 is 3.5, and is stored as the field’s type, so an integer field rounds the result. A formula that reads an optional field is .optional() too, unless coalesce() gives that field a value. A formula cannot read another formula. When the expression changes, the migration drops the column and adds it again, so an index on it must be created again in the same migration.
Neither field can be written through the API, have a default, or be sensitive, an AI field, a file, or the key, tenant, owner or soft delete field, and a formula cannot read a sensitive field. The server does not start while a declared column, function or trigger is missing or out of date, with a message that names the fields; the migration fixes that. It stops with an error, without writing anything, when the column already exists as the project’s own: a plain column where a formula is declared, a generated column it did not write, or a rollup column of another type.
Lookups
Section titled “Lookups”A lookup field shows a field of the record its record is linked to, such as an order’s customer name. It has no column of its own: the API reads it with the record, in the same query, from the linked table, so it always shows the linked record’s current value.
import { f, resource } from '@protobase/schema'
// Orders show their customer's name and tier through their own relation to the customer, and each customer the name// of their one account manager, whose record points at the customer.
/** shop.customers: one row per customer. */export const customers = resource('customers') .table('shop.customers') .fields({ id: f.integer().readOnly().filterable().sortable().dbDefault(), name: f.text().filterable().sortable(), tier: f.enum(['gold', 'silver', 'bronze']).filterable(), // From the one manager record whose customer_id is this customer; empty without one. manager_name: f.text().lookup({ from: 'account_managers', via: 'customer_id', field: 'name' }), }) .primaryKey((r) => r.id)
/** shop.account_managers: at most one per customer, by a unique index on customer_id. */export const accountManagers = resource('account_managers') .table('shop.account_managers') .fields({ id: f.integer().readOnly().filterable().dbDefault(), customer_id: f.relation('customers').filterable(), name: f.text(), }) .primaryKey((r) => r.id)
/** shop.orders: one row per order. */export const orders = resource('orders') .table('shop.orders') .fields({ id: f.integer().readOnly().filterable().sortable().dbDefault(), customer_id: f.relation('customers').filterable(), // The customer's name and tier, as the caller may read them; filtered and sorted as the customer's fields are. customer_name: f.text().lookup({ via: 'customer_id', field: 'name' }).filterable().sortable(), customer_tier: f.enum(['gold', 'silver', 'bronze']).lookup({ via: 'customer_id', field: 'tier' }).filterable(), }) .primaryKey((r) => r.id).lookup({ via, field }) reads field of the record that the record’s relation via points at. .lookup({ from, via, field }) reads it of the one record of resource from whose relation via points at the record, such as a customer’s account manager. That needs a unique index on via, which protobase doctor asks for, since a second such record makes every read of the field fail.
- It is declared with the linked field’s type, and for an enum its values. The server does not start while they differ, or while a resource or field it names is missing or the linked field is sensitive.
- It is read-only and optional: empty when there is no linked record, or none the caller may read.
- It shows in lists, record pages,
/metaand the API as any read-only field does, and the response of a write has it too. .filterable()and.sortable()take it when the linked field takes them. A filter on it keeps the records whose link is among the keys of the linked records that match, so it needs an index on the linked field in the linked table and one onviain this one; the scan guard and doctor ask for both, as for any other read. A sort by it needs them too.Sorting by a lookup field reads every record the list keeps before it returns a page, because no index orders one table by another table’s column. - It reads the linked records as the caller would: in their tenant, without soft-deleted ones, inside their row filter and the parents they read. A caller who may not read the linked resource, whose read rule there needs the record, or who may not read the linked field or the relation it goes through, does not have the lookup field at all: responses,
/meta, filters and sorts leave it out, as they leave out any field the caller may not read. Its own.access({ read })narrows that further. - It is not stored with the record, so the record’s ETag, events, history and the filters of access rules do not see it, and it cannot be a key, tenant, owner, author, soft delete, position, parent, link or search field, or have a column, a default, a rollup, a formula or an AI prompt.
Time rollups
Section titled “Time rollups”A large events table, such as millions of meter readings, gets a time rollup: a table with one row per hour or day and per group, holding how many records fell in it and the sums and greatest values of their numbers. A chart over months then reads a few thousand rows instead of millions. You declare the rollup as a resource over the events resource, and protobase migration writes its table, indexes and refresh function into the project’s next migration (NNN_computed.sql), with the rollup filled once. From then on the app keeps it up to date by itself, at most a minute behind. It is plain Postgres: no extension.
import { f, resource } from '@protobase/schema'
// Meter readings, millions of rows, and their hourly rollup per organization and meter.
/** metering.readings: one row per reading. */export const readings = resource('readings') .table('metering.readings') .fields({ id: f.bigint().readOnly().dbDefault(), organization_id: f.integer().filterable(), meter_id: f.relation('meters').filterable(), taken_at: f.timestamp().filterable().sortable(), watts: f.integer(), cost: f.decimal({ precision: 10, scale: 4 }), }) .primaryKey((r) => r.id) .tenant((r) => r.organization_id)
/** metering.readings_hourly: one row per hour, organization and meter, which the migration creates. */export const readingsHourly = resource('readings_hourly') .table('metering.readings_hourly') .bucketsOf(readings, { time: (r) => r.taken_at, every: 'hour', by: (r) => [r.organization_id, r.meter_id], measures: { watts: ['sum', 'max'], cost: ['sum'] }, late: '2 hours', }) // Its access is its own: every member of an organization reads its totals. .access({ read: () => true }).bucketsOf(source, { ... }) takes the source’s resource and sets the rollup’s fields, key and tenant from it:
| Option | What it is |
|---|---|
time |
The source’s timestamp field. A record’s bucket is its hour or day, in UTC. |
every |
'hour' or 'day'. |
by |
The source’s fields to group by besides the bucket. They must be required fields, and include the source’s tenant field. |
measures |
Per integer, bigint or decimal field of the source, ['sum'], ['max'] or both. Optional. |
late |
How late a record may arrive and still be counted by a refresh: a number of minutes, hours or days, such as '2 hours'. |
The rollup’s records have these fields, all read-only:
| Field | Value |
|---|---|
id |
The record’s key, a bigint. |
bucket |
The start of the hour or day. Filterable and sortable. |
the by fields |
The group’s values, under the source’s field names. Filterable and sortable. |
events |
How many records of the source fell in the bucket, as a bigint. |
<field>_sum |
The sum of the field: a bigint for an integer, a decimal of ten more digits for a bigint or a decimal. Empty when every value was. |
<field>_max |
The greatest value of the field, of its type. Empty when every value was. |
<field>_count |
How many records of the bucket have a value of the field, as a bigint, for every field in measures. |
Records the source soft deleted are left out. The migration creates the table in the rollup’s schema, with a unique index on (bucket, by...) and an index on (group, bucket) per group, so a list filtered on the bucket, on a group or on both passes the scan guard. It writes rollups.<table>_refresh(from timestamptz), which recomputes every bucket from the one from falls in, in one statement: it upserts their counts, sums and greatest values and deletes those left without records. When the rollup’s declaration changes, the migration drops its table and creates and fills it again. The table and function of a rollup the config no longer has stay; a migration of your own drops them, in a deploy after the one that stops reading them.
Only the database writes a rollup’s rows: creates, updates and deletes are refused whatever its rules say, and it cannot have soft delete, a manual order, an author, a parent or .openExisting(). Its access is its own .access(): the source’s rules do not reach it, so give it rules that let read only those who may see every record of a group. Its tenant is the source’s, which is why by includes it. A field that is sensitive or has its own read rule, such as .access({ read: roles.can('costs.read') }), cannot be grouped by or measured, and one with its own read rule cannot be the rollup’s time, since a bucket would show it to anyone who reads the rollup. The server does not start while the source has its own read or list rule in .access(), whatever the rule returns, or while a role reads only some of the source’s records that a bucket mixes with others: .own or .team while by does not include the source’s owner field, or a role’s filter on fields outside by. read or list access rule because declaring the fields such a rule filters on is not implemented.
Keeping it up to date
Section titled “Keeping it up to date”The app’s jobs keep every time rollup up to date: a built-in recurring job, buckets.refresh, runs every minute and calls each rollup’s refresh function from late before now, one query per rollup, such as select rollups.readings_hourly_refresh(now() - interval '2 hours') for the example. So the buckets from that time on take in the records added, changed and deleted since, and a dashboard on the rollup is at most a minute behind, while one run only reads the source’s records of the last late. A failed run is not retried, as the next minute’s run recomputes the same buckets; it is listed on the Failed jobs page. A time rollup turns jobs on, so protobase migration writes the jobs schema too, and the rollup is refreshed wherever the app runs its jobs, such as protobase serve or a protobase worker.
A record that arrives, or changes, later than late after its time, such as one imported from an older history, is counted only by a refresh from before it: protobase buckets rebuild recounts a rollup from an earlier time, such as protobase buckets rebuild readings_hourly --from 2026-07-01, which recomputes every bucket from that day’s first hour in one statement, or every bucket without --from.
The server does not start while a rollup’s table or function is missing or out of date, with a message that names the rollup; the migration fixes that. It stops with an error, without writing anything, when the table already exists as the project’s own.
Charts over a rollup
Section titled “Charts over a rollup”A Chart, :aggregate and :series read a rollup as they read any resource, and give the counts, sums, averages and maxima the source’s records give over the same buckets. Group by bucket for a chart over time, or by a by field. A group’s count is the records its buckets hold, and a measure names the rollup’s field that keeps it:
| Over the source | Over the rollup |
|---|---|
| The count | The count, or sum=events |
sum=watts |
sum=watts_sum |
average=watts |
average=watts_sum: the sum divided by the records with a value, watts_count, not an average of hourly averages; empty when no record has one |
maximum=watts |
maximum=watts_max |
Any other measure, such as average=watts_max or sum of a by field, is refused with 400 invalid-option, and so is what the buckets cannot tell apart:
- A granularity finer than the bucket, such as
15_minuteson an hourly rollup orhouron a daily one. - For an hourly rollup, a
time_zonewhose hours or days start inside a UTC hour over the range, such asAsia/Kolkata. Zones a whole number of hours off UTC, such asEurope/Amsterdam, give their own days, weeks and months. - For a daily rollup, any
time_zonebutUTC. A chart asks for the viewer’s time zone, so a chart on a daily rollup answers only to viewers in UTC; chart an hourly rollup for the others.
A bucket counts when its start is inside the range, so a range that starts inside an hour or day counts from the next one. Facets and histograms of a rollup count its rows, as for any resource. This dashboard charts the example’s readings over 90 days from the hourly rollup:
/** @jsxImportSource @protobase/layout */import { Chart, Grid, Page, page } from '@protobase/layout'
// A dashboard over the hourly rollup: each chart reads a few thousand buckets instead of millions of readings.export const energy = page( 'energy', <Page title="Energy" description="The last 90 days of every meter."> <Grid columns={2}> <Chart title="Readings per day" resource="readings_hourly" groupBy="bucket" range="90d" /> <Chart title="Average watts per day" resource="readings_hourly" groupBy="bucket" average="watts_sum" range="90d" type="line" /> <Chart title="Cost per week by meter" resource="readings_hourly" groupBy="bucket" splitBy="meter_id" sum="cost_sum" granularity="week" range="90d" /> <Chart title="Cost per meter" resource="readings_hourly" groupBy="meter_id" sum="cost_sum" filter="bucket >= now() - 90d" limit={5} /> </Grid> </Page>,)Sensitive fields
Section titled “Sensitive fields”A sensitive field, such as a bank account number, is written like any other field but never read with the record: lists, gets, :search, :seek, create and update responses and batch results leave it out, and it cannot be filtered, sorted, searched, counted or picked with fields. The record page shows it masked, with an eye button. Showing it asks the server for that one value with POST /{resource}/{key}:reveal (see REST API), which needs the same access as reading the record and the field, inside the caller’s tenant, and publishes an audit event before it answers.
iban: f.text().sensitive().access({ read: roles.can('screening.read') }),A role may also set a sensitive field it cannot read, such as a sealed value only a worker reads, when the field’s own create or update rule allows it: see write-only fields.
A sensitive field cannot be .filterable(), .sortable(), aliased, searched, or the key, tenant, owner or soft delete field, and a view may only put it in a record page section: in a list, filter, chart, sidebar, title, recent-record group or action it would always be empty, so the config fails to load.
A webhook subscription delivering as a role runs that role’s access rules on a captured change, which holds no sensitive field. A rule or row filter that reads one there throws, and the change is kept as failed for that subscription instead of delivered, so decide that access on a field that is not sensitive. A rule that reads the field before it checks the role, such as record.api_secret == null || ctx.user.roles.includes('admin'), fails even for as: { roles: ['admin'] }: check the role first, as in ctx.user.roles.includes('admin') || ....
Recent strong sign-in
Section titled “Recent strong sign-in”A field such as a recovery code or an API secret can ask for more than read access: .strongSignIn() reveals it only to someone whose sign-in proved a passkey or a second step in the last 15 minutes, or minutes you give; an account with neither confirms with an emailed code instead. It is sensitive too, so all of the above applies, and /meta marks it strongSignIn: { minutes }.
recoveryCode: f.text().encrypted().strongSignIn({ minutes: 10 }),Without such a sign-in, the reveal is refused with 403 strong-sign-in-required and the number of minutes, before anything is decrypted or audited. The record page then asks the person to confirm it’s them, with a passkey or the code of their authenticator app, whichever their account has, and shows the value once they did. A passkey sign-in counts, as does a password or emailed code followed by the second step; confirming later counts from then. Staff signed in as someone and an outside app acting as them, such as an MCP client, never count: they proved nothing as the person. See Recent strong sign-in for how the server knows.
Computed reveals
Section titled “Computed reveals”Some secrets are not in the app’s database, such as an API key another service keeps, or are built from several values, such as a file of settings. .reveals() names values revealed like a sensitive field but made when one is asked for:
resource('apps') // ...fields, key and tenant .reveals({ env: { value: (app, caller) => secrets.envFile(app.id), read: roles.is('owner'), strongSignIn: { minutes: 15 }, }, })POST /apps/{key}:reveal with { "field": "env" } reads the record as a get does, inside the caller’s tenant, row filter and record rules, so a record they cannot read is a 404. value gets the record with every field the caller may read but the sensitive ones, and the caller’s user and organization; its answer is the value, null when it returns nothing. read is a role rule like a field’s own read rule, and a caller it leaves out gets 400 as for an unknown field. strongSignIn asks for a recent strong sign-in, 15 minutes when it names no minutes. Each reveal publishes the same audit event as a field’s, with the reveal’s name as field, before the value is returned. A reveal cannot have the name of a field of its resource.
Encrypted fields
Section titled “Encrypted fields”An encrypted field is a sensitive field whose value the server encrypts before it reaches the database, so a dump, a backup, a replica, a realtime subscriber or anyone running SQL sees only ciphertext. Only its reveal decrypts it, for a caller who may read the record and the field, and your own jobs and functions on the server; every read is audited. Every API write encrypts it: the record form, REST, batches, imports, public forms and records in API functions. The Supabase-compatible REST API refuses to write or filter it.
api_key: f.text().encrypted().access({ read: roles.can('keys.read') }),It takes f.text() only, and cannot be .readOnly() or have a .dbDefault(). Its column must be text, with no length, pattern or unique constraint, index, default, trigger or generated column reading it: the database only ever sees ciphertext.
Write it only through the API. SQL of your own, in an API function’s db, a write hook’s transaction or the assistant’s approved changes, stores the value unencrypted, and its reveal then fails until protobase encryption apply encrypts it.
Your code never sees the stored value, only whether it is set. Access rules cannot filter on it: a rule that returns a filter on it fails the request. Record rules, validators and write hooks get a stored record with a set value as encrypted (exported from @protobase/schema) and an empty one as null. Check whether it is set with == null; the marker is never equal to anything, so a rule comparing it with a constant decides as if it held another value, and reading it as text throws. A webhook subscription’s access check cannot know whether it is set, as for every sensitive field. Rules and validators see the plaintext only where a write gives it, so a validator written this way checks each value written and leaves a stored one alone:
.validate((r) => (typeof r.iban === 'string' && !r.iban.startsWith('NL') ? [{ field: 'iban', message: 'A Dutch IBAN' }] : undefined))When you change a .sensitive() field to .encrypted(), change every rule, validator and hook that reads its stored value: from then on it gets encrypted, and TypeScript flags reading it as text.
No other field of the resource may be over the column, as its own or as a relation’s column, and another resource over the same table must leave the column out, or declare it .encrypted() too with the same .table(), tenant and key; the server does not start otherwise. A resource over a view of the table cannot be checked, so leave the column out of the view itself, not only out of the resource.
Reading in jobs and functions
Section titled “Reading in jobs and functions”A value the app must use itself, such as the password of a backup share, is read on the server with decryptField(resource, key, field) of a job’s context and of a protected API function’s:
const password = await context.decryptField('backup_targets', target.id, 'password')It returns the cleartext, or null when the field is empty. Like the context’s db, it skips access rules, row filters and tenant scope, and reads only live records. key is the record’s key, or its parts in the order of a composite key. A resource that is unknown, a field that does not exist or is not .encrypted(), and a record that does not exist are errors that name them, as is a value that does not decrypt.
Every read publishes a field.revealed audit event, whose reader names the job ({ job }, with no actor) or the function ({ function }, with its caller as actor), and the value is only returned once the event is published: when publishing fails, so does the read. A public function has no decryptField, since anyone may call it: enqueue a job that reads the value instead. No HTTP request reaches it.
The key
Section titled “The key”The app’s key is PROTOBASE_ENCRYPTION_KEY: 32 random bytes in base64, such as the output of openssl rand -base64 32. It is its own: never the app’s secret (PROTOBASE_SECRET) or an API key, nor derived from one, so rotating those loses nothing. Keep it apart from the database’s backups, since whoever holds both reads every value. The server does not start with an encrypted field and no key, or a key that is not 32 bytes in base64.
To rotate it on several instances:
- Add the new key to
PROTOBASE_ENCRYPTION_PREVIOUS_KEYS(comma separated) everywhere, so every instance can read what it seals. - Make the new key
PROTOBASE_ENCRYPTION_KEY, with the old one inPROTOBASE_ENCRYPTION_PREVIOUS_KEYS. - Run
protobase encryption apply, which encrypts the old key’s values with the new one. - Drop the old key once
protobase encryption statusshows none of its values. Keep retired keys as long as you keep backups made under them.
A lost key loses its values. Nothing can decrypt them; status lists them as unknown-key, and writing a new value replaces one. apply refuses to run while a column holds values under none of its keys, so a wrong key in a local .env does not seal values the app cannot read; clear values whose key is lost (set them to null with SQL) to go on.
.encrypted() on a field while its column holds encrypted values; status reports encrypted values in a field that is not encrypted.
What a value is bound to
Section titled “What a value is bound to”A value opens only where it was sealed: its table as .table() names it (with or without the schema), its column, its record’s tenant and its record’s key. Copying it to another row, column or tenant makes it unreadable rather than readable there.
- Renaming the resource or the field in the config changes nothing.
- Renaming the table or the column, moving the table to another schema, or adding or changing the schema in
.table()makes the field’s values unreadable untilprotobase encryption apply --rebind people --from-table <old table>(or--rebind people.iban --from-column <old column>) runs. Run it at update time, like a migration; reveals fail until then. - Changing a resource’s declared key or tenant field makes its values unreadable.
No command rebinds encrypted values after a change of a resource’s key or tenant field. Make such a change before encrypting. - The record key must be unique in its table, as
protobase doctorchecks, or at least within each tenant. A key changed in the database, by SQL, a trigger or a foreign keyon update cascade(whichstatuswarns about), makes that row’s values unreadable; the API refuses to change the key of a record with encrypted fields.
Encrypting an existing column
Section titled “Encrypting an existing column”- With events, history or live updates on the resource,
protobase migrationwrites the change of its capture trigger; apply it with your other migrations. - At update time, before the new version serves, run
protobase encryption apply. It encrypts every plaintext value and removes the field’s old values from the history and from the changes not yet dispatched. - With a rolling deploy, the old version writes plaintext until it stops: run
applyagain once the new version serves alone, and gate onprotobase encryption status, which exits with 1 while anything is left. Until then, reveals of plaintext values fail.
Do not import ciphertext from elsewhere, such as another database’s column encryption, into the column: apply would encrypt it as if it were plaintext. Export it decrypted instead.
What a move leaves behind: webhooks already sent carried the old values to their receivers, and webhook jobs keep their event, with the old values, in the jobs schema, a finished one for 7 days and a waiting one up to 14 days, so a backup made within a week of the move still holds them. Assistant conversations that showed the column keep what they showed. Older backups, the write-ahead log, replicas and the Postgres logs keep the old plaintext.
What it protects against
Section titled “What it protects against”It protects the values from database dumps, backups, replicas, and readers of raw SQL and realtime changes, who see only ciphertext. It does not protect them from whoever holds the key or the app’s environment, or can run code in the server. Someone who can write to the database can change a row’s tenant or roles, or put back an older value of the same record and field, from a backup say, which still opens. The ciphertext shows whether a value is empty, its length and when it changed. A key seals at most about 2³² values safely, as each gets a random IV; rotating starts a new key’s count.
Preparing a record
Section titled “Preparing a record”Some values only the server may make, such as a generated key, a random identifier or a name written the one way the table accepts. .prepare() fills them in or rewrites them before the record is written, on every create and update: through the REST API, a batch write, the MCP tools, a public form and the assistant alike. It gets the values as the field checks and .validate() rules accepted them, and returns the values to write:
import { randomBytes } from 'node:crypto'import { domainToASCII } from 'node:url'import { f, FieldIssue, resource } from '@protobase/schema'
export const api_tokens = resource('api_tokens') .table('api_tokens') .fields({ id: f.integer().readOnly().dbDefault(), domain: f.text(), // not null, and no request may write it token: f.text().readOnly(), }) .primaryKey((r) => r.id) .prepare((values, { operation }) => { // Bücher.de. is stored as xn--bcher-kva.de, as a check (domain = lower(domain)) wants const domain = values.domain === undefined ? {} : { domain: domainToASCII(values.domain.replace(/\.$/, '')) } if (domain.domain === '') throw new FieldIssue('domain', 'Not a domain name') return operation === 'create' ? { ...values, ...domain, token: randomBytes(24).toString('base64url') } : { ...values, ...domain } })- A field it fills stays
.readOnly(): a request that sends it is refused as read-only, and the hook sets it anyway, so anot nullcolumn the server makes can be created through the standardPOST. - Its second argument holds the
operation('create'or'update'), theuser, thesessionand thetenantthe write works in,before, the stored record an update changes, andtrx, the write’s transaction (Kysely): what the hook reads or writes there commits with the record, or not at all. - It runs after the field checks and
.validate()rules, which then check the record it returns again (400when one refuses it), and before the access rules decide on the record and the row is written; the write hooks run after the row is written, in the same transaction. - Throwing a
FieldIssuerefuses the write with422anderrors: [{ field, code: 'invalid-value', message }], the field named when the caller reads or writes it and_recordotherwise; anything else it throws rolls the write back as a server error. - It may not set the tenant column or the
.author()field, which only the server sets from the caller, nor a name that is not one of the resource’s fields: the write then fails as a server error that names it. - Each call adds a hook, run in order, each with the values the one before returned.
- The PostgREST-compatible API writes the tables under their own grants and policies rather than through the resources, so the hook does not run there: a table it writes takes such a value from a default or a trigger.
- It does database and CPU work only, such as generating a key pair. While it waits on anything else, such as an HTTP call, the transaction stays open; work that needs the network belongs in a job a write hook enqueues.
Opening an existing record
Section titled “Opening an existing record”A resource whose records are unique by some of their values, such as a direct message by its members, can have a create that repeats those values open the record that holds them instead of failing. .openExisting() names the unique key, as its fields:
resource('direct_messages') .table('direct_messages') .fields({ id: f.integer().readOnly().dbDefault(), organization_id: f.relation('organizations'), member_ids: f.json(), // generated always as (...) stored: the members sorted, without repeats member_key: f.text().readOnly(), }) .primaryKey((r) => r.id) .tenant((r) => r.organization_id) .openExisting((r) => [r.organization_id, r.member_key])- The fields are exactly the columns of a unique index or constraint that covers every row, in any order, such as
unique (organization_id, member_key); a column the database generates counts. A create that conflicts on another unique key answers as without the option. Without such an index every create of the resource fails with a server error naming it, andprotobase doctorreports it. - A create that conflicts on the key answers the
409conflictany unique violation answers, withexisting: { key }, the key of the record holding those values, but only when the caller may read that record: in their tenant, inside their row filter and the parents they read, and passing a record-level read rule, as aGETof it checks. Otherwise the answer is the same plain409, so it never tells anyone that a record they cannot see exists. A soft-deleted record counts as one they cannot read. - The create finds the record with
insert ... on conflict (...) do update ... wherea condition that only notes its key and is false, so nothing is updated and no update trigger runs, but the app’s database role needs the update privilege on the table, as for anyon conflict do update. - Two creates of the same values at the same moment both end on one record: the second waits for the first and then answers with its key.
- The create form then opens that record instead of saying it could not save.
- An encrypted or file field cannot be part of the key: the API stores those as values that never match another record’s.
Checks the database makes
Section titled “Checks the database makes”A rule the database keeps, such as a task that waits for a day staying parked, refuses a write with a check violation. The API leaves the database’s own message out, since it can name values the caller may not see, so by default the refusal says only that a check constraint rejected the record. .checks() names the checks whose refusal the app can explain, each by its constraint name, with a label:
resource('tasks') .table('tasks') .fields({ id: f.integer().readOnly().dbDefault(), title: f.text(), lane: f.enum(['parked', 'queued']), waits_until: f.timestamp().optional() }) .primaryKey((r) => r.id) .checks({ tasks_parked_by_hand: { label: '{title} waits for a day, so it stays parked.' } })The name is a CHECK constraint’s, or one a trigger gives with Postgres’s own fields: using errcode = 'check_violation', constraint = '<name>'. Its message is for the database’s logs and never leaves the server:
create function tasks_lane_check() returns trigger language plpgsql as $$begin if new.lane = 'queued' and new.waits_until > now() then raise exception 'Task % waits until %', new.id, new.waits_until using errcode = 'check_violation', constraint = 'tasks_parked_by_hand'; end if; return new;end $$;- A write the check refuses is a
400invalid-recordwhose one error is{ field: '_record', code: '<name>', message: '<label>' }, built from the config alone: nothing of the database’s message, detail or hint. A batch names the operation, as for any refusal. - The label is an ICU message whose
{field}values the admin app fills from the record it shows, such as the card dropped on a board, never from the database. Each value must be a field of the resource, or the server does not start. It is translated asresources.<resource>.checks.<name>.labelin the app’s texts. - A name is declared once across the app, since the error names only the check: a second resource declaring it stops the server at startup. A name cannot be one of the API’s own error codes, such as
required, and is at most 63 bytes, the most of a name Postgres keeps. - A check violation naming a check no resource declares keeps the generic refusal, and the server logs a warning with its name only. A plain
raise exceptionwithout these fields is an unexpected error, a500, reported to the app’s error hook.
Keys and relations
Section titled “Keys and relations”A key of several columns is a list, and a record’s address joins its parts with a comma (/stock/CHAIN-11,L). A relation to such a resource names its columns, in the order of that key:
import { f, resource } from '@protobase/schema'
// Keys of more than one column, and a relation that points at one.
/** shop.stock: one row per part and size. */export const stock = resource('stock') .table('shop.stock') .fields({ part_no: f.text().filterable().sortable(), size: f.text().filterable().sortable(), on_hand: f.integer().min(0), }) .primaryKey((r) => [r.part_no, r.size])
/** shop.part_orders: parts ordered from suppliers. */export const partOrders = resource('part_orders') .table('shop.part_orders') .fields({ id: f.uuid().readOnly().filterable().dbDefault(), // Two columns hold the key of one stock row, in the order of its primary key. part: f.relation('stock').columns(['part_no', 'part_size']), quantity: f.integer().min(1).max(50), // Filters may say `ref` as well as `supplier_reference`. supplier_reference: f.text().alias('ref').filterable(), ordered_at: f.timestamp().readOnly().filterable().sortable().dbDefault(), }) .primaryKey((r) => r.id)A relation’s value in the API is the other record’s key. The admin shows the other record’s name instead (its view’s title, else a field such as name or number) and links to it. The create form and the record’s form pick it from a list, with a link beside it on the record’s form; a relation the user may not change, the record’s own key and a relation to a record with a key of several columns stay links.
Schema API reference
Section titled “Schema API reference”Every builder, option and type that @protobase/schema exports has a doc comment, which your editor shows as you write a config, and the schema API reference lists them with their types. The types the builders return, such as ResourceBuilder, Field and RecordOf, are exported, so a helper of your own that takes or returns them is typed too.
Access
Section titled “Access”Without rules everyone who can sign in may do everything. Rules come in three kinds, and the Access reference explains the defaults:
- Per operation (
list,read,create,update,delete):.access({ update: rule }). A rule returnstrue,false, or an AIP-160 filter that limits the rows, like row-level security. A rule that reads the record (record.status) is checked against the stored row on a get and a write; a caller it reads the record for may not list, so a rule that should list is a filter. See Rules that read the record. - Per row: a filter from a rule, or a
.ownor.teamcapability with.owner(...):.owngives the records whose owner is the user,.teamthose owned by the users thatdefineRoles(roles, { teamOf: (user) => ids })returns for them. - Per field:
.access({ read, create, update })on the field. Field rules see only the user, never a record, so the fields a user can read are the same for every row.
defineRoles turns roles into capabilities (work_orders.update.own, money.read, *), and roles.can(...) and roles.is(...) make rules of them; .and() and .or() combine rules.
import { defineRoles, f, resource } from '@protobase/schema'
// Access for the bike shop's work orders: who may do what, which rows they see, and which fields.
/** Roles are bundles of capabilities: `<resource or area>.<action>[.own]`, `*` for everything. */export const roles = defineRoles({ admin: ['*'], desk: ['work_orders.read', 'work_orders.create', 'work_orders.update', 'money.read'], mechanic: ['work_orders.read.own', 'work_orders.update.own'],})
/** shop.work_orders */export const workOrders = resource('work_orders') .table('shop.work_orders') .fields({ id: f.integer().readOnly().filterable().sortable().dbDefault(), assignee: f.text().filterable(), task: f.text(), status: f.enum(['open', 'done']).default('open').filterable(), // Only roles holding `money.read` see the price of the labour; only an admin may change it. labour: f.decimal({ precision: 8, scale: 2 }).access({ read: roles.can('money.read'), update: roles.is('admin') }), }) .primaryKey((r) => r.id) // `.own` capabilities match the rows whose assignee is the signed-in user's id. .owner((r) => r.assignee) .access({ read: roles.can('work_orders.read'), create: roles.can('work_orders.create'), // A finished work order is closed: this rule needs the record, so it is checked against the stored row. update: roles.can('work_orders.update').and((_ctx, record) => (record as { status: string }).status !== 'done'), delete: roles.is('admin'), })Export the roles as roles from config/roles.ts, where the server finds them, and every operation without a rule needs its capability (<resource>.<action>). The ERP’s orders use .owner and .search with the ERP’s roles:
import { f, resource } from '@protobase/schema'import { erpAccess } from '../roles'
/** sales.orders. Unique: (organization_id, number) */export const orders = resource('orders') .table('sales.orders') .fields({ id: f.uuid().readOnly().filterable().sortable().dbDefault(), organization_id: f.relation('organizations').filterable().sortable(), number: f.text().filterable().sortable(), company_id: f.relation('companies').filterable().sortable(), person_id: f.relation('people').optional().filterable().sortable(), owner_id: f.relation('users').filterable().sortable(), status: f.enum(['draft', 'confirmed', 'picking', 'shipped', 'delivered', 'cancelled']).filterable().sortable(), currency_code: f.relation('currencies'), discount_percent: f.decimal({ precision: 5, scale: 2 }).default('0'), total: f.decimal({ precision: 14, scale: 2 }).readOnly().default('0').filterable().sortable(), paid: f.boolean().default(false).filterable().sortable(), notes: f.text().optional(), created_at: f.timestamp().readOnly().filterable().sortable().dbDefault(), updated_at: f.timestamp().readOnly().dbDefault(), }) .primaryKey((r) => r.id) .tenant((r) => r.organization_id) .owner((r) => r.owner_id) .search((r) => [r.number]) .access(erpAccess('orders'))The UI side of a resource, its names, columns, filters and record page, is in UI config.