Version:

JavaScript Service Worker SDK

Use the JavaScript service worker SDK in your browser extensions and serverless runtime.

RudderStack provides a service worker SDK that you can use in browser extensions and serverless runtimes. It exposes the same interface and applicable features as the RudderStack Node.js SDK.

Install the package

To install the package, run the following command:

npm install @rudderstack/analytics-js-service-worker --save

Then, run the following code snippet and use the exported object throughout your project:

import { Analytics } from '@rudderstack/analytics-js-service-worker';

const rudderClient = new Analytics('<WRITE_KEY>', '<DATA_PLANE_URL>/v1/batch');
warning

This NPM module is meant to be used only in non-browser environments. To integrate RudderStack with your Node.js apps, RudderStack recommends using the Node.js SDK instead.

Note that the APIs are the same in both the cases.

Usage in Chrome extensions

You can use the JavaScript SDK in Chrome extensions with the manifest v3 as:

For more information on usage in Chrome extensions, see the JavaScript SDK GitHub repository.

Usage in serverless runtimes

You can use the JavaScript service worker SDK in serverless runtimes like Cloudflare workers or Vercel Edge functions.

Cloudflare worker

To use the JavaScript SDK service worker in Cloudflare workers, start with the sample and integrate the SDK in the worker.js file:

import { Analytics } from '@rudderstack/analytics-js-service-worker';

const rudderClient = new Analytics(
  "<WRITE_KEY>",
  "<DATA_PLANE_URL>/v1/batch",
  {
    flushAt: 1
  }
);

Then, use the JavaScript SDK within the fetch methods with promisified flush:

const flush = () => new Promise((resolve) => rudderClient.flush(resolve));

rudderClient.track({
  userId: '123456',
  event: 'test cloudflare worker',
  properties: {
    data: {
      url: 'test cloudflare worker',
    },
  },
});

await flush();

For more information, see this sample implementation.

Vercel Edge

To use the JavaScript SDK service worker in Vercel Edge functions, start with the sample and integrate the SDK in the app/api/edge-function-sample/route.ts file:

import { Analytics } from '@rudderstack/analytics-js-service-worker';

const rudderClient = new Analytics(
  "<WRITE_KEY>",
  "<DATA_PLANE_URL>/v1/batch",
  {
    flushAt: 1
  }
);

Then, use the JavaScript SDK within the fetch methods as usual:

rudderClient.track({
  userId: '123456',
  event: 'test vercel edge worker',
  properties: {
    data: {
      url: 'test vercel edge worker',
    },
  }
});

For more information, see this sample implementation.



Questions? Contact us by email or on Slack