Instrumentation

What each of the Browser SDK's fourteen instrumentations captures, the spans it produces, the attributes Web Vitals emits, and how to turn each one on or off.

The Browser SDK ships fourteen instrumentations. Each wraps one browser API and stamps its spans with a distinct app.span.type. Dashboards and the session timeline sort data by that value, so which instrumentation uses which type is also what your queries key on.

Defaults

Instrumentationapp.span.typeDefaultOption that turns it on
fetchfetchon—
xhrxhron—
websocketwebsocketoffwebsocket
socketiosocket-iooffsocketio
documentrenderon—
postloadpost-docson—
visibilityvisibilityon—
connectivityconnectivityon—
longtasklongtaskon—
interactionsevent, routeon—
userJourneynoneoffuserJourney
errorserroron—
consolelogoffconsoleCapture
webvitalswebvitalsonwebVitals

Shared attributes

Every instrumentation except socketio's send spans and userJourney puts these on its spans.

AttributeValue
app.screen.nameScreen name, after screenNameOption and URL redaction
app.screen.typeScreen type
session.idSession id
url.fullOn an HTTP client span, the URL requested; elsewhere the current document. Redacted either way

Values identifying the app and the browser — service.name, service.version, sophonz.browser.name, os.name and the rest — ride on the resource once rather than on every span.

Network

fetch

Patches window.fetch and opens a client span per call, named after the method (HTTP GET).

It records the response status and size and the requested URL (url.full, http.url), and injects a traceparent header into requests matching tracePropagationTargets so the trace continues into your backend. When a response carries Server-Timing: traceparent, the server's span id is kept as link.spanId.

Turn on advancedNetworkCapture to include request and response headers and bodies.

(boolean or SophonzFetchInstrumentationConfig, optional)

Enables or disables Fetch API instrumentation. Set to true to automatically instrument Fetch requests. Provide a SophonzFetchInstrumentationConfig to adjust the configuration.

See @sophonz/instrumentation-fetch for details.

type SophonzFetchInstrumentationConfig = {
  advancedNetworkCapture?: () => boolean;
  clearTimingResources?: boolean;
  propagateTraceHeaderCorsUrls?: web.PropagateTraceHeaderCorsUrls;
  ignoreUrls?: Array<string | RegExp>;
  applyCustomAttributesOnSpan?: FetchCustomAttributeFunction;
  ignoreNetworkEvents?: boolean;
  measureRequestSize?: boolean;
}
  • advancedNetworkCapture: enables advanced network capture. Defaults to false.
  • clearTimingResources: clears timing resources. Defaults to false.
  • propagateTraceHeaderCorsUrls: list of URLs to which trace headers are propagated on CORS requests.
  • ignoreUrls: URL patterns to exclude from instrumentation.
  • applyCustomAttributesOnSpan: function to add custom attributes to spans. Defaults to undefined.
  • ignoreNetworkEvents: ignores network events. Defaults to false.
  • measureRequestSize: measures request size. Defaults to false.

xhr

Wraps XMLHttpRequest the same way. Span names, attributes and propagation rules match fetch; only app.span.type differs. Libraries built on XHR — jQuery, axios — are covered without extra configuration.

(boolean or SophonzXMLHttpRequestInstrumentationConfig, optional)

Enables or disables XMLHttpRequest instrumentation. Set to true to automatically instrument XMLHttpRequest requests.

See @sophonz/instrumentation-xml-http-request for details.

interface XMLHttpRequestInstrumentationConfig extends InstrumentationConfig {
    clearTimingResources?: boolean;
    propagateTraceHeaderCorsUrls?: PropagateTraceHeaderCorsUrls;
    ignoreUrls?: Array<string | RegExp>;
    applyCustomAttributesOnSpan?: XHRCustomAttributeFunction;
    ignoreNetworkEvents?: boolean;
    measureRequestSize?: boolean;
    advancedNetworkCapture?: () => boolean;
}
  • clearTimingResources: clears timing resources. Defaults to false.
  • propagateTraceHeaderCorsUrls: list of URLs to which trace headers are propagated on CORS requests.
  • ignoreUrls: URL patterns to exclude from instrumentation.
  • applyCustomAttributesOnSpan: function to add custom attributes to spans. Defaults to undefined.
  • ignoreNetworkEvents: ignores network events. Defaults to false.
  • measureRequestSize: measures request size. Defaults to false.
  • advancedNetworkCapture: enables advanced network capture. Defaults to false.

