Skip to content

Should You Build Your Own Chrome Extension Analytics?

7 min readModerok team

Build your own Chrome extension analytics, or buy it? The MV3 service worker, identity, retry and CORS problems a DIY collector has to solve first.

You can build your own Chrome extension analytics, and the server is the easy half: a POST endpoint and one table will take events all day. The cost sits on the client. A Manifest V3 service worker is terminated on conditions you do not control, loses every global variable when it goes, and will not reliably dispatch events to a listener registered inside a callback. Build it yourself when the data has to live in your own database or join your own accounts. Buy it when the list below is work you would rather not own.

TL;DR: The hard part of a DIY extension collector is not ingestion, it is surviving the service worker. Chrome's lifecycle docs warn that "Any global variables you set will be lost if the service worker shuts down," so an in-memory event array is the wrong data structure. You also have to invent the user id, define what a day means, separate retryable from fatal status codes, register lifecycle listeners at the top level, and settle CORS.

What a DIY collector has to handle

Every row below is forced by the platform.

ProblemWhat the platform documentsSource
An in-memory queue cannot survive"Any global variables you set will be lost if the service worker shuts down."Service worker lifecycle
A flush can be cut off mid-requestTermination "After 30 seconds of inactivity", when a request "takes longer than 5 minutes to process", and "When a fetch() response takes more than 30 seconds to arrive."Service worker lifecycle
Listeners buried in a callbackHandlers "need to be declared in the global scope" and "at the top level of the script", so "they are registered synchronously on initial script execution".Handle events
No: Identifier and no session existThe id "can be an arbitrary string, but should be unique to the client", and "there is no clear notion of a user session" to lean on.Use Google Analytics
Your POST is cross-originChrome's networking guide describes a request to another origin as treated as cross-origin unless the extension has host permissions.Network requests

The service worker shuts down in the middle of your flush

The version everyone writes first is an array and a timer:

let events = [];
setInterval(() => {
  fetch(MY_ENDPOINT, { method: "POST", body: JSON.stringify(events) });
  events = [];
}, 60_000);

Both halves are wrong in MV3. events is a global, and Chrome's lifecycle page is blunt about those: they "will be lost if the service worker shuts down", with the advice to "save values to storage" instead. The timer is the second problem: a 60 second interval is a poor fit for a worker the same page says is terminated "After 30 seconds of inactivity".

What works is a queue in chrome.storage.local, whose documented QUOTA_BYTES is 10,485,760 bytes unless the extension holds unlimitedStorage, written back after every accepted batch so a termination costs at most the batch in flight. Cap it, or an offline user returns with a backlog you POST in one request. Debounce the writes, because persisting on every track() call turns a counter increment into a storage write.

Then classify failures, the part that gets skipped. A 5xx is worth retrying, and so is a 429: the events are valid and the server is only declining them for now. A 400 is not, and retrying it forever is how you build a client that hammers your own endpoint. Honour Retry-After when it is sent, back off when it is not, and aim for bounded loss rather than none.

You are the one who has to invent the user id

Extensions have no login and no cookie. Chrome's GA4 integration guide puts the job on you: the client id "can be an arbitrary string, but should be unique to the client", and "should stay the same, as long as the extension is installed on a user's browser". In practice that is crypto.randomUUID() once, stored, reused. The trap is the storage it sits in: clear it, or hand the user a reset profile, and your extension mints a fresh id while your dashboard reports a new user who is not new. Mirroring the identifier into chrome.storage.sync can recover it, and the storage quotas explain why you mirror the id and not the queue: QUOTA_BYTES 102,400 total, QUOTA_BYTES_PER_ITEM 8,192, and MAX_WRITE_OPERATIONS_PER_MINUTE 120.

Defining what counts as active today is the second decision, and the same guide is explicit: "In Chrome extensions, unlike in normal websites, there is no clear notion of a user session. Hence, you must define what a user session means in your extension." The simplest definition is one ping per UTC day per user, and the ordering matters: advance the stored date only once the server has accepted the ping. Advance it at enqueue time instead, and a batch rejected at a usage cap silently marks the day as counted, so that user-day never reaches your actives. We worked through the definitions and the SQL in how to measure daily, weekly, and monthly active users.

Lifecycle events are not replayed

chrome.runtime.onInstalled is, per the runtime reference, "Fired when the extension is first installed, when the extension is updated to a new version, and when Chrome is updated to a new version." That third trigger is the one that inflates an install count, so branch on details.reason, documented there as install, update, chrome_update or shared_module_update. Nothing replays the events that fired before your handler existed, which is why Chrome's events guidance on where to register matters here:

// Not advised: registration happens inside a callback, so a freshly
// started worker can be sent the event before this line ever runs.
chrome.storage.local.get("analyticsOptIn").then(({ analyticsOptIn }) => {
  if (analyticsOptIn) chrome.runtime.onInstalled.addListener(recordLifecycle);
});

// Better: register at the top level, read the flag inside the handler.
chrome.runtime.onInstalled.addListener(async (details) => {
  const { analyticsOptIn } = await chrome.storage.local.get("analyticsOptIn");
  if (analyticsOptIn) recordLifecycle(details);
});

Uninstalls are their own small project. Per the runtime reference, setUninstallURL takes a URL that "must have an http: or https: scheme" with a "Maximum 1023 characters", so the identifier has to fit in a query string you build and refresh yourself. The hit arrives as a browser navigation after the extension is gone, so recording it is your endpoint's job, and it will not arrive for every removal: Moderok's own docs note the mechanism only fires on user-initiated removes.

CORS decides whether you need host_permissions

Chrome's networking guide treats a POST to another origin as cross-origin unless the extension has host permissions for that host. That leaves two routes: declare host_permissions for your endpoint, or have the endpoint return CORS headers itself.

Take the second route and the body's Content-Type decides whether you also implement OPTIONS. MDN's list of media types that keep a request simple is short: application/x-www-form-urlencoded, multipart/form-data and text/plain. application/json is not on it, so the browser preflights. The same JSON body sent as text/plain;charset=UTF-8 skips that, at the cost of a server parsing a body whose declared type is a lie.

Errors need a rate limit before they need a dashboard

If the collector is also your error reporter, put a dedupe window and a per-minute cap in front of the queue, or a crash loop in a worker Chrome keeps reviving sends the same stack over and over on the user's bandwidth. The handler-per-realm setup is in Chrome extension error tracking in production.

When building your own Chrome extension analytics is the right call

Sometimes it genuinely is:

  • The data cannot leave your infrastructure. A requirement that events land only in your own database settles it before features do.
  • You need to join analytics to your own accounts. If the question is whether licence holders use a feature more than trial users, the join lives in your database anyway.
  • You already run the pipeline. If the queue, schema and dashboards exist for your web app, one more event source is small, and at a high enough event rate your own table beats any per-event tier.

What buying gets you instead

That list is the surface area a vendor absorbs. Moderok's SDK is 5.7 kB gzipped, with zero runtime dependencies and no DOM globals in its source. __install, __update, __first_open, __daily_ping and __error are sent without you calling track(), the queue is capped and debounced with retryable failures retried with backoff, and events above 8 KiB are skipped. You can see what the reports look like first.

Either way, price your own build honestly, queue work included. If buying wins, setup is three parts, install @moderok/sdk, add the storage permission and call Moderok.init(), each of them covered in the getting started guide.