Frontend System Design · Lesson 65 of 86 · 4 min
Push Notifications for Web Apps
This comes up when designing any system that needs to re-engage users, like social media, e-commerce, or chat apps. You need to know the end-to-end flow.
After this, you'll be able to explain the full architecture of a web push notification system, from the user granting permission on the client to your server triggering a push. You will know the roles of the service worker, your backend, and the third-party push services that connect them.
The End-to-End Architecture
A push notification system has three main actors: your web app (the client), your application server (the backend), and a third-party Push Service.
The Push Service is the critical intermediary. It's a service provided by the browser vendor (e.g., Google's FCM, Apple's APNS) that maintains a persistent connection to the user's device. This is a hard problem you don't want to solve; it involves managing millions of connections, optimizing for battery life, and queuing messages for offline devices. Your job is to connect the pieces.
The entire flow looks like this:
Your server authenticates itself to the Push Service using VAPID (Voluntary Application Server Identification) keys. This is a public/private key pair. The public key is given to the client when it subscribes, and the private key is used by your server to sign the push request. This proves the request came from you.
The Client-Side: Subscribing the User
The frontend's first job is to get the user's permission and a PushSubscription object. This object contains a unique endpoint URL provided by the Push Service—it's the address your server will send messages to.
The flow is always:
- Register a service worker.
- Request notification permission from the user.
- If granted, use the
pushManager.subscribe()method to get aPushSubscription. - Send this subscription object to your backend to be stored.
The trap: Asking for permission on page load. Users will reflexively click "Block" on a prompt from a site they just landed on. Instead, ask for permission in response to a specific user action that implies interest, like clicking a "Notify me of new messages" button. Make the value proposition clear before showing the native browser prompt.
This is the code to get a subscription and send it to your server.
// In your main application code
async function subscribeUser() {
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
console.warn('Push notifications are not supported.');
return;
}
const registration = await navigator.serviceWorker.register('/sw.js');
const permission = await Notification.requestPermission();
if (permission !== 'granted') {
console.warn('Permission was not granted.');
return;
}
// This VAPID key is generated on your server and is safe to expose.
const applicationServerKey = 'YOUR_VAPID_PUBLIC_KEY';
const options = {
userVisibleOnly: true,
applicationServerKey,
};
const subscription = await registration.pushManager.subscribe(options);
// Send the subscription object to your backend.
await fetch('/api/save-subscription', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(subscription),
});
}
The userVisibleOnly: true option is mandatory. It's a promise to the browser that every push message will result in a visible notification. This prevents developers from silently tracking users in the background.
The Service Worker: Receiving and Displaying
The service worker does the actual work when a push message arrives. It runs in the background, separate from your main application tab. The browser wakes it up when a push message is delivered by the Push Service.
You need to listen for two key events: push and notificationclick.
The push event fires when a message arrives. Your handler parses the payload and calls self.registration.showNotification() to display it.
The notificationclick event fires when the user taps the notification. Your handler should open a relevant window or focus an existing one. A notification that does nothing when clicked is a dead end and a poor user experience.
Key detail: Any async work inside these event handlers must be wrapped in event.waitUntil(). This tells the browser to keep the service worker alive until your promise resolves. Without it, the service worker might be terminated mid-operation.
// In sw.js
self.addEventListener('push', (event) => {
const payload = event.data ? event.data.json() : {};
const title = payload.title || 'New Notification';
const options = {
body: payload.body || 'Something new happened!',
icon: '/images/icon-192x192.png',
data: {
url: payload.url || '/',
},
};
event.waitUntil(self.registration.showNotification(title, options));
});
self.addEventListener('notificationclick', (event) => {
// Close the notification
event.notification.close();
const targetUrl = event.notification.data.url;
// Focus an existing window or open a new one
event.waitUntil(
clients.matchAll({ type: 'window', includeUncontrolled: true }).then((clientList) => {
for (const client of clientList) {
if (client.url === targetUrl && 'focus' in client) {
return client.focus();
}
}
if (clients.openWindow) {
return clients.openWindow(targetUrl);
}
})
);
});
A push can also be "silent"—triggering the push event without displaying a notification. You can use this to sync data in the background, which is a powerful technique for offline-first apps, as discussed in the lesson on Offline Support and Background Sync.
Handling Payloads and Server Logic
Your backend stores the PushSubscription objects, usually mapped to a user ID. When an event occurs (e.g., a new message arrives), the server retrieves the relevant subscription(s) and sends a request to the endpoint URL.
Interview angle: A common question is how to handle expired subscriptions. If a user revokes permission or clears their browser data, the subscription becomes invalid. When your server tries to send a message to that endpoint, the Push Service will respond with a
410 GONEstatus code. Your backend must be designed to catch this response and delete the stale subscription from your database. This demonstrates you've thought about system maintenance and efficiency.
You also have to decide what goes into the push payload.
- Small payloads (a few KB): Send all necessary data directly in the push message (e.g., a chat message's text). The service worker can display it immediately. This is fast and simple.
- Large or sensitive data: Send a minimal payload, like an ID or a "new data available" flag. The service worker's
pushhandler then fetches the full data from your API. This keeps the push message light but adds a network request, introducing latency.
Try it
Use a library like web-push for Node.js to generate a VAPID key pair. Then, using the client-side code from this lesson, create a simple HTML page with a button. When clicked, it should request permission and log the resulting PushSubscription object to the console. This should take about 20 minutes.
Next: We'll compare the tools that bundle your code for production in Webpack vs Vite vs Parcel.
Lock it in — apply this lesson under interview conditions.