API Reference

Complete reference for every public API the Sophonz Browser SDK provides.

TIP — Sophonz Browser SDK API

The SophonzSDK object initializes and manages RUM (Real User Monitoring) and OpenTelemetry functionality in your web application. It provides session recording, user behavior tracking, exception logging, and more.

With the Sophonz Browser SDK you can send events from your frontend application to Sophonz, allowing you to view network requests and exceptions alongside backend events in a single unified timeline.

The sections below document the SophonzSDK object API. In a browser context the object is available at window.Sophonz. When installed via a package manager, import it with import SophonzSDK from "@sophonz/browser-sdk". The object lets you collect custom data during instrumentation and attach results from business logic that runs while the app is active.

API

init

SophonzSDK.init(config: SophonzSDKConfig): void

Initializes the SophonzSDK instance with the provided configuration. For all available options see the configuration reference.

  • Parameters:
    • config (SophonzSDKConfig): Configuration object.
      • collectorUrl (string): Collector endpoint (required)
      • appName (string): App name (required)
      • appKey (string): App key (required)
      • appVersion (string): App version (required)
      • Additional optional settings...

NOTE — Remote-configuration-based instrumentation control

When init() is called, if the previously stored app state (isCollecting) is false, instrumentation is automatically disabled. Calling init() also resets the Exporter failure counter.

deinit

SophonzSDK.deinit(): void

Shuts down the SophonzSDK instance and stops all instrumentation, including the session recorder.

  • Effects:
    • Removes Exporter event listeners
    • Stops OpenTelemetry instrumentation
    • Stops the session recorder
    • Cleans up the OpAMP client
// Stop instrumentation
SophonzSDK.deinit();

NOTE — Automatic deinit

When auto-stop is active and the exporter failure count reaches autoStopThreshold, deinit() is called automatically.

inited

SophonzSDK.inited: boolean

Returns whether SophonzSDK has been initialized.

  • Returns: (boolean): Initialization state.
if (SophonzSDK.inited) {
  console.log('SophonzSDK is initialized');
}

stopSessionRecorder

SophonzSDK.stopSessionRecorder(): void

Stops the session recorder.

resumeSessionRecorder

SophonzSDK.resumeSessionRecorder(): void

Resumes a previously stopped session recorder.

addAction

Call addAction to explicitly track a specific application event (e.g. sign-up, form submit) by passing an event name and optional metadata.

SophonzSDK.addAction(name: string, attributes?: Attributes): void

Records a user action.

  • Parameters:
    • name (string): Name of the action.
    • attributes (Attributes, optional): Additional attributes.
SophonzSDK.addAction('Form-Completed', {
  formId: 'signup-form',
  formName: 'Signup Form',
  formType: 'signup',
});

recordException

SophonzSDK.recordException(error: any, attributes?: Attributes): void

Records an exception.

  • Parameters:
    • error (any): The exception object to record.
    • attributes (Attributes, optional): Additional attributes.

The resulting log record carries the OpenTelemetry event name exception, alongside a Span whose status is set to error.

recordLog

Records a custom log message.

  • Parameters:
    • message (string): Custom log message.
    • attributes (Record<string, string>, optional): Additional custom attributes.
SophonzSDK.recordLog(message: string, attributes?: Record<string, string>): void

Call recordLog whenever you want to capture a specific event (e.g. API quota exceeded, user action). Logs are searchable and filterable in the Sophonz dashboard.

SophonzSDK.recordLog('API quota exceeded', {
  userId: 'user_123',
  url: 'https://api.sophonz.com/usage',
})

userEvent

API for tracking and analyzing user events. Measure the start and end of specific user actions or business logic flows to capture their full duration.

userEvent: {
  start(name?: string, attributes?: Attributes): string;
  end(id: string, attributes?: Attributes): void;
  getActive(): UserEventInstance | undefined;
  cancel(id: string): void;
}

Core methods:

  • start(): Starts a user event and returns a unique event ID.
  • end(): Completes the event for the given ID and records a span.
  • getActive(): Returns the currently active event instance.
  • cancel(): Cancels the event for the given ID without recording a span.

For detailed usage see the user event instrumentation section.

userEvent.start

SophonzSDK.userEvent.start(name?: string, attributes?: Attributes): string

Starts a user event and returns a unique event ID. All instrumentation (fetch, console, exceptions, etc.) that occurs after this call is grouped under this event's context.

  • Parameters:
    • name (string, optional): Event name (default: user-event-[randomId]).
    • attributes (Attributes, optional): Custom attributes to attach to the event.
  • Returns: Unique event identifier (string).

userEvent.end

SophonzSDK.userEvent.end(id: string, attributes?: Attributes): void

