CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-register-service-worker

Script for registering service worker with hooks for common events.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Register Service Worker

Register Service Worker is a simplified service worker registration system for web applications with comprehensive lifecycle hooks and event handling. It provides an easy-to-use API for registering service workers with configurable registration options, automatic localhost detection for development environments, and built-in error handling for offline scenarios.

Package Information

  • Package Name: register-service-worker
  • Package Type: npm
  • Language: JavaScript (with TypeScript definitions)
  • Installation: npm install register-service-worker

Core Imports

import { register, unregister } from "register-service-worker";

For CommonJS:

const { register, unregister } = require("register-service-worker");

Basic Usage

import { register } from "register-service-worker";

register("/service-worker.js", {
  registrationOptions: { scope: "./" },
  ready(registration) {
    console.log("Service worker is active.");
  },
  registered(registration) {
    console.log("Service worker has been registered.");
  },
  cached(registration) {
    console.log("Content has been cached for offline use.");
  },
  updatefound(registration) {
    console.log("New content is downloading.");
  },
  updated(registration) {
    console.log("New content is available; please refresh.");
  },
  offline() {
    console.log("No internet connection found. App is running in offline mode.");
  },
  error(error) {
    console.error("Error during service worker registration:", error);
  },
});

Architecture

Register Service Worker is built around several key components:

  • Automatic Environment Detection: Detects localhost vs production environments and applies different registration strategies
  • Lifecycle Hook System: Comprehensive event handling for all service worker states and transitions
  • Error Handling: Built-in offline detection and graceful error handling with appropriate hook triggering
  • Validation System: Service worker file validation on localhost (404 and content-type checks)
  • Promise-based Loading: Window load detection with Promise fallback for older environments

Capabilities

Service Worker Registration

Registers a service worker with comprehensive lifecycle hooks and intelligent environment handling.

/**
 * Registers a service worker with lifecycle hooks and handles various registration scenarios
 * @param swUrl - URL to the service worker file
 * @param hooks - Configuration object with lifecycle hooks and registration options
 */
function register(swUrl: string, hooks?: Hooks): void;

Usage Example:

import { register } from "register-service-worker";

register("/sw.js", {
  registrationOptions: { 
    scope: "./",
    updateViaCache: "none"
  },
  ready(registration) {
    // Service worker is ready and active
    console.log("SW ready:", registration.scope);
  },
  registered(registration) {
    // Service worker has been registered
    console.log("SW registered");
  },
  cached(registration) {
    // Content has been cached for offline use
    console.log("Content cached");
  },
  updatefound(registration) {
    // New service worker is downloading
    console.log("Update found");
  },
  updated(registration) {
    // New content is available
    console.log("New content available");
    // Prompt user to refresh
  },
  offline() {
    // App is running in offline mode
    console.log("App is offline");
  },
  error(error) {
    // Error during registration or validation
    console.error("SW error:", error);
  }
});

Service Worker Unregistration

Unregisters any active service worker registration.

/**
 * Unregisters any active service worker registration
 * Note: The current implementation (v1.7.2) has a bug where error handling 
 * references an undefined 'emit' variable. Errors during unregistration 
 * will cause a ReferenceError.
 */
function unregister(): void;

Usage Example:

import { unregister } from "register-service-worker";

// Unregister service worker (useful for development or user preference)
unregister();

Known Issues:

  • The current implementation contains a bug where the error handler references an undefined emit variable
  • If unregistration fails, a ReferenceError will be thrown instead of graceful error handling
  • This affects version 1.7.2 of the package

Types

Hooks Configuration

Configuration object containing lifecycle hooks and registration options for service worker management.

interface Hooks {
  /** Options passed to navigator.serviceWorker.register() */
  registrationOptions?: RegistrationOptions;
  /** Called when service worker is ready and active */
  ready?: (registration: ServiceWorkerRegistration) => void;
  /** Called when service worker has been registered */
  registered?: (registration: ServiceWorkerRegistration) => void;
  /** Called when content has been cached for offline use */
  cached?: (registration: ServiceWorkerRegistration) => void;
  /** Called when new content is available and service worker updated */
  updated?: (registration: ServiceWorkerRegistration) => void;
  /** Called when new service worker is downloading */
  updatefound?: (registration: ServiceWorkerRegistration) => void;
  /** Called when app goes offline */
  offline?: () => void;
  /** Called when errors occur during registration or validation */
  error?: (error: Error) => void;
}

RegistrationOptions Type

Options object passed to the native navigator.serviceWorker.register() method.

interface RegistrationOptions {
  /** String defining the service worker's registration scope */
  scope?: string;
  /** Controls caching behavior during updates */
  updateViaCache?: "imports" | "all" | "none";
}

The registrationOptions property supports standard ServiceWorkerRegistration options:

  • scope: String defining the service worker's registration scope
  • updateViaCache: Controls caching behavior during updates ("imports", "all", "none")

Error Handling

The library provides comprehensive error handling for common service worker registration scenarios:

Validation Errors (Localhost Only)

On localhost, the library validates the service worker file:

  • 404 Error: Service worker file not found
  • Content-Type Error: Service worker file has incorrect MIME type (expected JavaScript)
register("/sw.js", {
  error(error) {
    if (error.message.includes("Service worker not found")) {
      // Handle 404 - service worker file missing
    } else if (error.message.includes("Expected")) {
      // Handle content-type mismatch
    }
  }
});

Network Errors

Network-related errors are automatically detected and trigger appropriate hooks:

register("/sw.js", {
  offline() {
    // Called when navigator.onLine is false during an error
    console.log("Device is offline");
  },
  error(error) {
    // Called for all errors, including network errors
    console.error("Registration failed:", error);
  }
});

Registration Failures

Standard service worker registration failures are handled gracefully:

register("/invalid-sw.js", {
  error(error) {
    // Handles registration rejections, invalid service worker files, etc.
    console.error("Could not register service worker:", error);
  }
});

Browser Compatibility

  • Required: Modern browsers with service worker support
  • Environment: Browser environment only (requires window, navigator.serviceWorker)
  • Graceful Degradation: Does nothing in environments without service worker support
  • Promise Support: Built-in fallback for environments without Promise support
  • ES Modules: Designed for use with modern bundlers that handle ES module syntax

Environment Detection

The library performs automatic environment detection:

// Localhost detection (lines 8-16 in source)
const isLocalhost = () => Boolean(
  window.location.hostname === 'localhost' ||
  window.location.hostname === '[::1]' ||
  window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
);

// Service worker support check
if ('serviceWorker' in navigator) {
  // Registration logic
}

Promise Compatibility

The library includes a fallback for environments without Promise support:

// Promise fallback (lines 25-29 in source)
if (typeof Promise !== 'undefined') {
  waitWindowLoad = new Promise(resolve => window.addEventListener('load', resolve));
} else {
  waitWindowLoad = { then: (cb) => window.addEventListener('load', cb) };
}

The library automatically detects service worker support and gracefully handles unsupported environments without throwing errors.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/register-service-worker@1.7.x
Publish Source
CLI
Badge
tessl/npm-register-service-worker badge