Most recently for a NextJS PWA, I needed to get push notifications onto the phone in a way that would avoid having to download the app. With some trial and error — it was a huge success!
Service Workers & PWA Functionality
So — assuming every person reading this has a phone and has experienced a push notification, chances are you received a notification because you downloaded an app and then allowed notifications to be sent to you. This process uses signing certificates and authorizations from compiled code — which is really neat, but VERY limiting for web developers looking to give users functionality without maintaining native iOS or Android codebases.
So, here’s where service workers come into play. Think of them like a background worker that runs behind the scenes, handling tasks like caching, background sync, and—you guessed it—push notifications. What’s cool about service workers is that they don’t need the web page to be open to function. This makes them ideal for Progressive Web Apps (PWAs), which aim to blur the line between native apps and web apps. With a service worker, you can intercept network requests, serve up content from the cache when the user is offline, and manage push notifications all without native app constraints. It’s like giving the web app some native-like superpowers!
sequenceDiagram participant User as User Device participant Browser as Browser participant ServiceWorker as Service Worker participant Server as Push Server User->>Browser: Requests Notification Permission Browser->>User: Prompts for Permission User-->>Browser: Grants Permission Browser->>ServiceWorker: Registers Service Worker ServiceWorker->>Server: Subscribes to Push Server Server->>ServiceWorker: Push Notification Trigger ServiceWorker->>Browser: Push Notification Delivered Browser->>User: Displays Notification