Completes the user event for the given ID and records a span. The total duration is calculated automatically.

  • Parameters:
    • id (string, required): Event ID returned by start().
    • attributes (Attributes, optional): Additional attributes to attach on completion.

userEvent.getActive

SophonzSDK.userEvent.getActive(): UserEventInstance | undefined

Returns information about the currently active user event.

  • Returns: Active event instance or undefined.

userEvent.cancel

SophonzSDK.userEvent.cancel(id: string): void

Cancels the user event for the given ID. No span is recorded.

  • Parameters:
    • id (string, required): ID of the event to cancel.

Advanced API

Additional methods for complex workflows:

  • with(id, fn): Execute a function within a specific event's context.
  • withActive(fn): Execute a function within the currently active event's context.
  • switchTo(id): Switch context to a specific event.
  • getActiveContext(): Return the current active context.
  • hasActiveUserEvent(): Check whether an active event exists.
  • getContext(id): Return the context for a specific event.

For full details see the user event instrumentation docs.

Usage examples

// Track a button click event
function handleButtonClick() {
  const eventId = SophonzSDK.userEvent.start('button-click', {
    'button.name': 'submit',
    'page.url': window.location.href,
  });
 
  performBusinessLogic()
    .then(result => {
      SophonzSDK.userEvent.end(eventId, {
        'action.result': 'success',
        'items.count': result.count,
      });
    })
    .catch(error => {
      SophonzSDK.userEvent.end(eventId, {
        'action.result': 'error',
        'error.message': error.message,
      });
    });
}
 
// Track a form submission
function handleFormSubmit() {
  const eventId = SophonzSDK.userEvent.start('form-submission', {
    'form.type': 'contact',
    'form.fields': 'name,email,message',
  });
 
  try {
    validateForm();
    submitForm();
 
    SophonzSDK.userEvent.end(eventId, {
      'submission.result': 'success',
    });
  } catch (error) {
    SophonzSDK.userEvent.end(eventId, {
      'submission.result': 'error',
      'error.type': error.constructor.name,
    });
    throw error;
  }
}
 
// Cancellable operation example
function handleCancellableOperation() {
  const eventId = SophonzSDK.userEvent.start('file-upload');
 
  if (userCancelled) {
    SophonzSDK.userEvent.cancel(eventId);
    return;
  }
 
  uploadFile().then(() => {
    SophonzSDK.userEvent.end(eventId);
  });
}

setScreenAttribute

SophonzSDK.setScreenAttribute(name: string): void

The Sophonz Browser SDK collects screen names automatically. Use setScreenAttribute when you want to supply a more specific screen name. The function stores the name and records the current URL in a global variable.

This method operates dynamically: while location.href remains unchanged, performance is measured against the name you set. When the URL changes, the screen name is reset automatically according to the screenNameOption configuration.

To maintain accurate performance data across navigation, call setScreenAttribute again whenever the URL or screen changes.

Screen performance data collected this way is analysed per unique screen name in the Sophonz dashboard's screen analytics feature.

CAUTION — A screen name you set is not redacted

Automatically derived screen names pass through the URL sanitizer described in Data Redaction. A name you supply here is recorded exactly as given, so do not put a token, a session identifier or any other secret in it.

/**
 * Stores the supplied attribute value and records the current URL in a global variable.
 *
 * @param {string} attribute - A string representing the screen attribute to set.
 */
function setScreenAttribute(attribute: string) {
  savedScreenAttribute = attribute;
  lastUrl = window?.location?.href;
}

enableAdvancedNetworkCapture

Call enableAdvancedNetworkCapture or disableAdvancedNetworkCapture at any time to dynamically toggle network capture.

WARNING — Network capture privacy

Enabling network capture causes the Sophonz Browser SDK to collect network requests including body and header contents, which may include sensitive information. Ensure compliance with applicable privacy and security regulations before enabling this feature.

SophonzSDK.enableAdvancedNetworkCapture(): void

disableAdvancedNetworkCapture

Call disableAdvancedNetworkCapture to dynamically disable network capture that was previously enabled.

SophonzSDK.disableAdvancedNetworkCapture(): void

setGlobalAttributes

Metadata provides additional context for instrumentation. This can be called at any point during a client session. All events in the current session and all subsequent events will be associated with the supplied metadata.

Additional values can be specified to make events searchable.

SophonzSDK.setGlobalAttributes(attributes: Record<string, string>): void

Sets global attributes.

  • Parameters:
    • attributes (Record<string, string>): Global attributes object to set.
SophonzSDK.setGlobalAttributes({
  teamName: "your-team-name",
  groupName: "your-group-name",
  // additional custom attributes...
});

Global attributes land on every Span and log record, and are therefore subject to attributeScrubbers if you configure any.

getDeviceId

SophonzSDK.getDeviceId(): string | null

