Block controllers
The framework-agnostic state behind every block hook, and the ports that give it storage, shortcuts, files, push and deep links on the web and React Native.
Every block hook, such as useNotifications or useCommandSearch, is a
thin wrapper over a controller: a plain TypeScript object that loads the
block's data, follows its realtime topic and runs its actions. Controllers
import no React, DOM or React Native code, so the same hook runs in React DOM
and React Native, and a Vue, Svelte or Solid UI can use the controller
directly.
The contract
A controller has four members, the external-store contract that React's
useSyncExternalStore and the other frameworks' stores expect:
| Member | What it does |
|---|---|
subscribe(fn) | Adds a listener. The first one starts the work (loads, realtime, shortcuts); the last one to leave stops it |
getSnapshot() | The current state, the same object until it changes |
actions | The methods, such as refresh, dismiss or toggle |
dispose() | Stops the work and drops every listener |
import { createNotificationsController } from "better-supabase/blocks/notifications";
import { topicPort } from "better-supabase/realtime";
const unread = createNotificationsController({
auth: bsb.auth,
ports: { topic: topicPort(bsb.supabase) },
topic: `notifications:${userId}`,
load: () => listNotifications(),
});
const stop = unread.subscribe(() => {
badge.textContent = String(unread.getSnapshot().count);
});A Vue binding is a shallowRef that subscribe updates; a Svelte one is a
readable store whose start function returns the unsubscribe.
Controllers by block
Each block exports its controllers from its main entry,
better-supabase/blocks/<name>. The React hooks are registry items that you
copy into the app, so you can change them: npx shadcn add @better-supabase/use-<name> writes hooks/use-<name>.ts, which builds the
controllers from the provider's client. Vue, Svelte and Solid run a
controller with useBlockController (see
Vue, Svelte and Solid).
| Block | Controllers | Hooks |
|---|---|---|
ai-chat | createAiChatsController, createAiChatTreeController, createAiModelsController, createAiShareController | useAiChats, useAiChatTree, useAiModels, useAiShare |
announcements | createAnnouncementsController | useAnnouncements |
api-keys | createApiKeysController | useApiKeys |
audit | createAuditLogController | useAuditLog |
billing | createPlanPickerController | usePlanPicker |
bookings | createAvailableSlotsController | useAvailableSlots |
bulk-actions | createBulkSelectionController | useBlockController |
calendar | createCalendarController | useCalendar |
comments | createCommentsController | useComments |
entitlements | createFeatureGateController | useFeatureGate |
forms | createQuestionnaireController | useQuestionnaire |
inbox | createInboxController, createConversationController, createInboxWidgetController | useInbox, useConversation, useInboxWidget |
mfa | createMfaController, createStepUpController | useMfa, useStepUp |
notifications | createNotificationsController | useNotifications |
onboarding | createOnboardingController | useOnboarding |
organizations | createOrganizationsController, createMembersController, createInvitationsController | useOrganizations, useMembers, useInvitations |
reactions | createReactionsController | useReactions |
pipelines | createBoardController | useBlockController |
rules | createRuleBuilderController | useRuleBuilder |
saved-views | createSavedViewsController, matchSavedViews | useSavedViews |
search | createCommandSearchController | useCommandSearch |
sessions | createOAuthConsentController, createOAuthGrantsController | useOAuthConsent, useOAuthGrants |
settings | createSettingsController, settingFields | useSettings |
tags | createTagInputController | useTagInput |
undo | createUndoController | useUndoStack |
usage | createUsageMeterController | useUsageMeter |
workflows | createWorkflowRunsController, createWorkflowRunController | useWorkflowRuns, useWorkflowRun |
workflow-editor | createWorkflowEditorController, createWorkflowCanvasRunController | useWorkflowEditor, useWorkflowCanvasRun |
Controllers with a moving input take it as an action instead of starting
over: setRange on the calendar and bookings controllers and setSubjects
on the reactions controller keep the shown data until the new data arrives.
The comments, reactions and tag input controllers work on records: they take
the record as subject (subjects for reactions), a RecordRef such as
{ type: "task", id: taskId }, and a block client built with its tenant.
The hooks build that client from the provider's client, with the schema from
its blocks option and the tenant from its tenant option or the session's
tenant claim (see Block hooks).
Writing a React hook
The registry hooks use four exports of better-supabase/react, and you can
use them for a hook of your own. useBlockEnv() returns the provider's
client, session and ports, useBlockTenant(env) the tenant it acts in (and
renders again when it changes), and useController(create, deps) makes the
controller, makes it again when deps change and returns its state and
actions as view. envBlockOptions(env, block) from better-supabase/blocks
gives a block client the transport and schema gen wrote for that block.
"use client";
import { envBlockOptions, type RecordRef } from "better-supabase/blocks";
import {
createComments,
createCommentsController,
} from "better-supabase/blocks/comments";
import {
useBlockEnv,
useBlockTenant,
useController,
} from "better-supabase/react";
export function useComments(subject: RecordRef) {
const env = useBlockEnv();
const tenant = useBlockTenant(env);
return useController(
() =>
createCommentsController({
client: createComments({
...envBlockOptions(env, "comments"),
...(tenant === undefined ? {} : { tenant }),
}),
auth: env.auth,
ports: env.ports,
subject: tenant === undefined ? null : subject,
topic: "messages",
}),
[env, tenant, subject.type, subject.id],
).view;
}Vue, Svelte and Solid
useBlockController(create, options) from better-supabase/vue,
better-supabase/svelte and better-supabase/solid makes a controller once
and binds it to the framework. auth and ports come from the app's
better-supabase plugin, context or provider unless options has them. The
work starts on mount and stops when the component goes away.
Pass false as a third argument for a controller that takes neither auth
nor ports, so it runs without a provider: createAiModelsController,
createAiShareController, createAttachmentUploadController,
createAvailableSlotsController, createCalendarController,
createQuestionnaireController, createSavedViewsController and
createCommandSearchController. Without it, the call reads the provider and
fails when there is none.
| Entry | Returns |
|---|---|
better-supabase/vue | { state, actions }, with state a shallow ref of the snapshot |
better-supabase/svelte | a readable store of the snapshot (read with $), with .actions |
better-supabase/solid | { state, actions }, with state() reading the snapshot through from |
<script setup lang="ts">
import {
createAnnouncements,
createAnnouncementsController,
rpcTransport,
} from "better-supabase/blocks/announcements";
import { useBlockController, useSupabase } from "better-supabase/vue";
const { organizationId } = defineProps<{ organizationId: string }>();
const supabase = useSupabase();
const { state } = useBlockController(createAnnouncementsController, {
client: createAnnouncements({ transport: rpcTransport(supabase) }),
organizationId,
});
</script>
<template>
<ul>
<li v-for="item in state.items ?? []" :key="item.id">{{ item.title }}</li>
</ul>
</template>The trio every block has
A block's frontend is three parts. The client is the block's create<Name>,
which wraps the SQL functions as typed calls and takes hooks. The controller is
the generic createBlockQuery and createBlockMutation, which call any method of
any client and keep its state. The hooks are useBlockQuery, useBlockMutation
and useBlockEvent (and the Vue, Svelte and Solid versions) over that controller.
A block with its own UI state, such as bookings' slot picker, adds a bespoke
controller in client.ts next to it.
So a block only has to supply its client. tests/blocks/client-trio.test.ts fails
for a block that declares an entity that changes after it is created but has no
create. Three blocks are listed with the reason they have none: credentials
(read through vaultCredentials()), field-encryption (used by the SQL read
paths of the blocks that encrypt) and impersonation (started through the
support session). The list can only shrink.
Any block method
Blocks without a controller of their own, and renamed blocks, use three
generic hooks. They take any block client and a method name, and type the
arguments and data from the method. Each framework entry has them:
better-supabase/react, better-supabase/vue, better-supabase/svelte and
better-supabase/solid.
| Hook | What it does |
|---|---|
useBlockQuery(client, method, args, options) | Calls a read method on mount and when args change; refetch calls it again |
useBlockMutation(client, method) | mutate(...args) calls a write method and tracks status, data and error |
useBlockEvent(source, events, pattern, handler) | Calls handler for each block event matching pattern, such as "task.*" |
import {
useBlockEvent,
useBlockMutation,
useBlockQuery,
} from "better-supabase/react";
import { blockEvents } from "@/lib/supabase/blocks.generated";
export function TaskList({ tasks, workspaceId }: Props) {
const list = useBlockQuery(tasks, "list", [workspaceId, { open: true }], {
refetchOn: { source: bsb, types: ["task.created", "task.updated"] },
});
const rename = useBlockMutation(tasks, "update");
useBlockEvent(bsb, blockEvents, "task.*", (event) => {
console.log(event.type, event.data.taskId);
});
if (list.status === "loading") return <TaskSkeleton />;
if (list.status === "error") return <TaskError onRetry={list.refetch} />;
// ...
}refetchOn takes the client's betterSupabase (or anything with events)
and the event types that make the read stale. useBlockEvent types each
event's data from blockEvents in blocks.generated.ts.
One status for a list
blockListStatus(list) turns the state of a read that returns rows into one
union the list reads: loading, empty, error (with the DbError) or ready
(with rows). Rows that are already loaded stay ready while the read runs
again, and a failed read is error even when older rows exist. It uses no
framework, so it works with the Vue, Svelte and Solid hooks too.
const list = useBlockQuery(leave, "list", [{ organizationId }], {
refetchOn: blockRealtimeRefetch(leaveBlock, "leave_request", bsb),
});
const status = blockListStatus(list);blockRealtimeRefetch(block, entity, source) returns the refetchOn for an
entity whose manifest declares realtime: true, and undefined for one that
does not, so the list subscribes only when the manifest says its changes reach
clients. It listens to the block events that start with <entity>., or to every
event of the block when none does.
Sharing reads through an engine
By default each useBlockQuery keeps its own read. Pass engine and the
block's instance (its key in createBlocks) to keep the read in a data
engine instead: every hook on the same method and arguments then shares one
entry, and a useBlockMutation with the same options makes the instance's
reads stale when it succeeds. blockControllerEngine(queryClient) from
better-supabase/query keeps them in TanStack Query under the keys
blockQueries uses, so a hook and a
useQuery(bq.tasks.list(...)) read the same cache entry.
import { blockControllerEngine } from "better-supabase/query";
const blockReads = {
engine: blockControllerEngine(queryClient),
instance: "tasks",
};
const list = useBlockQuery(tasks, "list", [workspaceId], blockReads);
const rename = useBlockMutation(tasks, "update", blockReads);createBlockQuery and createBlockMutation take the same options outside
a framework hook.
Optimistic writes
With an engine, a write can show its result in the cached reads before the
call answers. Pass optimistic with the reads to rewrite and an apply
function, or build one with optimisticUpdate, optimisticArchive or
optimisticReorder. The reads are put back when the call fails, so a
STALE_WRITE conflict shows the old row again, and they are marked stale
when it succeeds. The helpers handle a cached list of rows and a page with
items; key names the row's id (id by default).
import { optimisticUpdate } from "better-supabase/react";
const rename = useBlockMutation(tasks, "update", {
...blockReads,
optimistic: optimisticUpdate({
reads: ["list"],
target: (input) => ({
id: input.changes[0].taskId,
patch: { title: input.changes[0].value },
}),
}),
});optimistic needs engine: without one there is no cache to rewrite.
Keep the object stable between renders, since the hook reads it once.
Ports
A controller reaches the platform only through ports, small interfaces the
client carries in bsb.ports. createClient from better-supabase/client
fills the web ones; a React Native app passes nativePorts() from
better-supabase/client/native to createNativeClient.
| Port | Type | Web default | React Native default | Used by |
|---|---|---|---|---|
topic | TopicPort | topicPort(supabase) | topicPort(supabase) | Every realtime controller |
storage | StoragePort | webStorage() over localStorage | nativeStorage(AsyncStorage) | useInboxWidget |
keyboard | KeyboardPort | webKeyboard() over keydown | none | useCommandSearch |
files | FilePickerPort | webFilePicker() | nativeFilePicker(DocumentPicker) | Apps, for now |
upload | UploadPort | storageUpload(supabase) | storageUpload(supabase) | Apps, for now |
push | PushTokenPort | webPushToken({ vapidPublicKey }) | expoPushToken(Notifications) | Apps, for now |
links | DeepLinkPort | webDeepLinks() | nativeDeepLinks(Linking) | Apps, for now |
The topic port defaults to topicPort(bsb.supabase) from
better-supabase/realtime when bsb.ports has none. A port the platform lacks stays unset, and the controller works
without it: useCommandSearch on a phone has no Cmd+K.
import { createNativeClient, nativePorts } from "better-supabase/client/native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import * as Linking from "expo-linking";
import * as Notifications from "expo-notifications";
export const bsb = createNativeClient(betterSupabase, supabase, {
ports: nativePorts({
supabase,
storage: AsyncStorage,
linking: Linking,
notifications: Notifications,
projectId: process.env.EXPO_PUBLIC_EAS_PROJECT_ID,
}),
});On the web, createClient(betterSupabase, { env, ports }) merges your
ports over the defaults, for example a push port with your VAPID key:
import { createClient, webPushToken } from "better-supabase/client";
export const bsb = createClient(betterSupabase, {
env,
ports: { push: webPushToken({ vapidPublicKey: env.vapidPublicKey }) },
});Testing a controller
Pass fakes for the client and the ports, subscribe once, and read the snapshot. No renderer is needed:
import { createNotificationsController } from "better-supabase/blocks/notifications";
const joined: string[] = [];
const controller = createNotificationsController({
auth: { current: () => signedIn, subscribe: () => () => undefined },
ports: {
topic: (topic, watch) => {
joined.push(topic);
watch.onStatus("subscribed");
return { leave: () => undefined, send: () => undefined };
},
},
topic: "notifications:u1",
load: async () => [{ id: "n1", readAt: null }],
});
const stop = controller.subscribe(() => undefined);
await Promise.resolve();
expect(controller.getSnapshot().count).toBe(1);
stop();defineController and whileSignedIn from better-supabase/client build
controllers of your own the same way.
Last updated on