Notifications & Push (FCM)
How the mobile inbox, per-category push preferences, and FCM/APNs device tokens fit together — the app reads and mutates notifications but never creates them; the server fans them out from domain events.
The Notifications domain has two surfaces stacked on each other: a server-persisted in-app inbox (rows you read, mark, and delete) and an FCM/APNs push channel layered on top for offline delivery. The mobile app reads its inbox via GET /api/v1/notifications, marks rows read, soft-deletes them, manages per-category push opt-outs, and registers/revokes device tokens. Every endpoint is Authorization: Bearer <oat_...> authenticated (the api guard) and scoped to the caller — none are public, owner-gated, or admin.
The inbox row is the source of truth. SSE (foreground) and push (offline) are best-effort delivery legs layered on top — if either drops, the row is still there on the next GET. Every response uses the standard { data, meta: { requestId } } envelope; the inbox list adds meta.unreadCount.
Audience: customer and owner mobile application engineers. This guide leads with the end-to-end sequence, then per-step detail, lifecycle states, and implementation notes.
The client cannot create notifications. There is no POST for inbox rows. Notifications are
emitted only by server-side domain events (order accepted, payment received, new chat message,
job decision, …) through an internal notificationService.enqueue. Your endpoints are read /
mark-read / delete for the inbox, plus preferences and device-token management. Do not
look for a "send notification" call — it does not exist.
The flow at a glance
Step 1 — Register the device push token (on every launch)
POST /api/v1/notifications/devices with { token, platform, provider }. This is idempotent on the token — run it on every app open. It refreshes lastSeenAt, re-enables a previously-revoked token, and never creates duplicates. A user with zero active tokens silently gets inbox + SSE only; push is a no-op. Register early, not lazily.
Step 2 — (Optional) Load and toggle push preferences
GET /api/v1/notifications/preferences returns only the categories the user has explicitly toggled. Anything absent is enabled (opt-out model). Render a missing key as ON. Flip a toggle with PATCH .../preferences sending only the changed categories — they merge over stored prefs.
Step 3 — A domain event fires server-side (no client action)
Something happens (order accepted, payment received, chat message). The backend calls notificationService.enqueue internally: it localizes the title/body to the recipient's saved language, persists the inbox row, broadcasts on the user's SSE channel for any foregrounded client, and — for push-eligible categories the user has not silenced — dispatches a background FCM job.
Step 4 — The FCM job delivers to active tokens
The job loads all of the user's active device tokens, sends a multicast push (Android channel + priority, APNs headers derived from the category), and reconciles per-token results: success resets the failure counter; FCM-invalid tokens are revoked immediately; transient failures auto-revoke after 5 consecutive strikes.
Step 5 — The user taps the push → deep link
The data payload carries server-controlled deep-link keys (route, id, link, plus orderId/truckId where relevant). Route off these — they always win over any caller-supplied keys.
Step 6 — Backfill on app open / pull-to-refresh
GET /api/v1/notifications returns the inbox newest-first and a global meta.unreadCount for the badge. This backstops anything the SSE/push legs missed.
Step 7 — Read or delete rows
PATCH /api/v1/notifications/:id/read marks one read (idempotent). DELETE /api/v1/notifications/:id soft-deletes one (hidden from future lists and excluded from unreadCount).
Step 8 — Revoke the token on logout
DELETE /api/v1/notifications/devices/:id soft-revokes the token so push stops to that handle. Always do this on logout, especially on shared devices.
Per-step detail
Step 1 — Register / refresh a device token
Body: token (8–4096 chars, required), platform (ios|android|web, required), provider (fcm|apns, optional — defaults fcm), locale (en|ar, optional), plus optional diagnostics manufacturer, deviceModel, osVersion, appVersion. The token is hashed (sha256) for lookup and encrypted at rest.
Idempotency: re-posting the same token re-enables it, clears revokedAt, reassigns it to the caller, and bumps lastSeenAt instead of creating a duplicate. Sparse re-registration keeps prior diagnostic values for omitted fields.
POST /api/v1/notifications/devices HTTP/1.1
Authorization: Bearer oat_xxx
Content-Type: application/json
{
"token": "fcm:eOPj3kQv-_8:APA91bF…<truncated FCM token>…",
"platform": "ios",
"provider": "fcm",
"locale": "en",
"deviceModel": "iPhone 16 Pro",
"appVersion": "1.4.0+102"
}Returns 201 when a brand-new row was created, 200 when an existing token row was updated. Treat both as success — do not branch on the status code.
{
"data": {
"id": "dvt_01jq8z...",
"platform": "ios",
"provider": "fcm",
"manufacturer": "Apple",
"deviceModel": "iPhone 16 Pro",
"osVersion": "19.2",
"appVersion": "1.4.0+102"
},
"meta": { "requestId": "req_abc" }
}Errors: 401 AUTH_REQUIRED, 422 VALIDATION_ERROR.
Step 2 — Push preferences (opt-out, stored sparsely)
GET .../preferences returns only the categories the user explicitly toggled. The 11 categories are: order, payment, chat, support, report, job, marketplace, truck, system, promotion, offer. Any category absent from the map is treated as true (push enabled).
GET /api/v1/notifications/preferences HTTP/1.1
Authorization: Bearer oat_xxx{
"data": { "preferences": { "promotion": false, "offer": false } },
"meta": { "requestId": "req_abc" }
}PATCH .../preferences is a partial merge — send only the categories you want to change; the rest are untouched. Setting a category to false silences only the FCM push for it; the inbox row is still written and the SSE broadcast still fires, so no data is lost. The response is the full merged map.
PATCH /api/v1/notifications/preferences HTTP/1.1
Authorization: Bearer oat_xxx
Content-Type: application/json
{ "preferences": { "promotion": false, "offer": false } }{
"data": { "preferences": { "promotion": false, "offer": false } },
"meta": { "requestId": "req_abc" }
}Errors: GET returns 401 AUTH_REQUIRED only (it takes no input to validate). PATCH returns 401 AUTH_REQUIRED or 422 VALIDATION_ERROR.
Not every category can be pushed. Push-eligible categories are order, payment, chat,
support, report, job, marketplace, truck. The categories system, promotion, and
offer are SSE + inbox only — they will never arrive as an FCM banner even with the preference
enabled. Do not promise users push for promos, offers, or system messages.
Step 6 — List the inbox
Query params:
| Param | Type | Notes |
|---|---|---|
unreadOnly | string "true" / "false" | A string, not a JSON boolean. unreadOnly=1 or a real boolean → 422. |
category | one of the 11 categories | Filters the page only. |
limit | number 1–200 (default 50) |
Newest-first. Soft-deleted rows (deletedAt set) are excluded. Each item: id, type, category, title, body (nullable), relatedType (nullable), relatedId (nullable), readAt (nullable ISO), createdAt (ISO).
GET /api/v1/notifications?unreadOnly=false&limit=50 HTTP/1.1
Authorization: Bearer oat_xxx
Accept-Language: en{
"data": {
"items": [
{
"id": "ntf_01jq9a...",
"type": "order_accepted",
"category": "order",
"title": "Order accepted",
"body": "Your order is being prepared.",
"relatedType": "order",
"relatedId": "ord_01jq8z...",
"readAt": null,
"createdAt": "2026-06-21T09:14:02.110Z"
}
]
},
"meta": { "requestId": "req_abc", "unreadCount": 7 }
}meta.unreadCount is a global unread total — a separate count query over all the user's
non-deleted, unread rows. It is not scoped by limit, category, or unreadOnly on the same
request. Use it for the badge; do not compute the badge from items.length.
Step 7a — Mark one read
Idempotent: if the row is already read, the existing readAt is kept (not refreshed). There is no mark-all-read, no bulk endpoint, and no un-read/unmark endpoint.
PATCH /api/v1/notifications/ntf_01jq9a.../read HTTP/1.1
Authorization: Bearer oat_xxx{
"data": { "id": "ntf_01jq9a...", "readAt": "2026-06-21T09:20:00.000Z" },
"meta": { "requestId": "req_abc" }
}Errors: 401 AUTH_REQUIRED; 403 FORBIDDEN if the row belongs to another user; 404 NOT_FOUND if the row is missing or soft-deleted.
Step 7b — Soft-delete one
Sets deletedAt. The row is hidden from future list calls and excluded from unreadCount. There is no way to restore a soft-deleted row.
DELETE /api/v1/notifications/ntf_01jq9a... HTTP/1.1
Authorization: Bearer oat_xxx{
"data": { "id": "ntf_01jq9a...", "deleted": true },
"meta": { "requestId": "req_abc" }
}Errors: 401 AUTH_REQUIRED; 403 FORBIDDEN cross-user; 404 NOT_FOUND if missing or already soft-deleted.
Step 8 — Revoke a device token
Soft-revoke: sets enabled=false + revokedAt (the row is kept for audit). The lookup is scoped to the caller's userId first, so a token belonging to another user returns 404 NOT_FOUND (existence is not leaked via 403); the ownership policy runs as defense-in-depth. Call this on logout.
DELETE /api/v1/notifications/devices/dvt_01jq8z... HTTP/1.1
Authorization: Bearer oat_xxx{
"data": { "id": "dvt_01jq8z...", "revoked": true },
"meta": { "requestId": "req_abc" }
}Errors: 401 AUTH_REQUIRED, 403 FORBIDDEN, 404 NOT_FOUND.
Order realtime push contract
Order pushes always contain both the visible notification block and string-only data. Order-category routing uses Android high priority, APNs priority 10, and the default sound.
| Trigger | Recipients | data.type | data.route |
|---|---|---|---|
| Customer creates an order | Truck owner + every active staff user | order_new | order |
| Customer cancels an order | Truck owner + every active staff user | order_cancelled | order |
| Owner changes order status | All devices belonging to the customer | order_status | track |
Owner new/cancel payload data:
{
"type": "order_new",
"route": "order",
"id": "ord_01jq...",
"orderId": "ord_01jq...",
"truckId": "trk_01jq...",
"orderNumber": "TM-20260713-0042"
}Use type: "order_cancelled" for customer cancellation; the remaining keys are identical.
Customer status payload data:
{
"type": "order_status",
"route": "track",
"id": "ord_01jq...",
"orderId": "ord_01jq...",
"status": "preparing",
"orderNumber": "TM-20260713-0042",
"truckName": "Crispy Cart",
"eta": "2026-07-13T18:30:00.000Z"
}eta is optional. status is sent on every owner transition (accepted, rejected, preparing, ready_for_pickup, completed, or owner-driven cancelled). The notification inbox keeps its existing internal types such as order_created and order_preparing; foreground refresh and deep-link code should use the FCM data.type values above.
How a push gets built (server-side, for reference)
The client does not trigger this process, but understanding the payload helps route deep links and diagnose missing pushes.
- The push data payload carries reserved deep-link keys:
route,id,link,type,notificationId,relatedType,relatedId, plusorderId/truckIdwhere relevant. These are server-controlled and always win over any caller-supplieddatakeys on collision — rely on them in your deep-link handler. (linkis an absolute{APP_URL}/app/{route}/{id}URL.) - Order notifications deep-link differently by recipient. FCM
order_new/order_cancelledroute toorder(owner order detail); FCMorder_statusroutes totrack(customer live tracking). Truck notifications (relatedTypeoftruckorfood_truck) route totruck. - Silent / data-only pushes exist for chat sync (
chat_read,chat_typing): no banner, no inbox row, and no SSE from the same call — your background/foreground FCM message handler must act on these purely from thedatapayload. (See Chat & Realtime.) - Title/body are localized at enqueue time using the recipient's saved
User.language— not the request'sAccept-Language. The stored inbox row is what the user saw, and the push title/body match it. Changing app language will not retranslate already-stored rows.
Lifecycle
Two independent entities have a lifecycle: the Notification (inbox row) and the DeviceToken (push handle).
Notification state table
| State | Meaning | How you got here | What's allowed next |
|---|---|---|---|
unread | readAt = null | Server-side domain event → notificationService.enqueue (no client call) | Mark read; soft-delete |
read | readAt set | PATCH .../:id/read | Soft-delete (cannot un-read) |
deleted | deletedAt set — hidden from inbox, excluded from unreadCount | DELETE .../:id | Terminal (no restore) |
DeviceToken state table
| State | Meaning | How you got here | What's allowed next |
|---|---|---|---|
active | enabled=true, revokedAt=null — eligible for push | POST .../devices (new, or idempotent re-activate of a revoked token) | Revoke (manual or server auto-revoke) |
revoked | enabled=false, revokedAt set — soft, kept for audit | DELETE .../devices/:id, or server auto-revoke | Re-activate by re-posting the same token |
Transitions
- (no row) →
Notification.unread— server domain event →notificationService.enqueue. Actor: server (not a client endpoint). unread→read—PATCH /api/v1/notifications/:id/read. Actor: the notification owner.unread|read→deleted—DELETE /api/v1/notifications/:id. Actor: the notification owner.- (no token) |
revoked→DeviceToken.active—POST /api/v1/notifications/devices(idempotent re-activate). Actor: the device owner. active→revoked—DELETE /api/v1/notifications/devices/:id(manual / logout). Actor: the device owner.active→revoked(server auto-revoke) — FCM reports an invalid/unregistered token (revoked on the next send), OR 5 consecutive transient send failures trip the per-token circuit breaker. Actor: server (SendPushNotificationJob). A previously-registered device can go silent with no client action — re-POST the token to revive it.
Implementation Notes
| Integration issue | Correct handling |
|---|---|
Looking for a POST to create a notification. | No client endpoint exists for notification creation. Notifications are emitted only by server-side domain events. Your inbox endpoints are read / mark-read / delete. |
| Expecting push to work right after registering a token. | Registering only makes the device eligible. A user with zero active tokens silently gets inbox + SSE, push is a no-op. Register early (on launch), not lazily. |
| Rendering a missing preference key as "off". | Preferences are opt-out and stored sparsely. A category absent from the GET map means enabled. Default missing keys to ON. |
Assuming PATCH preferences replaces the whole map. | It merges. Sending { promotion: false } does not reset other categories. |
Thinking pref=false fully mutes a category. | It silences only the FCM push. The inbox row is still written and SSE still fires — a muted category still appears in GET /notifications and still increments unreadCount. |
| Promising push for promos / offers / system. | system, promotion, offer are SSE + inbox only. They never arrive as a push banner even with prefs on. |
Computing the badge from items.length. | meta.unreadCount is a global count over all non-deleted unread rows, independent of limit/category/unreadOnly. Use it directly. |
Sending unreadOnly as a boolean or 1. | It is a string param — "true" / "false" only. Anything else → 422. |
| Expecting mark-read to refresh the timestamp, or looking for mark-all-read. | Mark-read is idempotent and keeps the original readAt. There is no bulk, no mark-all-read, no un-read, no restore-deleted. |
| A device stops receiving push. | Tokens are auto-revoked server-side (FCM-invalid immediately; 5 consecutive transient failures trip the breaker). Re-POST the token — idempotent re-registration clears revokedAt. |
Branching app logic on 200 vs 201 from device register. | Both mean success — 201 created, 200 updated. Treat them identically. |
Expecting 403 when revoking someone else's token id. | By design it returns 404 — the lookup is scoped to the caller before the policy check, so existence is not leaked. |
| Diagnosing a missing non-production push as a client defect. | If FCM credentials are not configured, push runs in silent no-op mode (logged, zero-success); inbox + SSE still work. Verify environment configuration before changing client behavior. |
| Ignoring the deep-link keys / hand-rolling routes. | Route off the server-controlled route/id/link/orderId/truckId data keys. Owner pushes use order_new / order_cancelled + route=order; customer updates use order_status + route=track. |
| Waiting for a banner on chat sync events. | chat_read / chat_typing are data-only silent pushes — no banner, no inbox row, no SSE on that call. Handle them in your FCM message handler from the data payload. |
Assuming the push language follows Accept-Language. | Title/body are localized at enqueue time from the recipient's saved User.language. Changing app language will not retranslate stored rows. |
Related
- Chat & Realtime — SSE channel + the silent chat-sync data pushes
- Order Lifecycle — the order events that fan out notifications
- API reference
Chat & Realtime (SSE)
How to integrate 1:1 and group chat — durable REST endpoints plus the two realtime transports (Socket.IO and SSE) that deliver live messages, read receipts, and typing indicators.
Uploads — the fileId Pattern
The two-step upload contract — trade a binary for a fileId at POST /api/v1/uploads, then anchor that fileId on a feature endpoint to make it live.