C.W.K.
Stream
Lesson 04 of 08 · published

Notification System

~10 min · app, notifications

Level 0Poller
0 XP0/60 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

Push, not poll

Notifications are the cleanest case for server push. The user is not asking; the server has news. Push it as a typed message; let the client UI choose whether to show a toast, increment a badge, or play a sound.

Multi-device fan-out

If the same user has phone + laptop + tablet open, they should see the notification on all three (and an "ack from any device clears it everywhere" if you implement that). The multi-device-aware manager from Track 4 makes this one line of code.

SSE is enough for most notification feeds

Notifications are server-to-client only. SSE wins on simplicity. Reach for WebSocket here only if the same connection also handles other bidirectional flows.

Code

Server: push notification to a user·python
import uuid
from datetime import datetime

async def notify(manager, user_id: str, *, title: str, body: str,
                  level: str = 'info', url: str | None = None):
    msg = {
        'type': 'notification',
        'data': {
            'id':    str(uuid.uuid4()),
            'title': title,
            'body':  body,
            'level': level,
            'url':   url,
            'ts':    datetime.utcnow().isoformat() + 'Z',
        },
    }
    sent = await manager.send_to_user(user_id, msg)
    if sent == 0:
        # User offline; persist for delivery on next connect.
        await db.notifications.insert(user_id, msg)
Client: toast + badge·javascript
ws.on('notification', (data) => {
  showToast({
    title:   data.title,
    body:    data.body,
    level:   data.level,           // info / warning / success / error
    onClick: () => data.url && (location.href = data.url),
  });
  unread += 1;
  setBadge(unread);
});

External links

Exercise

Build the notify() server function and a client toast. Trigger from a REST endpoint (POST /admin/notify). Open three browser tabs as the same user and one as a different user — only the matching user should see the toast across all three of their tabs.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.