Service Worker - agoenks29D/exzly GitHub Wiki

📡 Service Worker

This guide explains the service worker implementation in the feature/service-worker branch of Exzly, used for push notifications and asset caching.


📦 Overview

Exzly supports background push notifications from both Web Push and Firebase Cloud Messaging (FCM). It also uses Workbox to cache static assets (CSS, JS, images, fonts) to improve performance and offline support.

🔧 Firebase Configuration

file : client/src/config/index.ts

import { FirebaseOptions } from 'firebase/app';

export const firebaseConfig: FirebaseOptions = {
  apiKey: 'Enter your Firebase Web API Key here',
  authDomain: 'Enter your Firebase Auth domain here',
  projectId: 'Enter your Firebase Project ID here',
  storageBucket: 'Enter your Firebase Storage bucket here',
  messagingSenderId: 'Enter your Firebase Messaging sender ID here',
  appId: 'Enter your Firebase App ID here',
  measurementId: 'Enter your Firebase Measurement ID here',
};

⚙️ Service Worker Registration

The Exzly library handles service worker registration and messaging.

Make sure to include the library in your HTML view:

<script src="{{ assetsUrl('/public/exzly.bundle.js') }}"></script>
const { serviceWorkerManager } = Exzly;

if (serviceWorkerManager.isSupported()) {
  serviceWorkerManager.isRegistered().then(async (isRegistered) => {
    if (isRegistered && Notification.permission === 'default') {
      serviceWorkerManager.subscribeWebPush().then(
        (subscription) => {
          console.log({ subscription });
        },
        (error) => {
          console.log({ error });
        },
      );
    }

    if (!isRegistered) {
      await serviceWorkerManager.register();
    }
  });

  serviceWorkerManager.onMessage((message) => {
    console.log({ message });
  });
}

📬 Push Message Format

Push messages are expected to be structured like the following JSON. These are parsed from the service-worker.ts file using:

const push = event.data.json() as PushEventDataJSON;

Web Push:

{
  "data": {
    "uid": "...",
    "url": "https://www.example.com",
    "type": "notification",
    "ecmMessageId": "..."
  },
  "notification": {
    "title": "Notification Title",
    "body": "...",
    "image": "..."
  },
  "ecmMessageId": "..."
}

Firebase Push:

{
  "data": {
    "type": "notification",
    "url": "https://www.example.com",
    "uid": "...",
    "fcmMessageId": "..."
  },
  "notification": {
    "title": "Notification Title",
    "body": "...",
    "image": "..."
  },
  "fcmMessageId": "..."
}

📥 Push Message Payload Structure

When a message is received through the serviceWorkerManager.onMessage(...), it will have the following structure depending on the source:

✅ Web Push Format

{
  "messageType": "push-received",
  "isExzlyMessaging": true,
  "isFirebaseMessaging": false,
  "notification": {
    "title": "Notification Title",
    "body": "This is a sample push notification message.",
    "image": "...",
    "data": {
      "uid": "...",
      "url": "https://www.example.com",
      "type": "notification",
      "ecmMessageId": "..."
    }
  }
}
  • isExzlyMessaging: true: Indicates the push was sent using Web Push via your own backend
  • ecmMessageId: A unique ID generated for tracking Exzly push messages

✅ Firebase Push Format

{
  "messageType": "push-received",
  "isExzlyMessaging": false,
  "isFirebaseMessaging": true,
  "notification": {
    "title": "Notification Title",
    "body": "This is a sample push notification message.",
    "image": "...",
    "data": {
      "type": "notification",
      "url": "https://www.example.com",
      "uid": "...",
      "fcmMessageId": "..."
    }
  }
}
  • isFirebaseMessaging: true: Indicates the push was received through Firebase Cloud Messaging
  • fcmMessageId: A unique Firebase-generated message ID

🧠 Push Message Handling

The service worker listens to push events and processes them as follows:

  • If the message has a valid JSON body with a type notification, it will:

    • Display a system notification, or
    • Post the message back to open browser clients
    • Send feedback logs (received, clicked, closed) to the backend via web-push-feedback endpoint

🎯 Caching Strategy (Workbox)

Caching is only enabled in production mode. The following asset types are cached using CacheFirst strategy:

Type Description
Manifest Web App manifest
Style CSS stylesheets
Script JavaScript files
Source Map .map files for debugging
Font Font files
Image Static images

Each cache is valid for 24 hours.

✅ Summary

The service worker implementation in Exzly provides:

  • 🔔 Reliable push notification delivery
  • 💬 Real-time feedback to server
  • 📦 Asset caching for improved performance
  • 🔄 Seamless support for both Web Push and Firebase

For any integration issues or suggestions, feel free to open a discussion!

⚠️ **GitHub.com Fallback** ⚠️