Configure the Splunk Browser RUM instrumentation

Configure the Splunk RUM browser agent for your web applications.

You can configure the Splunk RUM browser agent from the Splunk Distribution of OpenTelemetry JS for Web to add custom attributes, adapt the instrumentation to your environment and application, customize sampling, and more.

Initialization method

To configure the Splunk RUM browser agent, edit the object passed to the SplunkRum.init() function:

<script src="https://cdn.signalfx.com/o11y-gdi-rum/latest/splunk-otel-web.js" crossorigin="anonymous"></script>
<script>
      SplunkRum.init(
      {
         applicationName: 'my-awesome-app',
         realm: 'us0',
         rumAccessToken: 'ABC123...789',
         version: '1.0.1'
         // Any additional general settings
      });
</script>

General settings

To configure the Splunk RUM browser agent, use the following properties in SplunkRum.init():

Property Type Description
applicationNameStringName of the application. Default: unknown-browser-app.
beaconEndpointString (required if realm isn’t set)Ingest URL to which the agent sends collected telemetry. When realm is set, the URL is in the form https://rum-ingest.<realm>.signalfx.com/v1/rum. When you set an endpoint manually, this overrides the value of realm.
context.asyncBooleanActivates the asynchronous context manager. See Asynchronous trace settings. Default: true.
cookieDomainStringDomain used for session tracking. For example, if you have sites on both foo.example.com and bar.example.com, setting cookieDomain to example.com allows both sites to use the same session identifier. See cookieDomain .
debugBooleanActivates debug logging in the developer console. Default: false.
deploymentEnvironmentStringEnvironment for all the spans produced by the application. For example, dev, test, or prod.
disableAutomationFrameworksBooleanDeactivates tracking of automation frameworks. Available in Splunk RUM browser agent version 0.20.0 and later. Default: false.
disableBotsBooleanDeactivates tracking of bots. Available in Splunk RUM browser agent version 0.20.0 and later. Default: false.
exporter.onAttributesSerializing(a: SpanAttributes, s?: Span) => SpanAttributesProvides a callback for modifying span attributes before they’re exported. The default value is (attrs) => attrs. A sample scenario is Sanitize Personally Identifiable Information (PII).
globalAttributesObjectSets additional attributes added to all spans. For example, version or user_id.
ignoreUrls(string\|regex)[]List of URLs that the agent must ignore. Matching URLs don’t produce spans. You can provide two different types of rules: strings or regular expressions.
instrumentationsObjectActivates or deactivates specific instrumentation modules. See Instrumentation settings.
persistance'cookie' | 'localStorage'Specifies where session data should be stored. Use 'localStorage' in environments without cookie support. Local storage has a limitation of not being able to track sessions across subdomains. Available in Splunk RUM browser agent version 0.20.0 and later. Default: cookie.
privacyObjectSpecifies privacy settings for click-text recording.
realmStringThe name of your organization’s realm. To find the realm name of your account, open the navigation menu in Splunk Observability Cloud, select Settings, and then select your username. The realm name appears in the Organizations section. Example: us0.
rumAccessTokenString (required)RUM token that authorizes the agent to send telemetry data to Splunk Observability Cloud. To generate a RUM access token, see Generate your RUM access token in Splunk Observability Cloud.
tracerObjectTracing configuration passed to WebTracerProvider. You can use it to configure sampling. See Sampling settings.
versionStringVersion of the application for all spans. For example, "1.0.1" or "20220820".

context.async

Traces that happen asynchronously, such as user interactions that result in a promise chain, might get disconnected from parent activity. To avoid this problem, the Splunk RUM browser agent includes a custom context manager that connects parent traces with traces that happen when using the following properties or patterns:

  • setTimeout with less than 34ms timeout

  • setImmediate

  • requestAnimationFrame

  • Promise.then / catch / finally

  • MutationObserver on textNode

  • MessagePort

  • Hash-based routers

Asynchronous trace linking is activated by default. In case of compatibility issues you can deactivate it by setting the context.async property to false.

The context manager allows Splunk RUM to link requests executed when a component is first rendered to the user interaction that caused the application to add the component to the page. XMLHttpRequest events and Fetch API events through promise methods are patched to preserve the parent context, so subsequent requests link to their parents.

The following limitations apply when using asynchronous tracing:

  • async/await functions aren’t supported. Down-compile the code using Babel and targeting older browsers.

    document.getElementById('save-button').addEventListener('click', async () => {
      const saveRes = await fetch('/api/items', {method: 'POST'});
    
      const listRes = await fetch('/api/items'); // Can be disconnected from click event when not transpiled
    });
  • Only code loaded by promise-based implementations is linked to the parent interaction.

cookieDomain

