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
| Instrumentation | app.span.type | Default | Option that turns it on |
|---|---|---|---|
| fetch | fetch | on | — |
| xhr | xhr | on | — |
| websocket | websocket | off | websocket |
| socketio | socket-io | off | socketio |
| document | render | on | — |
| postload | post-docs | on | — |
| visibility | visibility | on | — |
| connectivity | connectivity | on | — |
| longtask | longtask | on | — |
| interactions | event, route | on | — |
| userJourney | none | off | userJourney |
| errors | error | on | — |
| console | log | off | consoleCapture |
| webvitals | webvitals | on | webVitals |
Shared attributes
Every instrumentation except socketio's send spans and userJourney puts
these on its spans.
| Attribute | Value |
|---|---|
app.screen.name | Screen name, after screenNameOption and URL redaction |
app.screen.type | Screen type |
session.id | Session id |
url.full | On 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.
(
booleanorSophonzFetchInstrumentationConfig, 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 tofalse.clearTimingResources: clears timing resources. Defaults tofalse.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 toundefined.ignoreNetworkEvents: ignores network events. Defaults tofalse.measureRequestSize: measures request size. Defaults tofalse.
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.
(
booleanorSophonzXMLHttpRequestInstrumentationConfig, 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 tofalse.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 toundefined.ignoreNetworkEvents: ignores network events. Defaults tofalse.measureRequestSize: measures request size. Defaults tofalse.advancedNetworkCapture: enables advanced network capture. Defaults tofalse.
websocket
Off by default. Turning on
websocket opens a connect span and
records messages and errors on it as span events.
(
booleanorSophonzWebSocketInstrumentationConfig, 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.
(
booleanorSocketIoClientInstrumentationConfig, 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 toundefined. 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.
(
booleanorSophonzDocLoadInstrumentationConfig, 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.
(
booleanorSophonzPostDocLoadResourceInstrumentationConfig, 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.
(
booleanorInstrumentationConfig, 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.
(
booleanorInstrumentationConfig, 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.
(
booleanorInstrumentationConfig, 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 totrue.
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 } },
},
});(
booleanorSophonzUserInteractionInstrumentationConfig, 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 toDEFAULT_AUTO_INSTRUMENTED_EVENTS.- Pointer events:
click,dblclick,mousedown,mouseup - Form events:
submit,reset,change - Drag & Drop:
dragend,drop - Media events:
ended,pause,play
- Pointer events:
shouldPreventSpanCreation: callback invoked when a span is about to be created. Returntrueto prevent span recording.events: event configuration using theUserInteractionEventsConfiginterface.captureText: (boolean, default:true) whenfalse,target_element_textis excluded from all event span attributes andinnerTextis excluded from the Operation Name fallback.captureId: (boolean, default:true) whenfalse,target_element_idis excluded from all event span attributes andidis 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:
| captureText | captureId | innerText present | id present | Operation Name |
|---|---|---|---|---|
true | true | "Submit" | "formSubmit" | Submit [click] |
false | true | "Submit" | "formSubmit" | formSubmit [click] |
true | false | "Submit" | "formSubmit" | Submit [click] |
false | false | "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.
(
booleanorSophonzErrorInstrumentationConfig, 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 captureconsole.errorcalls as exceptions. Defaults totrue.true(default):console.errorcalls are captured as exceptionsfalse:console.errorinstrumentation 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.
(
booleanorSophonzConsoleInstrumentationConfig, 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 tofalse.loggerOptions: logger options for console instrumentation using theLoggerOptionsinterface.contextManager: usesMutableAsyncLocalStorageContextManagerto 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.
(
booleanorInstrumentationConfig, 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 totrue.
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.
| Old | New | Notes |
|---|---|---|
web-vital.name | browser.web_vital.name | The value is now lower-case: lcp, not LCP |
web-vital.value | browser.web_vital.value | |
web-vital.delta | browser.web_vital.delta | |
web-vital.rating | browser.web_vital.rating | |
web-vital.navigation_type | browser.web_vital.navigation_type | Absent when the browser does not report one |
| — | browser.web_vital.id | Added. 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.
eventNameisbrowser.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_typewhen defined, plusapp.screen.name. session.idandsophonz.browser.deviceare 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 sixbrowser.web_vital.*attributes, plus the screen name, screen type, session ID andurl.fullevery 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, andbrowser.web_vital.navigation_typewhen defined. browser.web_vital.idis excluded. It is unique per measurement, so including it would give every data point its own time series.
Attributes
| Attribute | Type | Requirement level | Notes |
|---|---|---|---|
browser.web_vital.name | string | Required | One of cls, fcp, inp, lcp, ttfb, lower-case |
browser.web_vital.value | number | Required | The measured value |
browser.web_vital.delta | number | Required | Change since the previous report of the same vital |
browser.web_vital.id | string | Required | Unique per measurement, e.g. v3-1677874579383-6381583661209 |
browser.web_vital.rating | string | Recommended | One of good, needs-improvement, poor |
browser.web_vital.navigation_type | string | Recommended | One 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:
falseturns the instrumentation off.- An object is layered over what the SDK supplies. Give
fetchan object and it still keepspropagateTraceHeaderCorsUrlsand 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.
| Property | Type | Required | Description |
|---|---|---|---|
console | boolean | optional | Enable or disable console instrumentation. |
document | boolean | optional | Enable or disable document load instrumentation. |
errors | boolean | SophonzErrorInstrumentationConfig | optional | Enable or disable error instrumentation. |
fetch | boolean | optional | Enable or disable Fetch API instrumentation. |
interactions | boolean | SophonzUserInteractionInstrumentationConfig | optional | Enable or disable user interaction instrumentation. |
longtask | boolean | optional | Enable or disable long task instrumentation. |
visibility | boolean | optional | Enable or disable page visibility instrumentation. |
connectivity | boolean | optional | Enable or disable network connectivity instrumentation. |
postload | boolean | optional | Enable or disable post-document-load resource instrumentation. |
socketio | boolean | optional | Enable or disable Socket.io client instrumentation. |
websocket | boolean | optional | Enable or disable WebSocket instrumentation. |
webvitals | boolean | optional | Enable or disable Web Vitals instrumentation. |
xhr | boolean | optional | Enable or disable XMLHttpRequest instrumentation. |