Notifications
Turning them on
Section titled “Turning them on”Notifications tell a user about something in the app, in a bell in the top bar and as push on their devices. Send notifications walks through turning them on and sending the first one. You turn them on in protobase.config.ts:
import { defineConfig } from '@protobase/config'
export default defineConfig({ notifications: {},})Then run protobase migration, which writes the devices and history tables, and the jobs schema that sending runs on, as a migration of the project’s own, and apply it with the project’s migrations. protobase dev and protobase serve refuse to start while a table is missing or lacks what notifications need, and name it. Without notifications there is none of it: no endpoints, no tables and no migration.
Every signed-in user gets the bell, browsers receive push through Web Push, the Android app through FCM and iOS devices through APNs. notifications: { ui: false } keeps only the backend, without the bell.
Devices
Section titled “Devices”A device is where a user receives push: a browser’s push subscription, or an Android or iOS app’s push token. Each signed-in user registers and removes only their own, through the API:
| Request | |
|---|---|
POST /api/notifications/devices |
registers the device the request comes from, or refreshes it; answers { id, kind, createdAt, lastSeenAt } |
DELETE /api/notifications/devices/<id> |
removes the caller’s device with that id; answers 204 whether or not the caller had it |
The body of a register is JSON (Content-Type: application/json, at most 8 KB), in one of four shapes:
// A browser: its PushSubscription as JSON{ "kind": "web", "endpoint": "https://…", "keys": { "p256dh": "…", "auth": "…" }, "userAgent": "…" }// An iOS app: its token in lowercase hex, the build's environment and bundle id{ "kind": "apns", "token": "…", "environment": "production", "appId": "net.example.app" }// An Android app: its token, and optionally its package name{ "kind": "fcm", "token": "…", "appId": "net.example.app" }// A mobile app's handle from a push relay{ "kind": "relay", "handle": "…" }A field that does not belong to the kind, a missing one, an unknown one such as an owner, or a value out of its format is a 400 that names the field and stores nothing. A browser’s endpoint must be an https URL on one of the browsers’ push services. environment is sandbox or production, and userAgent, optional for every kind, is at most 512 characters. The stored device keeps null in the fields its kind does not have.
userId, optional for every kind, names the user the client registers for, such as the one whose click turned push on. When someone else is signed in by the time the request arrives, it is a 409 of type other-user that stores nothing.
Who may call them:
- Only someone signed in as themselves, with the token of their own sign-in. Visitors are refused with a
401, and staff signed in as the user, outside apps acting for the user (such as an MCP client) and tokens minted withissueTokenwith a403. - An app with its own authenticator (
auth/authenticate.ts) marks a user’s own sign-in on the session it returns,signIn: { staff: false }; without that mark, its sessions are refused. - With Protobase’s auth, every token the endpoints take names its sign-in session; one that names none is refused with a
403.
A device is one token, or one endpoint for a browser. An Android or iOS token, or a relay handle, someone else had moves to the caller, as a new device with a new id that keeps nothing of the previous user’s, so a shared phone notifies whoever signed in on it last. A browser’s endpoint never moves: registering one another user holds is a 409 of type device-held that stores nothing, and the browser subscribes again for a new endpoint, as the browser helper does. A user keeps up to 20 devices: registering one more removes their least recently seen. Deleting a user removes their devices.
With Protobase’s auth, a device belongs to the sign-in session it was registered in. Once that session ends, the device gets no more push and is removed at the next send: when the user signs out, someone signs in on the same browser, the user signs out everywhere, a password change signs out their other devices, an admin ends their sessions or bans them, or the session expires. A device with no session recorded, such as one registered before devices kept their session, counts as ended too. Registering the device again ties it to the session of that request, which the browser helper does on its own for the same user, so such a device gets push again once its browser registers it. With an app’s own authenticator, a device stays its user’s until it is removed with DELETE. authenticate to report that a session ended is not implemented.
The path comes from devicesPath('/api', id), and the name of its id parameter from deviceIdParam, both exported by @protobase/server.
Sending
Section titled “Sending”Send notifications sends one from a record change, step by step. You send a notification from your server code, such as a job, a hook, an event subscription or an API function, with sendNotification(db, to, message) from @protobase/server. It is queued as a background job in db’s transaction when db is one, so it goes out only once your write commits, and nothing goes out when the transaction rolls back. A running job also has it as sendNotification in its context, beside mail, when the app has notifications.
Every send to users says whether it shows in their inbox:
- With
inbox: trueit is kept in each user’s history, which the bell shows, and is pushed to their devices, such as a notice that the app has a new version. - With
inbox: falseit is only pushed, such as a chat message that links to its chat. - A send to devices,
{ deviceIds }, is only pushed, and takes no inbox flag.
import { appPath } from '@protobase/schema'import { sendNotification, subscription } from '@protobase/server'
// The app's public origin, from its own configuration.const appOrigin = 'https://tasks.example.com'
/** Tells a task's owner when someone changes it. */export const taskChanged = subscription('taskChanged', { events: ['tasks.updated'], run: async ({ data }, { db }) => { const owner = data.after?.owner_id if (owner == null) return const url = new URL(appPath({ kind: 'record', resource: 'tasks', key: data.key }), appOrigin).href await sendNotification(db, { userIds: [String(owner)], inbox: true }, { title: `${data.after?.title} changed`, url }) },})The message is the one senders take. Its url opens on tap: a URL on your app’s origin opens inside the app, and any other http or https URL opens outside it. Any other scheme, such as javascript: or data:, is refused. Build the URL on your app’s configured origin, never on one a request names in Host, X-Forwarded-Host, Origin or its own URL, so nobody can make a notification lead to their site.
A send is checked before anything is queued, and a send that is not valid throws a NotificationSendError that names the field at fault, never its value. A valid send:
- names 1 to 1000 users or devices;
- has a user send’s
inboxastrueorfalse; - has a message of at most 16 KB as JSON, without a field that is not one of the message’s;
- for the inbox, has a message the history keeps.
The text you send shows on lock screens, where anyone holding the device can read it, so keep anything the recipient may not see out of it. It stays in the jobs table until the send is delivered, and in a failed send until it is retried or deleted in the admin app.
A send checks no permission. A device send reaches the devices whatever user holds them. So check ids taken from a request against the caller first, such as a device id against the caller’s own devices.
A user send reaches the user’s devices as they are when the job runs. A device that moved to someone else, or was removed, gets nothing. With Protobase’s auth, a device whose sign-in session has ended is removed instead; a send whose devices’ sessions cannot be read pushes to none of them and is retried. With an app’s own authenticator, a device keeps receiving its user’s notifications until it is removed. When a push service reports a device gone, the device is removed. A device whose push service asks to try again later is tried once more, on the job’s next try, and then given up on without being removed.
In an app with status, a user on do not disturb when the send’s job runs gets nothing pushed, by any sender, built-in or the app’s own, and a send to devices holds their devices too; a send for the inbox still keeps the notification in their history, which the bell shows unread. Nothing of the send is pushed to them once do not disturb ends, and the others in the send are pushed as usual.
History
Section titled “History”The history is each user’s inbox: every notification sent to a user with the inbox flag on is kept for them, and one sent without it is only pushed. Each signed-in user reaches only their own, through the API:
| Request | |
|---|---|
GET /api/notifications/history |
the caller’s notifications, newest first: { items, next } |
GET /api/notifications/history/unread |
how many are unread: { count }, at most 100, so show 99+ from there |
POST /api/notifications/history/<id>/read |
marks the caller’s notification with that id read; answers 204 whether or not the caller had it |
POST /api/notifications/history/read |
marks all read up to the newest one the caller was shown: { "upTo": "<its createdAt>" }, then 204 |
Each item is { id, title, body, url, data, createdAt, readAt }, with readAt null while unread. A notification read once keeps its first readAt, and marking all read leaves those read earlier as they were. Marking all read takes the createdAt of the newest notification the user saw, so one that arrives meanwhile stays unread.
The list gives 20 at a time, or as many as ?limit= says, up to 50. A full page’s next is a cursor: pass it as ?cursor= for the page after it, until next is null. A limit or cursor out of its format, and a parameter or body field the request does not take, such as a user, is a 400 that changes nothing. Both marks take JSON (Content-Type: application/json): marking one takes an empty body or {}. Answers about the history are never cached.
title and body are plain text: show them as text, never as HTML. url is a path on the app, such as /tasks/42, or an absolute URL on one of the app’s own origins; anything else, another site, javascript: or data:, is answered as null. A notification’s url and data are kept until its user is removed, so leave one-time links and secrets out of inbox notifications.
The same people may call them as may register devices: only someone signed in as themselves. With Protobase’s auth, deleting a user removes their history; an app that deletes users otherwise calls historyStore(db, notifications).removeAllForUser(userId) as it deletes one, with the config’s notifications (the history table’s names), or the removeAllForUser of its own notifications/history-store.ts.
The paths come from historyPath('/api'), historyPath('/api', 'unread'), historyPath('/api', 'read') and historyPath('/api', { read: id }), and the name of the id parameter from historyIdParam, all exported by @protobase/server.
The bell
Section titled “The bell”With notifications on, every signed-in user sees a bell in the top bar with how many of their notifications are unread. Its panel is their inbox: the newest notifications sent with the inbox flag on, never those sent without it, the unread ones in bold, each with how long ago it came. Opening one marks it read and goes to its page in the app, in the same tab: inbox links stay within the app, since the history never answers a url on another site. A notification without a url is not a link. “Mark all as read” marks those the panel shows read, and “Show more” brings older ones.
The panel also offers to turn push on for this device, where the device can receive it: a browser with Web Push, when the app has its keys. The browser asks for permission only once the user clicks “Turn on”, never when a page loads. Once push is on, the panel says so with a way to turn it off. When the browser blocks notifications, the panel says so and how to allow them again, and offers to turn push on once they are allowed.
- The count is read again every half minute while the page shows, on a return to it and when the panel opens, and shows
99+above 99. - Visitors and staff signed in as a user see no bell, since the history is the user’s own. Neither does a user of an app with its own authenticator that does not mark their own sign-in.
- The panel’s text comes in the app’s language.
Without the bell
Section titled “Without the bell”notifications: { ui: false } keeps sending, the history and devices, and the top bar draws no bell, so the app reads no notifications for it:
export default defineConfig({ notifications: { ui: false } })Your own UI then reads the history endpoints, through client.notifications of @protobase/client (list, unread, markRead and markAllRead) or the hooks, and turns push on with the browser helper, such as in a button of the top bar’s actions.
Web Push
Section titled “Web Push”Browsers receive push through the Web Push protocol: desktop and Android browsers, and web apps added to the home screen on iPhone. You generate a key pair with the CLI and set it, with a contact address, in three environment variables:
protobase notifications vapid-keys| Variable | |
|---|---|
PROTOBASE_VAPID_PUBLIC_KEY |
the public key the command prints |
PROTOBASE_VAPID_PRIVATE_KEY |
the private key the command prints |
PROTOBASE_VAPID_SUBJECT |
how push services reach you: a mailto: address or an https: URL |
Without them Web Push is off and the app has no sender for browsers. One or two of them set, a blank one, a key that is not one, or a public key that is not the private key’s stops startup, naming the variable without its value.
The private key is a secret: keep it out of client code, VITE_ variables and the repository. Anyone holding it and the stored subscriptions can push to every subscribed browser. Browsers subscribe with the public key, which /meta gives every caller as notifications.webPushKey, so a new key pair breaks every subscription until its browser registers again.
Each message is encrypted for its browser and signed with the key. It goes only to an endpoint on one of the browsers’ push services, never through a redirect, and only to the address the endpoint’s host resolves to when it is sent, which must be public: an endpoint whose host resolves to a private, loopback or link-local address gets no request and is refused; a device stored with any other endpoint, or with keys that are not a subscription’s, is refused. platform.web sets the request’s ttl, urgency and topic and fields merged into the JSON the browser receives (payload), in place of those built from the message; every URL in that JSON is checked as the message’s url is. The JSON also carries user, the id of the user the device is registered for, over any user in payload, and at most 3993 bytes.
In the browser
Section titled “In the browser”usePushNotifications() from @protobase/ui turns push on and off for the signed-in user in this browser, or in the iOS or Android app, for your own button or menu item. Its state tells whether push is on, off, blocked because the user refused notifications in the browser’s or the phone’s settings, or unsupported, and loading until it knows. Hide the button while it is unsupported: the browser has no Web Push, the app has no VAPID keys, or the Android app was built without google-services.json.
import { Button, usePushNotifications } from '@protobase/ui'
export const PushButton = () => { const push = usePushNotifications() if (push.state === 'loading' || push.state === 'unsupported') return null if (push.state === 'blocked') return <p>Notifications are blocked in this browser's settings.</p> const failed = push.failure && <p role="alert">Notifications could not be changed ({push.failure.kind}).</p> if (push.state === 'on') return <Button loading={push.busy} onClick={() => void push.turnOff()}>Turn off notifications</Button> return ( <> {failed} <Button loading={push.busy} onClick={() => void push.turnOn()}>Turn on notifications</Button> </> )}- Call
turnOnstraight from a click. The browser asks for permission then, and only then: without a click nothing happens, and push is never turned on when a page loads. Once the user said no,turnOndoes not ask again and answersblocked.stateis read again on a return to the page and when the browser says the permission changed, so it turns fromblockedtooffonce the user allows notifications. busyis true while push is being turned on or off. When turning it on or off fails,failuresays why until the next try, and the error goes to the console: the reason iOS or Android gave for not registering (registration), no push token from Apple’s or Google’s push service within 15 seconds (no-token), the server refusing the device (refused), a turn-off the device could not store, which may not outlast the app closing (off-not-stored), or anything else (other). The bell shows it, with a way to try again after a failed turn-on.- In the iOS and Android app, a user who allowed notifications when the phone asked gets push on by itself when the app opens or they sign in. The app never asks on its own. Android before 13 grants the permission without asking, so there this happens only for a user who turned push on in the app on that phone before. Turning push off with
turnOffkeeps it off on that phone until they turn it on again; signing out does not. Releases from before the app turned push on by itself did not store a turn-off, so a user who turned push off in one of them, and allowed notifications when the phone asked, gets push on again once after the update; turning it off again keeps it off.refreshreadsstateagain, as the bell does when it opens. - Only someone signed in as themselves can turn push on: a visitor’s click and staff signed in as the user do nothing.
- On iPhone and iPad, push works in the app added to the Home Screen; a browser tab answers
unsupported. - Signing out turns push off in this browser, and so does someone else signing in on it: what the browser showed is closed, the app’s badge cleared, and the device removed. Signing in again as the same user keeps it on. Each push names the user its device is registered for, and the browser shows nothing of a push for another user than the one it holds push for.
- A tap on a notification opens its
platform.web.payloadnotification.navigate, or itsurlwhen it has none, and each of the payload’snotification.actionsshows as a button that opens its ownnavigate, or the notification’s url when it has none. The browser checks each url again as the server does and opens nothing for one that fails; no other field, such asdata, is ever opened. A url on your app’s origin opens that page in the app, in an open window of it or a new one; any other url opens in a new tab.
protobase serve and protobase dev both serve the service worker that shows notifications, protobase dev only when the app has notifications.
The server delivers push to iOS devices through the Apple Push Notification service (APNs), with token authentication. You create an APNs key in your Apple developer account, under Certificates, Identifiers & Profiles, Keys, and set it in three environment variables:
| Variable | |
|---|---|
PROTOBASE_APNS_KEY |
the text of the .p8 file you download, from -----BEGIN PRIVATE KEY----- to -----END PRIVATE KEY-----, with its line breaks or pasted on one line without them |
PROTOBASE_APNS_KEY_ID |
the key’s id, ten letters and digits |
PROTOBASE_APNS_TEAM_ID |
your team’s id, ten letters and digits |
Without them APNs is off and iOS devices are skipped. One or two of them set, a blank one, a key that is no APNs key or an id that is not ten letters and digits stops startup, naming the variable without its value, and so do the three set in an app without a mobile section. The key is a secret: keep it out of client code, VITE_ variables and the repository. Anyone holding it can push to every iOS device of your apps. protobase mobile sets the app up: see Push notifications in the mobile app guide.
The topic of every notification is the mobile app’s appId. Each device goes to the environment it was registered with: development builds to the APNs sandbox, App Store and TestFlight builds to production. A device whose token is not lowercase hex, whose environment is neither sandbox nor production, or that was registered for another app id is refused.
When iOS refuses to register the app for push, such as for a build without the push entitlement, push stays off and the app’s error reporting receives the reason iOS gave. When the user pressed Turn on, the bell also shows the reason; registering by itself on launch or sign-in shows nothing in the bell. A push token that never arrives after Turn on also leaves push off, and the bell says so.
The notification’s title and body are its alert, with its badge and sound; the JSON also holds url, data and user, the id of the user the device is registered for. urgency sets the priority (very-low and low wait until the device saves power less), ttl how long APNs keeps it for a device that is offline, 28 days without one, and tag the collapse id. A message’s platform.apns is merged into the JSON, such as { aps: { 'thread-id': 'chat' } }, never into the request’s headers; a url in it is checked as the message’s is, and the JSON holds at most 4096 bytes. APNs answering that the device is unregistered, or that its token is bad, removes the device; any other refusal, such as a wrong topic or key, is retried and then fails the send, so a mistake in the configuration removes no device.
Android
Section titled “Android”Android devices receive push through Firebase Cloud Messaging’s HTTP v1 API. You create a service account key in your Firebase project (Project settings, Service accounts, Generate new private key) and set its JSON as PROTOBASE_FCM_SERVICE_ACCOUNT. Without it, Android devices are skipped. protobase mobile sets the app up from your google-services.json: see Push notifications in the mobile app guide.
JSON that is not a service account key, a project_id that is not a Google project id, or a private_key that is not an RSA key of at least 2048 bits stops startup, naming the variable without its value. The key is a secret: keep it out of client code, VITE_ variables and the repository. Anyone holding it can push to every Android device of the project.
The server signs in as the service account with a token scoped to sending through FCM only, and keeps one token until five minutes before it expires. When no token can be had before the first request, the send fails with nothing pushed and is retried; a token that fails later retries only the devices still waiting for one. Requests go only to Google’s token endpoint and to FCM, for the key’s own project, never through a redirect; the URLs in the key’s JSON are not read. A device is removed only when FCM reports its token unregistered. Any other refusal, such as a key without access to the project, keeps the device and retries it. A device stored with a token that is not an FCM token is refused.
A message’s title and body are the notification. Its data and url reach the app as FCM’s data, the url under url, which the app opens on tap; a message whose data holds a url of its own is refused, each value a string (other JSON as its text), with user, the id of the user the device is registered for, over any user given. Its ttl, urgency, tag, sound and badge set the Android delivery and notification. A message’s platform.fcm is merged over these, and may set only:
| Field | |
|---|---|
notification |
title, body and image |
data |
more data, each value a string |
android |
collapse_key, priority, ttl, direct_boot_ok, and its notification: title, body, icon, color, sound, tag, channel_id, image, ticker, sticky, notification_priority, default_sound, default_vibrate_timings, visibility, notification_count and local_only |
fcm_options |
analytics_label |
Any other field is refused, such as token, topic, webpush or click_action, so a message cannot reach another device or act on tap beyond its url. After the merge, the data’s url and every image are checked as the message’s url is, and a data key FCM keeps for itself, such as from or one starting with google, is refused.
fcmSender(readFcmSettings(process.env)!) from @protobase/server is the built-in sender, to list beside your own senders.
Push relay
Section titled “Push relay”An app can deliver mobile push through a relay instead of holding APNs or FCM keys itself. The relay holds the mobile app’s push keys, and your app sends to it with a relay credential of its own. You set the relay’s URL and your app’s credential in two environment variables:
PROTOBASE_PUSH_RELAY_URL=https://relay.example.comPROTOBASE_PUSH_RELAY_CREDENTIAL=...Without them the relay is off and relay devices are skipped. Only one of them set, a URL that is not https or that has a user, query or fragment, or a credential that is not 16 to 1024 letters, digits and -._~+/ stops startup, naming the variable without its value. The credential is a secret: keep it out of client code, VITE_ variables and the repository.
A device registered with a relay handle, { "kind": "relay", "handle": "…" } (see Devices), receives your app’s notifications with the usual inbox, do not disturb and sign-in session rules. The handle is what the relay gave the device for your app, never its own push token: 16 to 512 letters, digits, - and _.
Each send is POST <url>/send, with the credential as a bearer token, never through a redirect, and JSON with the message as senders get it and up to 100 devices, each with its handle and user, the id of the user it is registered for:
{ "message": { "title": "Task assigned", "url": "https://app.example.com/tasks/42" }, "devices": [{ "handle": "…", "user": "user-1" }] }The relay answers a 2xx with a result for each handle, ok, gone, retry or refused, as senders answer: { "results": [{ "handle": "…", "result": "ok" }] }. A handle the relay answers gone removes its device. A handle it does not answer, and every handle of any other answer, such as a wrong credential, a 429 or 5xx (after its Retry-After) or no answer within ten seconds, is retried, so a mistake in the configuration removes no device. A device stored with a token that is not a relay handle, or whose user id is longer than the 256 characters a store takes, is refused with no request, and the other devices are sent as usual.
relaySender(readRelaySettings(process.env)!) from @protobase/server is the built-in sender, to list beside your own senders. relaySendRequest and relaySendAnswer check the request and answer shapes.
Your own parts
Section titled “Your own parts”The device store is an interface with a Postgres default, the devices table. Your own store, such as one from a package that keeps devices elsewhere, is the default export of notifications/store.ts, and then no table is needed and protobase migration writes none:
import type { DeviceStore } from '@protobase/server'
const store: DeviceStore = { register: async (userId, device) => { /* add or refresh it, or move a phone's token to userId as a new device; undefined for a browser's endpoint another user holds */ }, remove: async (userId, id) => { /* only when the device is userId's */ }, listForUser: async (userId) => [], listByIds: async (ids) => [], removeGone: async (tokens) => {}, removeAllForUser: async (userId) => {},}
export default storeEvery method takes and returns plain data: the user id as text, and devices as { id, userId, kind, token, p256dh, auth, environment, appId, userAgent, sessionId, createdAt, lastSeenAt }, with token the endpoint for a browser and sessionId the sign-in session it was registered in. A store keeps sessionId as register gives it and returns it: with Protobase’s auth, a device whose store returns no sessionId gets no push and is removed at the next send. A method given an empty user id, id or token throws. listByIds and removeGone act on any user’s devices, for the code that sends; the endpoints never call them. A store missing a method stops startup, naming it.
When Protobase’s auth deletes a user, by an admin or with protobase users delete, it calls the store’s removeAllForUser before anything is deleted, so a store that throws stops the deletion, and once more afterwards. An app that deletes users otherwise calls deviceStore(db, notifications).removeAllForUser(userId) as it deletes one, with the config’s notifications (the devices table’s names), or the removeAllForUser of its own notifications/store.ts.
The built-in stores are postgresDeviceStore(db, notifications) and postgresHistoryStore(db, notifications) of @protobase/server, for a store of your own that wraps one of them.
The history store is an interface with a Postgres default too, the history table, and your own is the default export of notifications/history-store.ts:
import type { HistoryStore } from '@protobase/server'
const historyStore: HistoryStore = { record: async (userId, notification) => { /* keep it unread, created now, under a new id */ }, list: async (userId, { before, limit }) => [], // newest first, after `before` countUnread: async (userId) => 0, // counting up to 100 markRead: async (userId, id) => false, // true when userId has it markAllRead: async (userId, upTo) => {}, // the unread ones created up to `upTo` removeAllForUser: async (userId) => {},}
export default historyStoreA notification is { id, userId, title, body, url, data, createdAt, readAt }, and before is the { createdAt, id } of the last one of the page before. Each method touches only the given user’s notifications, and throws on an empty user id or id. An id is letters, digits, - and _, at most 64 characters, as it goes into a path. record keeps only what historyLimits allows: a title of up to 256 characters, a body and a url of up to 2048, and data of up to 4096 bytes of JSON. The endpoints answer with an error, showing nothing of it, when a store gives back another user’s notification. A store missing a method stops startup, naming it. Deleting a user calls its removeAllForUser as it does the device store’s; an app that deletes users otherwise calls its removeAllForUser itself.
Senders
Section titled “Senders”A sender delivers notifications to the devices of the kinds it names, through their push service. Web Push, APNs, FCM and the push relay are built in; your own senders, such as from a package, are the default export of notifications/senders.ts, an array, and they replace the built-in ones, at most one for each kind. To keep a built-in one beside them, list it too: webPushSender(readVapidSettings(process.env)!) from @protobase/server is the built-in Web Push sender, and readVapidSettings reads the VAPID variables, undefined when none is set; apnsSender(readApnsSettings(process.env)!, { appId }) is the built-in APNs sender, with the mobile app’s appId, and readApnsSettings reads the APNs variables the same way:
import type { PushSender } from '@protobase/server'
const sender: PushSender = { kinds: ['fcm'], send: async (message, devices) => devices.map((device) => ({ id: device.id, result: 'ok' })),}
export default [sender]send takes a message and a batch of devices of those kinds, and answers each device by its id with a result. The send job is what calls it, and only with devices that may get push now: with Protobase’s auth, ones whose session stands. Send through sendNotification, never by calling a sender yourself, which would skip that check. The results:
| Result | |
|---|---|
ok |
the push service took the message |
gone |
the device no longer exists there, and should be removed |
retry |
the push service may take it later; retryAfterSeconds says when, if the service does |
refused |
the sender never delivers to the device as it is stored, so it is neither retried nor removed |
A device with no answer, or an answer that is none of these, counts as retry, and answers for devices outside the batch are ignored. What a sender throws becomes an error that names only the sender’s place in the list, since its own error may name devices.
A message is plain data:
| Field | |
|---|---|
title |
the title, required |
body |
the text under it |
url |
opened on tap: an absolute http or https URL, on the app’s origin or any other |
data |
JSON the app reads when the notification is opened |
badge |
the number on the app’s icon |
sound |
the sound to play |
tag |
a later notification with the same tag replaces this one: up to 32 letters, digits, - and _ |
ttl |
how long, in seconds, a push service keeps it for a device that is offline, up to 28 days |
urgency |
very-low, low, normal or high |
platform |
each protocol’s own fields: web, apns and fcm |
pushMessage(message) checks a message and answers it as senders get it, or throws a PushMessageError that names the field at fault, never its value. Every sender gets a checked message: a url with any other scheme, such as javascript: or data:, or a relative one, is refused, and so is a field that is not one of the message’s, a key __proto__, constructor or prototype anywhere in it, or text with control characters. A sender for web devices names the VAPID publicKey browsers subscribe with, which /meta gives every caller; it must be a P-256 public key in base64url. Its JSON carries the device’s userId as user, as the built-in sender’s does: the service worker shows nothing of a push for another user, or for none.
The bell’s slot
Section titled “The bell’s slot”shell.bell in protobase.ui.tsx draws your own bell in place of the built-in one, from the project or a plugin; with both, the project’s. It is drawn where the built-in bell would be: with notifications on and ui not false, for someone signed in as themselves (see Shell slots). It takes no props and uses these hooks from @protobase/ui:
| Hook | |
|---|---|
useUnreadNotifications() |
the unread count as data, at most 100, kept current as the bell’s is |
useInbox({ enabled }) |
the notifications loaded so far as items, newest first, fetchNextPage for older ones while hasNextPage; read only while enabled |
useMarkNotificationsRead() |
markRead(item) for one, and markAllRead(newest) for all up to the newest one shown; the count and the list show it at once |
usePushNotifications() |
push on this device, as the browser helper says |
import { defineUi, useInbox, useMarkNotificationsRead, useUnreadNotifications } from '@protobase/ui'import { useState } from 'react'
const Bell = () => { const [open, setOpen] = useState(false) const unread = useUnreadNotifications() const inbox = useInbox({ enabled: open }) const { markRead } = useMarkNotificationsRead() return ( <div> <button type="button" onClick={() => setOpen(!open)}>Inbox ({unread.data ?? 0})</button> {open && inbox.items.map((item) => (item.url ? <a key={item.id} href={item.url} onClick={() => markRead(item)}>{item.title}</a> : <p key={item.id}>{item.title}</p>))} </div> )}
export default defineUi({ shell: { bell: Bell } })Table names
Section titled “Table names”The default store keeps devices in the table devices of the schema notifications:
| Column | |
|---|---|
id |
uuid, the id the endpoints answer with |
user_id |
the user’s id, of the same type as auth’s users table’s id; with Protobase’s auth a foreign key to that table, so a deleted user’s devices go with them |
kind |
web, apns or fcm |
token |
the token, or a browser’s endpoint; unique |
p256dh, auth |
a browser’s keys |
environment |
an iOS app’s sandbox or production |
app_id |
the app’s bundle id or package name |
user_agent |
what the device said it is |
session_id |
the id of the sign-in session it was registered in, never its token; NULL when the app’s authenticate names none |
created_at, last_seen_at |
when the user registered it, and last refreshed it |
protobase migration adds session_id to a devices table written before devices kept their session.
You rename the schema, the table and each column, as auth takes tables, such as to keep devices in a table you already have:
notifications: { schema: 'push', devices: { table: 'targets', columns: { user_id: 'owner_id', token: 'address' } },},The history is kept in the table history of the same schema:
| Column | |
|---|---|
id |
uuid, the id the endpoints answer with |
user_id |
the user’s id, as in the devices table; with Protobase’s auth a foreign key to auth’s users table, so a deleted user’s history goes with them |
title, body |
the text it shows |
url |
where it leads |
data |
jsonb, the app’s own |
created_at |
when it was kept |
read_at |
when its user read it, NULL while unread |
Two indexes keep a user’s newest-first pages and unread count cheap. You rename its table and columns as history.table and history.columns:
notifications: { history: { table: 'inbox', columns: { user_id: 'owner_id', read_at: 'seen_at' } },},A name is lowercase letters, digits and _, at most 63 characters. Startup stops, naming what is wrong, while a table lacks a configured column, while the devices table lacks a unique index on the token column alone, which moving a device relies on, or, with Protobase’s auth, while either table lacks the foreign key from its user column to the users table with on delete cascade.