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.
npm install register-service-workerimport { register, unregister } from "register-service-worker";For CommonJS:
const { register, unregister } = require("register-service-worker");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);
},
});Register Service Worker is built around several key components:
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);
}
});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:
emit variableReferenceError will be thrown instead of graceful error handlingConfiguration 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;
}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 scopeupdateViaCache: Controls caching behavior during updates ("imports", "all", "none")The library provides comprehensive error handling for common service worker registration scenarios:
On localhost, the library validates the service worker file:
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-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);
}
});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);
}
});window, navigator.serviceWorker)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
}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.