websocket

Off by default. Turning on websocket opens a connect span and records messages and errors on it as span events.

(boolean or SophonzWebSocketInstrumentationConfig, optional)

Enables or disables WebSocket instrumentation. Set to true to automatically instrument WebSocket connection events.

interface SophonzWebSocketInstrumentationConfig extends InstrumentationConfig {
  ignoreUrls?: (string | RegExp)[];
}
  • ignoreUrls: URL patterns to exclude from instrumentation.

socketio

Off by default. Turning on socketio tracks a Socket.IO client's connect, disconnect and emit. Send spans do not carry the screen and session attributes.

(boolean or SocketIoClientInstrumentationConfig, optional)

Enables or disables Socket.io client instrumentation. Set to true to automatically instrument Socket.io client events.

interface SocketIoClientInstrumentationConfig
  extends InstrumentationConfig {
  target?: string | SocketIOClient;
}
  • target: the target Socket.io client object. Defaults to undefined. Setting this enables automatic instrumentation of Socket.io events.

Page lifecycle

document

Records the initial document load as documentLoad, documentFetch and resourceFetch spans. Navigation timings — DNS, connect, TTFB — become span events, as do First Paint and First Contentful Paint.

There is one resourceFetch per subresource the document pulled, and its url.full is that resource's own URL.

(boolean or SophonzDocLoadInstrumentationConfig, optional)

Enables or disables document load instrumentation. Set to true to instrument document load events. Provide a SophonzDocLoadInstrumentationConfig to adjust the configuration.

interface SophonzDocLoadInstrumentationConfig
  extends InstrumentationConfig {
  ignoreUrls?: (string | RegExp)[];
}
  • ignoreUrls: URL patterns to exclude from instrumentation. Accepts strings or regular expressions.

See @sophonz/instrumentation-document-load for details.

postload

Tracks resource requests made after the document has loaded: lazily loaded images, code-split chunks, anything outside the initial load.

(boolean or SophonzPostDocLoadResourceInstrumentationConfig, optional)

Enables or disables post-document-load resource instrumentation. Set to true to automatically instrument resource loading events after the document has fully loaded. Particularly useful for component-level resource instrumentation in SPA applications.

See @sophonz/instrumentation-post-document-load for details.

interface SophonzPostDocLoadResourceInstrumentationConfig
  extends InstrumentationConfig {
  allowedInitiatorTypes?: string[];
  ignoreUrls?: (string | RegExp)[];
}
  • allowedInitiatorTypes: initiator types to instrument. Defaults to ["script", "link"].
  • ignoreUrls: URL patterns to exclude from instrumentation.

visibility

Listens for visibilitychange and spans the stretches where the tab was visible or hidden — the basis for measuring time a user actually spent looking at the page.

(boolean or InstrumentationConfig, optional)

Enables or disables page visibility instrumentation. Set to true to automatically instrument page visibility state changes (foreground/background transitions).

See @sophonz/instrumentation-visibility for details.

export interface InstrumentationConfig {
    enabled?: boolean;
}

connectivity

Records online and offline transitions. Useful for reading errors that happened while the network was gone.

(boolean or InstrumentationConfig, optional)

Enables or disables network connectivity instrumentation. Set to true to automatically instrument network state changes (online/offline transitions).

See @sophonz/instrumentation-connectivity for details.

export interface InstrumentationConfig {
    enabled?: boolean;
}

longtask

Spans any task that held the main thread for 50ms or more, with longtask.name and longtask.duration. Use it to narrow down input delay.

(boolean or InstrumentationConfig, optional)

Enables or disables long task instrumentation. Set to true to automatically instrument tasks that run for a long time.

See @sophonz/instrumentation-browser-longtask for details.

