Order #12 is ready for pickup, and Mrs. Rini wants to tell Mr. Darto. The way depends on where Mr. Darto is right now:
- If Mr. Darto is in the shop, she just calls out to him. In the app, "in the shop" means the app is open, and calling out to him is an in-app notification: news through that open app.
- If he is at home with his phone in his pocket, she asks an operator who can make his phone ring even with the app closed. This is Web Push.
- If that is not possible either, she sends a WhatsApp message: it costs money, but it will be read.
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}` })
}
}
- Every customer phone joins its own private room,
user:darto. Sending to that room is the most efficient way to reach one user: only their connections receive it. Broadcasting to everyone and filtering in the browser is wasteful, and it leaks Mr. Darto's news to other people's phones. - The server saves the notification to the database first, so the notification centre can read it even if every road fails.
- If Mr. Darto is online (his room is not empty, as in the Presence & Online Status lesson), in-app is enough. If not, Web Push.
| 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
- Mr. Darto taps a "Let me know" button, and the browser asks for permission (
Notification.requestPermission()). - The page registers a service worker (
/sw.js): a script the browser can wake up even when the tab is closed. 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: anendpoint(a URL) and two encryption keys.- The subscription is sent to the server and stored per device.
- 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 theendpoint. The push service answers 201 and delivers the news to the phone as soon as the phone is online. - 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))
})
- In
sw.js,selfis the service worker itself.event.waitUntil(...)makes the browser wait until the notification is shown before it stops the service worker again. A click on the notification closes it and opens itsurl. userVisibleOnly: trueis a promise that every push shows a notification. Chrome refuses to subscribe without it, and it also requiresapplicationServerKey.- A 404 or 410 from the
endpointmeans that subscription is dead (permission revoked, app removed). Delete it from the database. - Keep the push content small: a push service must accept at least 4,096 bytes, but because the message is encrypted, at most 3,993 bytes of your own content fit. Send a title and a URL, not the whole order. On a Node server, the
web-pushlibrary handles the encryption and the signature. - iPhone and iPad: Web Push exists since iOS 16.4, but only for web apps added to the home screen. Their manifest (the web app's settings file) must also have a
displaythat is not the default, for examplestandalone. In a plain Safari tab,Notificationdoes not even exist (undefined). So Mr. Darto, who opened the laundry app in a plain tab, gets no Web Push once the tab is closed. On a Mac, Web Push is in Safari 16 and later on macOS Ventura (according to browser-compat-data 8.1.5). - Android Chrome:
new Notification(...)in a page always throws aTypeError. Notifications have to go throughregistration.showNotification().
When to ask for permission
- Not when the page opens. Firefox (since version 72) only shows the prompt (the browser's permission question) from a user action such as a click, and so does Safari. People who are surprised also tend to refuse.
- Ask at a moment that makes sense: after Mr. Darto hands in his laundry, show a "Let me know when it is ready" button. The browser's prompt appears only after he taps it.
- A
'denied'answer is permanent for that site: the nextrequestPermission()answers'denied'right away, with no prompt. Only Mr. Darto can change it in the browser's settings.
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
}
- The number is counted from a
Mapbyid. A notification that arrives twice replaces itself, so it does not add to the count. - A
+1and-1counter in the browser drifts over time: events sent while disconnected are lost, duplicates add two, and notifications read on another tablet are not counted. - When Mr. Darto reads a notification, his phone sends
POST /api/notifications/301/read. Then the server emitsnotif:readto the roomuser:darto, so the bell number on all of Mr. Darto's devices changes too.
⚠️ Notifications that get refused, leak, or count wrong
- Asking for permission as soon as the page opens. If it is refused once, your site cannot ask again.
- Broadcasting to everyone and filtering in the client. Mr. Darto's news reaches other people's phones. Send to the room
user:darto. - Keeping the unread count as a local counter. Fetch it from the server on every connect.
- Relying on Web Push in an iPhone Safari tab. Web Push only works from the home screen. Provide in-app, and WhatsApp for important news.
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.