Service Worker

Service Workers power offline experiences, caching strategies and background sync for PWAs.

← Back

Key Concepts

  • Intercept network requests and serve cached responses
  • Background sync and periodic tasks
  • Push messages and notification handling
  • Lifecycle: install → activate → fetch
  • Use Workbox for common production patterns

React FCM Setup

Token:

🔧 What This App Does with Service Workers

1. Registration & Lifecycle

The service worker (/public/sw.js) is registered when you visit the demo page. It immediately claims all clients using skipWaiting() and clients.claim() during install/activate phases.

2. Push Notification Handling

Listens for push events from Firebase Cloud Messaging. When a push arrives, it parses the data payload and displays a notification with custom title, body, icon, and badge.

3. Local Push Simulation

For demo purposes, it also responds to message events from the page. When you click "Send Test Notification", the page sends a message to the service worker which then shows a notification locally.

4. Notification Clicks

Handles notificationclick events. When you click a notification, it closes it and either focuses an existing tab with the target URL or opens a new window.

🔁 How It Works:

  1. Page registers service worker at /sw.js
  2. Service worker installs & activates in background
  3. Page sends message or FCM sends push to service worker
  4. Service worker displays notification using Notification API
  5. User clicks notification → service worker handles click → opens/focuses window