javascript 57 lines · 10 steps

Batching analytics events in the browser

An event buffer that batches tracking calls and reliably flushes them on size, time, or page exit.

Explained by highlit
1const MAX_BATCH_SIZE = 20;
2const FLUSH_INTERVAL = 5000;
3const ENDPOINT = '/api/analytics';
4 
5class AnalyticsBuffer {
6 constructor() {
7 this.queue = [];
8 this.timer = null;
9 this.handleUnload = this.flush.bind(this, true);
10 window.addEventListener('visibilitychange', () => {
11 if (document.visibilityState === 'hidden') this.flush(true);
12 });
13 window.addEventListener('pagehide', this.handleUnload);
14 }
15 
16 track(name, props = {}) {
17 this.queue.push({
18 name,
19 props,
20 ts: Date.now(),
21 url: location.pathname,
22 });
23 
24 if (this.queue.length >= MAX_BATCH_SIZE) {
25 this.flush();
26 } else if (!this.timer) {
27 this.timer = setTimeout(() => this.flush(), FLUSH_INTERVAL);
28 }
29 }
30 
31 flush(isUnloading = false) {
32 if (this.timer) {
33 clearTimeout(this.timer);
34 this.timer = null;
35 }
36 if (this.queue.length === 0) return;
37 
38 const events = this.queue.splice(0, this.queue.length);
39 const payload = JSON.stringify({ events, sentAt: Date.now() });
40 
41 if (navigator.sendBeacon) {
42 const blob = new Blob([payload], { type: 'application/json' });
43 const ok = navigator.sendBeacon(ENDPOINT, blob);
44 if (!ok) this.queue.unshift(...events);
45 return;
46 }
47 
48 fetch(ENDPOINT, {
49 method: 'POST',
50 body: payload,
51 headers: { 'Content-Type': 'application/json' },
52 keepalive: isUnloading,
53 }).catch(() => this.queue.unshift(...events));
54 }
55}
56 
57export const analytics = new AnalyticsBuffer();
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Batching many small events into one request cuts network overhead and server load.
  2. 2Page-exit events like visibilitychange and pagehide are the last chance to flush pending data.
  3. 3sendBeacon and keepalive fetch survive navigation where a normal request would be cancelled.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Batching analytics events in the browser — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code