Push notifications
Push tokens per device with RLS, Expo device registration, and a sender for the Expo Push API that prunes dead tokens.
The push block stores the push tokens of each user's devices and sends to
them. The app registers a device after sign-in and removes it on sign-out;
the server sends through the Expo Push API and deletes the tokens Expo no
longer reaches. With the notifications block,
it is a delivery channel.
better-supabase add push| Table | Holds |
|---|---|
push_devices | One row per token: user_id, token, platform (ios, android, web), provider (expo by default), device_name, app_version, last_seen_at |
push_tickets | With notifications: Expo's ticket per delivery and device, pending until its receipt says ok or error. Only the service role reads it |
Each user reads and deletes their own devices; nobody else can. A token
belongs to one user: when a device signs in as someone else, registering
moves the token to them. Only the service role reads every user's tokens
(push_tokens_for) and prunes them (prune_push_tokens). With the
outbox, the functions record push.device_registered
and push.device_unregistered.
Register the device
Server code calls the push instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: usePush } = defineDataHooks(
"push",
(db: AppDb) => db.push,
);const rows = await db.push.list({ limit: 50 }).orThrow();"use client";
import { usePush } from "@/lib/supabase/hooks";
const rows = usePush({ limit: 50 });registerDevice asks for permission when it isn't granted yet (pass
request: false to only check), reads the Expo push token and registers it
for the signed-in user. It resolves with null when the user says no or the
platform has no push. Call it after every sign-in: a known token only
refreshes last_seen_at.
unregisterOnSignOut returns a sign-out function that removes the token
first, while the session can still call the database. A failed removal
doesn't block the sign-out.
Send
import { sqlTransport } from "better-supabase/blocks/push";
import { createPush, expoPush } from "better-supabase/blocks/push";
export const devices = createPush({ transport: sqlTransport(postgres.admin) });
export const push = expoPush({ accessToken: env.EXPO_ACCESS_TOKEN, devices });
const targets = await devices.tokensFor([userId]).orThrow();
const tickets = await push.send(
targets.map((target) => target.token),
{
title: "New comment",
body: "Ada replied to your post",
data: { path: "/posts/1" },
},
);expoPush uses fetch only, so it runs on every runtime. send posts 100
messages per request and returns one ticket per token, in order. A ticket
with DeviceNotRegistered deletes its token right away. accessToken is
needed only when the Expo project turns on push security; it is a
server-only key.
A request that gets a 429, a 5xx or a network error is retried up to
maxRetries times (default 3), after Retry-After when Expo sends one (at
most 30 seconds) and otherwise after 1, 2 and 4 seconds. When a request
still fails, its tokens get a ticket with the error RequestFailed
(EXPO_REQUEST_FAILED) and send moves on: the chunks already sent keep
their tickets, and send never throws after a partial send.
Pass idempotencyKey to send it as the idempotency-key header, suffixed
with the chunk number, and sent with the tickets of an earlier attempt:
tokens that already have a ticket id or DeviceNotRegistered are not sent
again.
const retried = await push.send(tokens, message, {
idempotencyKey: deliveryId,
sent: tickets,
});Expo reports most failures later, in receipts: about 15 minutes after
sending, pass the tickets to checkReceipts, which prunes the devices Expo
no longer reaches and returns every receipt it had ready in receipts, with
the failed ones in failed.
Your own fields
Columns you add to push_devices with alter table in your own schema files are fields of the block (details). register writes them from fields,
and tokensFor's targets return them in fields. Pass a Standard Schema as fields
to type them: writes are validated before they reach the database (a
validation error), and reads are parsed. hooks refuses, rewrites or
observes any method; see extending blocks.
alter table "better_supabase"."push_devices" add column "app_build" text;const client = createPush({
transport,
fields: v.object({ app_build: v.optional(v.string()) }),
});
await client.register({ token, platform: "ios", fields: { app_build: "142" } });As a notifications channel
import { createNotifications } from "better-supabase/blocks/notifications";
import { expoPushChannel } from "better-supabase/blocks/push";
export const notifications = createNotifications({
transport: sqlTransport(postgres.admin),
types,
render,
channels: [expoPushChannel({ devices, push })],
});expoPushChannel sends each push delivery to the recipient's Expo
devices, with the rendered title and body and the notification's id, type
and actionPath in data. A recipient without devices is skipped. It
stores every ticket in push_tickets and returns the first ticket id as the
delivery's providerMessageId.
The channel throws, and notifications.deliver() retries the delivery, when
a request to Expo still failed after its retries or when Expo rejected every
message for a reason other than an unregistered device. The retry reads the
stored tickets, sends only to the devices without one and uses the delivery
id as the idempotency key, so a device gets the push once. Pass
storeTickets: false to keep no tickets (push module version 1 has no
push_tickets), message to build the push yourself, and onTickets to
receive the tickets as well.
Check receipts from a cron
db.push.checkReceipts() (or devices.checkReceipts() over the service
role) reads up to 1000 tickets older than 15 minutes that have no receipt,
asks Expo for their receipts and stores them. Each receipt records
notification.delivered or notification.bounced on its delivery, which
the delivery's history and onDeliveryEvent show, and a
DeviceNotRegistered receipt prunes the device. With events
(betterSupabase.events, which createBlocks passes to every block), each receipt it records
for the first time also emits the notification.delivered or
notification.bounced block event, with the same data as
recordDeliveryEvent and provider: "expo", so your betterSupabase.on
handlers see push receipts and email webhooks the same way. A bounced push doesn't add
the user's address to the suppression list. Tickets Expo has no receipt for
yet stay unchecked for the next run.
import { devices, push } from "@/server/push";
export async function GET(): Promise<Response> {
const { receipts, pruned } = await devices.checkReceipts({ push }).orThrow();
return Response.json({ checked: receipts.length, pruned });
}Pass push when the sender needs an access token; it defaults to
expoPush({ devices }). limit and olderThan (a Temporal.Duration)
change how many tickets one run reads and how old they must be.
Without the client
db.push is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import * as Notifications from "expo-notifications";
import Constants from "expo-constants";
import { Platform } from "react-native";
import {
createPush,
registerDevice,
rpcTransport,
unregisterOnSignOut,
} from "better-supabase/blocks/push";
const devices = createPush({ transport: rpcTransport(supabase) });
let token: string | undefined;
export async function onSignedIn() {
const device = await registerDevice({
notifications: Notifications,
devices,
platform: Platform.OS,
projectId: Constants.easConfig?.projectId,
appVersion: Constants.expoConfig?.version,
}).orThrow();
token = device?.token;
}
export const signOut = unregisterOnSignOut({
signOut: () => supabase.auth.signOut(),
devices,
token: () => token,
});Last updated on
Notifications
In-app notifications with per-recipient state, subject subscriptions, channel preferences, email and push deliveries, and realtime updates on a private topic.
Inbox
A shared inbox for support conversations from an in-app widget, Slack, WhatsApp, SMS and other channels, with assignment, internal notes, read receipts, bot handoff and realtime updates.