The Splunk RUM browser agent uses the following cookies to link traces to sessions:

Name

Purpose

Comment

__splunk_rum_sid

Stores the session ID.

By default, a session lasts for 15 minutes after the last user interaction. The maximum session duration is 4 hours.

globalAttributes

Valid values:

Name

Description

version
user_id

instrumentations

To activate, deactivate, or configure Splunk RUM browser instrumentation modules, compose an instrumentations object and include it in your SplunkRum.init() function call. For example:

SplunkRum.init(
   {
      beaconEndpoint: 'https://rum-ingest.us0.signalfx.com/v1/rum',
      rumAccessToken: 'ABC123…789',
      applicationName: 'my-awesome-app',
      instrumentations:
      {
         interactions:
         {
            // Adds``gamepadconneted`` events to the
            // list of events collected by default
           eventNames: [
             ...SplunkRum.DEFAULT_AUTO_INSTRUMENTED_EVENT_NAMES,
             'gamepadconnected'
           ],
         },
         longtask: false, // Deactivates monitoring for longtasks
         websocket: true, // Activates monitoring for websockets
      },
   });

The following table describes the modules you can configure through the instrumentations object:

Module Default Description

connectivity

false

Activates the collection of connectivity events. See Connectivity.

document

true

Activates the collection of spans related to document load events. See Document load.

documentLoadActivates the documentLoad span. See Document load.
documentFetchActivates the documentFetch span. See Document load.

errors

true

Activates the collection of JavaScript errors. See Errors collected by the Browser RUM agent. You can specify the onError hook to modify errors spans before send.

fetch

true

Activates the collection of Fetch API requests. See XHR and Fetch instrumentations.

interactions

true

Activates the collection of user interactions, such as clicks or key presses. See User interactions.

interactions.eventNames

Array of DOM events that the instrumentation captures as user interactions. You can access the default values by accessing the SplunkRum.DEFAULT_AUTO_INSTRUMENTED_EVENT_NAMES property.

longtask

true

Activates the collection of long tasks. See Long tasks.

postload

true

Activates the collection of resources loaded after a load event. See Resources after load.

resourceFetchSee resourceFetch.

socketio

false

Activates the collection of socket.io messages. See Socket.io messages.

socketio.target

'io'

The global variable name to which the socket.io client is loaded, or the io object. See Socket.io messages.

visibility

false

Activates the collection of visibility events. See Visibility.

websocket

false

Activates the collection of websocket lifecycle events. See Websockets.

webvitals

true

Activates the collection of Google Web Vitals metrics. See Web Vitals.

xhr

true

Activates the collection of XMLHttpRequest events. See XHR and Fetch instrumentations.

privacy

The Splunk RUM browser agent avoids capturing potentially private information by default. In other words, it records only the HTML node name by default. Use maskAllText and sensitivityRules for opt-in fine-grained click-text capture.

Precedence rules:

  1. maskAllText is global unless overridden.

  2. Rules are evaluated in order; specific overrides should come last.

  3. exclude is absolute and cannot be overridden.

ParameterTypeDescription
maskAllTextbooleanMasks text for all elements unless a rule explicitly unmasks them. Default: true.
sensitivityRulesarray of SensitivityRule objectsOrdered rule list controlling masking, unmasking, exclusion using CSS selectors. Default: [].
privacy.sensitivityRules

The sensitivityRules array gives you fine-grained control over what is recorded. You can mask, unmask, or exclude specific elements on the page from being recorded. Put general rules at the beginning of the array, and more specific rules at the end of the array.

Available rule types:

  • mask: Replace the content of the element with black bars.

  • unmask: Show the content of a masked element.

  • exclude: Exclude the element from the recording. We do not record any interaction with this element;

ParameterTypeDescription
rulestringType of sensitivity. Valid values: 'mask', 'unmask', 'exclude'.
selectorstring

CSS selector for sensitive elements.

For example:

  • p.sensitive selects all p elements with class="sensitive".

  • ul ~ table selects all table elements that are siblings of a ul element.

Examples:

  • Default safety (only node names recorded; zero privacy risk)

    {
      "maskAllText": true,
      "sensitivityRules": []
    }
  • Selective unmask (all masked except safe product names)

    {
      "maskAllText": true,
      "sensitivityRules": [
        { "rule": "unmask", "selector": "p.product-name" }
      ]
    }
  • Mixed (p masked except product labels; user profiles excluded completely)

    {
      "maskAllText": true,
      "sensitivityRules": [
        { "rule": "mask", "selector": "p" },
        { "rule": "unmask", "selector": "p.item-label" },
        { "rule": "exclude", "selector": "#user-profile" }
      ]
    }
  • Unmasked by default, with specific mask (all text recorded except explicitly masked sensitive ones)

    {
      "maskAllText": false,
      "sensitivityRules": [
        { "rule": "mask", "selector": "p.sensitive" }
      ]
    }