export interface InstrumentationConfig {
    enabled?: boolean;
}
  • enabled: whether to enable instrumentation. Defaults to true.

Interaction

interactions

Records user events such as clicks and submits as event, and route changes as route (a routeChange span). Event spans carry the target element's text, tag, id and class as target_element_*.

This is the only instrumentation instrumentations can configure.

SophonzSDK.init({
  // ...
  instrumentations: {
    interactions: { events: { click: true, submit: false } },
  },
});

(boolean or SophonzUserInteractionInstrumentationConfig, optional)

Enables or disables user interaction instrumentation. Set to true to automatically instrument user interactions such as clicks and inputs. Provide a SophonzUserInteractionInstrumentationConfig to customize the configuration.

See @sophonz/instrumentation-user-interaction for details.

interface SophonzUserInteractionInstrumentationConfig extends InstrumentationConfig {
    eventNames?: EventName[];
    shouldPreventSpanCreation?: ShouldPreventSpanCreation;
    events?: UserInteractionEventsConfig;
    captureText?: boolean;
    captureId?: boolean;
}
  • eventNames: list of events to instrument. Defaults to DEFAULT_AUTO_INSTRUMENTED_EVENTS.
    • Pointer events: click, dblclick, mousedown, mouseup
    • Form events: submit, reset, change
    • Drag & Drop: dragend, drop
    • Media events: ended, pause, play
  • shouldPreventSpanCreation: callback invoked when a span is about to be created. Return true to prevent span recording.
  • events: event configuration using the UserInteractionEventsConfig interface.
  • captureText: (boolean, default: true) when false, target_element_text is excluded from all event span attributes and innerText is excluded from the Operation Name fallback.
  • captureId: (boolean, default: true) when false, target_element_id is excluded from all event span attributes and id is excluded from the Operation Name fallback.
type UserInteractionEventsConfig = {
  [type: string]: boolean;
};
const DEFAULT_AUTO_INSTRUMENTED_EVENTS: UserInteractionEventsConfig = {
  // pointer
  click: true,
  dblclick: true,
  mousedown: true,
  mouseup: true,
 
  // form
  submit: true,
  reset: true,
  change: true,
 
  // drag & drop
  dragend: true,
  drop: true,
 
  // media
  ended: true,
  pause: true,
  play: true,
};

Ignore configuration

To exclude a specific element from instrumentation, add the data-sophonz="ignore" attribute to the HTML element. No spans or traces will be created for events on that element.

<button data-sophonz="ignore">Sensitive button</button>
<input data-sophonz="ignore" type="text" placeholder="Personal information" />

Operation Name fallback logic

The Operation Name for user interaction events is determined by the following priority:

captureTextcaptureIdinnerText presentid presentOperation Name
truetrue"Submit""formSubmit"Submit [click]
falsetrue"Submit""formSubmit"formSubmit [click]
truefalse"Submit""formSubmit"Submit [click]
falsefalse"Submit""formSubmit"button [click]

Configuration example

SophonzSDK.init({
  collectorUrl: 'https://in.sophonz.ai',
  appName: 'my-frontend-app',
  appVersion: '1.0.0',
  appKey: '<YOUR_APP_KEY_HERE>',
  instrumentations: {
    interactions: {
      captureText: true,   // capture innerText (default: true)
      captureId: true,     // capture id (default: true)
      events: {
        click: true,
        dblclick: true,
        submit: true,
        change: true,
        mousedown: false,  // disabled
        mouseup: false,    // disabled
      }
    }
  }
});

userJourney

Off by default. Turning on userJourney stitches a visitor's screen-to-screen path together. It uses no app.span.type of its own and does not carry the shared screen and session attributes.

Errors and logs

errors

Records uncaught exceptions and unhandled rejections as error spans, stack trace included. Upload your source maps and the dashboard resolves them back to original positions.

(boolean or SophonzErrorInstrumentationConfig, optional)

Enables or disables browser error instrumentation. Set to true to activate a global error handler that automatically instruments errors in your application. Provide a SophonzErrorInstrumentationConfig object to customize the configuration.

