Forms
Versioned forms with steps and show or skip logic, a JSON Schema 2020-12 per version that Postgres checks on every submission, drafts, public links with a rate limit and a bot-check hook, and handlers that turn a submission into a record.
forms stores a form, its published versions and the submissions to them. Each version holds a definition (steps of fields, with showIf conditions) and the JSON Schema 2020-12 generated from it, and pg_jsonschema checks every submission against that schema inside Postgres. Reading forms needs forms.read, submitting needs forms.submit, and creating and publishing needs forms.manage. Respondents read their own submissions and delete their own drafts; reading anyone else's, reviewing and deleting needs forms.review.
better-supabase add formsServer code calls the forms instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useForms } = defineDataHooks(
"forms",
(db: AppDb) => db.forms,
);import { createForms } from "better-supabase/blocks/forms";
const form = await db.forms
.create({ organizationId, key: "signup", title: "Sign up" })
.orThrow();
await db.forms
.publish(form.id, {
steps: [
{
key: "contact",
title: "Contact",
fields: [
{ key: "name", label: "Name", type: "text", required: true },
{ key: "email", label: "Email", type: "email", required: true },
{
key: "plan",
label: "Plan",
type: "option",
options: [
{ value: "free", label: "Free" },
{ value: "team", label: "Team" },
],
},
],
},
{
key: "team",
showIf: { field: "plan", equals: "team" },
fields: [
{
key: "seats",
label: "Seats",
type: "integer",
min: 2,
required: true,
},
],
},
],
})
.orThrow();
await db.forms.update(form.id, { status: "open" }).orThrow();
await db.forms
.submit(form.id, { name: "Ada", email: "ada@example.com" })
.orThrow();"use client";
import { useForms } from "@/lib/supabase/hooks";
const rows = useForms({ limit: 50 });Paging a list
list is the capped convenience list. page is the full contract for forms (ADR 0749, 0939): it takes organizationId, which names the organization per call, and sort, filters whose values are lists (a row matches any of a filter's values), after and limit, and returns { items, hasMore, nextCursor }. Pass the nextCursor back as after. The sorts are createdAt, title and key; the default order is createdAt, newest first. The filter is status. The facet is status. list returns 200 forms unless you pass limit (500 at most). A cursor belongs to the sort it came from, so start again from the first page when sort or direction changes. A sort, filter, facet or text the entity does not declare returns an invalid_input error.
const open = await forms
.page({
organizationId,
filters: { status: ["open"] },
sort: { by: "title" },
limit: 20,
})
.orThrow();
const facets = await forms.facets({ organizationId }).orThrow();
const total = await forms.count({ organizationId }).orThrow();submissionPage pages the submissions of the organization the same way, newest first. Sorts are createdAt and submittedAt. Filters are formId, status, respondentId and includeArchived, each a list. q searches the answers as text. submissionFacets counts status and formId, and submissionCount returns { value, exact }. listSubmissions keeps working and is deprecated.
Definitions and versions
A definition is a list of steps, and each step a list of fields. publish(formId, definition) stores it as the form's next numbered version and makes it current; older versions and their submissions stay as they were. A form takes submissions only while its status is open (FORM_CLOSED otherwise).
| Field type | Answer | Options |
|---|---|---|
text, textarea | a string (500 and 10,000 characters max) | minLength, maxLength, pattern |
email, url, date | a string with that format | |
number, integer | a number | min, max |
bool | true or false | |
consent | true | |
option | one of options[].value | options |
multi | distinct values from options | options, min, max (items) |
json | any JSON value | |
nps | an integer from 0 to 10 |
required: true asks for the field, and for a non-empty string or list. A showIf on a step or field is { field, equals }, { field, in } or { field, filled: true }, naming an earlier field. A hidden field is never required, so its required becomes an if/then in the schema. A field with customField: "<definition id>" copies its label, type and required from a custom field when the version is published; give an option field its options in the form.
publish checks the definition against FORM_DEFINITION_SCHEMA, then for what the shape can't say (a key used twice, a condition on a later field, a choice field without options), and fails with FORM_DEFINITION_INVALID and the problems in issues. formDefinitionProblems(definition) runs the second check in the app, and formSchema(definition) returns the same schema Postgres stores.
Your own fields
Columns you add to forms with alter table in your own schema files are fields of the block (details):,
keyed by column name with their SQL type. create and update write them from fields, and create, update, get and list return them under fields. Pass a
Standard Schema as fields to type them,
parse them on reads and validate them on writes; a bad value is a
validation error before anything reaches the database (see
extending blocks):
import { z } from "zod";
const forms = createForms({
transport,
fields: z.object({ region: z.enum(["emea", "amer", "apac"]) }),
});
await forms.update(formId, { fields: { region: "emea" } });Submissions
A submission that doesn't match the version's schema fails with a validation error (hint JSON_SCHEMA_INVALID) whose issues name the fields. validateAnswers(schema, answers) checks the same keywords in the browser, and answersSchema(schema) wraps it as a Standard Schema for form libraries.
const draft = await forms
.submit(form.id, { name: "Ada" }, { draft: true })
.orThrow();
await forms
.submit(
form.id,
{ name: "Ada", email: "ada@example.com" },
{ submissionId: draft.id },
)
.orThrow();
const page = await forms
.listSubmissions(form.id, { status: "submitted" })
.orThrow();
await forms.review(page[0]!.id, "accepted").orThrow();draft: true saves answers without checking them, and a later submit with submissionId finishes the draft against the current version. Pass subjectType and subjectId to link a submission to a record the caller can read, such as a deal. listSubmissions returns the newest first, 50 to a page by default; pass the last createdAt as before for the next page.
archiveSubmission(id) hides a submitted, accepted or rejected submission from listSubmissions and nps and keeps its answers, score and review; restoreSubmission(id) brings it back, and listSubmissions takes includeArchived: true to list both. Both need the review permission, and a draft is refused (FORM_SUBMISSION_DRAFT) because the respondent's draft is purged, not archived. getSubmission still reads an archived submission by id, with archivedAt set. purgeSubmission(id) removes a submission for good: a reviewer any submission, a respondent their own draft. Set permissions.purge to a key of your own to split it from review.
Scores and quizzes
Give a field a correct answer to score it, and points to weigh it (1 by default). scoring.passMark is the percentage of the points a submission needs to pass. Every field type takes a correct answer except consent, json and nps, and the answer has to be one the field accepts.
await forms
.publish(form.id, {
scoring: { passMark: 70 },
steps: [
{
key: "quiz",
fields: [
{
key: "capital",
type: "text",
label: "Capital of France",
correct: "Paris",
},
{
key: "giants",
type: "multi",
label: "Gas giants",
options: [
{ value: "jupiter", label: "Jupiter" },
{ value: "mars", label: "Mars" },
{ value: "saturn", label: "Saturn" },
],
correct: ["jupiter", "saturn"],
points: 2,
},
],
},
],
})
.orThrow();publish moves the correct answers into the form_answer_keys table, which no client role can read. Respondents get the definition without them; callers with forms.manage get them merged back. When a submission is final, Postgres scores it inside submit and stores score, maxScore and passed on the row, so a client can't send its own grade. Text answers match without case and surrounding spaces, a multi answer matches as a set, and other answers match as the same JSON value. A field hidden by its showIf (or its step's) counts toward neither score. passed is absent without a pass mark, and score is absent on drafts and unscored versions.
formScore(definition, answers) computes the same grade in the app, for a preview from a definition that still holds its correct answers. Over a submissions table of your own, the block adds the score, max_score and passed columns it lacks. When columns.submissions maps one of them to null, scoring is off and publish refuses a correct answer with FORM_SCORING_UNAVAILABLE.
Net Promoter Score
An nps field takes an integer from 0 to 10. nps(formId, options) counts the submitted and accepted answers: 9 and 10 are promoters, 7 and 8 passives, 0 to 6 detractors, and score is the promoters' share minus the detractors', from -100 to 100 to one decimal. It needs forms.review.
const nps = await forms
.nps(form.id, {
since: Temporal.Instant.from("2026-01-01T00:00:00Z"),
bucket: "month",
})
.orThrow();
// { field: "nps", responses: 40, promoters: 22, passives: 10, detractors: 8, score: 35, periods: [...] }field picks the field (the current version's first nps field by default, FORM_NPS_FIELD_MISSING without one). since and until bound submittedAt, and bucket (day, week, month, quarter or year, in UTC) adds a row per period. npsCategory(answer) and npsScore(counts) give the same buckets and score in the app.
Turn a submission into a record
options.handlers maps a form key to a function that receives the submission id. It runs in the submission's transaction, and when it returns { subjectType, subjectId } the submission is linked to that record.
blocks: {
forms: { options: { handlers: { contact: "public.lead_from_submission" } } },
},create function public.lead_from_submission(submission_id uuid) returns jsonb
language plpgsql security definer set search_path = '' as $$
declare v_id uuid;
begin
insert into public.leads (organization_id, name, email)
select s.tenant_id, s.answers ->> 'name', s.answers ->> 'email'
from better_supabase.form_submissions s where s.id = submission_id
returning id into v_id;
return jsonb_build_object('subjectType', 'lead', 'subjectId', v_id);
end;
$$;Public forms
With the share-links module, a link with subject type form and role respond lets anyone who holds it read and submit the form, without an account:
const link = await shareLinks
.create(organizationId, "form", form.id, "respond")
.orThrow();
// On the public page:
const publicForm = await forms.getPublic(token).orThrow();
await forms
.submitPublic(token, answers, { botToken: turnstileToken })
.orThrow();An unknown, revoked or expired token fails with FORM_LINK_INVALID. With the rate-limit SQL module, each caller (the user, else the right-most x-forwarded-for address) gets 20 public submissions per form per hour, a BS429 error with Retry-After after that. options.publicLimit sets { max, period } (an ISO 8601 duration), or false to turn it off. To check a bot challenge, implement the before_public_form_submission(form_id uuid, answers jsonb, bot_token text) hook and raise when the token fails; Postgres can't call the challenge's API, so verify it in an Edge Function or keep a table of tokens your server has verified.
Vue
useBlockController from better-supabase/vue runs
createQuestionnaireController with its options, as
Block controllers
explains. state is a shallow ref of the snapshot and actions are the
controller's actions. The work starts on mount, and the controller is
disposed with the component.
<script setup lang="ts">
import { useBlockController } from "better-supabase/vue";
import {
createQuestionnaireController,
type QuestionnaireForm,
} from "better-supabase/blocks/forms";
const { version } = defineProps<{ version: QuestionnaireForm }>();
const { state, actions } = useBlockController(
createQuestionnaireController,
{ form: version, onSubmit: (answers) => submitForm(formId, answers) },
false,
);
</script>
<template>
<p>{{ state.step?.title }}</p>
<button @click="actions.next()">Next</button>
</template>submitForm stands for your server call that runs forms.submit(formId, answers).
Svelte
useBlockController from better-supabase/svelte runs
createQuestionnaireController with its options. It returns a readable store of
the snapshot, read with $, with the actions on .actions. The work starts on
mount, and the controller is disposed with the component.
<script lang="ts">
import { useBlockController } from "better-supabase/svelte";
import {
createQuestionnaireController,
type QuestionnaireForm,
} from "better-supabase/blocks/forms";
let { version }: { version: QuestionnaireForm } = $props();
const questionnaire = useBlockController(createQuestionnaireController, {
form: version,
onSubmit: (answers) => submitForm(formId, answers),
}, false);
</script>
<p>{$questionnaire.step?.title}</p>
<button onclick={() => questionnaire.actions.next()}>Next</button>Solid
useBlockController from better-supabase/solid runs
createQuestionnaireController with its options. state() reads the snapshot
through from, and actions are the controller's actions. The work starts on
mount, and the controller is disposed with the owner.
import { useBlockController } from "better-supabase/solid";
import {
createQuestionnaireController,
type QuestionnaireForm,
} from "better-supabase/blocks/forms";
export function Component(props: { version: QuestionnaireForm }) {
const { state, actions } = useBlockController(
createQuestionnaireController,
{ form: props.version, onSubmit: (answers) => submitForm(formId, answers) },
false,
);
return (
<>
<p>{state().step?.title}</p>
<button onClick={() => actions.next()}>Next</button>
</>
);
}Events and hooks
The module records form.created, form_version.published, form_submission.submitted (with versionId and source: member, public or service), form_submission.reviewed (with status), form_submission.archived, form_submission.restored and form_submission.purged. The submission events carry the linked subjectType and subjectId, so an outbox consumer can count submissions per record. Creating a form, publishing, reviewing, archiving, restoring and purging go to the audit log. It calls before_form_publish, after_form_publish, before_form_submission, after_form_submission and before_public_form_submission.
With ReUI
useQuestionnaire is a registry item: install it with npx shadcn add @better-supabase/use-forms, which writes hooks/use-forms.ts into the app. It holds the answers, the visible steps and the issues per field for one version, so a ReUI Stepper and its questionnaire layouts render the form without other state:
"use client";
import { useQuestionnaire } from "@/hooks/use-forms";
const q = useQuestionnaire({
form: version,
onSubmit: (answers) => forms.submit(formId, answers).orThrow(),
});
// <Stepper value={q.step?.key} onValueChange={q.goTo}>: one StepperItem per q.steps entry, completed={step.completed}
// q.step?.fields: render each with its input, value={q.answers[field.key]}, error={q.issues[field.key]?.[0]}
// Back: q.back(), hidden when q.isFirst. Next: q.isLast ? q.submit() : q.next()next() checks the step's fields against the version's schema and stays on the step when one fails. Answering a field that hides later steps moves past them, and submit() sends only the answers of fields still visible. Submissions render in a ReUI data grid from listSubmissions, with accept and reject actions that call review.
Signatures moved to their own block in 0.14; see Signatures.
Without the client
db.forms is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createForms } from "better-supabase/blocks/forms";
const forms = createForms({ transport });
const form = await forms
.create({ organizationId, key: "signup", title: "Sign up" })
.orThrow();
await forms
.publish(form.id, {
steps: [
{
key: "contact",
title: "Contact",
fields: [
{ key: "name", label: "Name", type: "text", required: true },
{ key: "email", label: "Email", type: "email", required: true },
{
key: "plan",
label: "Plan",
type: "option",
options: [
{ value: "free", label: "Free" },
{ value: "team", label: "Team" },
],
},
],
},
{
key: "team",
showIf: { field: "plan", equals: "team" },
fields: [
{
key: "seats",
label: "Seats",
type: "integer",
min: 2,
required: true,
},
],
},
],
})
.orThrow();
await forms.update(form.id, { status: "open" }).orThrow();
await forms
.submit(form.id, { name: "Ada", email: "ada@example.com" })
.orThrow();Last updated on
Digital asset management
Renditions of drive files made through the drive's preview renderers, and usage rights with a territory, a channel and an expiry date.
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.