createBlocks
Build several blocks from one set of options and the generated block config, and wire them on the ports they provide and consume, from better-supabase/blocks.
defineBlocks and createBlocks build the blocks you list with one
transport and set of error mappers, and wire them on their ports: each block
that consumes a port, such as ai-schedules and reminders consuming notifier,
gets it from the block that provides it, here notifications. Every block
exports its manifest from its subpath (organizationsBlock from
better-supabase/blocks/organizations), so only the blocks you list end up
in the bundle.
Each block also reads the settings its SQL half has in the blocks config:
its schema, its API schema and the options both halves share, such as
attachments.requireScan. better-supabase gen writes them to
blocks.generated.ts, and defineBlocks takes that file's blockConfig, so
you set each of them once, in better-supabase.config.ts.
import {
type RpcClient,
defineBlocks,
rpcTransport,
} from "better-supabase/blocks";
import { auditBlock } from "better-supabase/blocks/audit";
import {
createNotifications,
notificationsBlock,
} from "better-supabase/blocks/notifications";
import { organizationsBlock } from "better-supabase/blocks/organizations";
import { blockConfig } from "./supabase/blocks.config";
export const blockSet = defineBlocks(blockConfig, {
organizations: organizationsBlock,
audit: auditBlock,
notifications: notificationsBlock.using((options) =>
createNotifications({ ...options, types, render }),
),
});
export function blocks(supabase: RpcClient) {
return blockSet.create({ transport: rpcTransport(supabase) });
}
const { organizations, audit, notifications } = blocks(supabase);The result has one key per block with a client, typed from its creator,
plus sinks and close(). A block with only SQL, such as membershipsBlock, is
skipped.
Block instances on db
Register the set on the definition with .blocks() and every Db carries
each instance under its key in camel case: db.comments, db.leadScoring.
gen writes the blocks map in blocks.generated.ts with every installed
instance's manifest, so you list only the blocks that take app definitions:
import { createSupabase } from "better-supabase";
import { defineBlocks } from "better-supabase/blocks";
import { createNotifications } from "better-supabase/blocks/notifications";
import { blockConfig, blocks } from "./blocks.generated.ts";
import { schema } from "./generated-schema.ts";
const blockSet = defineBlocks(blockConfig, {
...blocks,
notifications: blocks.notifications.using((options) =>
createNotifications({ ...options, types, render }),
),
});
export const betterSupabase = createSupabase(schema).blocks(blockSet);export const addNote = bsb.action(
{ input: NoteInput, requireTenant: true },
async ({ customerId, text }, { db }) =>
db.comments.add({ type: "customer", id: customerId }, text),
);Each client runs through the Db's executor, so it acts as the same caller
(RLS and each function's checks apply), and works in the Db's organization
(db.$context.tenant). It is built the first time you read it on that Db,
so db.$with({ tenant }) and every request get their own. The browser client
of createClient gets the same properties on bsb.db.
Blocks that keep files (attachments, ai-files, drive and data-lifecycle) get
the Db's Storage as storage, so db.$blocks.attachments.download(id)
signs its URL as the same caller and the bucket policies apply. A Db
connected without Storage passes none. A storage you pass yourself, through
.with({ storage }), blockSet.client(db, key, { storage }) or
createBlockClient, wins over the Db's.
When a table already holds the property, such as an app tasks table next to
the tasks block, the table keeps db.tasks and the instance is on
db.$blocks.tasks. db.$blocks holds every instance.
db.$api(fn, args) calls a function in the API schema that has no typed
client, such as flag_enabled. It runs through db.$rpc in that schema, so
it returns a Result with a DbError instead of throwing, and .orThrow()
gives the value. Pass a returns schema to validate the value and type it:
const quotes = await db
.$api("list_quotes", { tenant }, { returns: v.array(QuoteRow) })
.orThrow();blockSet.call(db, fn, args) does the same outside a Db with blocks on it
and also returns a Result.
createSupabase(schema, { temporal }) passes its temporal to every
instance .blocks() builds, so a runtime without a global Temporal needs it
only there.
The generated config
gen writes blocks.generated.ts next to generated.ts when the config
installs blocks. It holds one entry per installed block, keyed by the
block's name:
export const blockConfig = {
attachments: {
schema: "better_supabase",
api: "api",
options: { requireScan: true },
},
notifications: {
schema: "better_supabase",
api: "api",
options: { topic: "notifications:{userId}" },
},
} as const satisfies GeneratedBlocks;schema and api resolve blocks.<block>.schema and .api over
database.sql.schema and database.sql.api. options holds the options marked as shared in
the block's manifest, with the module's default when the config leaves one
out. Each block's creator gets the API schema when there is one (the
wrappers there are what the caller may run), otherwise the module schema,
plus the shared options. A creator you call yourself takes the same values
from generatedOptions:
import { generatedOptions } from "better-supabase/blocks";
const attachments = createAttachments({
...generatedOptions(blockConfig.attachments),
transport,
storage: supabase.storage,
});The realtime controllers take their topic from the same file. The
notifications topic is a template, which fillTopic fills in:
fillTopic(blockConfig.notifications.options.topic, { userId }).
| Option shared with TypeScript | Read by |
|---|---|
attachments.requireScan | createAttachments |
bulk.limit | createBulkActions |
notifications.topic | the notifications feed controller and hook |
announcements.topic | the announcements controller and hook |
inbox.topic | the inbox controllers and hooks |
reactions.topic | the reactions controller and hook |
ai-chat.topic, listTopic | the chat controllers and hooks |
time-entries.timeZone | toWeeklyGrid |
waitlist.codeField | waitlistHook |
webhooks.allowHttp | publicUrl, the webhook URL check |
A server set for routes that need few blocks
betterSupabase.blocks() over blocks loads every installed block into every
route that imports the server. Name a subset in gen.serverBlocks and gen
writes blocks.<name>.ts with <name>Instances and <name>Blocks, a
defineBlocks over only those instances, each imported from its own subpath:
export default defineConfig({
gen: { serverBlocks: { core: ["permissions"] } },
});import { app } from "./app.ts";
import { coreBlocks } from "./blocks.core.ts";
export const betterSupabaseCore = app.blocks(coreBlocks);createNext(betterSupabaseCore, options) then gives a server whose db has the
app's tables and db.permissions. gen fails when a listed block requires a
port (notifier, files, attachments, workflows, mailer, recordAccess)
that no listed block provides, and createBlocks checks the same at runtime.
Spread coreInstances into your own defineBlocks to give a block its options,
as blocks.generated.ts allows. A renamed instance can't be listed. Each server
keeps its own session memo, so a route imports one of them.
On the Next.js example the sign-in page, the customers API and the customers page build their server from sets, and their server chunks shrink by 48, 54 and 50 percent (ADR 0542).
Options
| Option | What it does |
|---|---|
transport | Calls as the caller: dbTransport(ctx.db), rpcTransport(supabase) or sqlTransport(ctx.postgres) |
service | Calls as the service role, for the blocks with service-only calls |
config | blockConfig from blocks.generated.ts; defineBlocks passes it, createBlocks takes it here |
mappers | Error mappers that run before each block's built-in ones |
temporal | The Temporal namespace for runtimes without a global one |
credentials | A CredentialProvider for connectors, ai-keys and the workflow builder |
events | betterSupabase.events, for the blocks that emit block events |
audit | An EventSink, such as auditLog.sink(), that every block event goes to; needs events |
hooks | Hooks around each block's methods, keyed like the blocks (see Hooks) |
tenant | The organization the subject methods act in: an id, or a function that returns the current one |
Tenants
The blocks whose methods work on a subject (comments, attachments, tags,
reactions, relations, versions, sla, share links, custom fields, reminders,
time tracking and approvals) act in one organization, which they read from
the memberships option instead of taking an organizationId argument. Pass an
id, or a function that returns the current one, such as
() => ctx.tenant; the function runs on every call. A call without a tenant
fails with invalid_request and the hint TENANT_REQUIRED before it reaches
the database. The SQL functions still check that the caller belongs to that
organization.
Each of these methods takes the record it works on as a RecordRef,
{ type, id }, and its rows carry it as subject. Batch methods such as
comments.counts(subjects) and reactions.summary(subjects) return a record
keyed type:id, which subjectKey(subject) from better-supabase/blocks
builds.
One block per request
createBlockClient(db, block, options?) builds one block for a request. It
calls through dbTransport(db) and acts in the Db's tenant
(db.$context.tenant), so a server action or route handler needs no wrapper
that passes the organization:
import { createBlockClient } from "better-supabase/blocks";
import { commentsBlock } from "better-supabase/blocks/comments";
import { blockConfig } from "@/lib/supabase/blocks.config";
import { bsb } from "@/lib/supabase/server";
const ctx = await bsb.context();
const comments = createBlockClient(ctx.db, commentsBlock, {
config: blockConfig,
});
const thread = await comments
.list({ type: "customer", id: customerId })
.orThrow();blockSet.client(db, key, options?) does the same for a block of a set
built with defineBlocks, with the set's config, so
blockSet.client(ctx.db, "comments") returns the same client typed from the
set. The options are those of createBlocks without audit, plus hooks
for the one block: transport replaces dbTransport(db), and tenant
replaces the Db's tenant, for a job that works in an organization other
than the caller's.
A block's own options
with sets options one block gets on top of the shared ones, such as the
notification type ai-schedules sends:
defineBlocks(blockConfig, {
aiTasks: aiSchedulesBlock.with({ notification: "ai_task.finished", run }),
notifications: notificationsBlock,
}).create({ transport, service });using builds a block with your own call to its creator, which keeps the
creator's type parameters, such as the notification types or the metric
definitions, or passes what the creator needs from your code:
settingsBlock.using((options) => createSettings({ ...options, settings })).
Settings from an earlier with still reach the creator and the block's
ports. The options hold the shared ones, so a client built from a Db with
Storage finds the caller's Storage in options.storage.
Transports
A transport decides how a block's functions are called and as whom. All three reject with the raw database error, so a block maps the same codes and hints whichever one you pick.
| Transport | Calls through | Use it when |
|---|---|---|
dbTransport(db, { schema }) | the executor of a Db (db.$executor) | the blocks should run wherever ctx.db runs |
rpcTransport(supabase, { schema }) | a supabase-js client over the Data API | you hold a supabase-js client, such as in the browser |
sqlTransport(client) | a SqlClient, such as postgres.asUser(claims) | you call over Postgres as a fixed role, such as postgres.admin |
dbTransport follows the Db it gets. ctx.db runs over the Data API in a
normal request, and over direct Postgres as the target user in a
support session or for an API key, so blocks
built on dbTransport(ctx.db) need no second code path for those requests:
import {
type DbTransportSource,
defineBlocks,
dbTransport,
} from "better-supabase/blocks";
import { organizationsBlock } from "better-supabase/blocks/organizations";
import { blockConfig } from "./supabase/blocks.config";
const blockSet = defineBlocks(blockConfig, {
organizations: organizationsBlock,
});
export function blocksFor(db: DbTransportSource) {
return blockSet.create({ transport: dbTransport(db) });
}
const { organizations } = blocksFor(ctx.db);Each block calls the schema from its generated entry: the API schema that
blocks.<block>.api (or database.sql.api) writes wrappers into, or the module
schema without one. Over the Data API that schema has to be exposed; over
Postgres the same wrappers work. A transport's own schema option sends
every call there instead. The executor needs rpc(): the built-in PostgREST
and Postgres executors have it.
Renamed blocks
When the config renames the tenant (blocks.memberships.names.organization),
a block's entities (blocks.<name>.names) or its functions
(blocks.<name>.functions), the SQL writes the block functions under other
names. gen writes those names into each block's names entry in
blocks.generated.ts, and defineBlocks wraps that block's transport with
blockNames(names), so the clients call the renamed functions with no change
to lib/blocks.ts. Rows that a function returns whole get their renamed
tenant columns (workspace_id) back under the names the clients read
(organization_id).
A renamed entity also renames the TypeScript side. For each block whose
entities the config renames, gen writes the block and its types under the
new names, so you import tasksBlock and Task instead of tasksBlock
and Task:
export const tasksBlock = renameBlock(tasksBlock, blockConfig["tasks"].names);
export type Task<F extends object = Record<never, never>> = RenamedType<
Task<F>,
WorkItemsRenames
>;
export type TasksEvents = RenamedEvents<TasksEvents, WorkItemsRenames>;renameBlock renames the client's methods (createWorkItem to createTask),
the keys of their arguments and results (taskId to taskId) and the
block's event types (task.created to task.created). The block keeps
its name, SQL and ports, and hooks see the renamed client. The tenant rename
stays in SQL: payloads and client types keep organizationId. See
Typed blocks for the config key.
A creator you call yourself takes the same middleware:
import {
blockNames,
generatedOptions,
wrapTransport,
} from "better-supabase/blocks";
import { createOrganizations } from "better-supabase/blocks/organizations";
import { blockConfig } from "./supabase/blocks.config";
const entry = blockConfig.organizations;
const organizations = createOrganizations({
...generatedOptions(entry),
transport: entry.names
? wrapTransport(transport, blockNames(entry.names))
: transport,
});Ports
A block's manifest says which ports it provides and consumes. createBlocks
hands each consumed port to the block from the one block in the set that
provides it, never by the key you gave it, and refuses two providers of one
port or a missing required one.
| Port | Provided by | Consumed by |
|---|---|---|
notifier | notifications | ai-schedules (with notification), reminders (with notification) |
files | ai-files | knowledge |
attachments | attachments | drive, which downloads files through it |
recordAccess | access-requests | drive, which requests and lists access to nodes through it |
workflows | workflows | workflow-editor, which writes schedule triggers' schedules through it |
mailer | mail-sync | sequences, which sends email steps through it |
sink | search, metrics | none: each one lands in sinks, keyed like the block (see Outbox sinks) |
With a notification type, ai-schedules sends it to the task's user in the
task's organization, keyed by the run id, with the data
{ taskId, runId, ok, error?, chatId? }. The type's schema in your
notification types has to accept that data. Reminders send theirs for each
delivered occurrence to the reminder's owner and the subject's watchers,
keyed by reminder:<id>:<occurrenceAt>, with the data
{ reminderId, occurrenceAt }; reminders.job then delivers through it.
const { aiTasks, reminders } = defineBlocks(blockConfig, {
aiTasks: aiSchedulesBlock.with({ notification: "ai_task.finished", run }),
reminders: remindersBlock.with({ notification: "reminder.due" }),
notifications: notificationsBlock.using((options) =>
createNotifications({ ...options, types, render }),
),
}).create({ transport, service });Some pairs wire in SQL instead, when both modules are installed: approvals
move the state machine, the bulk block gets a trash.trash action, and the
search block drops soft-deleted rows. The blocks have nothing to wire for
those.
Outbox sinks
sinks holds the outbox consumers the blocks provide. searchBlock provides
searchSink: a trashed or purged subject leaves the
index and a restored one is read again. metricsBlock with a sink option
provides metricsSink, which rolls up the listed
metrics for each event. Build these blocks with the service transport, and
relay the sinks from your cron route:
import "server-only";
import { defineBlocks } from "better-supabase/blocks";
import { metricsBlock } from "better-supabase/blocks/metrics";
import { searchBlock } from "better-supabase/blocks/search";
import { outbox } from "@/lib/outbox";
import { blockConfig } from "@/lib/supabase/blocks.config";
const app = defineBlocks(blockConfig, {
search: searchBlock,
metrics: metricsBlock.with({
sink: { on: { "order.placed": ["orders", "revenue"] } },
}),
}).create({ transport: service });
export const GET = outbox.relayRoute({
secret: process.env.CRON_SECRET,
consumers: { ...app.sinks },
});Hooks
hooks, keyed like the blocks and then by method name, runs your code
around a block's methods: a before hook can refuse a call or replace its
arguments, and an after hook observes a copy of the result. Ports are built
from the hooked block, so a send hook also runs when ai-schedules notifies. See
Extending blocks.
export const app = defineBlocks(blockConfig, {
notifications: notificationsBlock.using((options) =>
createNotifications({ ...options, types }),
),
}).create({
transport,
hooks: { notifications: { send: { before: refuseDuringQuietHours } } },
});Typed events
defineBlocks also takes your own events
(defineEvents) after the blocks, and
types every event they can emit. on listens with that typing, and create
builds the blocks with the generated config:
import { defineBlocks, defineEvents, event } from "better-supabase/blocks";
import { blockConfig } from "./supabase/blocks.config";
const appEvents = defineEvents({
"invoice.sent": event<{ readonly invoiceId: string }>(),
});
export const app = defineBlocks(
blockConfig,
{ organizations: organizationsBlock, comments: commentsBlock },
appEvents,
);
app.on(betterSupabase, "comment.*", (event) => {
console.log(event.data.subjectType, event.data.subjectId);
});
const { organizations, comments } = app.create({ transport });Forwarding block events to the audit log
With events and audit, every block event becomes a CloudEvent with the
source /better-supabase/blocks (BLOCK_EVENT_SOURCE) and goes to the sink.
audit.sink() records each one in
the audit log. The forwarding listens on events until you call close(),
so build these blocks once, at module scope, rather than per request.
const log = createAudit({ transport: service });
export const app = defineBlocks(blockConfig, {
organizations: organizationsBlock,
}).create({
transport: service,
events: betterSupabase.events,
audit: log.sink(),
});Last updated on