@comprehend/telemetry-browser
v0.2.4
Published
Integration of comprehend.dev with OpenTelemetry in browser environments.
Maintainers
Readme
@comprehend/telemetry-browser
Integration of comprehend.dev in browser environments, for both architectural and product metrics. This builds upon OpenTelemetry for what it provides, and adds some additinal mechanisms for what isn't yet standardized or doesn't fit naturally with OpenTelmetry.
Functionality includes automatic collection of network request telemetry data, collection of custom metrics (configured on comprehend.dev), view tracking, and user flows (for tracking, for instance, signup flows or user behavior in a given area of the application; these are also configured on comprehend.dev).
Installation
npm install @comprehend/telemetry-browserPeer Dependencies
npm install @opentelemetry/api @opentelemetry/sdk-trace-web @opentelemetry/core @opentelemetry/sdk-metricsQuick Start
import { ComprehendSDK } from '@comprehend/telemetry-browser';
import { WebTracerProvider } from '@opentelemetry/sdk-trace-web';
import { getWebAutoInstrumentations } from '@opentelemetry/auto-instrumentations-web';
import { registerInstrumentations } from '@opentelemetry/instrumentation';
import { MeterProvider, PeriodicExportingMetricReader } from '@opentelemetry/sdk-metrics';
// Initialize the SDK
const sdk = new ComprehendSDK({
organization: 'your-org-name',
token: 'your-api-token',
serviceName: 'web-frontend',
// serviceNamespace: 'production', // Optional
// environment: 'prod', // Optional
// debug: true, // Optional: enable debug logging
});
// Set up tracing
const provider = new WebTracerProvider({
spanProcessors: [sdk.getSpanProcessor()]
});
provider.register();
// Set up metrics (optional)
const meterProvider = new MeterProvider({
readers: [
new PeriodicExportingMetricReader({
exporter: sdk.getMetricsExporter(),
exportIntervalMillis: 30000,
}),
],
});
// Enable automatic instrumentation for browser
registerInstrumentations({
instrumentations: [
getWebAutoInstrumentations({
'@opentelemetry/instrumentation-fetch': {},
'@opentelemetry/instrumentation-xml-http-request': {},
}),
],
});Features
Automatic View Tracking
The SDK automatically tracks page navigations by hooking into the History API (pushState, replaceState) and the popstate event. Each navigation creates a new view context with the current URL, enabling per-page telemetry analysis.
View durations reflect the time the user had the page visible — the view context is ended when the tab becomes hidden (via the Page Visibility API) and a new one starts when it becomes visible again. This means idle time in a background tab is not counted. Telemetry from background work (e.g., in-flight requests that complete while the tab is hidden) is still captured under the application context, making it possible to distinguish activity the user was actively watching from activity that happened in the background.
You can optionally provide a viewAttributes function to extract structured data from URLs and attach it to view contexts:
const sdk = new ComprehendSDK({
organization: 'your-org-name',
token: 'your-api-token',
serviceName: 'web-frontend',
viewAttributes: (url) => {
const path = new URL(url).pathname;
const parts = path.split('/').filter(Boolean);
// e.g. /acme-corp/settings -> { org: 'acme-corp', section: 'settings' }
return {
...(parts[0] ? { org: parts[0] } : {}),
...(parts[1] ? { section: parts[1] } : {}),
};
},
});The function is called for every view (initial page load and subsequent navigations). It can return attributes synchronously or as a Promise for async use cases (e.g., looking up a route definition).
URL Redaction
The SDK sends the page URL with the application context and every view. If your URLs can carry secrets, such as one-time codes on an OAuth callback page, provide a redactUrl function to clean them up first:
const sdk = new ComprehendSDK({
organization: 'your-org-name',
token: 'your-api-token',
serviceName: 'web-frontend',
redactUrl: (url) => {
const parsed = new URL(url);
parsed.searchParams.delete('code');
parsed.searchParams.delete('state');
return parsed.toString();
},
});viewAttributes receives the redacted URL too.
User Flow Context
Track user flows (e.g., checkout, onboarding, account setup) to correlate telemetry with what the user is trying to accomplish:
// Start a user flow
sdk.startUserFlow('checkout', { cartSize: 3 });
// Start a session-persisted user flow (survives page reloads)
sdk.startUserFlow('onboarding', { plan: 'pro' }, 'session');
// End the current user flow
sdk.endUserFlow();The user flow ID and attributes are to be defined in the comprehend.dev product document. Actions taken on the UI are recorded as custom metrics, and correlated automatically with the ongoing user flow.
Session-persisted user flows are stored in sessionStorage and automatically resumed when the SDK initializes. This is not the default, but is useful for tracking flows where the user has to leave the application for some time, for example to complete an OAuth flow in a third party system.
Custom Metrics
The SDK supports server-driven custom metric collection. Custom metric specifications are received from comprehend.dev and automatically applied to both the span processor (for span-based observations) and the metrics exporter (for timeseries/cumulative metrics).
Trace Spans
Every span processed by the SDK is reported as a trace span, enabling distributed trace visualization.
Browser Attributes
The SDK automatically collects browser attributes per OpenTelemetry semantic conventions:
user_agent.original- The full user agent stringbrowser.language- The browser's language settingbrowser.platform- The platform (vianavigator.userAgentData)browser.mobile- Whether the browser is on a mobile devicebrowser.brands- Browser brand information
What it Tracks
- Network Requests: HTTP calls made via
fetch()andXMLHttpRequest - Service Discovery: Identifies your browser application as a service
- Request Metrics: Duration, status codes, request/response sizes
- Error Information: Captures and reports network errors
- Trace Spans: Full distributed tracing support with span/trace IDs
- Custom Observations: Server-driven span matching for custom metrics
- View Navigation: Automatic tracking of page navigations
- User Flow Context: User flow correlation
API Reference
ComprehendSDK
const sdk = new ComprehendSDK({
organization: string; // Your comprehend.dev organization name
token: string; // Your API token
serviceName: string; // Name for your browser application
serviceNamespace?: string; // Optional service namespace
environment?: string; // Optional deployment environment
debug?: boolean | ((message: string) => void); // Debug logging
viewAttributes?: (url: string) => Record<string, AttributeType> | Promise<Record<string, AttributeType>>;
redactUrl?: (url: string) => string; // Clean the page URL before it is sent
});
sdk.getSpanProcessor(); // Returns a SpanProcessor for OpenTelemetry
sdk.getMetricsExporter(); // Returns a PushMetricExporter for OpenTelemetry
sdk.startUserFlow(userFlowId: string, attributes?: Record<string, AttributeType>, lifetime?: 'session');
sdk.endUserFlow();
await sdk.shutdown(); // Clean shutdown: ends contexts, closes connectionDebug Mode
// Boolean debug (logs to console)
const sdk = new ComprehendSDK({
organization: 'my-org',
token: 'token-123',
serviceName: 'my-app',
debug: true
});
// Custom debug function
const sdk = new ComprehendSDK({
organization: 'my-org',
token: 'token-123',
serviceName: 'my-app',
debug: (message) => console.log('[Telemetry]', message)
});Browser Compatibility
This package supports modern browsers with:
- ECMAScript 2022 features
- WebSocket API
crypto.randomUUID()support- Fetch API and XMLHttpRequest
Security
- Only architectural patterns and performance metrics are collected
- No application data or personal information is transmitted
TypeScript Support
This package includes full TypeScript definitions and supports TypeScript projects out of the box.
License
LicenseRef-Proprietary-Audit
Support
For support and questions, visit comprehend.dev or check the documentation.
