Every button click, page view, and JavaScript error is data. But capturing, enriching, and shipping that data reliably from a browser is surprisingly hard. The page might close mid-request. The user might go offline. A promise rejection might fire silently. This article breaks down how I would design a client-side analytics and error tracking SDK from scratch — the kind of thing Segment analytics.js, Sentry's Browser SDK, and PostHog's JS library all implement.
System DesignAnalyticsError TrackingSDKBrowser
What Are We Building?
A client-side SDK that two teams can drop into their app with a <script> tag or npm install, and immediately start seeing data flow to their backend. No complex setup. No required server infrastructure on their side. Think Sentry's Raven.captureException() or Segment's analytics.track() — but built from first principles.
Here is the mental model I carry: the SDK is a pipeline. Events enter at one end — either from the developer calling track(), or from automatic hooks that sniff browser events — and they exit at the other end as HTTP requests to an ingestion endpoint. The pipeline handles everything in between: enrichment, batching, compression, retry, and persistence.
Figure 1 — Five-stage analytics pipeline. Events flow left to right through capture, enrichment, and batching, then down through queue and dispatch. Each stage is a replaceable plugin.
The SDK also understands errors as a first-class event type. An error is not just an event with a different name — it carries a stack trace, source location, breadcrumb trail, and metadata about the browser state at the moment of failure. The error capture system hooks into browser internals: window.onerror, unhandledrejection, console.error interceptions, and fetch response monitors.
Tip
I scoped out session replay (recording DOM mutations and playback) for this article. That's a separate SDK with its own pipeline — rrweb's architecture deserves its own deep dive. I also scoped out server-side ingestion infrastructure. This is purely the client-side SDK design.
1 · Requirements (R)
Before writing a single line, I asked myself: what does a production-grade SDK absolutely need, and what can wait for v2? Here is the list that came out of that exercise.
Functional requirements
Custom event tracking:analytics.track('Order Completed', { revenue: 29.99 }). The most fundamental API. Name + properties, send to server.
Automatic page views: Detect URL changes and fire a page event. Must work with both MPA (full navigation) and SPA (pushState/popstate).
User identification:analytics.identify('user_123', { name: 'Alice', plan: 'pro' }). Link all subsequent events to this user.
Anonymous ID fallback: Before identify() is called, generate a UUID stored in localStorage so sessions can be correlated.
Error capture: Catch JS runtime errors, unhandled promise rejections, resource load failures, and uncaught exceptions in async code. Send them as error events.
HTTP error monitoring: Intercept fetch and XMLHttpRequest to capture failed network requests with status codes, URLs, and response bodies.
Breadcrumbs: Record a trail of user actions (navigation, clicks, console logs, XHR calls) leading up to an error. Attach to error events automatically.
Session management: Generate a session ID per tab. Track referrer, UTM parameters, and campaign data for the session.
Batching: Group events into batches before sending. Avoid one HTTP request per event — that destroys battery and fills the network queue.
Retry with backoff: If a request fails (network error, 429, 5xx), retry with exponential backoff. Give up after a maximum number of attempts.
Non-functional requirements
Zero-dependency core: The core pipeline must have zero npm dependencies. If you import it in a tree-shaking setup, you should get exactly what you use and nothing else.
Bundle size under 5 KB gzip: This includes the core pipeline, event schema, and default transport. Error capture and breadcrumbs are separate modules that add 2 KB each.
No main thread blocking: All encoding, batching, and persistence must happen in microtasks, idle callbacks, or web workers. Never a synchronous loop that stalls the UI thread.
99.9% delivery guarantee: Events must not be lost during page unload, network interruptions, or browser crashes. Use sendBeacon for unload, IndexedDB for offline persistence.
Privacy-first: Opt-out mechanism (localStorage flag). Automatic PII scrubbing for email-like patterns in event properties. Never send full URLs with query parameters unless explicitly configured.
Cross-browser compatibility: Support browsers back to the last two major versions. Feature-detect APIs like sendBeacon, IndexedDB, and requestIdleCallback before using them.
Tip
I deliberately left out A/B testing, feature flags, and personalization from the core SDK. Those are higher-level products that build on top of analytics, not part of the foundational telemetry layer. Segment and Sentry follow the same split — analytics.js does not do feature flags.
2 · Architecture (A)
The architecture follows a strict pipeline pattern. Each stage is a pure function that transforms the event and passes it to the next stage. This makes the system testable, extensible, and easy to reason about.
Pipeline stages
The pipeline has five stages, each represented by a plugin interface. I settled on this after iterating through a few designs. The key insight is that every stage must be replaceable and testable in isolation.
example.typescript
interface PipelinePlugin {
name: string;
// Transform an event before it reaches the next stage
process(event: RawEvent): RawEvent | Promise<RawEvent>;
// Called when a batch is ready to send
onFlush?: (batch: Batch) => void;
}
class Pipeline {
private plugins: PipelinePlugin[] = [];
use(plugin: PipelinePlugin): void {
this.plugins.push(plugin);
}
async process(event: RawEvent): Promise<ProcessedEvent> {
let current: RawEvent = { ...event };
for (const plugin of this.plugins) {
current = await plugin.process(current);
}
return current as ProcessedEvent;
}
}
The pipeline is a chain-of-responsibility pattern. Each plugin receives the event, transforms it, and returns it. A plugin can also decide to drop the event by returning null — this is how sampling works.
Plugin modules
The SDK ships with a set of built-in plugins that users can enable or disable:
Plugin
Purpose
Size
EnrichmentPlugin
Adds device, page, session, and UTM context
1.2 KB
ErrorCapturePlugin
Hooks into window.onerror, unhandledrejection, etc.
2.1 KB
BreadcrumbPlugin
Auto-records navigation, clicks, and XHR as breadcrumbs
0.8 KB
PerformancePlugin
Captures LCP, FID, CLS, and navigation timing via PerformanceObserver
1.5 KB
SamplingPlugin
Deterministic or rate-based event sampling
0.5 KB
Why not a monolithic class?
The first version I wrote had a single AnalyticsClient class with methods for everything. It worked, but it was a pain to test — I had to mock browser APIs, the fetch function, IndexedDB, and timers all at once. The plugin architecture lets me test each plugin independently with a simple { process(event) } interface. It also lets consumers write custom plugins — say, a GDPR consent plugin that redacts PII based on user preferences.
Key Insight
Sentry's SDK follows a similar pattern with their "integrations" system. Each integration hooks into a specific browser API and produces events. The breadcrumbs integration listens for clicks; the browser integration listens for onerror. This composability is what makes Sentry's SDK extensible across frameworks — React, Vue, Angular plugins are all just integrations.
Singleton vs factory
The SDK exposes a singleton analytics object initialized once. Multiple tabs get separate singletons (sessionStorage scopes them). But I also export a factory for testing and advanced use cases where you need multiple instances — think a dashboard that tracks user behavior inside an iframe.
example.typescript
// Singleton — most common usage
import { analytics } from '@acme/analytics';
analytics.init({ dsn: 'https://key@host/project' });
analytics.track('Page Viewed', { path: '/pricing' });
// Factory — for testing or iframes
import { createAnalytics } from '@acme/analytics';
const testAnalytics = createAnalytics({ dsn: 'https://key@host/project' });
testAnalytics.track('Test Event');
3 · Data Model (D)
The data model is the contract between the SDK and the server. Every event must have a minimum set of fields that the server understands. I designed the schema to be forward-compatible: add new fields without breaking old events.
Base event schema
example.typescript
interface BaseEvent {
/** UUID v4, generated client-side for dedup on the server */
id: string;
/** Event type discriminator */
type: 'track' | 'page' | 'identify' | 'error' | 'performance';
/** Human-readable event name, e.g. 'Order Completed' */
name: string;
/** ISO 8601 timestamp when the event was created */
timestamp: string;
/** Auto-generated session ID (resets per tab) */
sessionId: string;
/** User ID (null until identify() is called) */
userId?: string;
/** Anonymous device ID (persists in localStorage) */
anonymousId: string;
/** Arbitrary key-value payload */
properties: Record<string, unknown>;
/** Enrichment context — added by EnrichmentPlugin */
context: {
device: {
screen: string; // "1440x900"
userAgent: string;
language: string; // "en-US"
platform: string; // "MacIntel"
viewport: string; // "1440x900"
};
page: {
url: string;
referrer: string;
title: string;
encoding: string; // document.charset
};
utm?: {
source?: string;
medium?: string;
campaign?: string;
term?: string;
content?: string;
};
locale: string;
timezone: string;
};
/** SDK version for schema migration */
sdkVersion: string;
}
Error event schema
Error events extend the base event with error-specific fields. I purposely keep the error schema flat — nested objects make it hard to query in ClickHouse or BigQuery later.
example.typescript
interface ErrorEvent extends BaseEvent {
type: 'error';
error: {
message: string; // Human-readable, e.g. "Cannot read property 'x' of undefined"
stack: string; // Full stack trace
type: ErrorType; // 'js' | 'promise' | 'resource' | 'console' | 'http'
filename?: string; // Source file URL
lineno?: number; // Line number in source
colno?: number; // Column number
functionName?: string; // (v8 only) function where error originated
source?: string; // (resource errors) the URL that failed to load
statusCode?: number; // (HTTP errors) the status code
responseBody?: string; // (HTTP errors) truncated response
};
/** Breadcrumb trail — last 20 actions before the error */
breadcrumbs: Breadcrumb[];
/** Current route when error occurred */
route?: string;
}
interface Breadcrumb {
type: 'navigation' | 'click' | 'fetch' | 'console' | 'custom';
message: string;
timestamp: string;
data?: Record<string, unknown>;
level?: 'debug' | 'info' | 'warning' | 'error';
}
Batch protocol
Events are grouped into batches before sending. The batch itself is a JSON structure with metadata that helps the server acknowledge and deduplicate.
example.typescript
interface Batch {
/** Unique batch ID for server-side dedup */
batchId: string;
/** Project identifier from the DSN */
projectId: string;
/** Array of serialized events */
events: SerializedEvent[];
/** Batch size in bytes (for server-side limits) */
sizeBytes: number;
/** Client timestamp when batch was queued */
queuedAt: string;
/** Retry count (server uses for monitoring) */
retryCount: number;
}
interface SerializedEvent {
id: string;
type: string;
name: string;
timestamp: string;
payload: string; // JSON-encoded string
}
The batch protocol uses payload as a JSON string inside the batch JSON. This double-encoding is intentional: it means the server can parse the batch structure without parsing every event, and event schemas can evolve independently of the batch format. Sentry uses a similar approach with their { "event_id": "...", "message": "..." } envelope format.
Note
The double-encoding pays off when you need to add compression. You compress the payload fields individually, not the entire batch. This way the server can acknowledge receipt of the batch (parse the outer JSON) before it decompresses and processes individual events.
4 · Interface (I)
The public API is deliberately small. I have seen analytics SDKs with fifty methods — nobody remembers them. I prefer five methods that compose well over fifty that don't.
The error capture plugin exposes its own API on top of the base analytics instance:
example.typescript
interface ErrorCapture {
/** Manually capture an exception */
captureException(
error: Error,
context?: Record<string, unknown>,
): void;
/** Capture a message with severity level */
captureMessage(
message: string,
level?: 'info' | 'warning' | 'error',
): void;
/** Set the current user (available in error context) */
setUser(user: { id: string; email?: string } | null): void;
/** Add a breadcrumb to the current scope */
addBreadcrumb(breadcrumb: BreadcrumbInput): void;
/** Create a child scope for nested context */
withScope(callback: (scope: Scope) => void): void;
}
Usage flow
A typical integration looks like this. The developer initializes the SDK once at app startup, configures which plugins to enable, and then calls track() and captureException() as needed.
SDK installs error handlers, breadcrumb listeners, and PerformanceObserver. Generates anonymous ID and session ID.
track() / captureException()
Event enters the pipeline. Enrichment adds device, page, session context. Sampling decides if it's kept.
Batching — max 100 or 5s
Events accumulate in a batch buffer. First event starts a 5-second flush timer. At 100 events, flush immediately.
Queue — IndexedDB
Batch is persisted to IndexedDB before sending. This ensures no data loss if the page closes mid-request.
Dispatch — sendBeacon > fetch > pixel
sendBeacon for page unload. fetch with keepalive for normal sends. Image pixel as last resort.
Ack — remove from queue
Server responds 200 OK. Batch is removed from IndexedDB. If 429/5xx, retry with backoff.
5 · Browser Internals Deep Dive
This is the part that separates a toy SDK from a production one. The browser environment is hostile to telemetry — pages close, network drops, background tabs get throttled. Understanding how the browser actually works under the hood is what makes the SDK reliable.
sendBeacon — the unload savior
Here is a nightmare scenario: a user fills out a checkout form, clicks "Place Order," and the page navigates to the order confirmation. You wanted to track the "Order Completed" event. But fetch() inside a beforeunload or unload event may or may not complete — the browser is under no obligation to finish pending network requests during teardown.
navigator.sendBeacon() solves this. It queues the request and tells the browser "deliver this reliably, even during unload." The browser guarantees delivery — the request will be sent even if the page is already gone. The catch? It is a POST with no way to read the response. You fire and forget.
Behind the scenes, sendBeacon does not use the standard fetch path. It bypasses the fetch controller and queues directly into the browser's networking stack at a priority level that survives page teardown. The browser processes beacon requests in its own time, even after the tab is closed. This is why it can only handle Blob, FormData, or URLSearchParams — no streaming, no custom headers beyond a few built-in ones.
Warning
sendBeacon has a payload size limit of ~64 KB. If your batch exceeds this, the beacon is silently dropped. Always check the return value — sendBeacon returns false if the payload is too large. The fix is to split the batch or fall back to fetch() with the keepalive flag.
requestIdleCallback — not all events are urgent
Not every event needs to be sent immediately. A button click? Yes, flush soon. A scroll position update? That can wait. requestIdleCallback is the browser API that schedules work during idle periods — when the event loop has nothing else to do.
The SDK uses requestIdleCallback for non-critical work: serializing batches, writing to IndexedDB, and performing retry checks. These operations would otherwise compete with the UI thread for time. The callback receives a Deadline object with timeRemaining() — if the browser needs to render a frame, the callback is paused.
example.typescript
function scheduleIdle(task: () => void, timeout = 2000): void {
if (typeof requestIdleCallback !== 'undefined') {
requestIdleCallback(
(deadline) => {
// If we have time, run the task
if (deadline.timeRemaining() > 0) {
task();
}
},
{ timeout }, // Guarantee it runs within timeout
);
} else {
// Fallback for browsers without rIC
setTimeout(task, 1);
}
}
// Usage in the SDK — serialize batches during idle time
scheduleIdle(() => {
const serialized = batch.events.map(serializeEvent);
persistToIndexedDB(serialized);
});
The timeout parameter is critical. If the browser stays busy (say, an animation loop), requestIdleCallback might never fire. The timeout guarantees it runs — even if the browser is busy — after the specified millisecond. This prevents starvation.
window.onerror vs addEventListener('error')
There are two ways to catch runtime errors, and they are not equivalent. The difference matters when you are trying to build a reliable error SDK.
Property
window.onerror
addEventListener('error')
Stack trace
Full stack available via error argument (5th param in old browsers)
Same via event.error
Cross-origin scripts
Returns "Script error." unless CORS header is set + crossorigin attribute
Same limitation
Resource errors
❌ Does not catch failed image/script loads
✅ Catches resource load failures (event.target)
Multiple handlers
Only one handler (assignment, not add)
Multiple listeners
The practical answer: use both. Hook window.onerror for JS runtime errors, and addEventListener('error', ...) in capture mode (third argument { capture: true }) for resource load failures. The capture phase is important — without it, the event might be stopped by stopPropagation() in a framework component before your handler sees it.
Unhandled promise rejections are especially dangerous because they do not trigger window.onerror. They have their own event: unhandledrejection. Before this event existed (it was added in Chrome 49 / 2016), rejected promises were silently swallowed. Your app could fail silently for minutes, hours, or days before anyone noticed.
The event gives you the rejection reason (event.reason), which is typically an Error object but could be anything — a string, a number, an object. Always wrap it: event.reason instanceof Error ? event.reason : new Error(String(event.reason)). The event.promise property (the rejected promise) is useful for debugging but usually not included in the report.
One more trick: call event.preventDefault() in the handler. This prevents the browser's default console warning ("Unhandled Promise Rejection"). Your error SDK now owns that reporting, and the console stays clean for actual debug logs.
Figure 2 — Error capture flow. Six error sources funnel into a central handler that normalizes, deduplicates, and attaches breadcrumbs before passing to the analytics pipeline.
PerformanceObserver — automatic Web Vitals
The PerformanceObserver API lets you subscribe to performance entries without polling. I use it to capture LCP (Largest Contentful Paint), FID (First Input Delay), and CLS (Cumulative Layout Shift) as automatic analytics events.
example.typescript
function observeWebVitals(
onMetric: (metric: { name: string; value: number }) => void,
): void {
if (typeof PerformanceObserver === 'undefined') return;
// Largest Contentful Paint
try {
const lcpObserver = new PerformanceObserver((list) => {
const entries = list.getEntries();
const last = entries[entries.length - 1];
if (last) {
onMetric({
name: 'LCP',
value: last.startTime,
// For LCP, startTime is the render time of the largest element
});
}
});
lcpObserver.observe({ type: 'largest-contentful-paint', buffered: true });
} catch (e) { /* not supported */ }
// First Input Delay
try {
const fidObserver = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
onMetric({
name: 'FID',
value: (entry as PerformanceEventTiming).processingStart
- entry.startTime,
// processingStart - startTime = input delay
});
}
});
fidObserver.observe({ type: 'first-input', buffered: true });
} catch (e) { /* not supported */ }
// Cumulative Layout Shift
try {
let clsValue = 0;
const clsObserver = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
if (!(entry as LayoutShift).hadRecentInput) {
clsValue += (entry as LayoutShift).value;
}
}
onMetric({ name: 'CLS', value: clsValue });
});
clsObserver.observe({ type: 'layout-shift', buffered: true });
} catch (e) { /* not supported */ }
}
The buffered: true flag is crucial. It tells the observer to replay past entries that were recorded before the observer was created. Without it, you would miss LCP and CLS measurements on pages that load fast — the metrics fire before your SDK script finishes initializing.
IndexedDB — the offline queue
If the user goes offline (subway, airplane, bad connection), events need to survive until connectivity returns. IndexedDB is the right storage for this — it handles structured data, has larger storage limits than localStorage (usually 50 MB+ vs 5 MB), and works asynchronously without blocking the main thread.
On every page load, the SDK checks IndexedDB for pending batches and attempts to send them. This is the recovery mechanism. If the tab crashed mid-request, the batch is still in IndexedDB and will be sent on the next page load.
Note
I considered using the Cache API (from Service Workers) instead of IndexedDB. The Cache API is designed for HTTP responses, not for arbitrary queuing. IndexedDB gives me cursor iteration for FIFO ordering, transaction atomicity, and simpler error handling. Don't use the Cache API as a general-purpose database.
Figure 3 — Event lifecycle state machine. Events flow through five states. Failures trigger retry with backoff. Sampling discards before queuing.
6 · Optimizations (O)
An analytics SDK that makes the page slower is worse than no analytics at all. Every optimization is a tradeoff between data fidelity and performance. Here is how I balance them.
Batching with configurable thresholds
Sending one HTTP request per event is wasteful. Each request has TCP handshake overhead (at least 1 RTT), TLS negotiation (2 RTTs), and HTTP headers (~500 bytes). For a 1 KB event payload, the overhead is over 200%. Batching 100 events into one request amortizes that overhead.
The SDK batches by two criteria: max events (default 100) or max wait time (default 5 seconds), whichever happens first. The first event in a batch starts a 5-second timer. If 100 events arrive before the timer fires, flush immediately. If not, flush at 5 seconds. This guarantees events never sit longer than 5 seconds, but also caps batch size at 100.
High-volume events (scroll positions, mouse movements) do not need 100% capture. Sampling reduces volume while preserving statistical accuracy. I support two sampling strategies:
Deterministic sampling: hash the user's anonymous ID modulo 100, and only capture events if the result is below the sample rate threshold. Same user — same sampling bucket. This preserves funnels and user journeys for a representative subset of users.
Rate-based sampling: a simple random check per event. Cheaper, but destroys per-user continuity. Use this for raw metrics where individual user journeys are not needed.
example.typescript
function shouldSample(
anonymousId: string,
sampleRate: number,
strategy: 'deterministic' | 'rate' = 'deterministic',
): boolean {
if (sampleRate >= 1) return false; // 100% — no sampling
if (strategy === 'deterministic') {
// Simple hash: sum char codes mod 100
const hash = anonymousId
.split('')
.reduce((acc, c) => acc + c.charCodeAt(0), 0);
return (hash % 100) >= (sampleRate * 100);
}
// Rate-based: random check
return Math.random() >= sampleRate;
}
// Usage in SamplingPlugin
class SamplingPlugin implements PipelinePlugin {
name = 'sampling';
private sampleRate: number;
private strategy: 'deterministic' | 'rate';
constructor(config: { sampleRate: number; strategy?: 'deterministic' | 'rate' }) {
this.sampleRate = config.sampleRate;
this.strategy = config.strategy ?? 'deterministic';
}
process(event: RawEvent): RawEvent | null {
if (shouldSample(event.anonymousId, this.sampleRate, this.strategy)) {
return null; // Drop the event
}
return event;
}
}
Exponential backoff with jitter
When a request fails, retry immediately is almost always wrong. The server is likely overloaded (5xx) or rate-limited (429). A thundering herd of retries will make it worse. Exponential backoff spreads retries out.
example.typescript
function getBackoffDelay(
attempt: number,
baseMs: number = 1000,
maxMs: number = 30000,
): number {
const exponential = baseMs * Math.pow(2, attempt - 1);
const capped = Math.min(exponential, maxMs);
// Add jitter: ±25% random offset to prevent thundering herd
const jitter = capped * (0.75 + Math.random() * 0.5);
return Math.round(jitter);
}
// Retry loop
async function sendWithRetry(
batch: Batch,
transport: Transport,
maxAttempts: number = 5,
): Promise<void> {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
try {
const response = await transport.send(batch);
if (response.ok) return; // Success
// 429 Too Many Requests — back off
// 5xx Server Error — back off
if (response.status === 429 || response.status >= 500) {
const delay = getBackoffDelay(attempt);
await sleep(delay);
batch.retryCount = attempt;
continue;
}
// 4xx other than 429 — client error, don't retry
throw new Error(`Non-retryable status: ${response.status}`);
} catch (err) {
if (attempt === maxAttempts) {
// Last attempt failed — persist for next page load
await persistBatch(batch);
return;
}
const delay = getBackoffDelay(attempt);
await sleep(delay);
}
}
}
The jitter (±25%) is not optional. Without jitter, all clients that encountered the error retry at exactly the same time — the thundering herd problem. A random offset spreads the load across a wider window.
Transport strategy decision tree
The transport layer chooses the best delivery mechanism based on the context. The decision tree is evaluated at flush time:
Figure 4 — Transport decision tree. sendBeacon is preferred during page unload. For normal loads, payload size determines sendBeacon vs fetch vs image pixel fallback.
The keepalive flag on fetch() is the unsung hero. Available in all modern browsers, it tells the browser to keep the request alive even if the page unloads. It has a similar guarantee to sendBeacon but supports custom headers (important for your DSN auth). The 64 KB limit still applies.
Bundle size breakdown
Module
Size (min+gzip)
Dependencies
Core pipeline
3.2 KB
Zero
Enrichment plugin
1.2 KB
Zero
Error capture
2.1 KB
Zero
Breadcrumbs
0.8 KB
Zero
Performance (Web Vitals)
1.5 KB
Zero
IndexedDB queue
1.0 KB
Zero
Total with all plugins: 9.8 KB gzip. The core pipeline that most users need (core + enrichment + batching + transport) is under 5 KB. The zero-dependency policy means you never worry about transitive dependencies or version conflicts.
Key Insight
The zero-dependency rule is non-negotiable for an analytics SDK. If your SDK ships with lodash and the project uses a different lodash version, the SDK is now a bundler problem. Sentry and Segment both follow this rule — their browser SDKs have zero runtime dependencies. The tradeoff is you write a lot of utilities yourself, but that is the right call for a foundational library.
7 · Testing Strategy
Testing an analytics SDK is uniquely challenging because it interacts with browser APIs that do not exist in Node.js. A unit test that calls track() and checks that a fetch was made is only testing the plumbing. The hard parts are the browser integrations.
Unit tests — pipeline and plugins
Each plugin is tested in isolation with a mock event. The pipeline is tested with a mock plugin chain. These tests are fast (milliseconds) and run in Jest or Vitest with no browser environment.
The error capture plugin needs real browser API surfaces. I use vitest's jsdom environment (or happy-dom) to provide mock implementations of window.onerror, addEventListener, and PerformanceObserver. For true browser tests, Playwright in headed mode.
The most important test: run the full SDK in a real browser, fire events, and verify they reach a mock server. I use a Playwright script that opens a page with the SDK injected, triggers errors in various ways, and inspects the network requests.
The scenarios I consider must-pass before any release:
Custom event delivery:analytics.track() results in a POST request with the correct JSON body.
Error capture: An uncaught throw new Error() triggers an error event with stack trace.
Promise rejection: An async function that throws without a catch generates an unhandledrejection event.
Page unload: Events fired during beforeunload are sent via sendBeacon and arrive at the server.
Offline queue: Disconnect the network, fire events, reconnect — events arrive after reconnection.
Sampling: With sampleRate=0.5, roughly 50% of events are sent (within statistical margin).
Cross-origin errors: An error from a CDN-hosted script without CORS headers is reported as "Script error." (or as much detail as the browser allows).
Batch integrity: Flushed batch JSON is valid and matches the expected schema.
Tip
The "page unload" test is the hardest to automate. Playwright closes the page, but the sendBeacon fires asynchronously. I use Playwright's page.waitForRequest() with a route handler that intercepts the beacon URL and confirms receipt. If the request never arrives, the test fails. This is the closest we can get to asserting sendBeacon reliability without checking browser internals.
8 · Key Takeaways
Pipeline architecture beats monolithic classes. A chain of small, single-purpose plugins is easier to test, extend, and reason about than a single Analytics class with every feature baked in. Each plugin implements process(event) and nothing else.
sendBeacon for unload, fetch for everything else. During page teardown, sendBeacon is the only reliable transport. During normal page life, fetch with keepalive gives you custom headers and response handling. Image pixel is the last resort for ancient browsers.
IndexedDB is your crash insurance. Persist every batch before attempting to send it. If the send fails or the tab crashes, the batch is recovered on the next page load. localStorage cannot handle structured data at the scale of an analytics queue.
Zero dependencies is a feature, not an accident. An analytics SDK is a foundational library. Every dependency is a potential bundle size increase, version conflict, or security vulnerability. I write my own debounce, my own UUID generator, and my own queue.
Use both onerror and addEventListener('error'). They catch different things. onerror catches JS runtime errors with stack traces. addEventListener in capture mode catches resource load failures. Neither catches promise rejections — you need unhandledrejection for that.
Batching is a performance and cost optimization. Amortize HTTP overhead across multiple events. 100 events per batch reduces requests by 99% compared to one request per event. The 5-second max wait prevents data staleness.
Sampling is not just about volume. Deterministic sampling based on user ID hash preserves user journeys for a representative subset. Rate-based sampling is cheaper but loses continuity. Choose based on your analysis needs.
Exponential backoff with jitter prevents thundering herds. Without jitter, retries cluster. With ±25% jitter, they spread across the backoff window. Implement this in the transport layer, not in each plugin.
requestIdleCallback for non-critical work. Serialize batches, write to IndexedDB, and check the retry queue during idle time. Always provide a timeout fallback to prevent starvation.
PerformanceObserver with buffered:true. Without the buffered flag, you miss initial metrics on fast-loading pages. The observer replays past entries when created.
Building an analytics and error SDK is a humbling exercise. It forces you to confront every browser quirk — the silent promise rejection, the cross-origin "Script error.", the 64 KB beacon limit, the IndexedDB transaction that fails because the user is in private browsing mode. A production-grade SDK is not the one that handles the happy path perfectly. It is the one that survives all of these edge cases and still delivers the event.