Approvals
Approval requests with steps per subject type and action, approvers by permission, role, team, user or the requester's manager, tenant policies that tighten the configured ones, confirm or authorize modes, single-use approvals bound to a request fingerprint, delegation, expiry and reminders.
approvals files a request for an action on a subject (send an invoice, publish a page), asks each step's approvers in turn, and runs what the policy unlocks once the last step is approved. Requests snapshot their policy, so a config change leaves pending requests alone. Filing a request needs approvals.request and read access to the subject, reading other people's requests needs approvals.read, and cancelling someone else's request needs approvals.manage. Who may decide a step comes from the policy, not from a permission key.
With the drive installed, requests on drive_node follow the node's grants: listing them needs read access to the node, and filing one needs write access. drive.requestApproval files them for one revision of a file.
better-supabase add approvalsServer code calls the approvals instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useApprovals } = defineDataHooks(
"approvals",
(db: AppDb) => db.approvals,
);import { createApprovals } from "better-supabase/blocks/approvals";
const invoice = { type: "invoice", id: invoiceId };
const request = await db.approvals
.request(invoice, { action: "send", reason: "Q3 invoice" })
.orThrow();
const waiting = await db.approvals.list({ assigned: true }).orThrow();
const onInvoice = await db.approvals
.list({ subject: invoice, status: null })
.orThrow();
await db.approvals.approve(request.id, "Looks right").orThrow();"use client";
import { useApprovals } from "@/lib/supabase/hooks";
const rows = useApprovals({ limit: 50 });request(subject, input) takes the subject as a RecordRef ({ type, id }), and request and list act in the block's tenant, an organization id or a function that returns the current one. createBlocks and createBlockClient pass the request's tenant; a call without one fails with invalid_request and the hint TENANT_REQUIRED. Each request carries subject and organizationId.
Configure policies
options.policies maps a subject type, then an action, to its steps. The subject type comes from config.recordTypes, which decides who can read the subject.
blocks: {
approvals: {
options: {
policies: {
invoice: {
send: {
steps: [
{ approvers: { permission: "invoices.approve" }, required: 2 },
{ approvers: { users: ["8b0f6c1e-0000-4000-8000-000000000001"] }, required: "all" },
],
expiresIn: "P7D",
run: { transition: "sent" },
},
},
},
},
},
},| Option | Default | What it does |
|---|---|---|
steps[].approvers | none | permission, role (membership role), team (a teams id), users, manager: true or decider: true; any match may decide |
steps[].required | 1 | Approvals the step needs; "all" with users means every listed user, and with only permission every holder of it when the request is filed |
steps[].escalateAfter, steps[].escalateTo | none | After the step waited this ISO 8601 duration, escalate_approvals() lets the escalateTo approvers decide it too |
effects | none | Tags such as money-movement that tenant and platform policies match on |
expiresIn | none | An ISO 8601 duration such as P7D; expire_approvals() closes the request after it |
selfApproval | false | Whether the requester may decide a step |
mode | "authorize" | "confirm" lets the requester approve their own request as a second look; see confirm or authorize |
run | none | { transition: "<status>" } through the state machine, or { queue: "<queue>" } through jobs |
A subject can have one pending request per action (APPROVAL_PENDING). The subject types that leave, expenses and time tracking file themselves (leave_request, expense, timesheet) are refused from request_approval for anyone but the service role (APPROVAL_SUBJECT_BLOCK_FILED), and those blocks only act on a decision of the request their own row points at. A rejection on any step closes the request. An approver decides a step once, and delegate(id, userId) hands their place on the step to another member of the organization, who is then asked.
An action name may have dotted segments, such as quote.send or access.member.role.update, so an action catalog keeps its own keys. A floor under the action "*" covers every action of its subject type that has no floor of its own, such as every tool an AI agent can call. A floor under the subject type "*" holds an action for every subject type, so one floor covers quote.send whether it is filed on a chat thread, an MCP client or a workflow run. The most specific floor wins: the subject type and action, then the subject type's "*", then the action under "*", then "*" under "*".
policies: {
"*": {
"quote.send": { steps: [], effects: ["money-movement"] },
},
},With required: "all" and only approvers.permission, the request asks every holder of the permission in the organization (the requester only with selfApproval), resolved to users when it is filed; nobody holding it fails with APPROVAL_APPROVERS_EMPTY. It needs an access model that lists holders (the roles or catalog model, or a provider or custom model with holdersOf).
A required: "all" step completes once each listed user has approved, either themselves or through a delegate they handed their place to. Approvals by anyone else don't count toward it, so a delegate's approval stands in for the user who delegated and never for another listed user. After the step escalates, the fallback approvers' approvals count toward the number of listed users instead.
Policies are fixed per subject type and action. To pick one by the record's values, such as the finance chain for an expense over 500, give each chain its own action and let a tenant-edited rule choose it: approvalsAction from better-supabase/blocks/automations files the request for the action in the matching rule's config.action.
Declare floors as rows
A floor can be an approval_floor row in supabase/rows/approvals.sql. The subject and the key are
<subjectType>:<action>, with * for either part, and the value is the policy the request
snapshots (steps, selfApproval, expiresIn, run, mode, effects). The most specific
declared row wins (the exact pair, then <subjectType>:*, then *:<action>, then *:*), and a
declared row beats the same floor in options.policies. better-supabase db rows writes the data
migration, and better-supabase codemod declared-rows moves the floors you already have.
Confirm or authorize
A policy's mode says what an approval proves. authorize, the default, means someone other than the requester decided every step (unless selfApproval is on). confirm means the requester looked again: they may approve their own request, and their approval finishes it at once, whatever steps remain. Other approvers still decide the steps as usual. Use confirm for a deliberate second click before a risky action, and authorize when another person has to agree.
steps[].approvers.manager: true lets the requester's manager decide the step, or the manager of the employee a request's policy names in managerOf (the leave, time tracking and expenses integrations set it to the request's employee). The manager comes from the employees block: the requester's employee record names a manager, whose user decides while they are an active member of the organization and not offboarded. The offboarded check reads the employees block's values.employees.status mapping, so a manager whose row holds the app's mapped value (for example ended) decides nothing. A policy that names a manager needs the employees block in managed mode.
steps[].approvers.decider: true lets the block that files the request decide who else may approve the step, such as the app function in options.decider of the leave, time tracking and expenses blocks. The function takes the request's subject id and answers for the caller. A subject type whose block names no decider matches nobody, so a tenant policy can only turn a configured decider on or off, never name a function. The selfDecideWhenTopOfChain option of the leave and expenses blocks also lets a requester who holds the approve permission approve their own request without selfApproval when they have no active manager up their reporting chain or nobody else can decide it.
A module that files a request through open_approval may add excludedUserIds, a list of user ids, to the policy snapshot. Those users are left out of deciding the request like the requester: approval_eligible and the queue (approval_eligible_ids, page_approvals) skip them, a step with required: "all" doesn't ask them, the request notifications leave them out, and their decision, also one the service role makes for them, fails with APPROVAL_FORBIDDEN. Expenses list an expense's creator there. It needs the policy column on the requests table.
Tenant policies
With options.tenantPolicies: true, each organization keeps its own policies in the approval_policies table, and the configured policies act as the platform's floor. A tenant policy names the subject type and action of a configured policy (APPROVAL_POLICY_UNKNOWN otherwise) and can only tighten it:
- its steps run after the floor's steps and those of earlier tenant policies;
authorizeoutranksconfirm, andconfirmoutranks a floor that asks for nothing;selfApprovalstays on only when every matching policy allows it;- the shortest
expiresInwins.
A floor with steps: [] asks for nothing until a tenant policy adds a step or a mode, so an organization can opt into approvals for an action the platform leaves open. Without tenantPolicies, a floor needs at least one step or mode: "confirm".
conditions is a filter tree over the subject type's rule fields, matched against the request's payload. A policy without conditions always applies. Conditions need the automations block; without it, saving a policy with conditions fails with APPROVAL_CONDITIONS_UNSUPPORTED. With options.conditions: "payload", the block matches the tree itself against the payload by each rule's path, without automations or rule fields: numbers compare as numbers, everything else as text, with the operators of the filter tree (is, gt, between, is_any_of, contains, has_any_of and the rest). An unknown operator fails with APPROVAL_CONDITIONS_INVALID. Put what a condition needs, such as actorKind or amount, in the request's payload.
A tenant policy can match more than one floor: subjectType: "*" matches every subject type and action: "*" every action, and effect limits it to floors that declare that effect. One policy then covers every money-moving tool:
await db.approvals
.savePolicy({
subjectType: "*",
action: "*",
effect: "money-movement",
name: "Money moves",
steps: [{ approvers: { permission: "finance.approve" }, required: 1 }],
})
.orThrow();A tenant policy still needs a floor it tightens: one for its subject type, action and effect, where * matches any (APPROVAL_POLICY_UNKNOWN otherwise).
Platform policies
With options.platformPolicies: true (next to tenantPolicies), rows of approval_policies without an organization are platform policies: platform staff with approvals.manage edit them at runtime with savePolicy(input, { platform: true }), listPolicies({ platform: true }) lists them, and they apply to every organization before its own policies. A platform policy also stands in for a floor the config doesn't have, so a subject type and action can need approval without a deploy, and tenant policies can tighten it.
permissions.platform gives platform policies their own platform key: reading and editing them then needs that key at platform level, and an organization's managers and platform staff with only approvals.manage are refused (APPROVAL_FORBIDDEN). Without it, edits need approvals.manage and reads approvals.read, at platform level.
blocks: {
approvals: {
permissions: { platform: "platform.approvalPolicy.manage" },
options: { tenantPolicies: true, platformPolicies: true },
},
}await db.approvals
.savePolicy({
subjectType: "invoice",
action: "send",
name: "Large invoices",
conditions: {
id: "root",
type: "group",
combinator: "and",
rules: [
{
id: "amount",
type: "rule",
path: ["amount"],
operator: "gt",
value: 10000,
},
],
},
steps: [{ approvers: { manager: true }, required: 1 }],
})
.orThrow();
const needed = await db.approvals
.requirement("invoice", "send", { amount: 25000 })
.orThrow();Each step of a tenant policy has its own quorum, checked the same way as the config: required is a whole number of at least 1 or "all". On a step that only lists users, a number above the number of users fails with APPROVAL_POLICY_INVALID, and "all" is saved as that number with all: true, so listPolicies returns required: 2, all: true for two users. A tenant can't set all itself; the save strips it from every other step. A step with decider: true on a subject type no block decides fails with APPROVAL_POLICY_DECIDER_UNAVAILABLE.
Saving and removing a policy needs approvals.manage and goes to the audit log; listPolicies needs approvals.read. requirement(subjectType, action, payload) returns the merged policy for a payload, or null when nothing is required, so the app can run the action without a request. request refuses a request nothing requires with APPROVAL_NOT_REQUIRED.
Page through requests
list is the capped convenience list. page is the full list contract
(ADR 0749, 0949) over the block tenant's requests, and it returns the same
requests list shows the caller: their own, the ones their role may read and
the ones they can decide. It takes sort, filters whose values are lists,
after and limit, and returns { items, hasMore, nextCursor }. Sorts are
createdAt (the default, newest first) and action. Filters are status,
subjectType, subjectId, action and assigned, and the facets are status
and subjectType. assigned: ["true"] keeps the requests whose current step
the caller can decide. Requests carry no text search, so q returns
invalid_input. Unlike list, page has no tenantless option: requests
without an organization stay on list. The SQL function is page_approvals.
const mine = await approvals
.page({ filters: { status: ["pending"], assigned: ["true"] } })
.orThrow();
const facets = await approvals.facets().orThrow();
const total = await approvals
.count({ filters: { status: ["pending"] } })
.orThrow();A cursor belongs to the sort it came from.
Requests without an organization
options.tenantless lists subject types whose requests may have no organization, for a personal AI chat or a platform action. request(subject, { action, tenantless: true }) files one as the signed-in user, list({ tenantless: true }) lists them and requirement(..., { tenantless: true }) checks one. Their approvers are named users, a provider's isApprover, or platform staff holding the step's permission; roles, teams and managers belong to an organization and don't match. Platform policies apply to them; tenant policies don't. A request without an organization for any other subject type fails with APPROVAL_TENANT_REQUIRED, and these requests send no notifications. organizationId is null on them.
Escalation
A step with escalateAfter and escalateTo lets the fallback approvers decide it too once it waited that long, counted from the request or the previous step's last decision. Schedule escalate_approvals() like the reminders; it marks the step escalated, records approval.escalated and asks the fallback approvers. The original approvers keep deciding. It needs the requests table's policy column.
steps: [
{
approvers: { manager: true },
escalateAfter: "PT48H",
escalateTo: { permission: "finance.approve" },
},
],Deciding for a user
Code that runs as the service role, such as a chat bot or a workflow, decides for the user who clicked: approve(id, comment, { decidedBy: userId }) and reject record that user as the approver. The service role skips the approver check, but the requester still can't decide their own request unless the policy allows it, and a user decides a step once. A signed-in caller who names someone else fails with APPROVAL_FORBIDDEN.
Requests under the app's own policy
Some approvers are not a policy row: a workflow's approval node names its own users, a workflow action asks for a confirmation, or nobody but the requester could approve. Code that runs as the service role passes its own policy to request, and requestedBy for the user it files for:
await approvals
.request(
{ type: "workflow_run", id: runId },
{
action: "approval",
requestedBy: startedBy,
policy: {
mode: "authorize",
expiresIn: "P2D",
steps: [
{
approvers: { users: [a, b] },
required: "all",
escalateAfter: "PT4H",
escalateTo: { permission: "workflow.manage" },
},
],
},
},
)
.orThrow();The app's policy only tightens the configured floor and the tenant and platform policies that match the request, as a tenant policy does: their steps come first and the app's steps after them, authorize outranks confirm, self-approval needs both to allow it, and the shorter expiry applies. A run or effects come from the floor. When no floor, tenant or platform policy matches, the app's policy is the request's whole policy. So a policy passed this way can never lower what an organization or the platform asks for an action; to file a confirmation where a floor asks for an approver, file it under its own action without a floor.
Steps map other approval models: any of several approvers is required: 1, a quorum is required: n, all of them is required: "all" (every listed user, or every holder of a lone permission), and a sequence is one step per approver. managerOf names an employee whose manager an approvers.manager step asks.
requestedBy makes that user the requester: they can't decide the request unless the policy allows self-approval or it is a confirm request, a required: "all" step leaves them out, and they get the decision's notification. A signed-in caller that passes policy, or a requestedBy other than themselves, fails with APPROVAL_FORBIDDEN; a malformed policy fails with APPROVAL_POLICY_INVALID. In SQL, request_approval takes them as policy and requested_by.
Wait for a decision
requestAndWait({ subject, input, timeoutMs?, intervalMs?, signal? }) files a request and polls it every intervalMs (default 1000) until it leaves pending, then resolves with the request's detail: approved, rejected, cancelled or expired. After timeoutMs (default 30000) it fails with a timeout error, hint APPROVAL_WAIT_TIMEOUT, and the request stays pending. Aborting signal ends the wait early with the same error. Use it for a short, interactive decision; for a long one, resume a workflow instead (below).
const done = await approvals
.requestAndWait({ subject, input: { action: "send" }, timeoutMs: 60_000 })
.orThrow();Use an approval once
isApproved answers whether a subject was approved, which suits a status change. For an operation such as a refund or an export, bind the approval to the exact request and use it once. Pass a fingerprint when you file the request, and call consume with the same fingerprint right before the operation runs:
import { approvalFingerprint } from "better-supabase/blocks/approvals";
const operation = { refund: invoiceId, amount: 2500, currency: "EUR" };
const fingerprint = await approvalFingerprint(operation);
const request = await db.approvals
.request(invoice, { action: "refund", payload: operation, fingerprint })
.orThrow();Once the request is approved, the code that runs the refund consumes it first:
await db.approvals
.consume(request.id, await approvalFingerprint(operation))
.orThrow();
await refund(operation);approvalFingerprint hashes the value as JSON with sorted keys, with SHA-256. consume moves the request to the consumed status, sets consumedAt, and fails with APPROVAL_NOT_APPROVED before the final approval, APPROVAL_CONSUMED on a second call and APPROVAL_FINGERPRINT_MISMATCH when the operation changed. The requester, a member with approvals.manage and the service role may consume a request. A check on the requests table keeps consumedAt set exactly when the status is consumed, and isApproved still answers true for a consumed request.
Requests consumed before version 6 of the module kept the approved status. better-supabase upgrade writes a reviewed migration that allows the new status, moves those requests to consumed and adds the check. Over a requests table of your own, consume keeps setting only consumedAt and leaves the status alone, so a status check or enum of yours keeps working.
Run the approved action
With run: { transition }, the final approval calls transition() for the subject. Mark the edge with requiresApproval on the machine so nobody can skip the request:
"state-machine": {
options: {
machines: {
invoice: { table: "public.invoices", column: "status", initial: "draft", transitions: { draft: ["sent"] }, requiresApproval: { draft: ["sent"] } },
},
},
},With run: { queue }, the final approval enqueues a job with requestId, organizationId, subjectType, subjectId, action and the request's payload. Without run, check isApproved(subject, action) or handle approval.approved. Access requests file their requests here with their own policy, and the final approval grants the role. Time tracking files submitted timesheets the same way, and the final approval locks the week.
Tool calls and support sessions
When the AI chat or impersonation module is installed next to approvals, its waiting requests become approval requests too, so one approvals inbox lists them:
| Module | subjectType | subjectId | action | Who decides |
|---|---|---|---|---|
| ai-chat | ai_tool_approval | the tool call's approval id | run | the chat's owner, or the users the provider's isApprover allows for kind ai-tool |
| impersonation | support_request | the support request id | start | platform staff with the approve permission, or the provider's isApprover for support-session |
The module that filed the request keeps deciding who approves it, so the
policy's approvers, roles and delegation don't apply (delegate refuses with
APPROVAL_DELEGATE_INVALID). A decision syncs both ways: approving or
rejecting the request with approve or reject decides the tool call or the
support request, and decide_ai_tool_approval or approve_support_request
closes the request. A rejected support request can no longer start a
session. Only the requester, the eligible approvers and the service role read
these requests; approvals.read alone doesn't show them. A support request
without a tenant stays in support_requests only.
Approvers from your authorization provider
Under the provider access model, a provider that sets
authorization.functions.isApprover can name approvers the policy doesn't:
approval_eligible also allows a user the template accepts for kind
<subject type>.<action> (for example refund.approve), the subject id
and the request's tenant. The requester never counts, even with
selfApproval. The policy's own approvers still decide as well. See
Authorization providers.
Server code can ask the same question through the hooks' approverOf. Pass
it with the user the transport runs as, and approve, reject and
delegate refuse with APPROVAL_FORBIDDEN unless both the SQL check and
the hook allow the caller:
const approvals = createApprovals({
transport: sqlTransport(postgres.asUser(ctx.auth.claims)),
authorization: { approverOf: hooks.approverOf },
approver: { userId: ctx.auth.claims.sub, claims: ctx.auth.claims },
});Delegation and out-of-office
delegate(id, userId) hands the caller's place on the current step of one
request to another member of the organization. It never outlives the
request. This block does not store out-of-office covers, where one user
approves for another until a date.
When your authorization provider keeps covers, let it own them: its
isApprover answers for the cover, and approval_eligible passes the
request's requested_by as {requester} so a cover never lets the
requester's own delegator approve. It passes the current step's approvers
with its required count as {approvers} (jsonb), or the step's
escalateTo while the step is escalated, so a provider can let a cover
decide where the absent user is a named approver, and nowhere else. Every module that waits for an approval
then honours the same covers. Configure covers in the provider only, and
don't mirror them with delegate calls. Without such a provider, call
delegate per request. Under the provider model, delegate checks that
the delegate is a member through the provider's memberIdsFor when the
provider sets it. See
Authorization providers.
Resume a workflow when a request is decided
A request's id is a random uuid, so it works as the token a paused workflow
waits on: only decide_approval, after its approver check, can end the
wait. Call wakeOnApproval from your outbox consumer, and it resumes the
run waiting on the request with { approved, status, requestId } for
approval.approved, approval.rejected, approval.expired and
approval.cancelled. See
Workflow SDK.
import { wakeOnApproval } from "better-supabase/workflow-sdk";
for (const event of events) await wakeOnApproval(event);Read many requests at once
getMany(ids) (get_approvals(request_ids)) returns the requests with their decisions and items in one call, in the order you ask, with the same shape as get. A sweep that escalated or expired twenty requests notifies about them after one read, instead of calling get once per request. A request that is missing or that the caller cannot read has no entry, so the result can be shorter than the list.
const requests = await approvals.getMany(escalatedIds).orThrow();
for (const request of requests) {
await notifyEscalated(request);
}Expiry and reminders
Schedule both functions with pg_cron or the jobs drain. remind_approvals(after) asks the current step's approvers again for requests pending longer than after (default one day), once per after.
select cron.schedule('expire-approvals', '*/15 * * * *', 'select better_supabase.expire_approvals()');
select cron.schedule('remind-approvals', '0 9 * * *', 'select better_supabase.remind_approvals()');Notifications, events and hooks
With the notifications module, the current step's approvers get approval.requested (and approval.reminder), a delegate gets approval.delegated, and the requester gets approval.approved, approval.rejected or approval.expired. Approvers named by permission are reached through the notification's permission audience.
options.notifications: false sends none of these, so an app that sends its own approval notifications from the events below doesn't send two. To keep them and add to them, create a hook function approval_notification(request_id uuid, kind text, notification jsonb) returns jsonb in the hooks schema. Its result is merged into the notification before it is sent, so it can set action_path, priority, actions or subject_label, and its data is merged into the block's { requestId, action, step }. Returning null skips that notification.
create function public.approval_notification(request_id uuid, kind text, notification jsonb)
returns jsonb language sql stable as $$
select jsonb_build_object(
'action_path', '/approvals/' || request_id,
'data', jsonb_build_object('subjectPath', '/' || (notification ->> 'subject_type') || 's/' || (notification ->> 'subject_id'))
)
$$;The module records approval.requested, approval.approved, approval.rejected, approval.cancelled, approval.expired, approval.delegated, approval.consumed and approval.escalated, each with organizationId, subjectType, subjectId, the request id, action, status and step. Tenant policies record approval_policy.created, approval_policy.updated and approval_policy.deleted with organizationId, id, subjectType and action. Every event but approval.expired also goes to the audit log. It calls before_approval_request, after_approval_request, before_approval_decide, after_approval_decide and approval_notification.
With ReUI
An approvals inbox renders list({ assigned: true }) in a ReUI data grid with approve and reject actions. A request sheet shows get(id): the steps as a stepper with the current step highlighted, and decisions as a timeline. Show the approve buttons only when canDecide is true.
Over your own requests table
The requests and decisions tables can be your own: map tables.requests and tables.decisions and their columns, as with every block table. Logical columns your table lacks map to null, and the block leaves out what needs them: without policy a request follows the live policy, without step a policy has one step, and a reason, payload, expiry, reminder, delegate or comment the table has no column for is refused (APPROVAL_REASON_UNSUPPORTED and the like). A status column may be an enum. Your other columns stay as they are, or take the request's values through extraColumns.
approvals: {
tables: {
requests: "public.approval_requests",
decisions: "public.approval_decisions",
},
columns: {
requests: { tenant: "organization_id", decidedAt: "closed_at", remindedAt: null },
decisions: { request: "request_id", tenant: "organization_id", delegateTo: null },
},
},Your own fields
Columns you add to approval_requests with alter table in your own schema files are fields of the block (details):,
keyed by column name with their SQL type. Pass createApprovals a Standard Schema
for them as fields: request take them next to the block's own keys and
validate them (a bad value is a validation error), and every request read return them
parsed. A column the module already uses is refused. See
your own fields.
const client = createApprovals({
transport,
fields: z.object({ priority: z.number().int().positive().nullable() }),
});Columns you add to approval_policies with alter table in your own schema files are fields of the block (details): the same way, such as a description. It needs tenantPolicies. savePolicy writes them from fields, where a key left out keeps its value, and listPolicies and savePolicy return them under fields.
await approvals
.savePolicy({
subjectType: "invoice",
action: "send",
name: "Large invoices",
steps: [{ approvers: { permission: "finance.approve" } }],
fields: { description: "Invoices over 10,000 need finance" },
})
.orThrow();Fields of requests a block files
A block that files its own requests for a record's owner, such as leave with approvalOwner: "employee", expenses with standaloneApprovals or timesheets per employee, makes that owner's account the requester. When the owner has no account the request has no requester, so the member who filed it is never treated as the requester and may decide it. Such a block doesn't pass fields. options.requestColumns fills your columns of those requests instead: per subject type, a SQL expression per column over subject.tenant, subject.subject_id, subject.action, subject.payload and subject.requested_by. open_approval sets them right after it inserts the request, and request_approval drops the same keys from the caller's fields, so the configured value always wins. Each column must be one your schema files add to approval_requests, and each value one expression, or rendering fails. For a subject type that members file themselves through request_approval, subject.payload and subject.subject_id are whatever the caller sent, so don't derive a column that grants anything from them.
approvals: {
options: {
requestColumns: {
leave_request: {
source: "'hr'",
employee_id:
"(select r.employee_id from better_supabase.leave_requests r where r.id = subject.subject_id::uuid)",
},
},
},
},Policies over the requests you may decide
better_supabase.approval_eligible_ids_in(tenants, outside) returns the pending requests the caller may decide, as a set. tenants defaults to the tenants the caller is a member of (member_organization_ids()); pass an array for others. With outside => true it answers the requests outside those tenants instead, tenantless ones included: there only a named user, a delegation, an access provider's isApprover or platform staff can make the caller an approver, and that path checks every such pending request, so a policy asks for it only on the rows outside the caller's tenants.
It applies the rules of approval_eligible as one query over the pending requests: users, roles, teams, managers and delegations are joins, and each permission is checked once through tenant_ids_with, the tenants the caller holds it in. A block's selfDecides rule runs only for the caller's own requests, and the expenses block answers all of them in one expense_self_decides_many call. A block's decides rule (decider: true steps) runs once per subject type when the block sets options.deciderMany, the set form of its options.decider; without it, once per request. Requests that nothing else lets the caller decide go to the access provider: once in all through its isApproverMany template when it sets one, else through isApprover once per distinct kind, tenant, requester and approvers. Only a linked block's approvable check still runs once per request. The function is stable and writes nothing; Postgres evaluates each set once per scan when you write in (select ...). A parity test keeps the sets and approval_eligible in step.
Use it in two parts in a policy on the requests table, or on a table that points at a request, instead of calling approval_eligible(request_id) for every row:
create policy approval_requests_select on public.approval_requests
for select to authenticated
using (
requested_by = (select auth.uid())
or id in (select better_supabase.approval_eligible_ids_in())
or (
(organization_id is null
or organization_id not in (select better_supabase.member_organization_ids()))
and id in (select better_supabase.approval_eligible_ids_in(outside => true))
)
);A page that reads one of the caller's organizations never reaches the second part, so the per-request checks outside the caller's tenants don't run. Don't call approval_eligible_ids(tenant) once per member organization: the first part answers all of them in one call. approval_eligible_ids(tenant) stays for one organization, and without a tenant it returns both parts. list_approvals uses it.
On the local stack with 60 tenants, 2,400 pending requests and a caller who owns 14 of them, one statement that scans the requests three times took, with the policy that calls approval_eligible_ids once per member tenant and once without a tenant, 38 ms filtered to one owned tenant and 122 ms over every tenant. The two-part policy takes 6.3 ms and 18 ms. tests/bench/approval-eligible-payload.ts measures both shapes. The pgTAP file 900_better_supabase_approvals_eligible_ids.test.sql checks both parts against approval_eligible for each user in the test database, in one transaction.
Without the client
db.approvals is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createApprovals } from "better-supabase/blocks/approvals";
const approvals = createApprovals({ transport, tenant: organizationId });
const invoice = { type: "invoice", id: invoiceId };
const request = await approvals
.request(invoice, { action: "send", reason: "Q3 invoice" })
.orThrow();
const waiting = await approvals.list({ assigned: true }).orThrow();
const onInvoice = await approvals
.list({ subject: invoice, status: null })
.orThrow();
await approvals.approve(request.id, "Looks right").orThrow();Decide and guard by subject
decideForSubject({ subject, action, decision }) approves or rejects the pending request for action on a record, so a button doesn't need the request id. It fails with not_found when nothing is pending. The service role passes decidedBy to decide for the user who clicked.
guarded({ subject, action, run }) runs run when the action is approved and otherwise files a request and returns it, as { ran: true, value } or { ran: false, request }.
const sent = await approvals
.guarded({
subject: { type: "invoice", id },
action: "send",
run: () => invoices.issue({ invoiceId: id }).orThrow(),
})
.orThrow();Requests with items
A request can ask for several things at once, such as the invoice, the contract and the email an agent wants to create. Pass items to request: each item has a key, and may carry a label, a payload, a permission that its decider holds, and dependsOn, the keys of items listed before it. Items are stored in approval_items, and get returns them. Columns you add to approval_items with alter table in your own schema files are fields of each item: pass them as the item's fields, and read them from fields on the item. A request with items takes no fields of its own, and is not available for a subject type another module decides.
const request = await approvals
.request({
subject: { type: "chat", id: chatId },
input: {
action: "run",
items: [
{
key: "invoice",
label: "Create the invoice",
permission: "invoices.approve",
},
{ key: "send", label: "Email it", dependsOn: ["invoice"] },
],
},
})
.orThrow();
await approvals
.decideItems({
id: request.id,
decisions: [{ key: "invoice", decision: "approve" }],
})
.orThrow();decideItems checks each item's own permission; an item without one follows the policy's approvers, and the requester can't decide unless the policy allows it. An item can't be approved while an item it depends on is pending or rejected (APPROVAL_ITEM_BLOCKED), and rejecting an item rejects the pending items that depend on it. The request settles when no item is pending: it is approved when any item was approved and rejected otherwise, with the same approval.approved and approval.rejected events as a request without items. approve and reject refuse a request with items (APPROVAL_ITEMS_REQUIRED).
After an approved item runs, recordCreated({ id, key, type, recordId }) stores the record it created, once per item, so a retried run finds it. The service role closes a request that nobody will decide with settle({ id, outcome, reason }). It writes a decision without an approver, settles the pending items to the outcome and records the same events, so requestAndWait and the workflow waiter wake.
The approvals module is at version 2 for the new table and functions, so run better-supabase upgrade.
Last updated on
Search
A search index kept up by triggers from config.recordTypes, search(q) as the caller, recents and favorites, and useCommandSearch for a Cmd+K dialog.
Assets and locations
A location hierarchy (site, building, unit) and an asset registry with tags, status, coordinates and assignment to members or records. Optional PostGIS stores points and areas as geography; booking resources and work items can name an asset.