Templates
Versioned templates that create records, such as an invoice or a project with its tasks, system starters each organization forks, merge fields for text and email, and the workflows each new record starts.
templates stores templates of a type you define, such as invoice, project or onboarding-email. A template has settings, a versioned body and a language, and applying it creates a record from the newest published version through your type's apply. The module records which version made which record, and starts the workflow-editor workflows attached to the template on the new record.
System templates (no organization) are starters your app ships and keeps by key with sync. An organization forks one to change it, and the fork tracks the version it copied, so you can tell when the starter moved on.
Reading templates needs templates.read, applying one needs templates.apply, and creating, editing, publishing, forking and attaching workflows needs templates.manage. Admins get every permission, and members get templates.read and templates.apply. Only the service role changes system templates.
Record templates
A template is always a row in templates. Its content is either a versioned body (an email or a document) or real rows of another table. Turn that on per block with options.templates, or tag an app table @bsb template. The row's template_id points at the templates row. While it is set, numbering, search, pipelines, the state machine and domain events skip the row. Audit still records the edit.
tasks.clone, and the same shape on quotes and invoices, copies a row and its block-owned children into a live record. templates.instantiate does that for a published rows template and records the application. pack snapshots the rows into a version body, and unpack materializes that body again, which is how a fork of a starter becomes editable rows.
Extra data about the template, not the record, goes in settings (checked against the type's JSON Schema when jsonb-schemas is installed), in a column you add to templates, or in an extension table the type names.
better-supabase add templatesThe module needs memberships and access. With outbox it records events, with audit it audits publishes and applications, with workflow-editor it attaches workflows, and with jsonb-schemas it checks a workflow's inputs against its whole input schema.
Paging templates
templatePage pages the templates by name (ADR 1077) with templateFacets, templateCount and getTemplate. Sorts are name (the default), createdAt and updatedAt. Filters are type, language, scope and isDefault, each a list. q searches the name and the key. getTemplate returns a not_found error for a template that is missing or hidden from the caller.
const emails = await templates
.templatePage({ organizationId, filters: { type: ["email"] } })
.orThrow();list keeps working and is deprecated. A cursor belongs to the sort it came from, so start again from the first page when sort changes. A sort, filter, facet or text the entity does not declare returns an invalid_input error. Block lists describes the options every block list shares.
Template types
A type gives a template its Standard Schemas and creates the record. settings and body are checked on every write and parsed again before apply. apply returns the record it created as a subject.
Server code calls the templates instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useTemplates } = defineDataHooks(
"templates",
(db: AppDb) => db.templates,
);const rows = await db.templates.list({ limit: 50 }).orThrow();"use client";
import { useTemplates } from "@/lib/supabase/hooks";
const rows = useTemplates({ limit: 50 });A type without apply stores templates you render yourself, such as emails. Applying one returns an invalid_request error.
A rows type in blocks.templates.options.types lists the child tables a pack copies as children: [{ table: "public.quote_lines" }]. The parent column, the one that references the root row, comes from the foreign key your schema files declare from the child to the root table. Name it ({ table, parent }) when the child has none or more than one.
Starters, forks and defaults
await service
.sync([
{
key: "launch",
type: "project",
name: "Product launch",
body: { tasks: ["Kickoff", "Plan", "Retro"] },
},
])
.orThrow();
const [starter] = await templates.list(null, { type: "project" }).orThrow();
const fork = await templates.fork(starter.id, organizationId).orThrow();
await templates.setDefault(fork.id).orThrow();sync upserts system templates by key as the service role, and publishes a new version of each starter whose body changed (it compares the SHA-256 of the body). It returns how many versions it published, so running it on every deploy is cheap.
fork(source, organizationId) copies the source's newest published version into a new template in that organization, published as version 1, with its workflow attachments. The fork keeps forkedFrom and forkedFromVersion. upstreamVersion is the source's newest published version, and behind is true when it is newer than the one the fork copied.
list(organizationId) returns the organization's templates and the system ones, defaults first; list(null) returns only the system ones. setDefault makes a template the default for its organization, type and language; a unique index keeps one.
Brand starters
When one app serves several brands, a starter can belong to one brand. better-supabase has no brands table: the brand is a column you keep, as for a custom flag context. Set options.brand to the table and column that hold a tenant's brand, and give the starter a brand in sync:
templates: {
options: { brand: { table: "public.organizations", column: "brand" } },
},await service
.sync([
{
key: "launch",
type: "project",
brand: "acme",
name: "Acme launch",
body: { tasks: ["Kickoff", "Brand review", "Retro"] },
},
])
.orThrow();A brand starter has scope brand, no organization and the brand in brand. Every organization whose column holds that brand reads, forks and applies it like a system starter, and other organizations don't see it. Keys and defaults count the brand, so each brand keeps its own launch. A brand table other than the tenant table takes tenant, the column there with the tenant id (id by default). Without options.brand, sync refuses a starter with a brand.
To name the brand source once for every block that reads one, set database.sql.brand: { table, column, tenant? } in the config. Option sets and pipelines read it too, and a block's own options.brand overrides it.
Fields and preview
variables({ type }) lists the merge fields a template type offers, in catalog order, for an editor's field picker. It returns not_found for a type not in options.types and an empty list for a type without a catalog.
preview({ template, values?, draft?, escape? }) renders the newest published body (the draft with draft: true) with values, falls back to each field's example, and lists the fields the type does not define. Nothing is written.
const fields = await templates.variables({ type: "invoice" }).orThrow();
const view = await templates
.preview({ template: id, values: { total: "10" } })
.orThrow();Versions
await templates.versions
.upsert(fork.id, { tasks: ["Kickoff", "Plan"] })
.orThrow();
await templates.versions.publish(fork.id).orThrow();versions.upsert updates the open draft, or opens the next version when the last one is published; a template has at most one draft. versions.publish publishes the draft (TEMPLATE_NO_DRAFT when there is none) and records template.published. Published versions don't change, so an application always points at the exact body it used. get returns the template with its newest published version and its draft, bodies included; getMany(ids) reads many templates the same way in one call, in the order you ask, and leaves out the ones the caller can't read. versions.list lists them without bodies.
Applying a template
const { subject, runs } = await templates
.apply(templateId, { into: organizationId, values: { month: "October" } })
.orThrow();apply reads the newest published version (TEMPLATE_NOT_PUBLISHED without one), calls the type's apply with the parsed settings and body, the organization, your values and your key, then records the application and its template.applied event. A throw from apply returns as an error and records nothing. applications.list(organizationId, { template, subject }) lists what each template made.
Then it starts each enabled attached workflow on the new record through workflows.run, with the attachment's inputs as the run's input, the record as its subject and template-application:<application>:<definition> as its idempotency key. A run starts as the caller, so a member who may apply a template but not run the workflow gets the record and an error in runs for that workflow; apply doesn't fail. Pass a builder with a service transport when the workflows should run anyway.
Workflows on new records
const version = await builder.versions
.upsert(definition.id, graph, {
inputSchema: {
type: "object",
required: ["owner"],
properties: { owner: { type: "string" } },
},
})
.orThrow();
await builder.versions.publish(version.id).orThrow();
await templates.workflows
.attach({
template: fork.id,
definition: definition.id,
inputs: { owner: userId },
})
.orThrow();workflows.attach checks inputs against the inputSchema of the definition's published version: its required keys always, and the whole schema with jsonb-schemas installed (TEMPLATE_WORKFLOW_INPUT_INVALID). apply checks them again, because the definition may have published a new schema since. The definition has to belong to the template's organization or be a system one (TEMPLATE_WORKFLOW_NOT_FOUND), and it has to run on the subject type apply returns. Attaching it again replaces the inputs; detach removes it.
Recurring records
The templates.apply step creates a record from a workflow, so a scheduled workflow builds the monthly invoice or the weekly checklist.
import {
TEMPLATES_APPLY_STEP,
templatesApplyStep,
} from "better-supabase/blocks/templates";
export const stepLibrary = [TEMPLATES_APPLY_STEP, ...otherSteps];
export const steps = {
"templates.apply": templatesApplyStep(templatesFor(postgres.admin)),
...otherHandlers,
};A node's config takes template and optional values, and the step applies the template in the run's organization. It passes <runKey>:<node> to your type's apply as key, so a retried step can find the record it already created instead of creating a second one. It returns { applicationId, subject, runs }. Publishing a graph with the node checks templates.apply.
Schedules
Without a workflow, a schedule applies a template at each occurrence of a recurrence rule. The rule lives in the reminders module's recurrence_rules (subject type template_schedule), so install reminders with ruleFormat: "rrule" and the queue module, and pass the queue client as jobs:
export const templatesFor = (sql: Sql) =>
createTemplates({
transport: sqlTransport(sql),
types: { invoice },
jobs: jobsFor(sql),
});const schedule = await templates.recurring
.upsert({
template: invoiceTemplate.id,
organizationId,
dtstart: Temporal.Instant.from("2026-11-01T08:00:00Z"),
tzid: "Europe/Amsterdam",
rrule: "FREQ=MONTHLY;BYMONTHDAY=1",
input: { plan: "pro" },
})
.orThrow();upsert needs templates.manage in the organization, and the template must be one the organization can apply. list(organizationId, template?) and remove(id) read and remove schedules; removing a schedule or its template removes its rule.
Two service-role calls run the schedules. The manifest's recurring schedule calls recurring.schedule() every five minutes: it expands every enabled rule in its time zone and enqueues one templates.recur job per occurrence in the next day (horizonMinutes, default 1440), and also an occurrence missed in the last 15 minutes (lookbackMinutes). The dedupe key is the schedule and the occurrence, so running it again enqueues nothing new. Work the templates.recur queue with recurring.job:
import { TEMPLATE_RECUR_QUEUE } from "better-supabase/blocks/templates";
const templates = templatesFor(postgres.admin);
await jobs.work(TEMPLATE_RECUR_QUEUE, templates.recurring.job, {
signal: controller.signal,
});The job calls recurring.run(schedule, occurrenceAt). It claims the occurrence in template_schedule_runs, applies the template in the schedule's organization with the schedule's input as values, and records the application. An occurrence that already made a record returns { status: "skipped" }. Two workers that claim the same occurrence before either records it both call your type's apply, with the same key template-schedule:<id>:<occurrence>, so use the key in apply to return the record the first one created. A rule that doesn't expand (an unknown time zone) counts in skipped and the other schedules still run.
Merge fields
import {
composeTemplateEmail,
renderMergeFields,
} from "better-supabase/blocks/templates";
renderMergeFields("Hi {{ customer.name }}", { customer: { name: "Ada" } });
invoiceFields.unknown("Total: {{ total }} {{ vat }}"); // ["vat"]
const email = composeTemplateEmail(
{ subject: "Invoice {{ number }}", html: "<p>Hi {{ customer.name }}</p>" },
values,
{ category: "notification", templateKey: "invoice-v3" },
);renderMergeFields replaces {{ name }} with its value and {{{ name }}} with its value unescaped. With escape: "html", {{ name }} is escaped for HTML. A dotted name reads that key first and then the nested path, never an inherited property. A missing value renders as empty, or as the field itself with missing: "keep". Values print as text: dates as ISO 8601, Temporal values with their toString, arrays joined with commas and plain objects as JSON; pass format to change that. It has no dependencies and runs on every WinterTC runtime.
defineMergeFields(subjectType, fields) declares the fields a record type offers, for an editor's field picker: names, examples() for a preview, unknown(text) for the fields a template uses that the catalog doesn't define, and a typed render. composeTemplateEmail renders an email body for the notifications email channel's compose, with the HTML escaped and the subject and text left as text.
Events and hooks
The module records template.published with the versionId, version and type, and template.applied with the templateId, versionId and the new record as its subject, so the record's activity feed shows which template made it. It calls before_template_save, after_template_save, before_template_apply and after_template_apply; hooks in createTemplates wraps the client's methods.
Errors carry these hints: TEMPLATE_INVALID, TEMPLATE_NOT_FOUND, TEMPLATE_FORBIDDEN, TEMPLATE_NO_DRAFT, TEMPLATE_NOT_PUBLISHED, TEMPLATE_WORKFLOW_NOT_FOUND and TEMPLATE_WORKFLOW_INPUT_INVALID.
Tables
| Table | What it holds |
|---|---|
templates | One row per template: organization (none for a system one), type, name, language, default, settings, the fork's source |
template_versions | The versions of each template, with the body and its SHA-256; the draft has no published_at |
template_applications | Which version of which template created which record, by whom |
template_workflows | The workflow definitions each template starts on a new record, with their inputs (with workflow-editor) |
template_schedules | Recurring records: the template, organization, input and whether it runs; the rule is in reminders (with reminders) |
template_schedule_runs | One row per occurrence a schedule claimed, with the application it made (with reminders) |
Your own columns
Add columns to the template table with alter table ... add column in your own schema files
(column name to SQL type), then pass a Standard Schema for them as fields.
upsert validates and writes them, and upsert, list, get and fork return them parsed under
fields. The block also takes hooks around its methods; see
extending blocks.
import { createTemplates } from "better-supabase/blocks/templates";
import { z } from "zod";
const client = createTemplates({
transport,
fields: z.object({ priority: z.enum(["low", "high"]) }),
});Without the client
db.templates is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import "server-only";
import * as v from "valibot";
import {
createTemplates,
defineMergeFields,
defineTemplateType,
sqlTransport,
} from "better-supabase/blocks/templates";
const project = defineTemplateType({
settings: v.object({ color: v.string() }),
body: v.object({ tasks: v.array(v.string()) }),
apply: async ({ body, settings, organizationId, key }) => {
const created = await projects
.create({ organizationId, color: settings.color, tasks: body.tasks, key })
.orThrow();
return { subject: { type: "project", id: created.id } };
},
});
export const invoiceFields = defineMergeFields("invoice", {
"customer.name": { label: "Customer", example: "Ada Lovelace" },
total: { label: "Total", example: "€120.00" },
});
export const templatesFor = (sql: Sql) =>
createTemplates({
transport: sqlTransport(sql),
types: { project },
workflows: builderFor(sql),
});Last updated on
Signatures
Simple electronic signatures on a frozen version of a record, with sequential or parallel signers, a SHA-256 hash per signature and a check that the signed content is unchanged.
Content
Pages, posts and other typed entries per organization, with locales, scheduled and approved publishing, versions and a public read by slug.