DEV Community

wanjiang
wanjiang

Posted on

Our analytics read zero for a month. Three bugs were hiding in plain sight

We shipped three custom metrics to answer one question: how long does a user spend on each tool, and how much do they produce?

seconds. output_kb. A dimension called tool_slug. Two weeks later the GA4 report looked like this:

city event name events seconds output_kb
(not set) — 12 0 0
Rome — 8 0 0
Kuala Lumpur — 6 0 0
Total 59 0 0

59 events. Every custom metric zero. The obvious reading is "we configured something wrong", so I spent the first hour in the GA4 admin UI, re-checking custom definitions, looking for a typo in a parameter name.

The configuration was fine. What was broken was three layers deeper, and each layer looked healthy on its own.

Here is the pipeline, with the three places it broke:

Three-layer analytics pipeline: the event never fired, the queue stopped draining, and the fix never reached returning visitors

The only method that works: trust the wire

Dashboards lie by omission. A metric showing 0 means "no rows", which is indistinguishable from "no data" and from "no such event". So before touching any config, I asked the browser what it actually sent:

performance.getEntriesByType('resource')
  .map(r => r.name)
  .filter(n => n.includes('/collect'))
Enter fullscreen mode Exit fullscreen mode

That is every GA4 hit the page made — including sendBeacon and fetch requests that the DevTools Network panel shows but that a window.fetch monkey-patch will miss (gtag caches the native reference).

The result:

en=page_view          (no custom parameters)
(no en)               (consent/config ping)
Enter fullscreen mode Exit fullscreen mode

Two requests total. Not one of our custom events. Not tool_view, not file_selected, not process_start, not export_download. The dashboard was not empty because of a config mistake — it was empty because nothing was ever sent.

That reframed the whole problem. The question stopped being "why is the number zero" and became "where do the events die".

Break #1 — the event that never fired

seconds and output_kb were supposed to ride on an event called tool_finish, wired to a window CustomEvent that every export dispatches:

// analytics.ts — fires when any tool produces a file
window.addEventListener('musepdf:download', (event) => {
  track('tool_finish', {
    tool_slug: slug,
    seconds: Math.round((Date.now() - started) / 1000),
    output_kb: Math.round(event.detail.bytes / 1024),
  });
});
Enter fullscreen mode Exit fullscreen mode

tool_finish never appeared in the dataLayer. So I dispatched the event by hand:

window.dispatchEvent(new CustomEvent('musepdf:download', { detail: { bytes: 123456 } }))
// dataLayer: 21 -> 21
Enter fullscreen mode Exit fullscreen mode

Nothing. The listener was never attached — the wiring ran, but the browser's listener registry had no entry for that event type. So the single event carrying both metrics had never fired in production, and no amount of GA4 configuration could have produced a row.

Meanwhile, the events that did fire carried the wrong shape entirely:

process_start     { tool_slug }
process_success   { tool_slug, duration_bucket: "<1s" }
export_download   { tool_slug, output_size_bucket: "<10mb" }
Enter fullscreen mode Exit fullscreen mode

duration_bucket is a string. A GA4 custom metric is numeric. Even if those events had reached the network, "<1s" can never average to a number.

Lesson one: a registered custom metric is not a collected one. GA4 will happily accept a definition for a parameter that no event ever sends. The definition is not the problem; it just reports the absence faithfully.

Break #2 — the queue that stops draining

Fixing the listener was not enough, because the events were also not leaving the page. dataLayer contained all seven events, in both shapes, with Google's own gtm.uniqueEventId stamped on them:

{ event: "export_download", tool_slug: "merge", output_size_bucket: "<10mb", gtm.uniqueEventId: 25 }
["event", "export_download", { tool_slug: "merge", output_size_bucket: "<10mb" }]
Enter fullscreen mode Exit fullscreen mode

So track() worked, dataLayer worked, and window.dataLayer.push was still gtag.js's own hooked function — I checked:

String(window.dataLayer.push).slice(0, 40)
// "function(){var h;ao();if(Zn.H.SANDBOXED_JS_SEMAPHORE>0){h=[];for(var k=0;k<argum"
Enter fullscreen mode Exit fullscreen mode

And yet: no network request.

The decisive experiment was timing. Calling gtag('event', …) by hand:

  • immediately after load → hit sent, en=probe&epn.seconds=7 on the wire;
  • four seconds later → nothing;
  • with consent defaulted to granted up front → still nothing.

So gtag.js on this property drains whatever was queued while it initialised, and then stops reading the array. Every event pushed after that point — which is every real user action, since nobody merges a PDF in the first 500 ms — went into a queue nobody drains.

I could not find the upstream cause with confidence, and I stopped looking once I had a reproducible boundary, because there is a supported answer that does not depend on gtag's internals: send the hit yourself.

Break #3 — the fix that never shipped

Two bugs fixed, bundle deployed, and the metrics were still zero — because returning visitors were running last week's JavaScript.

