Open MercatoDocsSearch docsAPI reference

Tutorials

Devices & Push Notifications — Getting Started

Follow a notification from a registered device to delivery. The device registry identifies the recipient, the notification defines the message and a provider handles transport.

Tip · Where to go next

This page is the happy path. Once it works, the reference pages carry the detail: Notification Delivery (which channels a type may use, and why one was dropped), Devices (the registration API a client app calls), Push Notifications (transport, retries, error codes, environment variables), and the admin guide for the screens.


1. The 30-second mental model

You want a message to pop up on a user's phone. Four small modules cooperate to make that happen:

ModuleOne-line jobThink of it as…
devicesRemembers each user's phones/tablets and their push tokensThe address book of devices
notificationsDefines notification types, stores in-app messages, and tracks per-user opt-out preferencesThe content + rules
push_notificationsTakes a notification and actually delivers it to devices (queue, retries, delivery log)The mail carrier
communication_channels (+ channel-fcm / channel-apns / channel-expo)Talks to Apple / Google / Expo using your credentialsThe post office for each platform

Flow in one sentence:

Your app registers a device → later your backend creates a notification → the push module looks up the user's devices → and hands each one to FCM/APNs/Expo.

[Mobile app]                 [Your backend]
     |                             |
  register device           create notification
     |                             |
     v                             v
  devices module  <----------  push_notifications  ---->  communication_channels
  (token stored)              (find devices, queue)        (FCM / APNs / Expo)
                                                                   |
                                                                   v
                                                            📱 push lands

2. The devices module – the address book

What it stores

One row per user device (a UserDevice). Important fields:

Registering a device (what the mobile app calls)

POST /api/devices
Authorization: Bearer <user-token>

{
  "deviceId": "A1B2-C3D4",
  "platform": "ios",
  "pushToken": "<token from APNs/FCM/Expo>",
  "pushProvider": "apns",
  "clientAppVersion": "1.2.3",
  "osVersion": "17.5"
}

Other endpoints

Permissions (ACL)


3. The notifications module – content + rules

Notification types

Every notification has a type (a frozen id like sales.order.created). A module declares its types in a notifications.ts file. A type carries:

User preferences (opt-out)

Users can disable a type per channel (in-app, push, …):

Per-type channel eligibility (business types ship without push)

Notification types can declare which channels they may deliver on. Every user-configurable built-in type does so explicitly: business and actionable types ship channels: ['in_app', 'email'], while the demo.silent_ping and demo.push_playground fixtures ship channels: ['push']. Push is therefore off for ordinary business notifications out of the box, so connecting a push provider does not blast the entire catalogue to phones. A channel outside the type's set never delivers and users cannot enable it in their preferences (the cell shows as locked).

Two ways to change the set:

Registering a new channel does not automatically make existing built-in types eligible for it. Channel authors should declare it on notification types their module owns; operators can add it to other types through the tenant-scoped override.

Channels inside the set behave as usual: users opt in/out per type, and nonOptOut types always deliver. The eligibility check runs before both – a channel outside the set is off even for nonOptOut types.

Creating a notification (this is what triggers a push)

POST /api/notifications

{
  "recipientUserId": "<uuid>",
  "type": "sales.order.created",
  "titleKey": "notifications.sales.order_created.title",
  "bodyKey": "notifications.sales.order_created.body",
  "bodyVariables": { "orderNumber": "12345" },
  "linkHref": "/backend/sales/orders/<uuid>",
  "data": { "orderId": "<uuid>" },          // custom fields delivered inside the push
  "pushOptions": { "sound": "default", "badge": 1 }
}

Bulk variants exist too: /api/notifications/batch, /role, /feature.

From code (the common, event-driven way), resolve the service via DI:

const notificationService = ctx.resolve('notificationService')
await notificationService.create(input, { tenantId, organizationId })

4. The push_notifications module – the mail carrier

