Real-time Notifications — Realtime

Save the notification to the database first. Then send it to the private room user:darto (the most efficient way to reach one user) if that user is online, or…

Order #12 is ready for pickup, and Mrs. Rini wants to tell Mr. Darto. The way depends on where Mr. Darto is right now:

Every message is also written in a book, so it can be read later. In the app, that book is the database. The list that shows what it holds is called the notification centre.

That is what a realtime notification does: it tells one person about something that concerns them, right when it happens, over a road that can still reach them.

One event, several roads

When Eko marks #12 as Ready for pickup, the Laravel server calls the function notify on the realtime server:

async function notify(userId, data) {
  const notif = await db.notifications.save({ userId, ...data, read: false }) // 1. save first
  const online = io.of('/').adapter.rooms.get(`user:${userId}`)?.size > 0
  if (online) return io.to(`user:${userId}`).emit('notif:new', notif)       // 2. in-app
  for (const sub of await db.subscriptions.of(userId)) {                       // 3. Web Push
    await sendPush(sub, { title: data.title, url: `/orders/${data.order}` })
  }
}
Road Reaches him when Needs Cost
In-app (socket) the app is open nothing free
Web Push the app is closed too permission, a service worker, a subscription free
WhatsApp or SMS any time, no app needed a phone number, a business account paid per message

Web Push: news while the app is closed

  1. Mr. Darto taps a "Let me know" button, and the browser asks for permission (Notification.requestPermission()).
  2. The page registers a service worker (/sw.js): a script the browser can wake up even when the tab is closed.
  3. pushManager.subscribe(...) asks the browser's own push service (FCM for Chrome, Mozilla's for Firefox, Apple's for Safari) for an address. This push service is the operator in the picture above. The result is a subscription: an endpoint (a URL) and two encryption keys.
  4. The subscription is sent to the server and stored per device.
  5. To notify, the server encrypts the content with the subscription's two keys, then signs it with its VAPID private key (a secret key only the server holds). The signature proves that the sender owns the public key that belongs with it, which the page gave when subscribing (applicationServerKey). Then the server sends a POST to the endpoint. The push service answers 201 and delivers the news to the phone as soon as the phone is online.
  6. The browser wakes the service worker, and the service worker must show a notification.

This is the code for steps 1 to 4 on the page, then the service worker's code for step 6:

// the page: inside the click handler of the "Let me know" button
const permission = await Notification.requestPermission() // 'granted', 'denied' or 'default'
if (permission === 'granted') {
  const reg = await navigator.serviceWorker.register('/sw.js')
  const sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: VAPID_PUBLIC_KEY })
  await fetch('/api/push/subscriptions', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(sub) })
}

// sw.js
self.addEventListener('push', (event) => {
  const data = event.data.json()
  event.waitUntil(self.registration.showNotification(data.title, { data: { url: data.url } }))
})
self.addEventListener('notificationclick', (event) => {
  event.notification.close()
  event.waitUntil(clients.openWindow(event.notification.data.url))
})

When to ask for permission

WhatsApp and SMS

WhatsApp and SMS reach anyone with a number, with no app and no browser permission. Most laundry customers do read WhatsApp. But you pay per message. A WhatsApp message started by a business also has to use a template (a message text) that WhatsApp approved in advance. Use them for important news only (ready for pickup), or as a backup when a notification is still unread after 30 minutes.

The notification centre and the unread count

The number on the bell icon has to stay right after the page reloads, after a reconnect, or after a notification is read on another device. So its source is the database, and the socket only updates it between two fetches:

let unread = new Map() // id -> notification

socket.on('connect', async () => {
  const list = await fetch('/api/notifications?unread=1').then((r) => r.json())
  unread = new Map(list.map((n) => [n.id, n])) // on every connect: fetch again
  drawBell()
})
socket.on('notif:new', (n) => { unread.set(n.id, n); drawBell() })   // same id: replaced
socket.on('notif:read', ({ id }) => { unread.delete(id); drawBell() }) // read on another phone

function drawBell() {
  bell.textContent = unread.size // counted from the contents, not +1 and -1
}

⚠️ Notifications that get refused, leak, or count wrong

TL;DR: Save the notification to the database first. Then send it to the private room user:darto (the most efficient way to reach one user) if that user is online, or through Web Push if the app is closed. Web Push needs three things: permission (asked from a button, not when the page opens; denied is permanent), a service worker (a script the browser wakes up even when the tab is closed), and a subscription (an address from the browser's push service). The server sends encrypted content, signed with a VAPID key (proof of who sent it), to that subscription's address (its endpoint), and the service worker must call showNotification. On iOS 16.4 and later, Web Push is only for web apps on the home screen. WhatsApp and SMS reach anyone, but cost money. The unread count is counted from a list by id fetched again from the server on every connect, not from a local counter.

⚡ Send to a private room

Write:

const online = io.of('/').adapter.rooms.get(`user:${userId}`)?.size > 0
if (online) return io.to(`user:${userId}`).emit('notif:new', notif)

Meaning: Every customer phone joins its own private room, for example user:darto for Mr. Darto. If that room has members (size > 0), that user is online, and the notification is sent with the event notif:new to that room only. Sending to that room is the most efficient way to reach one user. Broadcasting to everyone and filtering in the browser is wasteful, and it leaks Mr. Darto's news to other people's phones.

⚡ Web Push while the app is closed

Meaning: If Mr. Darto is not online, the news goes through Web Push, which can show a notification even when the app is closed. Web Push needs permission, a service worker (a script the browser can wake up even when the tab is closed), and a subscription (an address from the browser's own push service). The service worker must call showNotification to show the notification.

⚡ Ask for permission from a button

Guess first: the page asks for notification permission as soon as it opens, and Mr. Darto refuses. Can the site ask again tomorrow?

No. A 'denied' answer is permanent for that site: the next permission request (requestPermission()) gets 'denied' right away, with no prompt (the browser's permission question).

Meaning: So do not ask for permission when the page opens. Ask from a "Let me know" button, at a moment that makes sense, for example after Mr. Darto hands in his laundry.

⚡ The bell's number comes from a list

Meaning: The number on the bell icon (how many notifications are unread) is counted from a Map by id. Its contents are fetched again from the server on every connect. A +1 and -1 counter in the browser drifts over time, because events sent while disconnected are lost and duplicates add two.

What you will learn