Notifications
In-app notifications with per-recipient state, subject subscriptions, channel preferences, email and push deliveries, and realtime updates on a private topic.
The notifications SQL module stores one event per change
and one row per recipient, with read, dismissed and resolved state each user
controls. createNotifications from better-supabase/blocks/notifications
sends and reads them with typed data, and the useNotifications hook keeps a
list current over Supabase Realtime. The hook is a registry item: install it
with npx shadcn add @better-supabase/use-notifications, which writes
hooks/use-notifications.ts into the app.
pnpm better-supabase add notificationsConfig installs the block for you when gen.powersync.instances or
gen.clientBlocks names it.
Sending goes through notify(jsonb), a security definer function, so a
client can't write notification rows directly or pick another user as the
actor. With the access contract installed, the sender
needs notifications.send in the organization and every recipient needs
notifications.read; the actor and non-members are left out. With the
outbox, every notification also emits
notification.created.
Sending
Declare each type with a Standard Schema for its data. send validates the
data before it reaches the database:
Server code calls the notifications instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useNotifications } = defineDataHooks(
"notifications",
(db: AppDb) => db.notifications,
);const rows = await db.notifications.list({ limit: 50 }).orThrow();"use client";
import { useNotifications } from "@/lib/supabase/hooks";
const rows = useNotifications({ limit: 50 });const ctx = await bsb.context();
const notifications = notificationsFor(ctx.auth.claims);
await notifications
.send("task.assigned", {
tenant: organizationId,
recipients: [assigneeId],
subject: { type: "task", id: task.id, label: task.title },
actionPath: `/tasks/${task.id}`,
data: { title: task.title },
key: `task-assigned-${task.id}-${assigneeId}`,
})
.orThrow();send returns { id, eventId, recipients }: the event id (twice, id and
eventId hold the same value) and the user ids that hold it after the watchers, the audience hook, preferences and the read
filter are applied, or null when nobody was left to notify. A composer
can report how many people it reached from recipients.length, and
onSent and the notification.created block event get the same list.
With a key, sending again in the same organization returns the first id,
so a retried request never notifies twice. In SQL, send_notification(jsonb)
returns the same { "id", "recipients" } object and notify(jsonb) returns
only the id. rpcTransport(supabase) calls the
same functions over the Data API instead, when the block schema is exposed.
| Input | Meaning |
|---|---|
recipients | User ids. Subject watchers and the notification_audience hook add more |
subject | What it is about, { type, id, label? }. Watchers of the subject get it too |
activity | participating (default) reaches every watcher; all reaches only watchers at level all |
priority | One of options.priorities (low, normal, high, urgent). Defaults to normal |
channels | The channels to deliver on. Defaults to options.channels |
includeActor | Also notify the user who caused it |
watchers | false leaves the subject's watchers out, for a composer that reaches named people only (a mention, an assignment); ignore still holds |
exclude | User ids left out after the watchers and the hook are added, such as the members a separate mention already reached |
permission | A permission key. The holders in tenant are added. It needs tenant. A provider uses authorization.functions.holdersOf and refuses the send when that is unset, rather than notifying every member |
resolved | Store it already resolved, for a record of something that needs no action |
actions | Up to 10 buttons, { key, label, operation?, payload? }, that the app renders and handles. See below |
actorId | The actor when the service sends for a user. A signed-in sender is always the actor themselves |
Actions
actions stores what the recipient can do from the notification itself,
such as approving a request. The block only stores and returns them: the app
renders a button per action and runs operation (an operation name of your
own, such as an oRPC procedure) with payload when the user picks one.
await notifications
.send("approval.requested", {
tenant: organizationId,
recipients: [approverId],
subject: { type: "invoice", id: invoice.id },
data: { amount: invoice.total },
actions: [
{
key: "approve",
label: "Approve",
operation: "invoices.approve",
payload: { id: invoice.id },
},
{ key: "reject", label: "Reject", operation: "invoices.reject" },
],
})
.orThrow();send_notification checks them before it stores anything: an array of at
most 10 objects with a unique key (letters, digits, _, ., : and -,
at most 64), a label of 1 to 100 characters, an optional operation of at
most 200 characters and an optional payload object, and no other keys.
Anything else fails with NOTIFICATION_ACTIONS_INVALID. Only the service
role sends actions, because a button runs its operation for whoever presses
it: a signed-in sender gets NOTIFICATION_ACTIONS_FORBIDDEN, so send them from
your server. Items return them in item.actions, an empty array when the
notification has none.
Reading
The same client reads the signed-in user's notifications. render runs at
read time, so text follows the reader's locale and later copy changes:
const items = await notifications
.list({ tenant: organizationId, status: "unread", locale: "nl" })
.orThrow();
const { unread, actionable } = await notifications
.counts({ tenant: organizationId })
.orThrow();
const one = await notifications.get(items[0].id).orThrow();
const { count, items: changed } = await notifications
.markRead({ ids: [items[0].id] })
.orThrow();
await notifications.dismiss([items[0].id]);
await notifications.resolve({
type: "approval.requested",
subject: { type: "invoice", id },
resolution: { action: "approve", by: userId },
});resolution is an optional JSON object stored on every recipient's copy, so
the list can show how the notification was handled ("Approved by Ada").
Items return it in item.resolution, null when there is none. A value
that isn't an object fails with NOTIFICATION_RESOLUTION_INVALID.
Each user gets a recipient row for the event. A list() item's id (also
recipientId) is that row's id, and eventId is the id send returned.
get, markRead, markUnread, dismiss and resolve take the recipient
row id, so pass item.id, not the id from send.
get(id, { locale?, include? }) reads one of the caller's notifications by
its recipient row id, dismissed ones included, rendered like a list item, or
null when the caller has no such notification. It calls
get_notification(id).
get, list and page parse each item's data with the schema of its type
in types, so item.data narrows on item.type: after checking
item.type === "approval.requested", item.data.amount is a number. Data
the schema rejects makes the read fail with a validation error and the hint
NOTIFICATION_DATA_INVALID; a type that isn't in types keeps its data as
stored. NotificationOf<typeof types> is that item type.
bulk(ids, action, options) is the same calls in the shape every block with a
bulk call shares (ADR 0854). action is read, unread or dismiss, and the
result is { succeeded, failed: [{ id, error }] }: an id the call did not
change (missing, not yours, or already in that state) is failed with
not_found. More ids than options.limit (500 by default) fail with
BULK_TOO_MANY before anything runs.
const { succeeded, failed } = await notifications
.bulk(selectedIds, "dismiss")
.orThrow();markRead, markUnread, dismiss and resolve return { count, items }:
how many rows changed, and the caller's own notifications as they are after
the change, so an app can update its state without reading them back. For
resolve, count covers every recipient and items holds only the
caller's own copies, which is empty for the service. The SQL functions
return the same object as jsonb, with each item in the shape that
list_notifications returns.
list pages with cursor and limit (50 by default, at most 500). Pass the
last item of the previous page as cursor: the block orders by created_at
and then id, so items created at the same instant are not skipped. It filters with status (all, unread, read, unresolved, settled),
read, resolved, dismissed, types, subjectTypes and search. resolve marks every recipient's copy of a type about one subject
as handled, for example when someone approves the invoice.
search matches text in the summary, the subject label, the type and,
with the profiles module, the actor's username, full name, first and last
name, ignoring case; % and _ in it are plain characters. subjectTypes keeps
notifications about subjects of the listed types. Every status except
settled leaves dismissed notifications out, and settled lists the
resolved and the dismissed ones, for an archive view.
read, resolved and dismissed are independent booleans that combine
with each other and with status. read: false keeps unread ones, and
resolved: true keeps resolved ones. dismissed defaults to false;
true lists only dismissed notifications and null lists both. settled
keeps its meaning and ignores dismissed.
| View | Filters |
|---|---|
| Unread and open | { read: false, resolved: false } |
| Handled | { resolved: true } |
| Dismissed | { dismissed: true } |
| Everything | { dismissed: null } |
| Archive (settled) | { status: "settled" } |
Without a resolved_at column, resolved: true matches nothing and
resolved: false matches everything.
Pages with a total
An inbox with numbered pages uses page, which takes the same filters with
an offset instead of before and returns the matching total next to the
items:
const { items, total } = await notifications
.page({ tenant: organizationId, search: "invoice", limit: 20, offset: 40 })
.orThrow();It calls notification_page(tenant, status, types, subject_types, search, max_items, skip, read, resolved, dismissed, before, before_id, total_cap).
Both reads build their query from the filters you pass, so the default inbox
reads the partial inbox index in order. The total stops at totalCap
(default 10,000) and totalCapped says when it did, so an inbox with
hundreds of thousands of rows is never counted in full; pass totalCap: null
for an exact count. Pass cursor (the last item's createdAt and id)
instead of offset to page by key: the page then never reads the skipped
rows, and hasMore says whether an older page exists. list stays the
cheaper choice for an infinite scroll.
page returns limit, the page size it applied: limit clamped to 1
through 500. A page with fewer items than you asked for and hasMore set
asked for more than 500 rows, so ask again from where it stopped.
page also sorts and filters in ways list does not:
| Option | What it does |
|---|---|
order | newest (default), oldest, type, subject or status, each but the first two with _desc |
excludeTypes | Leaves out these types |
subjectIds | Keeps notifications about these subject ids |
anyOf | Keeps notifications that match at least one group; an empty array matches nothing |
type and subject compare the type and the lowercased subject label by
code point, so a client that merges its own items into the page can sort
them the same way. status sorts unread, then read, then resolved. Ties
sort newest first. cursor pages only newest; page another order with
offset.
An anyOf group takes types, excludeTypes, subjectTypes, read and
resolved, and a notification matches a group when it matches every key in
it. The groups combine with the other filters, so a "happened" view (anything
that is not an open request) is one call:
const happened = await notifications
.page({
tenant: organizationId,
order: "status",
anyOf: [{ excludeTypes: ["approval.requested"] }, { resolved: true }],
})
.orThrow();The SQL parameters are exclude_types, subject_ids, any_of (a jsonb
array of objects with snake_case keys) and order_by.
Unread again and counts
markUnread({ ids, tenant? }) clears the read time of the caller's own
notifications, so a reader can keep one for later. It returns the count and
the changed notifications and leaves dismissed notifications alone.
counts() returns unread, actionable (unresolved notifications of the
actionable types) and actionableSubjects, which counts each subject
once. Each count stops at cap (default 100), so a badge reads at most 100
rows of the unread index and shows "99+" above it; counts({ cap: null })
counts every row. Two reminders about the same invoice count as two in actionable and
as one in actionableSubjects, which suits a badge that counts open tasks.
Hydrating a page
render runs once per item. When it needs data from elsewhere, such as actor
names or subject titles, hydrate loads it for the whole page in one call,
and render reads the result from context.hydrated:
const notifications = createNotifications({
transport,
types,
hydrate: async (items) => ({
tasks: await loadTaskTitles(
items.flatMap((item) => (item.subject ? [item.subject.id] : [])),
),
}),
render: (item, { locale, hydrated }) => ({
title: t(locale, item.type, {
task: hydrated?.tasks.get(item.subject?.id ?? ""),
}),
}),
});With the profiles module installed alongside,
list({ include: ["actor"] }) adds each item's actor (id, username,
fullName, firstName, lastName, avatar and avatarPath, those the
profiles table has) in one call to notification_actors(ids), which returns
only actors of the caller's own notifications.
avatarPath is a Storage object path. With the avatars option the block
turns it into actor.avatarUrl: pass a function of the path, such as
getPublicUrl from a supabase-js client for a public bucket:
const users = supabase.storage.from("users");
const notifications = createNotifications({
transport,
types,
avatars: (path) => users.getPublicUrl(path).data.publicUrl,
});Realtime
By default each new or changed recipient row is broadcast on the user's
private topic, notifications:{userId}. The payload carries ids only; the
client reloads through RLS. useNotifications joins the topic with the
user's token, reloads on each message and after a reconnect, and merges any
other sources you pass:
"use client";
import { useNotifications } from "@/hooks/use-notifications";
export function Inbox({
userId,
organizationId,
}: {
userId: string;
organizationId: string;
}) {
const { items, count } = useNotifications({
topic: `organization:${organizationId}:notifications:${userId}`,
load: () =>
fetch(`/api/notifications?organization=${organizationId}`).then((res) =>
res.json(),
),
});
return <Bell count={count} items={items ?? []} />;
}The same hook runs in React Native: the Expo example
(apps/examples/expo-powersync/src/lib/notifications.ts) shows an unread
count with it. Outside React, createNotificationsController from
better-supabase/blocks/notifications holds the same state (see
block controllers).
| Option | Default | Meaning |
|---|---|---|
realtime | broadcast | broadcast, changes (adds the table to supabase_realtime) or none |
topic | notifications:{userId} | The topic template; {tenantId} adds the organization |
createdEvent | notification_created | The broadcast event for a new notification |
updatedEvent | notification_updated | The broadcast event for a read, dismissed or resolved one |
The module adds a realtime.messages policy so each user can join only
topics that match the template with their own id.
Vue
useBlockController from better-supabase/vue runs
createNotificationsController with its options, as
Block controllers explains;
auth and ports come from app.use(betterSupabase(bsb)) unless you pass
them. 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 { createNotificationsController } from "better-supabase/blocks/notifications";
import { useBlockController } from "better-supabase/vue";
const { userId } = defineProps<{ userId: string }>();
const { state, actions } = useBlockController(createNotificationsController, {
topic: `notifications:${userId}`,
load: () => listNotifications(),
});
</script>
<template>
<p>{{ state.count }}</p>
<button @click="actions.refresh()">Refresh</button>
</template>listNotifications stands for your server call that runs
notifications.list().
Svelte
useBlockController from better-supabase/svelte runs
createNotificationsController with its options; auth and ports come from
setBetterSupabase(bsb) unless you pass them. 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 { createNotificationsController } from "better-supabase/blocks/notifications";
import { useBlockController } from "better-supabase/svelte";
let { userId }: { userId: string } = $props();
const notifications = useBlockController(createNotificationsController, {
topic: `notifications:${userId}`,
load: () => listNotifications(),
});
</script>
<p>{$notifications.count}</p>
<button onclick={() => notifications.actions.refresh()}>Refresh</button>Solid
useBlockController from better-supabase/solid runs
createNotificationsController with its options; auth and ports come from
<BetterSupabaseProvider client={bsb}> unless you pass them. 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 { createNotificationsController } from "better-supabase/blocks/notifications";
import { useBlockController } from "better-supabase/solid";
export function Component(props: { userId: string }) {
const { state, actions } = useBlockController(createNotificationsController, {
topic: `notifications:${props.userId}`,
load: () => listNotifications(),
});
return (
<>
<p>{state().count}</p>
<button onClick={() => actions.refresh()}>Refresh</button>
</>
);
}Subscriptions and preferences
Users watch a subject with subscribe({ subject, level }). Level all gets
routine activity too, participating only what involves them, and ignore
mutes the subject even when a sender names them. null removes the
subscription.
To make the author or an assignee follow a subject without overriding a
choice they made, pass ifAbsent: true with their userId:
await notifications
.subscribe({
subject: { type: "task", id: taskId },
level: "participating",
tenant: organizationId,
userId: assigneeId,
ifAbsent: true,
})
.orThrow();It adds the level only when the member has none for the subject, so their
ignore or all stays. A signed-in sender with the send permission in the
tenant may do this for another member of it; without ifAbsent, only the
service sets another member's level. In SQL the flag is
set_notification_subscription(..., member, if_absent => true).
The caller reads their own subscriptions with subscriptions({ tenant?, subject? }), where subject is { type, id? }, and their channel choices
with preferences({ tenant? }). With tenant, preferences returns the
choices for that organization and the ones that hold everywhere (tenant
null), so a settings page can show both. In SQL they are
list_notification_subscriptions(tenant, subject_type, subject_id) and
list_notification_preferences(tenant), granted to authenticated. A page
payload RPC that returns list_notification_subscriptions rows parses each
with subscriptionOf(row) from better-supabase/blocks/notifications, the
way the client does; it returns undefined for a row with an unknown level.
With
database.sql.api set, the module also writes security_invoker views of
notification_recipients and notification_preferences in that schema, so
the Data API and PowerSync uploads reach them while row level security on
the tables still decides every row.
On PowerSync, powersyncNotificationsTransport answers preferences and
setPreference from the synced notification_preferences table, so a
settings page works offline, and notificationPreferencesRoute(server, powersync) replays the changes. Removing a choice (enabled: null) still
goes to the server.
setPreference({ type, channel, enabled, tenant? }) turns a type (or *)
on or off on a channel. The most specific row wins: the organization and
type, the organization and *, everywhere and type, everywhere and *,
then options.channelDefaults. Without a default, in_app is on and every
other channel is off until the user turns it on, so nobody gets email they
did not ask for. The block resolves the preferences of all recipients in one
query, and notify refuses more than options.maxRecipients (1,000)
recipients with NOTIFICATION_TOO_MANY_RECIPIENTS; fan out larger audiences
from a job.
Deleted subjects
subject_type and subject_id are text with no foreign key, so deleting a
subject row leaves its notifications in every recipient's inbox. Without
blocks.notifications.on, every subject type in config.recordTypes whose table is yours (outside the block schema) cascades
(ADR 0370). To choose the types, list them in blocks.notifications.on with
cascade: true, and the module writes an after delete trigger on each
table that deletes the subject's notifications (their recipients and
deliveries go with them) and the subscriptions to it:
blocks: {
notifications: {
on: {
expense: { table: "expenses", cascade: true },
"support-ticket": { table: "support_tickets", cascade: true },
},
},
},The key is the subject_type your notifications store, and it may contain
hyphens. id names the subject's id column when it isn't id. Without
on the module reads config.recordTypes, so a registered type
with cascade: true cleans up its notifications too. A list of registered
type names (on: ["expense"]) limits it to those. The subject tables
must exist before the module file, and the events table needs its
subjectType and subjectId columns.
Time off doesn't need a table of your own: the leave block keeps requests, their approvals and each member's balance.
Email, push and other channels
options.resolveAddress names an app function, better_supabase.member_address(user uuid, channel text) returns text, that says where a member is reached on a channel, such as a work email in your own profile table. Claimed deliveries, claimed digests and the suppression of a bounced address use it, and a null answer falls back to the member's sign-in email. The function runs inside the block's definer functions, so it needs no grant for signed-in users.
options.externalRecipients (default false) lets a notification reach people who are not members. send_notification then takes an external list next to recipients, where each entry is { "address": "someone@example.com" } or { "contact": "<uuid>" }. A contact is resolved through resolveAddress, with the contact id in the user argument, so the option needs it. External recipients have no inbox, count toward maxRecipients, and are reached on the email channel only, with the same claim, retry and bounce suppression as members. The recipient user column becomes nullable, with a check that exactly one of user, address and contact is set, and add and upgrade write the columns and the check into existing databases.
Every channel except in_app gets a pending delivery row per recipient.
Pass email for mail and a NotificationChannel for any other channel,
then call deliver() from a cron route or a job, with a service connection:
import "server-only";
import {
createNotifications,
resendTransport,
sqlTransport,
} from "better-supabase/blocks/notifications";
import {
createPush,
expoPush,
expoPushChannel,
} from "better-supabase/blocks/push";
import { env } from "@/env";
import { types } from "@/lib/notifications";
import { unsubscribeUrl } from "@/lib/unsubscribe";
const devices = createPush({ transport: sqlTransport(postgres.admin) });
const notifications = createNotifications({
transport: sqlTransport(postgres.admin),
types,
email: {
transport: resendTransport({ apiKey: env.RESEND_API_KEY }),
from: "Acme <notifications@acme.com>",
unsubscribe: (message) => ({
url: unsubscribeUrl(message.userId, message.notification.type),
}),
},
channels: [expoPushChannel({ push: expoPush({ devices }), devices })],
});
export async function GET() {
return Response.json(await notifications.deliver({ budgetMs: 50_000 }));
}The push block's expoPushChannel sends the push
deliveries to Expo, stores the tickets and confirms them later with
devices.checkReceipts() from a second cron.
Each delivery renders in its recipient's locale: with the
profiles module installed, claim_notification_deliveries
returns the locale column of the recipient's profile, and the channel's
message carries it in message.locale (null without one). A locale
column that is an enum or a domain, such as public.app_locale, works the
same: the claim reads it as text, so message.locale is the label. hydrate
runs once per locale among the claimed deliveries. When render or hydrate
throws, only the deliveries it was rendering fail, and they are retried like
a throwing channel.
deliver claims pending rows with for update skip locked and leases them
(lease, five minutes by default), so two runs never send the same message.
A channel that throws leaves the row pending until next_attempt_at, a
random time up to 30 seconds that doubles per attempt to at most an hour.
The database marks it failed after maxAttempts (5), and also when a
worker died while it held the last attempt. testNotificationChannel from
better-supabase/testing checks a channel against the contract.
Run purge() (purge_notifications(older_than, batch) in SQL) from a
scheduled job to delete notifications older than 90 days with their
recipients and deliveries, 10,000 per call.
email adds a channel named email that sends through a
DeliveryTransport: { apiVersion: 1, channel: "email", provider, send(message, { idempotencyKey }) }.
The idempotency key is the delivery id, so a retried delivery reaches the
provider under the same key and sends one email. Passing email next to a
channel named email throws.
| Option | Use |
|---|---|
transport | The DeliveryTransport that sends the mail |
from | The sender, e.g. Acme <notifications@acme.com> |
replyTo | An optional reply address |
compose | (message) => ({ subject, text?, html?, replyTo?, category?, templateKey? }); defaults to the rendered title and body |
unsubscribe | (message) => ({ url?, mailto? }): your signed unsubscribe link for notification mail |
composeContact | (message) => ComposedEmail for a contact recipient; defaults to the same subject and text as compose's default |
A recipient without an email address is skipped. Without compose, the
block needs render, and a notification it can't render fails its delivery.
A templateKey from compose (for example assigned-v2) is stored on the
delivery's template_key column, so you can tell which template a sent
email used.
Contacts without an account
recipients also takes { email, name? } for someone without an account,
such as a customer who receives a quote. send checks the address, stores
the notification for the user recipients as usual and hands it to each
contact right away through every channel with sendToContact (the email
channel has it). A contact gets no inbox row and no delivery row, so a failed
send is not retried; the result reports it in contacts:
const sent = await notifications
.send("quote.sent", {
tenant: organizationId,
data: { quoteId: quote.id },
key: `quote-sent:${quote.id}`,
recipients: [ownerId, { email: "cara@client.example", name: "Cara Lee" }],
})
.orThrow();
sent?.contacts; // [{ email, channel: "email", status: "sent", providerMessageId }]The idempotency key is the event id, the channel and the lowercased address,
so a contact gets one mail per notification. When no user receives it, the
contacts still do, under the id key:<key> when the send has a key (a
repeated send reaches the provider under the same key) or a new id without
one. The name goes into the To header without quotes, backslashes or line
breaks. An invalid address fails the send with NOTIFICATION_CONTACT_EMAIL
before anything is stored. Contact mail has no unsubscribe link of its own;
put one in composeContact when the mail is not transactional.
resendTransport({ apiKey }) posts to https://api.resend.com/emails with
fetch and the delivery id in the Idempotency-Key header. Read the key
from your own environment; the block never reads one. A failed call throws a
ResendError with Resend's HTTP status and error name, and the delivery
retries. baseUrl and fetch replace the endpoint and the client, e.g. in
tests.
Headers per category
compose returns a category, notification by default. The channel sets
the headers from it with mailHeaders(category, unsubscribe):
| Header | notification | security | approval |
|---|---|---|---|
Auto-Submitted: auto-generated (RFC 3834) | Yes | Yes | Yes |
List-Unsubscribe (RFC 2369) | Yes | No | No |
List-Unsubscribe-Post: List-Unsubscribe=One-Click | With a URL | No | No |
List-Unsubscribe lists the url and the mailto target that
unsubscribe returns. RFC 8058 one-click needs an https URL, so the
List-Unsubscribe-Post header appears only with one. A URL that isn't
https, or an address that doesn't start with mailto:, throws. Security
and approval mail never carries an unsubscribe header, and the channel
doesn't call unsubscribe for it. The unsubscribe endpoint is yours: it
receives a POST with List-Unsubscribe=One-Click in the body and turns the
type off through setPreference.
Audience
audience is a SubscriberPolicy that every recipient passes before
deliver sends to them. Without it, deliver uses the server's
authorization.delivery.audience (Runtime hooks).
When the server has hooks but no delivery.audience, deliver uses
subjectReaders(transport): a notification about a
registered subject only goes to
recipients who hold its read key.
const notifications = createNotifications({
transport: sqlTransport(postgres.admin),
types,
email,
server: { authorization },
});The policy runs once per notification for the claimed recipients, after
suppressed addresses are left out and before any send. It receives
{ type, tenant, actorId, payload, subject } and the recipients as
{ principal: userId, kind: "user" }. A recipient it leaves out is
skipped with the error audience. It can narrow the list but never widen
it: a principal that wasn't passed in is ignored. A policy that throws, or
returns something other than a list, sends to no one; the deliveries stay
pending with audience check failed: … and retry.
Suppressions
notification_suppressions holds the addresses a channel must not send to:
one row per channel and lowercase address, with a reason (bounce,
complaint or manual), the user it belongs to, the provider and its event
id. deliver skips a suppressed address before the audience check and any
send, and records the delivery as skipped with the error
suppressed: <reason>.
RLS lets users read their own rows; only the service role writes them.
| Method | SQL | Who |
|---|---|---|
suppress({ address, reason }) | suppress_notification_address | service role |
unsuppress(address, channel?) | unsuppress_notification_address | service role |
suppressions({ limit? }) | list_notification_suppressions(max_items) | the user, RLS |
suppress returns true for a new row and false when the address was
already suppressed; the first reason stays. unsuppress returns whether a
row was removed.
resendWebhook records every delivery status Resend reports (see
Delivery tracking) and writes the suppressions from
its bounce and complaint events. It verifies the Svix signature (svix-id, svix-timestamp,
svix-signature, or the webhook- names) with the endpoint's signing
secret, and answers 204:
import "server-only";
import {
createNotifications,
resendWebhook,
sqlTransport,
} from "better-supabase/blocks/notifications";
import { env } from "@/env";
import { types } from "@/lib/notifications";
export const POST = resendWebhook({
secret: env.RESEND_WEBHOOK_SECRET,
notifications: createNotifications({
transport: sqlTransport(postgres.admin),
types,
}),
});| Resend event | Delivery event | Suppression |
|---|---|---|
email.delivered | delivered | None |
email.delivery_delayed | delayed | None |
email.opened | opened | None |
email.clicked | clicked | None |
email.bounced, bounce type not Transient | bounced | bounce, per recipient |
email.bounced, bounce type Transient | bounced | None |
email.complained | complained | complaint, per recipient |
| Anything else | None | None |
A bad signature answers 401, a body over maxBodyBytes (256 KiB) 413, and a
method other than POST 405. A failed write answers with its problem, so
Resend retries the event. Pass seen to refuse a replayed message id, and
an array of secrets while rotating. resendDeliveryEvent(event, id) and
resendSuppressions(event, id) map an event without the handler, e.g. from
a queue.
Delivery tracking
notification_delivery_events keeps what the provider reports after a send:
one row per event, with the delivery, a kind (delivered, opened,
clicked, bounced, complained or delayed), the provider's event id
(unique, so a retried webhook writes one row), occurred_at and a detail
object. The delivery itself gets provider_status and provider_status_at,
which only move forward: an opened that arrives after a clicked is stored
as an event but leaves the status at clicked.
recordDeliveryEvent finds the delivery by provider and
providerMessageId and calls record_delivery_event, which only the
service role can run. A hard bounce or a complaint also suppresses the
address through suppress_notification_address, unless you pass
suppress: false. A new event emits notification.<kind> with the
notification's subject (subjectType, subjectId), through the outbox in
SQL and on betterSupabase.events in TypeScript. It returns null when no
delivery has that message id, and recorded: false for an event id it has
already stored.
await notifications
.recordDeliveryEvent({
provider: "postmark",
providerMessageId: event.MessageID,
kind: "bounced",
providerEventId: String(event.ID),
occurredAt: Temporal.Instant.from(event.BouncedAt),
detail: { type: event.Type },
})
.orThrow();subjectDeliveries({ subject, tenant?, limit? }) calls
list_subject_deliveries and lists the deliveries of every notification
about one record, newest first, each with its status, provider status,
template key and events. The service role can always read it; with the
access module installed, a member with notifications.send in the
organization can too. Use it to show "sent, opened, bounced" next to a deal
or an invoice.
| Method | SQL | Who |
|---|---|---|
recordDeliveryEvent(input) | record_delivery_event | service role |
subjectDeliveries({ subject, tenant, limit }) | list_subject_deliveries | service role, or senders |
Other providers
A transport for another provider is an object with send. Postmark, Amazon
SES and SMTP have no built-in transport; these sketches put the same pieces
on each provider's API. Each one passes testDeliveryTransport from
better-supabase/testing.
import type { DeliveryTransport } from "better-supabase/blocks/notifications";
export const postmark = (token: string): DeliveryTransport => ({
apiVersion: 1,
channel: "email",
provider: "postmark",
async send(message, { idempotencyKey }) {
const response = await fetch("https://api.postmarkapp.com/email", {
method: "POST",
headers: {
"content-type": "application/json",
"x-postmark-server-token": token,
},
body: JSON.stringify({
From: message.from,
To: message.to,
Subject: message.subject,
TextBody: message.text,
HtmlBody: message.html,
MessageStream:
message.category === "notification" ? "broadcast" : "outbound",
Headers: [
...Object.entries(message.headers),
["X-Delivery-Id", idempotencyKey],
].map(([Name, Value]) => ({ Name, Value })),
}),
});
if (!response.ok) throw new Error(`Postmark answered ${response.status}`);
const { MessageID }: { MessageID: string } = await response.json();
return { providerMessageId: MessageID };
},
});Postmark has no idempotency key, so the sketch sends the delivery id as a
header to deduplicate on. For Amazon SES, call SendEmail of the SES v2 API
with @aws-sdk/client-sesv2 and pass the headers in
Content.Simple.Headers; SES has no idempotency key either. For SMTP, send
with nodemailer from a Node.js runtime, with the headers in headers and
the delivery id as the Message-ID local part, so a retry repeats the same
id. Point the provider's delivery webhooks at a route that calls
notifications.recordDeliveryEvent with the service connection; it
suppresses hard bounces and complaints for you.
From outbox events
notifications.sink({ map }) is an outbox sink that turns events into
notifications. map receives each CloudEvent, with the
dev.better-supabase. prefix stripped from its type, and returns a
notification or null to skip it:
await outbox.relay(
"notify",
notifications.sink({
map: (event) =>
event.type === "organization.member_added"
? {
type: "organization.joined",
recipients: [String(event.data.userId)],
data: { title: "You joined the organization" },
}
: null,
}),
);The notification's key defaults to the event id and its tenant to the
event's partitionkey, so a replayed batch sends nothing twice. A failed
send throws, and the relay retries the batch.
The sink sends up to 1,000 notifications per call through
better_supabase.send_notifications(events jsonb), which runs
send_notification for each element. notifications.sendMany(items) calls it
directly, each item a send input with its type, and returns one Result
per item. send hooks don't run for sendMany; hook sendMany instead. With
a send hook, the sink sends one notification at a time so the hook sees
each of them.
Partitioned delivery events
blocks.notifications.options.partitioned creates a new
notification_delivery_events table partitioned by month on created_at,
with the primary key (id, created_at). purge_notifications drops every
month past the notifications retention cutoff. The other notification tables
stay unpartitioned: they're referenced and leased by id. An existing table
stays as it is, and better-supabase doctor reports it as BS335.
SQL modules notify through the notifications module in the same
transaction, not through this sink. The messaging module already sends a
notification for every mention (message.mentioned), and the comments
module sends comment.posted to a record's followers, so don't map
message.sent again.
Watchers
watcherHandler(notifications, { types }) from
better-supabase/blocks/notifications maps subject events to notifications
for the subject's watchers. An event qualifies when its data carries
organizationId, subjectType and subjectId, which every subject event
does (SubjectEventData in better-supabase/events). types maps an event
type to a notification type, or to a rule with activity, recipients,
data and summary:
import { watcherHandler } from "better-supabase/blocks/notifications";
await outbox.consume(
"watchers",
watcherHandler(notifications, {
types: {
"status.changed": "deal.moved",
"subject.tagged": { type: "deal.tagged", activity: "tags" },
"reminder.sent": {
type: "reminder.due",
recipients: (data) => [String(data["userId"])],
},
},
}),
);Each notification is keyed by watch:<event id>, so a replayed batch sends
nothing twice. Events without a subject or a tenant, and types not in
types, are skipped.
watcherHandler takes outbox rows, through outbox.consume or a
relayRoute consumer, and leaves out the actor each row records, so whoever
tags, moves or shares a subject is not notified of it. watcherSink takes
CloudEvents, which carry no actor, so it can only leave out an actor the
event data names (actorId, or a message's authorId). Use it when the
events come from a relay or a broker rather than from the outbox itself.
Extending it
| Hook or event | Use |
|---|---|
notification_audience hook | A SQL function that adds recipients, e.g. everyone with a role on the subject |
before_notification_send hook | A SQL function that gets the notification as jsonb and raises to refuse it |
after_notify hook | A SQL function that runs in the same transaction after the rows are written |
hooks option | Refuses, rewrites or observes any method in TypeScript, e.g. quiet hours on send; see Extending blocks |
audience option | Narrows who deliver sends to; see Audience |
onSent option | Runs after send stores a notification, e.g. to call Next's updateTag |
notification.* block events | created, delivered, failed, and the provider's opened, clicked, bounced, complained and delayed, with the subject |
notifications.send permission | Rename it with blocks.notifications.permissions.send |
Columns the app adds to the events table belong to the event, so every recipient sees the same values:
const notifications = createNotifications({
transport,
types,
fields: v.object({ campaign: v.optional(v.string()) }),
});
await notifications.send("digest.weekly", {
recipients,
data: { count: 3 },
fields: { campaign: "weekly" },
});Existing tables
The managed tables are notification_events (with type, data and
actor_id), notification_recipients (keyed on user_id),
notification_deliveries, notification_subscriptions,
notification_preferences, keyed on organization_id,
notification_suppressions and notification_delivery_events. When your
app has its own, the module runs over them: rename what differs and map the
optional columns and tables you don't want to null. Over your tables the
module honours suppressions only when tables.suppressions names your table,
and tracks delivery events only when tables.deliveryEvents does (its
provider_event_id must be unique):
export default defineConfig({
blocks: {
notifications: {
schema: "public",
idType: "uuid",
tables: { subscriptions: null },
columns: {
events: { key: null, actor: "actor_user_id", data: "metadata" },
recipients: { user: "recipient_user_id", resolvedAt: null },
},
options: {
topic: "organization:{tenantId}:notifications:{userId}",
channels: ["in_app", "email"],
},
},
},
});Without a key column, keyed sends derive the event id from the organization
and key instead: a UUIDv8 (RFC 9562) built from the MD5 of both, so the id
stays deterministic and passes strict validators such as z.uuid(). Events
stored by an earlier version under the plain MD5 id keep that id, and a
keyed send that matches one still returns it instead of notifying twice. A recipient with in-app off for a type still gets a row,
stored as dismissed, so other channels can deliver it.
Over your own notification_deliveries, the status check must accept every
value the block writes: pending, sent, failed, skipped, held and
digested. A narrower check, such as one that predates digests, rejects a held
or folded delivery and the send fails. Doctor reports such a check as
BS361.
Digests
A member picks how often a type reaches them on a channel with a cadence on
notification_preferences: immediate (the default), daily, weekly or
off. off works like a turned-off preference, so no recipient row is
written for the channel. A daily or weekly choice holds the delivery
(status held) instead of sending it. In-app delivery is never held.
select better_supabase.set_notification_cadence('comment.created', 'email', 'daily');The digest_run housekeeping job calls run_notification_digests, which folds
a member's held deliveries into one notification_digests row once the oldest
is a day (daily) or a week (weekly) old. Each folded delivery gets status
digested. createNotificationDigests sends each row as one email through the
mailer port of the mail-sync block. A digest without an address is skipped, a failed send returns to pending
for the next run, and a failed claim or completion stops the run.
import { createNotificationDigests } from "better-supabase/blocks/notifications";
const digests = createNotificationDigests({
transport,
service: serviceTransport,
mailer: db.mailSync,
accountId: process.env.DIGEST_MAIL_ACCOUNT_ID!,
});
export async function GET() {
return Response.json(await digests.sendDue({ limit: 50 }).orThrow());
// { claimed, sent, failed, skipped }
}A send that fails goes back to pending and runs again, until
max_attempts ends it as failed. A member without an email address is
skipped. Every notification a block sends through send_notification follows
the cadence, which covers comments, mentions, approvals, announcements and SLA
notifications whenever they send on a non-in-app channel. Notifications that a
block delivers outside send_notification are not folded.
Consent
A notification that names consentPurpose sends nothing, and returns null
like a send without recipients, while its subject has no consent in force for
that purpose. The check needs the consents block and a subject. See
Require a consent.
Error codes
hint | When |
|---|---|
NOTIFICATION_TYPE_REQUIRED | notify without a type |
NOTIFICATION_TYPE_UNKNOWN | send with a type that isn't in types (checked in TypeScript) |
NOTIFICATION_DATA_INVALID | stored data that its type's schema rejects on a read (TypeScript) |
NOTIFICATION_FORBIDDEN | The sender lacks notifications.send in the organization |
NOTIFICATION_PRIORITY_UNKNOWN | A priority that isn't in options.priorities |
NOTIFICATION_ACTIVITY_UNKNOWN | An activity other than participating or all |
NOTIFICATION_ACTIONS_INVALID | actions that aren't the shape described under Actions |
NOTIFICATION_RESOLUTION_INVALID | A resolution that isn't a JSON object |
NOTIFICATION_LEVEL_UNKNOWN | A subscription level other than participating, all or ignore |
NOTIFICATION_CONTACT_EMAIL | A { email } recipient whose address isn't valid (TypeScript) |
NOTIFICATION_STATUS_UNKNOWN | Completing a delivery or a digest with a status the block doesn't know |
NOTIFICATION_CADENCE_UNKNOWN | A cadence other than immediate, daily, weekly or off |
NOTIFICATION_TOO_MANY_RECIPIENTS | More recipients than options.maxRecipients |
NOTIFICATION_SUPPRESSION_ADDRESS | suppress without an address |
NOTIFICATION_SUPPRESSION_REASON | A suppression reason other than bounce, complaint or manual |
NOTIFICATION_DELIVERY_EVENT_KIND | recordDeliveryEvent with a kind the block doesn't know |
NOTIFICATION_DELIVERY_MESSAGE_ID | recordDeliveryEvent without a provider message id |
Without the client
db.notifications is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import "server-only";
import {
createNotifications,
sqlTransport,
} from "better-supabase/blocks/notifications";
import { z } from "zod";
export const types = {
"task.assigned": z.object({ title: z.string() }),
"approval.requested": z.object({ amount: z.number() }),
};
export const notificationsFor = (claims: Record<string, unknown>) =>
createNotifications({
transport: sqlTransport(postgres.asUser(claims)),
types,
actionable: ["approval.requested"],
events: betterSupabase.events,
render: (item) => ({ title: `${item.type}: ${item.subject?.label ?? ""}` }),
});Last updated on