GET /assets/analytics-v2.js
Cache-Control: public, max-age=31536000, immutable
Age: 182168
cf-cache-status: HIT
Enter fullscreen mode Exit fullscreen mode

Age: 182168 — the edge was serving a 50-hour-old copy of a file I had deployed twice since. Same URL, query string or not:

/assets/analytics-v2.js            8781 bytes  (old)
/assets/analytics-v2.js?x=1759...  9113 bytes  (new)
Enter fullscreen mode Exit fullscreen mode

The cause was in public/_headers:

/assets/analytics-v2.js
  Cache-Control: public, max-age=0, must-revalidate

/assets/*
  Cache-Control: public, max-age=31536000, immutable
Enter fullscreen mode Exit fullscreen mode

Cloudflare Pages applies every matching rule in order and the last value wins. The wildcard came second, so immutable was what shipped — for a file whose whole purpose is to be updated.

immutable means the browser will not even revalidate for a year. So every analytics fix I had ever shipped was invisible to anyone who had already visited. Add a contradictory must-revalidate and it does not save you: immutable wins.

The fix

Three changes, each addressing one layer, none of them clever:

1. Emit the event where the data is. tool_finish now fires from the export click handler, which already knows the blob size — not from an event listener that may or may not be attached.

const report = (bytes: number, filename: string) => {
  const seconds = Math.max(1, Math.round(performance.now() / 1000));
  const kb = Math.max(1, Math.round(bytes / 1024));

  track('export_download', { tool_slug: slug, seconds, output_kb: kb, /* … */ });
  if (taskFinished) return;          // one finish per page view
  taskFinished = true;
  track('tool_finish', { tool_slug: slug, seconds, output_kb: kb, output_type: type });
};
Enter fullscreen mode Exit fullscreen mode

2. Post the hit directly, in gtag's own encoding. Same endpoint gtag uses, same ep. / epn. convention, cookieless:

function ping(event: string, params: Record<string, unknown>): void {
  const q = new URLSearchParams({ v: '2', tid: measurementId, cid: sessionId(), sid: sessionId(), en: event });
  for (const [key, value] of Object.entries(params)) {
    if (value === null || value === undefined || value === '') continue;
    q.set(typeof value === 'number' ? `epn.${key}` : `ep.${key}`, String(value));
  }
  navigator.sendBeacon(`https://www.google-analytics.com/g/collect?${q}`);
}
Enter fullscreen mode Exit fullscreen mode

sessionId() lives in sessionStorage only — it dies with the tab, which is exactly what a cookieless ping should do.

3. Version the URL by content. A post-build script hashes the loader and rewrites the reference in every built page:

const hash = createHash('sha256').update(body).digest('hex').slice(0, 10);
html.replace(/\/assets\/(analytics-v\d+\.js)(?!\?)/g, `/assets/$1?v=${hash}`);
Enter fullscreen mode Exit fullscreen mode

A new build is a new cache key. And the specific _headers rule moved below /assets/* so future edits revalidate even if the hash is identical.

Verified end to end on production, on the wire:

en=tool_finish        ep.tool_slug=merge  epn.seconds=6  epn.output_kb=1  ep.output_type=pdf
en=export_download    ep.tool_slug=merge  epn.output_kb=1  epn.seconds=7
en=process_success    ep.tool_slug=merge  ep.duration_bucket=<1s
Enter fullscreen mode Exit fullscreen mode

Six custom events, all six on the wire, plus page_view — seven hits where there used to be one, with exact numbers where exact numbers belong.

A checklist you can run on your own site

  1. Read the wire, not the dashboard. performance.getEntriesByType('resource').filter(n => n.includes('/collect')). A 0 in a report and a missing request are different bugs.
  2. Confirm the event that carries your parameter actually fires. Push to dataLayer and check it appears. If it does not, nothing downstream matters.
  3. Check the shape of your parameters. GA4 metrics are numeric. duration_bucket: "<1s" is a dimension; it will never fill seconds.
  4. Check your assets' cache headers. curl -I https://yoursite/assets/app.js | grep -i cache. If you see immutable with a long max-age on a file you intend to change, every fix you ship is optional for returning visitors.
  5. Do not assume consent mode is the culprit. I did, and it cost a day: granting analytics_storage up front changed nothing.
  6. Watch revokeObjectURL. Unrelated to analytics, but the same debugging session: revoking a blob URL immediately after a.click() can cancel a large download with no error at all. Defer it.

What this cost, and what it bought

The expensive part was not the fix — it was the assumption that a familiar tool (gtag + dataLayer + a track() helper) was doing the obvious thing. Each layer had a plausible excuse, and the dashboard reported all three identically: 0.

The cheap part is now: one function that posts hits, and a build step that guarantees the code actually reaches the browser.

See it working — this is the product the metrics belong to, a client-side PDF toolkit where nothing is uploaded:

MusePDF demo: merge two PDFs, then retype a heading in the editor, all in the tab

40 seconds, no upload: musepdf.app · MP4 · source

Top comments (0)