Now.js Framework Documentation

Now.js Framework Documentation

ServiceWorkerManager

EN 15 Dec 2025 08:19

ServiceWorkerManager

Overview

ServiceWorkerManager is the Service Worker management system in Now.js Framework. It supports caching, offline support, and push notifications.

When to use:

  • Need offline support
  • Need to cache static assets
  • Need push notifications
  • Need background sync

Why use it:

  • ✅ Automatic caching
  • ✅ Multiple caching strategies
  • ✅ Push notification support
  • ✅ Update management
  • ✅ Precache configuration

Basic Usage

Initialization

await ServiceWorkerManager.init({
  enabled: true,
  serviceWorkerPath: '/service-worker.js',
  cacheName: 'my-app-cache-v1',
  debug: true
});

With Push Notifications

await ServiceWorkerManager.init({
  enabled: true,
  push: {
    enabled: true,
    publicKey: 'YOUR_VAPID_PUBLIC_KEY'
  }
});

Configuration

ServiceWorkerManager.init({
  // Enable/disable
  enabled: true,

  // Service worker file path
  serviceWorkerPath: '/service-worker.js',

  // Scope
  scope: '/',

  // Version for cache busting
  version: '1.0.0',

  // Cache name
  cacheName: 'now-js-cache',

  // Debug logging
  debug: false,

  // Update check interval (ms)
  updateInterval: 24 * 60 * 60 * 1000,  // 24 hours

  // URLs to precache
  precache: [
    '/index.html',
    '/css/styles.css',
    '/js/app.js'
  ],

  // Caching strategies by path
  strategies: {
    '/api/': 'network-first',
    '/images/': 'cache-first',
    '/static/': 'cache-only'
  },

  // Push notification config
  push: {
    enabled: false,
    publicKey: null
  }
});

Caching Strategies

Strategy Description
cache-first Fetch from cache first, fallback to network
network-first Fetch from network first, fallback to cache
stale-while-revalidate Use cache but update in background
cache-only Fetch from cache only
network-only Fetch from network only

API Reference

ServiceWorkerManager.init(options)

Initialize service worker

Returns: Promise<ServiceWorkerManager>

ServiceWorkerManager.isSupported()

Check browser support

Returns: boolean

if (ServiceWorkerManager.isSupported()) {
  await ServiceWorkerManager.init({ enabled: true });
}

ServiceWorkerManager.cacheUrls(urls)

Cache specified URLs

Parameter Type Description
urls array Array of URLs

Returns: Promise<boolean>

await ServiceWorkerManager.cacheUrls([
  '/offline.html',
  '/images/logo.png'
]);

ServiceWorkerManager.clearCache()

Clear all cache

Returns: Promise<boolean>

await ServiceWorkerManager.clearCache();

ServiceWorkerManager.update()

Force update service worker

Returns: Promise<boolean>

await ServiceWorkerManager.update();

ServiceWorkerManager.skipWaiting()

Force activate waiting worker

Returns: Promise<boolean>

await ServiceWorkerManager.skipWaiting();

ServiceWorkerManager.isOfflineReady()

Check offline readiness

Returns: boolean

Push Notifications

Subscribe

const subscription = await ServiceWorkerManager.subscribePush();
// Send subscription to server
await fetch('/api/push/subscribe', {
  method: 'POST',
  body: JSON.stringify(subscription)
});

Unsubscribe

await ServiceWorkerManager.unsubscribePush();

Check Status

if (ServiceWorkerManager.isPushEnabled()) {
  console.log('Push enabled');
}

Events

// Offline ready
EventManager.on('sw:offline-ready', () => {
  console.log('App ready for offline');
});

// Update available
EventManager.on('sw:update-available', () => {
  if (confirm('Update available. Reload?')) {
    window.location.reload();
  }
});

// Cache updated
EventManager.on('sw:cache-updated', () => {
  console.log('Cache refreshed');
});

Real-World Examples

Progressive Web App

// app.js
if ('serviceWorker' in navigator) {
  await ServiceWorkerManager.init({
    enabled: true,
    cacheName: 'my-pwa-v1',
    precache: [
      '/',
      '/manifest.json',
      '/css/app.css',
      '/js/app.js',
      '/images/icons/icon-192.png'
    ],
    strategies: {
      '/api/': 'network-first',
      '/images/': 'cache-first'
    }
  });
}

With Push Notifications

await ServiceWorkerManager.init({
  enabled: true,
  push: {
    enabled: true,
    publicKey: process.env.VAPID_PUBLIC_KEY
  }
});

// Subscribe button
document.getElementById('notify-btn').onclick = async () => {
  const subscription = await ServiceWorkerManager.subscribePush();

  await fetch('/api/push/register', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(subscription)
  });

  NotificationManager.success('Notifications enabled!');
};

Update Prompt

EventManager.on('sw:update-available', () => {
  const toast = NotificationManager.show({
    message: 'New version available',
    type: 'info',
    duration: 0,  // Persistent
    actions: [
      {
        label: 'Update',
        callback: () => {
          ServiceWorkerManager.skipWaiting();
          window.location.reload();
        }
      }
    ]
  });
});

Service Worker File

Create the service-worker.js file:

// service-worker.js
const CACHE_NAME = 'my-app-v1';

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => {
      return cache.addAll([
        '/',
        '/index.html',
        '/css/styles.css',
        '/js/app.js'
      ]);
    })
  );
});

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request).then((response) => {
      return response || fetch(event.request);
    })
  );
});

Common Pitfalls

⚠️ 1. HTTPS Required

// ❌ Doesn't work on HTTP (except localhost)
// Service Workers require HTTPS

// ✅ Use HTTPS
https://example.com

⚠️ 2. Check Support First

// ❌ Not checking support
ServiceWorkerManager.init({ enabled: true });

// ✅ Check first
if (ServiceWorkerManager.isSupported()) {
  ServiceWorkerManager.init({ enabled: true });
}