Retrieves the native app device ID in a WebView environment. This method only returns a valid value when running inside a WebView that is integrated with the Sophonz Android or iOS SDK.

  • Returns: (string | null): Device ID, or null when not in a WebView or when native resources are unavailable.

Behavior:

  • Android WebView: Queries device.id from native resources via window.SophonzNative.getResources().
  • iOS WebView: Reads device.id from window.__sophonz_resources.
  • Standard browser: Returns null.
const deviceId = SophonzSDK.getDeviceId();
 
if (deviceId) {
  console.log('Device ID:', deviceId);
} else {
  console.log('Not in a WebView or device ID unavailable.');
}

NOTE — WebView-only feature

This API only works correctly inside a WebView within a native app that has the Sophonz Android or iOS SDK installed. It always returns null in a standard browser environment.

setUserIdAttribute

Adding a user ID allows you to search and filter sessions and events in the Sophonz dashboard. This can be called at any point during a client session. The current session and all subsequent events will be associated with the supplied user ID.

setUserIdAttribute(userId: string): void

(userId: string) => void

Sets the user ID attribute.

  • Parameters:
    • userId (string): User ID to set.
window.Sophonz.setUserIdAttribute("_sophonz_user_0001");

Use a custom user ID to enable per-user session analysis in the dashboard.

getSessionId

getSessionId(): string | undefined

Returns the current session ID.

  • Returns: (string | undefined): Session ID, or undefined if unavailable.
const sessionId = SophonzSDK.getSessionId();

getSessionUrl

getSessionUrl(): string | undefined

Returns the Sophonz session detail link for the session currently being instrumented. Open the returned URL to inspect that session's traces, logs, and session replay directly in the Sophonz dashboard.

  • Returns: (string | undefined): Sophonz session detail link, or undefined if unavailable.

attachToReactErrorBoundary

When using React, pass your error boundary component to attachToReactErrorBoundary to automatically capture errors thrown inside that boundary.

// Import your ErrorBoundary (react-error-boundary shown as example)
import { ErrorBoundary } from 'react-error-boundary';
 
// Attach to the ErrorBoundary component so all errors inside it are captured.
SophonzSDK.attachToReactErrorBoundary(ErrorBoundary);
attachToReactErrorBoundary(errorBoundary: ErrorBoundaryComponent): void
  • Parameters:
    • errorBoundary (ErrorBoundaryComponent): The Error Boundary component to attach to.
import { ErrorBoundary } from 'react-error-boundary';
 
// Captures errors from all instances of this ErrorBoundary.
SophonzSDK.attachToReactErrorBoundary(ErrorBoundary);

getAgentControl

SophonzSDK.getAgentControl(): AgentControlResponse | null

Returns the currently stored app status.

  • Returns: (ServiceStatusResponse | null): App status object or null.
interface AgentControlResponse {
  isCollecting: boolean;    // Whether instrumentation collection is active
  autoStop: boolean;        // Whether auto-stop is enabled
  autoStopThreshold: number; // Failure threshold
  token: string;            // Token issued by the server
}
 
// Example usage
const status = SophonzSDK.getAgentControl();
if (status) {
  console.log('Is collecting:', status.isCollecting);
  console.log('Auto-stop enabled:', status.autoStop);
  console.log('Auto-stop threshold:', status.autoStopThreshold);
}

recordExporterFailure

SophonzSDK.recordExporterFailure(): boolean

Manually records an Exporter failure. Primarily used internally, but can be called manually when using a custom Exporter.

  • Returns: (boolean): true if the failure threshold was reached and instrumentation was stopped, false otherwise.
// Call when a custom Exporter fails
const shouldStop = SophonzSDK.recordExporterFailure();
if (shouldStop) {
  console.log('Threshold reached, instrumentation stopped');
}

recordExporterSuccess

SophonzSDK.recordExporterSuccess(): void

Manually records an Exporter success. Primarily used internally.

NOTE — Failure counter behavior

Calling recordExporterSuccess() does not reset the failure counter. The failure counter is only reset when init() is called.

Enabling resource timing for CORS requests

If your frontend application makes API requests to a different domain, you can optionally configure your server to send the Timing-Allow-Origin header with responses. This allows the Sophonz Browser SDK to capture detailed resource timing information for those requests — such as DNS lookup time and response download duration — via PerformanceResourceTiming.

Using the express and cors packages, enable the header as follows:

var cors = require('cors');
var onHeaders = require('on-headers');
 
// ... other code
 
app.use(function (req, res, next) {
  onHeaders(res, function () {
    var allowOrigin = res.getHeader('Access-Control-Allow-Origin');
    if (allowOrigin) {
      res.setHeader('Timing-Allow-Origin', allowOrigin);
    }
  });
  next();
});
app.use(cors());