interface SophonzErrorInstrumentationConfig extends InstrumentationConfig {
  /**
   * Whether to capture console.error calls as exceptions.
   * @default true
   */
  captureConsoleError?: boolean;
  /**
   * A callback function for adding custom attributes to the span/log when an error is recorded.
   * @param error - The error object or string that is being recorded.
   * @returns Attributes to add to the span and log.
   */
  applyCustomAttributes?: (error: Error | string | Event) => Attributes;
}
  • captureConsoleError: whether to capture console.error calls as exceptions. Defaults to true.
    • true (default): console.error calls are captured as exceptions
    • false: console.error instrumentation is disabled
  • applyCustomAttributes: callback function that adds custom attributes to the span/log when an error is recorded. Receives the error object and returns an attributes object.

applyCustomAttributes example:

SophonzSDK.init({
  // ... base config
  instrumentations: {
    errors: {
      applyCustomAttributes: (error) => {
        if (error instanceof Error) {
          return {
            'error.category': error.name === 'TypeError' ? 'type-error' : 'general',
            'error.component': 'frontend',
          };
        }
        return {};
      },
    },
  },
});

See @sophonz/instrumentation-browser-exception for details.

WARNING — Error instrumentation scope

This feature instruments errors that occur in the browser. Errors occurring on the server or in edge environments (e.g. SSR) are not instrumented. A separate server-side agent is required to instrument server-side errors.

console

Off by default. Turning on consoleCapture collects console.debug, info, warn and error as log. Console arguments are sent as they are, so check your redaction settings if anything logs sensitive values.

(boolean or SophonzConsoleInstrumentationConfig, optional)

Enables or disables console instrumentation. Set to true for default console instrumentation. Provide a SophonzConsoleInstrumentationConfig object to customize the configuration.

WARNING — Circular object caution

When this feature is enabled, console output is serialized via JSON.stringify(). If circular references are present in logged objects, a circular reference error will occur during serialization. Exercise caution when logging objects that may contain circular references.

interface SophonzConsoleInstrumentationConfig
  extends InstrumentationConfig {
  betaMode: boolean;
  loggerOptions: LoggerOptions;
  contextManager?: MutableAsyncLocalStorageContextManager;
}
  • betaMode: enables beta mode for console instrumentation. Defaults to false.
  • loggerOptions: logger options for console instrumentation using the LoggerOptions interface.
  • contextManager: uses MutableAsyncLocalStorageContextManager to manage async context. AsyncHooksContextManager reference

Web Vitals

webvitals

Collects LCP, CLS, INP, FCP and TTFB as webvitals, emitting them under the OpenTelemetry browser.web_vital semantic convention.

(boolean or InstrumentationConfig, optional)

Enables or disables Web Vitals instrumentation. It is on by default, and the top-level webVitals option turns it off too.

interface InstrumentationConfig {
  enabled?: boolean;
}
  • enabled: whether to enable instrumentation. Defaults to true.

web-vital.* was replaced by browser.web_vital.*

WARNING — Queries on the old attribute names return nothing

The SDK no longer emits web-vital.name, web-vital.value, web-vital.delta, web-vital.rating or web-vital.navigation_type. The old names are not emitted alongside the new ones, so dashboards, queries, alerts and exports that read them have to be updated.

OldNewNotes
web-vital.namebrowser.web_vital.nameThe value is now lower-case: lcp, not LCP
web-vital.valuebrowser.web_vital.value
web-vital.deltabrowser.web_vital.delta
web-vital.ratingbrowser.web_vital.rating
web-vital.navigation_typebrowser.web_vital.navigation_typeAbsent when the browser does not report one
—browser.web_vital.idAdded. Required by the convention

The names, the lower-case metric values and the requirement levels below are those of the OpenTelemetry browser events convention and the browser attribute registry. Both are at Development stability, so they can still change upstream.

The span is unchanged and still carries app.span.type = "webvitals". Queries that select web vitals by span type are unaffected.

Emitted signals

One reported vital produces up to three signals.

The event

