Skip to content

Service Worker

What Nudgr needs

Nudgr requires a real service worker file that the browser can fetch from your own origin.

Examples:

  • /nudgr-sw.mjs
  • /push/nudgr-sw.mjs

The SDK then registers that file with:

ts
navigator.serviceWorker.register(swPath, {
  scope: swScope,
  type: "module",
});

Default setup

If you do not already have a service worker, copy:

text
node_modules/nudgr/dist/nudgr-sw.mjs

to a static URL on your site, such as:

text
/nudgr-sw.mjs

and initialize the SDK with:

ts
const nudgr = new Nudgr({
  apiKey: "nk_...",
  swPath: "/nudgr-sw.mjs",
  swScope: "/",
});

Existing service worker

If your app already has a service worker, keep that file and import Nudgr inside it instead of creating a second overlapping root worker.

Recommended shape:

ts
import "nudgr/sw";

Then point the SDK at your own worker URL:

ts
const nudgr = new Nudgr({
  apiKey: "nk_...",
  swPath: "/existing-worker.js",
  swScope: "/",
});

Dedicated scope

If you want to isolate Nudgr from another worker, use a dedicated path:

ts
const nudgr = new Nudgr({
  apiKey: "nk_...",
  swPath: "/push/nudgr-sw.mjs",
  swScope: "/push/",
});

Use this when:

  • another service worker already owns /
  • you only need Nudgr under one part of the site
  • you want to reduce PWA scope conflicts

What the Nudgr worker does

The worker handles:

  • push: displays the notification payload
  • notificationclick: opens the notification URL and reports the click
  • message: receives foreground push decisions from the visible page

Foreground behavior

If the app is visible, the page can decide whether a push should still become a system notification:

ts
const nudgr = new Nudgr({
  apiKey: "nk_...",
  foreground: {
    timeoutMs: 1200,
    async onPush(payload) {
      showToast(payload.title);
      return { showNotification: false };
    },
  },
});

Behavior:

  • visible page + showNotification: false => suppress system notification
  • visible page + timeout/error => show system notification
  • no visible page => show system notification

Nudgr documentation preview