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:
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'))
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)
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),
});
});
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
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" }
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" }]
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"
And yet: no network request.
The decisive experiment was timing. Calling gtag('event', …) by hand:
-
immediately after load → hit sent,
en=probe&epn.seconds=7on the wire; - four seconds later → nothing;
-
with consent defaulted to
grantedup 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
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)
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
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 });
};
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}`);
}
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}`);
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
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
-
Read the wire, not the dashboard.
performance.getEntriesByType('resource').filter(n => n.includes('/collect')). A0in a report and a missing request are different bugs. -
Confirm the event that carries your parameter actually fires. Push to
dataLayerand check it appears. If it does not, nothing downstream matters. -
Check the shape of your parameters. GA4 metrics are numeric.
duration_bucket: "<1s"is a dimension; it will never fillseconds. -
Check your assets' cache headers.
curl -I https://yoursite/assets/app.js | grep -i cache. If you seeimmutablewith a longmax-ageon a file you intend to change, every fix you ship is optional for returning visitors. -
Do not assume consent mode is the culprit. I did, and it cost a day: granting
analytics_storageup front changed nothing. -
Watch
revokeObjectURL. Unrelated to analytics, but the same debugging session: revoking a blob URL immediately aftera.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:
40 seconds, no upload: musepdf.app · MP4 · source


Top comments (0)