The convention defines browser.web_vital as an event — a log record — and requires the event name to be exactly browser.web_vital.

  • eventName is browser.web_vital. It is a native field on the log record, not an attribute.
  • The record is bound to the span below, so it carries the same trace and span ID.
  • Attributes: browser.web_vital.name, .value, .delta, .id, .rating, .navigation_type when defined, plus app.screen.name.
  • session.id and sophonz.browser.device are not repeated on the record. They are resource attributes, already present on every log record the SDK sends.

The span

The session timeline selects on app.span.type, so the span is emitted as well.

  • Span name: @sophonz/instrumentation-webvitals.
  • Zero duration — it starts and ends at the same timestamp.
  • Attributes: app.span.type = "webvitals", the six browser.web_vital.* attributes, plus the screen name, screen type, session ID and url.full every SDK span carries.

The histogram

A metric instrument named webvitals, recording the vital's value.

  • Attributes: app.span.type, browser.web_vital.name, browser.web_vital.delta, browser.web_vital.rating, and browser.web_vital.navigation_type when defined.
  • browser.web_vital.id is excluded. It is unique per measurement, so including it would give every data point its own time series.

Attributes

AttributeTypeRequirement levelNotes
browser.web_vital.namestringRequiredOne of cls, fcp, inp, lcp, ttfb, lower-case
browser.web_vital.valuenumberRequiredThe measured value
browser.web_vital.deltanumberRequiredChange since the previous report of the same vital
browser.web_vital.idstringRequiredUnique per measurement, e.g. v3-1677874579383-6381583661209
browser.web_vital.ratingstringRecommendedOne of good, needs-improvement, poor
browser.web_vital.navigation_typestringRecommendedOne of navigate, reload, back-forward, back-forward-cache, prerender, restore. Absent when the browser does not report one

Collected metrics

cls, fcp, inp, lcp and ttfb. Each is reported at most once per page load.

FID is not collected. It was superseded by INP.

Aggregating

Google defines the Core Web Vitals thresholds — LCP 2.5 s, INP 200 ms, CLS 0.1 — at the 75th percentile of page views. Percentiles do not compose, so compute p75 from the raw events rather than rolling up per-screen percentiles.

A vital is reported once per page load, but bfcache restores and soft navigations produce a new browser.web_vital.id. Group by that ID and take the last value per group to deduplicate.

browser.web_vital.rating aggregates as a ratio: the share of events rated good can be rolled up across any grouping.

Turning instrumentations on and off

The instrumentations object passed to init() disables or configures any instrumentation individually.

SophonzSDK.init({
  // ...
  instrumentations: {
    longtask: false,                                           // off
    interactions: { events: { click: true, submit: false } },  // configured
  },
});

Three rules:

  • false turns the instrumentation off.
  • An object is layered over what the SDK supplies. Give fetch an object and it still keeps propagateTraceHeaderCorsUrls and the capture callback; only the fields you name change.
  • Omit a key and the SDK's default stands.

Where an instrumentation also has a top-level option — consoleCapture, webVitals, websocket, socketio, userJourney — a false from either side wins. Neither can silently re-enable what the other turned off.

PropertyTypeRequiredDescription
consolebooleanoptionalEnable or disable console instrumentation.
documentbooleanoptionalEnable or disable document load instrumentation.
errorsboolean | SophonzErrorInstrumentationConfigoptionalEnable or disable error instrumentation.
fetchbooleanoptionalEnable or disable Fetch API instrumentation.
interactionsboolean | SophonzUserInteractionInstrumentationConfigoptionalEnable or disable user interaction instrumentation.
longtaskbooleanoptionalEnable or disable long task instrumentation.
visibilitybooleanoptionalEnable or disable page visibility instrumentation.
connectivitybooleanoptionalEnable or disable network connectivity instrumentation.
postloadbooleanoptionalEnable or disable post-document-load resource instrumentation.
socketiobooleanoptionalEnable or disable Socket.io client instrumentation.
websocketbooleanoptionalEnable or disable WebSocket instrumentation.
webvitalsbooleanoptionalEnable or disable Web Vitals instrumentation.
xhrbooleanoptionalEnable or disable XMLHttpRequest instrumentation.