Event Tracking and Data Reporting

Learn common event tracking and reporting approaches, and use sendBeacon to send data reliably to your server.

🎯 Introduction

The previous article collected information about failures. This one answers a different question: what users do on the page. By the end, you will be able to:

  • Distinguish manual tracking from automatic tracking and choose an appropriate approach.
  • Implement basic click tracking and impression tracking.
  • Use navigator.sendBeacon for reliable reporting, even as a page closes.

🧱 Common Tracking Approaches

Event tracking adds recording code at the points you want to measure to collect user behavior, much like a supermarket measuring which shelves customers stop at and which products they pick up. The full flow is collection → reporting → analysis. This article covers the first two steps.

There are two main approaches: manual tracking is precise and flexible but requires code for each event; automatic tracking is easier to set up but lacks business context. Prefer manual tracking for core business metrics.

Manual tracking (code-based tracking) adds collection code at specific points, for example to count button clicks:

monitor.js
// Shared collection function; we will implement its reporting logic below
function track(event, data) {
    console.log('Event collected:', event, data);
}

document.querySelector('#buy-btn').addEventListener('click', () => {
    track('click', {
        button: 'buy',
        page: location.pathname,
    });
});

You control exactly which events and data to collect. The tradeoff is that each event requires code, and changing requirements means changing code and releasing again.

Automatic tracking (autocapture) uses an SDK to collect all clicks and page views automatically, then lets you select relevant elements in a dashboard afterward. It is convenient and supports retrospective analysis, but raw information such as "a div was clicked" provides less context for detailed analysis than manually defined events.

Real projects often combine them: manually track core actions such as ordering and payment, and use autocapture for broader behavior analysis.

🧱 Impression Tracking: Measuring Visibility

Impression tracking records whether a module has entered the viewport. Use IntersectionObserver to report once when the element becomes visible. The lazy-loading article in the Performance Optimization course covers this API in detail; here we will use it directly:

index.html
<!-- Banner whose impressions we want to track -->
<div class="banner" data-track="home-banner">Summer Sale</div>
exposure.js
const observer = new IntersectionObserver((entries) => {
    entries.forEach((entry) => {
        // isIntersecting is true when the element enters the viewport
        if (entry.isIntersecting) {
            track('exposure', {
                module: entry.target.dataset.track,
                page: location.pathname,
            });
            observer.unobserve(entry.target); // Count once, then stop observing
        }
    });
});

document.querySelectorAll('.banner').forEach((el) => {
    observer.observe(el);
});

Notice unobserve: without it, scrolling past the same banner repeatedly would count multiple impressions.


🧱 Reporting Methods

Prefer sendBeacon for event reporting. Data such as time on page is often sent only when the user leaves. During unloading, browsers can cancel unfinished ordinary asynchronous requests and lose the data. Three common approaches are:

Tracking pixels: create an Image, encode data in its URL parameters, and set src to trigger a GET request:

report-image.js
function report(data) {
    const img = new Image();
    // The server records the request and returns a blank 1x1 image
    img.src = '/collect?data=' + encodeURIComponent(JSON.stringify(data));
}

This is simple and works across origins, but supports only GET, is limited by URL length, and does not tell you whether reporting succeeded.

fetch: flexible and configurable, but unfinished requests can be canceled during unloading, making ordinary fetch unsuitable for reporting as users leave.

sendBeacon: a browser API designed to send data even during page unloading:

report-beacon.js
function report(data) {
    const blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
    navigator.sendBeacon('/collect', blob);
}

The browser takes over and queues delivery, allowing it to continue in the background even if the user immediately closes the page. Think of handing a parcel to a courier: delivery no longer depends on you staying there.

ComparisonTracking pixelfetchsendBeacon
Request methodGET onlyAnyPOST
When the page closesData may be lostLikely to be canceledBrowser continues sending
Payload sizeLimited by URL lengthLargerLimited (about 64 KB)
Use casesSimple counters, legacy sitesOrdinary API requestsEvent and log reporting

Continue using fetch for ordinary API requests whose responses you need to process.

A true return value from sendBeacon only means the data was queued successfully, not that the server received it. For data with strict reliability requirements, design server-side deduplication and recovery mechanisms to handle missing records.

🛠 Putting It Together: A Minimal Tracking Utility

monitor.js
// Common fields included in every record
const common = {
    page: location.pathname,
    time: Date.now(),
};

// Shared reporting: prefer sendBeacon, fall back to fetch in older environments
function report(data) {
    const body = JSON.stringify(data);
    if (navigator.sendBeacon) {
        navigator.sendBeacon('/collect', new Blob([body], { type: 'application/json' }));
    } else {
        fetch('/collect', { method: 'POST', body, keepalive: true });
    }
}

// Public collection function
function track(event, data = {}) {
    report({ event, ...common, ...data });
}

// Track clicks
document.querySelector('#buy-btn').addEventListener('click', () => {
    track('click', { button: 'buy' });
});

// Report time on page before leaving
const start = Date.now();
window.addEventListener('pagehide', () => {
    track('stay', { duration: Math.round((Date.now() - start) / 1000) });
});

Two details deserve attention: keepalive: true in the fallback lets the browser continue the request after unloading. We listen for pagehide rather than beforeunload because it is more reliable on mobile devices.


❓ Questions and Answers

Q1: Why does a tracking pixel endpoint return a 1x1 image?

The request only needs to deliver its parameters; nobody uses the response content. A tiny blank image lets the request complete without an image error while keeping the response small.

Q2: Why does reporting with fetch in beforeunload often lose data?

Once unloading starts, the browser can cancel unfinished asynchronous requests. Use sendBeacon or fetch with keepalive: true to let delivery continue.

Q3: Does sendBeacon have a payload size limit?

Yes, commonly around 64 KB. Individual tracking events are usually small enough. Batch or compress large logs before sending them.

Q4: Can autocapture completely replace manual tracking?

No. Autocapture records raw events such as an element click, without distinguishing business actions such as buying product A versus product B. Prefer manual tracking for core business metrics.

Q5: Does impression tracking count modules that users scroll past quickly?

Yes. Entering the viewport even briefly triggers it. To count only impressions lasting a minimum duration, delay reporting by a few hundred milliseconds in the callback and cancel if the element leaves in the meantime.


🧪 Exercises

Exercise 1: Add click tracking to the Buy Now button, including the button identifier and current page path:

function track(event, data) {
    console.log('Event collected:', event, data);
}

document.querySelector('#buy-btn').addEventListener('click', () => {
    // Write your code here: report a click event
});

Exercise 2: Replace ordinary fetch in this reporting function with sendBeacon to reduce data loss when the page closes. Include a fallback for older browsers:

function report(data) {
    // Write your code here: prefer sendBeacon, fall back to fetch with keepalive
    fetch('/collect', { method: 'POST', body: JSON.stringify(data) });
}

Afterward, consider why the sendBeacon branch uses a Blob with type application/json. What Content-Type would the server receive if you passed a string directly?


🎉 You now know how to track events and report data! Next, we will examine how to collect and report data about page speed.