You are viewing documentation for an older version.
JavaScript SDK Service Worker
4 minute read
RudderStack’s JavaScript SDK provides a service worker that you can use in browser extensions and serverless runtimes. It exposes the same interface and 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 --saveThen, 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');This NPM module is meant to be used only for service worker usage. To integrate RudderStack with your Node.js apps, use the Node.js SDK instead.
Usage in Chrome extensions
You can use the JavaScript SDK in Chrome extensions with the manifest v3 - both as a content script (via the JavaScript SDK package) or as background script (via service worker package).
For more information on usage in Chrome extensions, see the JavaScript SDK GitHub repository.
Background script
You can use the RudderStack service worker npm package as a background script. To do so, place it in your Chrome extension resources by following either of these approaches:
- Copy the file from the node modules and place it as a part of the resources.
- Use a JS bundler and bundle it as a part of your service worker script.
You need to enable relevant permissions in the manifest file according to the required capabilities and allowed connections.
Also, setting the background script
typeas amoduleis recommended, as it allows to import the script as ESM.
"permissions": ["storage", "tabs"],
"host_permissions": [
"https://*.dataplane.rudderstack.com/*",
"https://*.rudderlabs.com/*",
"*://*/*"
],
"externally_connectable": {
"matches": [
"https://*.dataplane.rudderstack.com/*",
"https://*.rudderlabs.com/*"
]
},
"background": {
"service_worker": "service-worker.js",
"type": "module"
},Then, follow the Node.js SDK documentation for further usage.
You can also react to events available in the background scripts using the Chrome API.
The following example tracks any URL changes:
// If file is copied from node_modules/@rudderstack/analytics-js-service-worker/npm/esm/index.js in extension resources folder
import { Analytics } from "./rudderAnalytics.js";
// If the package is imported directly as umd and then bundled in the background script
import { Analytics } from "@rudderstack/analytics-js-service-worker/umd/index.js";
// If the package is imported directly as es-module and then bundled in the background script
import { Analytics } from "@rudderstack/analytics-js-service-worker";const rudderClient = new Analytics("<WRITE_KEY>","<DATA_PLANE_URL>/v1/batch");
chrome.tabs.onUpdated.addListener((tabId, tab) => {
if (tab.url) {
rudderClient.track({
userId: "123456",
event: "Event Name",
properties: {
data: { url: tab.url },
}
});
}
});Content script
To use the RudderStack Analytics JavaScript SDK as a content script, place it in your Chrome extension resources by following either of these approaches:
- Download the file and place it as a part of the resources.
- Use a JS bundler and bundle it as part of your content script.
You need to enable relevant permissions in the manifest file according to the required capabilities and allowed connections.
"permissions": ["storage", "tabs"],
"host_permissions": [
"https://*.dataplane.rudderstack.com/*",
"https://*.rudderlabs.com/*",
"*://*/*"
],
"externally_connectable": {
"matches": [
"https://*.dataplane.rudderstack.com/*",
"https://*.rudderlabs.com/*"
]
}Then, follow the SDK documentation for further usage.
You can also react to events available in both the content and background scripts by leveraging the Chrome API.
The following sample scripts help you track any URL changes:
# prepend the JS SDK file here
rudderanalytics.load("<WRITE_KEY>", "<DATA_PLANE_URL>");
chrome.runtime.onMessage.addListener((obj, sender, response) => {
const { type, value } = obj;
if (type === "trackURL") {
rudderanalytics.track("URL change", { url: value });
}
});chrome.tabs.onUpdated.addListener((tabId, tab) => {
if (tab.url) {
chrome.tabs.sendMessage(tabId, {
type: "trackURL",
value: {
url: tab.url
},
});
}
});Usage in serverless runtimes
You can use the JavaScript 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.