tracer

By default, the Splunk RUM browser agent collects all of the data from all of the users. You can adjust sampling by passing a custom sampler to the tracer property.

The following example shows how to restrict sampling to logged in users:

CDN
<script src="https://cdn.signalfx.com/o11y-gdi-rum/latest/splunk-otel-web.js" crossorigin="anonymous"></script>
<script>
   var shouldTrace = isUserLoggedIn();

   SplunkRum.init({
      realm: '<realm>',
      rumAccessToken: '<your_rum_token>',
      applicationName: '<application-name>',
      tracer: {
         sampler: shouldTrace ? new SplunkRum.AlwaysOnSampler() : new SplunkRum.AlwaysOffSampler(),
      },
   });
</script>
npm
// When using npm you can get samplers directly from @opentelemetry/core
import {AlwaysOnSampler, AlwaysOffSampler} from '@opentelemetry/core';
import SplunkOtelWeb from '@splunk/otel-web';

SplunkOtelWeb.init({
   beaconEndpoint: 'https://rum-ingest..signalfx.com/v1/rum',
   rumAccessToken: '<your_rum_token>',
   applicationName: '<application-name>',
   tracer: {
      sampler: userShouldBeTraced() ? new SplunkRum.AlwaysOnSampler() : new SplunkRum.AlwaysOffSampler(),
   },
});

The Splunk Distribution of OpenTelemetry JS for Web includes the following samplers:

Sampler

Description

AlwaysOnSampler

Sampling activated for all requests. This is the default sampler.

AlwaysOffSampler

Sampling deactivated for all requests.

ParentBasedSampler

Inherits the sampler configuration of the parent trace.

SessionBasedSampler

Session-based sampling. See Session-based sampler.

Session-based sampler

The Splunk Distribution of OpenTelemetry JS for Web includes a custom sampler that supports sessions. Session ratios are preferable to trace ratios, as they keep data from each session intact.

You can access the session-based sampler in the following ways:

  • Use the SplunkRum.SessionBasedSampler export when using the Splunk CDN build.

  • Use the SessionBasedSampler export when using the npm package.

The session-based sampler accepts the following settings:

Option

Type

Default value

Description

ratio

number

1.0

Percentage of sessions reported, ranging from 0.0 to 1.0.

sampled

Sampler

AlwaysOnSampler

Sampler to be used when the session is sampled.

notSampled

Sampler

AlwaysOffSampler

Sampler to be used when the session is not to be sampled.

The following example shows how to collect RUM data from half of the sessions:

CDN
<script src="https://cdn.signalfx.com/o11y-gdi-rum/latest/splunk-otel-web.js" crossorigin="anonymous"></script>
<script>
  SplunkRum.init({
    realm: '<realm>',
    rumAccessToken: '<your_rum_token>',
    applicationName: '<application-name>',
    tracer: {
      sampler: new SplunkRum.SessionBasedSampler({
      ratio: 0.5
      }),
    },
  });
</script>
npm
import SplunkOtelWeb, {SessionBasedSampler} from '@splunk/otel-web';

SplunkOtelWeb.init({
  realm: '<realm>',
  rumAccessToken: '<your_rum_token>',
  applicationName: '<application-name>',
  tracer: {
      sampler: new SessionBasedSampler({
        ratio: 0.5
      }),
  },
});

Context propagation settings

The Splunk RUM browser agent doesn’t register any context propagators, as it collects traceparent data from Server-Timing headers. If needed, you can register context propagators by using the OpenTelemetry API:

import {propagation} from '@opentelemetry/api';
import {B3Propagator} from '@opentelemetry/propagator-b3';

propagation.setGlobalPropagator(new B3Propagator());

When calling the OpenTelemetry API directly, make sure the API version you’re using matches the one used by the Splunk RUM browser agent.

Exporter settings

By default, the Splunk RUM browser agent uses the Zipkin exporter to send data to Splunk Observability Cloud.

Starting from version 0.17.0 and higher, you can configure the Splunk RUM browser agent to use the OTLP exporter. The following example shows how to configure the Splunk RUM browser to use the OTLP exporter:

   SplunkRum.init({
      realm: '<realm>',
      rumAccessToken: '<your_rum_token>',
      applicationName: '<application-name>',
      deploymentEnvironment: '<deployment-env>',
      exporter: {
         otlp: true
      },
   });

When setting the beaconEndpoint manually, use https://rum-ingest.<realm>.signalfx.com/v1/rumotlp as the OTLP endpoint. The endpoint is set automatically when exporter.otlp is true and a realm is configured.