You usually don't call this directly. When a notification is created, a delivery strategy runs automatically and:

  1. Checks the user's preferences (unless the type is nonOptOut; silent types are still preference-gated).
  2. Loads the recipient's devices that have a push token.
  3. Writes a PushNotificationDelivery row (status pending) per device.
  4. Enqueues a background job.
  5. A worker resolves the right adapter (FCM/APNs/Expo), sends, and on failure retries with backoff. If a token is permanently invalid, the device is auto-deactivated.

Observability for admins:

Silent / background push

There is no dedicated silent-push primitive. A silent push is just a normal notification whose type is declared silent: true – create it through the ordinary notificationService.create() path and the push delivery strategy sends a data-only, content-available wake-up (no banner):

// type declaration (module notifications.ts): { type: 'system.security.new_login', silent: true, nonOptOut: true, ... }
const notificationService = ctx.resolve('notificationService')
await notificationService.create({
  recipientUserId: userId,
  type: 'system.security.new_login',   // registered with silent: true
  title: 'New login',                   // required; not shown for a silent push
  data: { ipAddress: '203.0.113.42' },  // delivered inside the push payload
}, { tenantId, organizationId })

Because silent types respect preferences, mark the type nonOptOut: true if it must always fire. For an admin one-off visible push, use pushNotificationService.sendCustomPush(...) (or the Send Push admin page).


5. One-time setup: connect a push provider

Push tokens are useless without credentials. Credentials live per tenant in the admin UI (no env vars): Settings → Module Configs → Communication Channels → Connect.

ProviderPlatformsWhat you pasteWhere to get it
Firebase (FCM)Android + iOSService-account JSONFirebase Console → Project settings → Service accounts → Generate key
Apple (APNs)iOS.p8 key + Key ID + Team ID + Bundle ID + production flagApple Developer → Keys → APNs key
ExpoAndroid + iOS(optional) access tokenexpo.dev → Account → Tokens

A device is routed to a provider by the pushProvider it registers with, never by its platform. So FCM serves iOS as well as Android – the adapter emits the apns payload block (priority headers, aps.sound/aps.badge, and content-available: 1 for silent pushes) alongside the android block on every send.

Choosing between FCM and APNs for iOS:

Connecting both is fine: each device is delivered through whichever provider it registered with.

Existing tenants: sync the new ACL grants

These modules ship new ACL features (devices.*, push_notifications.view_deliveries, and the channel_fcm / channel_apns / channel_expo grants). New tenants pick them up automatically during setup, but existing tenants only receive newly declared grants after you run the idempotent sync command once:

yarn mercato auth sync-role-acls

Without it, an admin on an existing tenant may not see the push delivery log or the provider connect UI because their role is missing the freshly added grants. Use --tenant <tenantId> to target a single tenant.


6. End-to-end checklist for your first push

  1. Connect a provider (FCM/APNs/Expo) in Communication Channels.
  2. Register a device from the mobile app: POST /api/devices with pushToken + pushProvider.
  3. Make sure the type is push-eligible – business and actionable built-ins ship without push, so enable it for the type first (Settings → Notification Delivery, or PATCH /api/notifications/types). The demo.silent_ping and demo.push_playground fixtures already ship with push eligibility. The recipient must also not have opted out of push for that type.
  4. Create a notification: POST /api/notifications with recipientUserId + type.
  5. Watch it land and verify in the delivery log: GET /api/push_notifications/deliveries.

7. Good-to-know rules

For the rules that decide whether a channel delivers at all – per-type eligibility, operator overrides, non-opt-out, and the default that makes a type without a declared channel list push-eligible – see Notification Delivery.

8. Environment variables

Every OM_PUSH_* variable is optional; push works with none of them set. The full table, including the reclaim and receipt-polling knobs and the two test-only provider flags, lives in Push Notifications → Environment variables.

Both test flags must reach the worker process as well as the app, because the push worker runs in its own process.

Previous: Material Availability Check · Next: Tutorial - build your first Open Mercato app