Skip to content

Web Application Integration


After completing the configuration on this page, the Browser RUM SDK automatically collects page Views, resource requests, front-end errors, and user actions, and reports the data to TrueWatch.

Choose an Integration Path

First select an entry point based on the application type to avoid configuring Views repeatedly or accessing browser APIs during server-side rendering.

Application Type Recommended Entry Point Description
Uses build tools such as Webpack, Vite, or Rollup NPM Integration Recommended for version pinning and on-demand integration
No frontend build process CDN Asynchronous Loading Does not block page parsing, but may miss requests and errors that occur before initialization
Must capture errors and requests from the earliest stage of the page CDN Synchronous Loading Initializes as early as possible, but consumes page load time
Only needs basic RUM and cares about frontend bundle size Slim RUM SDK Keeps standard RUM collection, without Session Replay or intake compression
React, Vue, or Angular single-page applications Frontend Framework Plugin Integration Automatically manages Router Views and framework errors
Next.js, Nuxt Integration with SSR Frameworks Distinguishes server-side and browser environments to avoid duplicate Views
Electron Electron Application Integration Initialize only in the renderer process

Prepare Integration Information

  1. Go to RUM > Application List > Create Application > Web.
  2. Create an application and obtain the console-generated configuration, such as applicationId, env, and version.
  3. Choose a data reporting method:

  4. Public OpenWay: Obtain site and clientToken; no DataKit deployment is required.

  5. DataKit Direct Connection: Prepare datakitOrigin; DataKit must have the RUM collector enabled and be configured to be publicly accessible and have the IP geolocation database installed.
Do not configure both reporting methods at the same time

Public OpenWay uses site and clientToken; DataKit Direct Connection uses datakitOrigin. Keep only the fields required by your current integration method.

Reporting Methods

{
  applicationId: "<APPLICATION_ID>",
  datakitOrigin: "<DATAKIT_ORIGIN>"
}

{
  applicationId: "<APPLICATION_ID>",
  site: "<PUBLIC_OPENWAY_URL>",
  clientToken: "<CLIENT_TOKEN>"
}

Integrate the SDK

Integration Method
Description
NPM Bundles the SDK code into the frontend project, making it easy to pin versions. May miss requests and errors that occur before SDK initialization.
CDN Asynchronous Loading Loads the SDK script asynchronously via a CDN without affecting page load performance. May miss requests and errors that occur before initialization.
CDN Synchronous Loading Loads the SDK script synchronously via a CDN to completely capture all errors and performance metrics. May affect page load performance.

NPM Integration

Install and import the SDK in your frontend project:

npm install @truewatchtech/browser-rum @truewatchtech/browser-core

Initialize the SDK in your project:

import { datafluxRum } from "@truewatchtech/browser-rum"

datafluxRum.init({
  applicationId: "<APPLICATION_ID>",
  site: "<PUBLIC_OPENWAY_URL>",
  clientToken: "<CLIENT_TOKEN>",
  service: "web-app",
  env: "production",
  version: "1.0.0",
  sessionSampleRate: 100,
  trackUserInteractions: true
})

CDN Synchronous Loading

Add the script to your HTML file:

<script
  src="https://static.truewatch.com/browser-sdk/v3/dataflux-rum.js"
  type="text/javascript"
></script>
<script>
  window.DATAFLUX_RUM &&
    window.DATAFLUX_RUM.init({
      applicationId: "<APPLICATION_ID>",
      site: "<PUBLIC_OPENWAY_URL>",
      clientToken: "<CLIENT_TOKEN>",
      service: "web-app",
      env: "production",
      version: "1.0.0",
      sessionSampleRate: 100,
      trackUserInteractions: true
    })
</script>

CDN Asynchronous Loading

Add the script to your HTML file:

<script>
  ;(function (h, o, u, n, d) {
    h = h[d] = h[d] || {
      q: [],
      onReady: function (c) {
        h.q.push(c)
      },
    }
    d = o.createElement(u)
    d.async = 1
    d.src = n
    n = o.getElementsByTagName(u)[0]
    n.parentNode.insertBefore(d, n)
  })(
    window,
    document,
    "script",
    "https://static.truewatch.com/browser-sdk/v3/dataflux-rum.js",
    "DATAFLUX_RUM"
  )
  DATAFLUX_RUM.onReady(function () {
    DATAFLUX_RUM.init({
      applicationId: "<APPLICATION_ID>",
      site: "<PUBLIC_OPENWAY_URL>",
      clientToken: "<CLIENT_TOKEN>",
      service: "web-app",
      env: "production",
      version: "1.0.0",
      sessionSampleRate: 100,
      trackUserInteractions: true
    })
  })
</script>

The examples above use Public OpenWay. When using DataKit Direct Connection, remove site and clientToken, and configure datakitOrigin instead.

Slim RUM SDK

Starting with RUM SDK 3.3.3, a slim version is available. The slim version uses the same initialization method as the full version and supports standard RUM capabilities such as View, Resource, Long Task, Error, Action, user and global Context, custom events, and distributed tracing. It is suitable for applications that do not need page recording and want to reduce frontend bundle size.

NPM Integration

Replace the standard RUM package with the slim package of the same version:

npm install @truewatchtech/browser-rum-slim @truewatchtech/browser-core
import { truewatchRum } from "@truewatchtech/browser-rum-slim"

truewatchRum.init({
  applicationId: "<APPLICATION_ID>",
  site: "<PUBLIC_OPENWAY_URL>",
  clientToken: "<CLIENT_TOKEN>",
  service: "web-app",
  env: "production",
  version: "1.0.0",
  sessionSampleRate: 100,
  trackUserInteractions: true
})

CDN Integration

The synchronous and asynchronous loading methods are the same as the full version; simply replace the script file name with the one for the slim version. The following is a synchronous loading example:

<script
  src="https://static.truewatch.com/browser-sdk/v3/dataflux-rum-slim.js"
  type="text/javascript"
></script>
<script>
  window.DATAFLUX_RUM &&
    window.DATAFLUX_RUM.init({
      applicationId: "<APPLICATION_ID>",
      site: "<PUBLIC_OPENWAY_URL>",
      clientToken: "<CLIENT_TOKEN>",
      service: "web-app",
      env: "production",
      version: "1.0.0",
      sessionSampleRate: 100,
      trackUserInteractions: true
    })
</script>

Capability Differences Compared with the Full Version

The slim version does not include the following capabilities:

  • Session Replay and recording APIs such as startSessionReplayRecording(), stopSessionReplayRecording(), and isRecording();
  • Canvas 2D, WebGL/WebGL2 recording, and Canvas APIs such as snapshotCanvas();
  • compressIntakeRequests intake compression and the corresponding Worker.

The slim version forces sessionReplaySampleRate, sessionReplayOnErrorSampleRate, and replayCanvasEnabled to be disabled, and forces compressIntakeRequests to false. Do not pass these options during integration, and you do not need to set workerUrl or replayCanvasWorkerUrl. If you later need session replay, Canvas recording, or compressed intake, switch the NPM package or CDN file back to the full version; the other basic initialization parameters can continue to be used.

Verify Integration

  1. Open a page that has the SDK integrated, and perform a page navigation, a button click, and an API request.
  2. In the Network tab of browser developer tools, filter for /v1/write/rum and confirm that a successful intake request exists.
  3. Check the Console and confirm there are no initialization errors such as Application ID is not configured or datakitOrigin or site is not configured.
  4. Go to RUM > Application List, open the corresponding Web application, filter by service, env, and version in the Explorer, and confirm that View, Resource, or Action data exists.
Seeing View data means the basic integration is successful

Error, Resource, and Action data appear only after the corresponding events actually occur on the page. If there is no data, first check whether the current Session was sampled by sessionSampleRate, then refer to the FAQ.

Common Optional Configurations

After confirming that the basic data is successful, enable additional capabilities as needed:

Goal Configuration or API Documentation
Correlate frontend and backend traces allowedTracingUrls, traceType Tracing Configuration
Rate-limit API requests by anonymous visitor visitorId, resetVisitorId() Visitor ID
Control sampling ratio sessionSampleRate, startSession() Sampling Configuration
Enable Session Replay startSessionReplayRecording() Web Session Replay
Automatically manage SPA Router Views plugins Frontend Framework Plugin Integration
Record WebGL/WebGL2 plugins, automatic Canvas recording Canvas Recording Manual
Identify logged-in users setUser() Custom User Identity
Add business fields or events Global Context, addAction(), addError() Custom Data and Events

Distributed Tracing Configuration (Optional)

When integrating with NPM + TypeScript, traceType must use the TraceType enum imported from the corresponding brand's browser-core package:

import { TraceType } from "@truewatchtech/browser-core"
import { datafluxRum } from "@truewatchtech/browser-rum"

datafluxRum.init({
  applicationId: "<APPLICATION_ID>",
  site: "<PUBLIC_OPENWAY_URL>",
  clientToken: "<CLIENT_TOKEN>",
  allowedTracingUrls: ["https://api.example.com"],
  traceType: TraceType.DDTRACE
})

The runtime value of TraceType.DDTRACE remains "ddtrace". CDN integration has no module imports, so use the corresponding runtime string when configuring it explicitly. After enabling distributed tracing, you also need to allow the corresponding Trace Header on the API server. For details, see How APM Correlates with RUM.

If a regular Session is not selected by sampling but you still need to pass the Trace Header to the backend, you can explicitly enable allowTraceHeaderWithoutSession:

datafluxRum.init({
  applicationId: "<APPLICATION_ID>",
  site: "<PUBLIC_OPENWAY_URL>",
  clientToken: "<CLIENT_TOKEN>",
  sessionSampleRate: 0,
  sessionOnErrorSampleRate: 0,
  allowedTracingUrls: ["https://api.example.com"],
  allowTraceHeaderWithoutSession: true
})

When enabled, the SDK still injects the Trace Header only into XHR and Fetch requests that match allowedTracingUrls. This option does not create or force-enable a RUM Session, nor does it report View, Error, Resource, or Action data for unsampled Sessions. The API server must still allow the request headers corresponding to the selected traceType; cross-origin requests also require correct CORS configuration.

Parameter Configuration

Initialization Parameters

Parameter
Type
Required
Default
Description
applicationId String Yes The application ID created in TrueWatch.
datakitOrigin String When using DataKit Direct Connection The DataKit intake URL. Format: protocol (including ://) + domain name or IP + optional port. For example, https://datakit.example.com.
clientToken String When using Public OpenWay The Public OpenWay intake token, obtained from the TrueWatch console.
site String When using Public OpenWay The Public OpenWay intake URL, obtained from the TrueWatch console.
env String No The current environment of the Web application. For example: prod: production environment; gray: canary environment; pre: pre-release environment; common: daily environment; local: local environment.
version String No The version number of the Web application.
service String No The service name of the current application. Defaults to browser and can be customized.
sessionSampleRate Number No 100 Percentage of sessions to collect:
100 means collect all; 0 means collect none.
sessionOnErrorSampleRate Number No 0 Compensatory sampling rate for error sessions: when a session is not sampled by sessionSampleRate, if an error occurs during the session, events are collected at this rate. Such sessions begin recording events when the error occurs and continue recording until the session ends. SDK version >= 3.2.19 is required.
sessionReplaySampleRate Number No 100 Session Replay data collection percentage:
100 means collect all; 0 means collect none.
sessionReplayOnErrorSampleRate Number No 0 Compensatory sampling rate for error-session replay: when a session is not sampled by sessionReplaySampleRate, if an error occurs during the session, it is replayed at this rate. Such replays record up to one minute of events before the error and continue recording until the session ends. SDK version >= 3.2.19 is required.
trackSessionAcrossSubdomains Boolean No false Subdomains under the same domain share the session cache.
usePartitionedCrossSiteSessionCookie Boolean No false Whether to enable partitioned secure cross-site session cookies. Details
useSecureSessionCookie Boolean No false Use a secure session cookie. This disables RUM events sent over insecure (non-HTTPS) connections.
traceType TraceType No TraceType.DDTRACE (runtime value: ddtrace) Configures the distributed tracing type. NPM integration uses the TraceType enum; CDN integration uses the corresponding runtime string. The following values are supported: DDTRACE (ddtrace), ZIPKIN_MULTI_HEADER (zipkin), ZIPKIN_SINGLE_HEADER (zipkin_single_header), W3C_TRACEPARENT (w3c_traceparent), W3C_TRACEPARENT_64 (w3c_traceparent_64bit), SKYWALKING_V3 (skywalking_v3), and JAEGER (jaeger).

❗️
1. OpenTelemetry supports 4 types: zipkin_single_header, w3c_traceparent, zipkin, and jaeger.
2. This option takes effect only when allowedTracingUrls is configured.
3. When configuring the corresponding type, you must set the appropriate Access-Control-Allow-Headers on the API service. For details, see How APM Correlates with RUM.
traceId128Bit Boolean No false Whether to generate traceID in 128-bit mode. Corresponds to traceType; currently supported by zipkin and jaeger.
allowedTracingUrls Array No [] List of URL matchers for requests allowed to have Trace Headers injected. Array items can be a full URL, a regular expression, a matching function, or an object containing match and traceType. For example: ["https://api.example.com/xxx", /https:\/\/.*\.my-api-domain\.com\/xxx/, (url) => url.includes("/api/")].
allowTraceHeaderWithoutSession Boolean No false Whether to still inject Trace Headers into XHR and Fetch requests that match allowedTracingUrls when the current RUM Session is not sampled. Enabling this does not create a Session or report RUM data for unsampled Sessions.
allowedTracingOrigins Array No [] Deprecated and retained only for compatibility with older configurations. Use allowedTracingUrls for new integrations; when both are configured, allowedTracingUrls overrides this option.
trackUserInteractions Boolean No false Whether to enable user interaction collection.
enablePrivacyForActionName Boolean No false Whether to make automatic Action names respect DOM privacy levels. When enabled, masked names use a fixed placeholder, and clicks on hidden elements do not generate automatic Actions; explicitly configured Action name attributes remain available. SDK version >= 3.3.14 is required. See Protecting Automatic Action Names.
trackViewsManually Boolean No false Whether to disable automatic Views in the SDK and have the application start Views manually by calling startView(). The framework Router plugin manages this option automatically, so you do not need to set it in your business code. See details
plugins Array No [] Registers RUM plugins and must be passed during init(). Framework plugins can collect Router Views and framework errors for React, Vue, Angular, Next.js, and Nuxt. SDK version >= 3.3.6 is required. See Frontend Framework Plugin Integration for details. WebGL Replay is available starting from SDK 3.3.7, requires RUM main package version >= 3.3.7, and the plugin should use the same SDK release version as the main package. See Canvas Recording Manual for details.
enableExperimentalFeatures Array No [] Enables experimental features. Configure ["track_websockets"] to collect native WebSocket connection-level Resources. SDK version >= 3.3.6 is required. See details
actionNameAttribute String No Version requirement: >3.1.2. Add custom attributes to elements to specify action names. For usage details, see Tracking User Actions.
beforeSend Function(event, context):Boolean No Version requirement: >3.1.2. Data interception and modification. See details
storeContextsToLocal Boolean No Version requirement: >3.1.2. Whether to cache user-defined data to local storage, for example, custom data added through the setUser and addGlobalContext APIs.
storeContextsKey String No Version requirement: >3.1.18. Defines the key stored in local storage. When left empty, it is generated automatically. This option is mainly used to differentiate stores shared by different subpaths under the same domain. For user identity and session boundary configuration, see Page Refresh and Local Storage.
compressIntakeRequests Boolean No Compresses the content of RUM intake requests to reduce bandwidth usage when sending large amounts of data and to reduce the number of requests sent. Compression is performed in a Web Worker thread. For CSP security policies, see CSP Security. SDK version >= 3.2.0 is required. DataKit version >= 1.60 is required. Deployment Plan requires >= 1.96.178.
workerUrl String No Session Replay and compressIntakeRequests data compression are both performed in Web Worker threads. Therefore, by default, when CSP security access is enabled, worker-src blob: must be allowed. This option allows you to set a self-hosted Worker address. For CSP security policies, see CSP Security. SDK version >= 3.2.0 is required.
remoteConfiguration Boolean No Whether to enable remote configuration for data collection. Disabled by default. Remote configuration allows you to dynamically modify data collection options without releasing a new version. For example, you can modify the sampling rate, whether user interaction collection is enabled, and so on through remote configuration. Remote configuration requires enabling environment variable settings in the TrueWatch console. SDK version >= 3.2.20 is required. DataKit version >= 1.60 is required. How to enable environment variables in the TrueWatch console
replayCanvasWorkerUrl String No Worker address dedicated to Canvas snapshot encoding. This does not replace workerUrl. This option allows you to set a self-hosted Worker address. For CSP security policies, see CSP Security. SDK version >= 3.3.0 is required.
replayCanvasEnabled Boolean No false Whether to enable Canvas recording. If disabled, Canvas content is not collected. SDK version >= 3.3.0 is required.
replayCanvasMode 'manual' \| 'auto' No auto Canvas recording mode. manual requires manually calling snapshotCanvas(canvas); auto records automatically.
replayCanvasSampling number \| 'all' No 2 Takes effect only when replayCanvasMode: 'auto' is set. A positive number selects the automatic snapshot path, and 2 is recommended as the starting value; the value itself does not control the Canvas 2D collection frequency. 'all' makes Canvas 2D attempt higher-fidelity command capture, although complex scenes may still fall back to snapshots; the WebGL plugin always uses budgeted pixel snapshots.
replayCanvasAutoInterval number No 250 Target interval between automatic snapshots for each Canvas, in milliseconds. Multiple Canvases are fairly rotated, and the actual pace is also constrained by cooldown, backoff, page visibility, and the global runtime budget.
replayCanvasQuality 'low' \| 'medium' \| 'high' \| number No 0.4 Canvas snapshot encoding quality. String presets also adjust sampling and the automatic scheduling budget; pass a number between 0 and 1 if you only want to change image quality.
replayCanvasAutoCooldown number No 250 Minimum cooldown time for automatic snapshots of the same Canvas, in milliseconds.
replayCanvasAutoUnchangedBackoff number No 3000 The interval, in milliseconds, before the next full encoding check when the lightweight signature remains unchanged; during this period, changes are still probed at a bounded, adaptive pace.
replayCanvasAutoFailureBackoff number No 5000 Backoff time after an automatic collection failure, in milliseconds.
replayCanvasAutoMaxPerRun number No 2 Maximum number of Canvases processed in a single automatic scheduling run.
replayCanvasFlushImmediately boolean No manual: true
auto: false
Whether to flush as a priority after Canvas frames successfully enter the replay.
silentMultipleInit boolean No Whether to silently ignore repeated initialization.

When the string presets low, medium, and high are not used, the Canvas automatic scheduling baseline is: sampling 2, target interval of 250 ms per Canvas, cooldown 250 ms, unchanged backoff 3000 ms, failure backoff 5000 ms, and a maximum of 2 Canvases per run. String presets replace all these budgets and the encoding quality at the same time; multiple Canvases are also subject to fair rotation and the global collection budget. Explicit per-option configuration overrides the corresponding preset value. See Canvas Recording Manual for the complete preset matrix.

The high-frequency scheduling baseline above applies to Canvas 2D. When the WebGL plugin does not have interval/cooldown configured explicitly, it continues to use a more conservative GPU readback pace; explicit per-option configuration overrides each value separately.

site Parameter Handling

Node Name Address
International Zone 1 (Oregon) https://us1-openway.truewatch.com
Europe Zone 1 (Frankfurt) https://eu1-openway.truewatch.com
Asia Pacific Zone 1 (Singapore) https://ap1-openway.truewatch.com
Asia Pacific Zone 2 (Singapore) https://ap2-openway.truewatch.com
Africa Zone 1 (South Africa) https://za1-openway.truewatch.com
Indonesia Zone 1 (Jakarta) https://id1-openway.truewatch.com

Runtime Session Control

RUM SDK 3.3.6 adds startSession(). Calling it immediately ends the current Session and starts a new Session according to the current sampling configuration, without waiting for the next user interaction:

datafluxRum.startSession()

You can also override the runtime sessionSampleRate at the same time:

datafluxRum.startSession({
  sessionSampleRate: 100,
})

The sampling rate must be between 0 and 100. This override value is used for the current and all subsequent automatically renewed Sessions. This API is supported by both the full RUM package and the slim RUM package. For detailed semantics and use cases, see Restarting a Session at Runtime.

Enable Advanced Capabilities as Needed

Collect Only Error Session Events

Version requirement

SDK version >= 3.2.19 is required.

When an error is triggered on the page, the SDK automatically performs the following:

  • Continuous recording: from the moment the error is triggered, records the full lifecycle data of the session.
  • Precise compensation: an independent sampling channel ensures error scenarios are not missed.

Configuration

window.DATAFLUX_RUM &&
  window.DATAFLUX_RUM.init({
    applicationId: "<APPLICATION_ID>",
    site: "<PUBLIC_OPENWAY_URL>",
    clientToken: "<CLIENT_TOKEN>",
    sessionSampleRate: 0,
    sessionOnErrorSampleRate: 100
  })

The example above uses Public OpenWay. When using DataKit Direct Connection, replace the intake URL fields according to the basic integration example.

Data Compression

When collecting a large number of static resources (such as JS, CSS, and images) with full collection enabled, the SDK may generate a large amount of data after initialization, causing a backlog of requests and even affecting the application thread state.

With compressIntakeRequests: true, the SDK compresses intake data using deflate in a Web Worker, reducing request size and the number of requests.

Configuration Example

window.DATAFLUX_RUM &&
  window.DATAFLUX_RUM.init({
    applicationId: "<APPLICATION_ID>",
    site: "<PUBLIC_OPENWAY_URL>",
    clientToken: "<CLIENT_TOKEN>",
    compressIntakeRequests: true
  })

Notes

  1. Data compression is performed in a Web Worker. If a CSP security policy is enabled, blob: must be allowed in worker-src. For more information, see CSP Security Policy.
  2. The SDK supports specifying a self-hosted Worker address through the workerUrl option.
  3. The SDK version required for this feature is >= 3.2.

Custom Data and Events

This basic integration page does not repeat all public APIs. Go to the corresponding pages based on your business objective to get CDN, NPM, and full parameter examples:

Web Session Replay

Prerequisite

Use the full RUM package, which includes Session Replay; the slim RUM package does not include session replay capability.

Enable Recording

After the SDK is initialized, call startSessionReplayRecording() to enable session replay recording. You can choose to enable it under specific conditions, such as starting session recording after a user logs in.

Version requirement

SDK version >= 3.2.19 is required.

When an error occurs on the page, the SDK automatically performs the following operations:

  • Retroactive collection: records a complete page snapshot from 1 minute before the error;
  • Continuous recording: continues recording from the moment the error occurs until the session ends;
  • Intelligent compensation: an independent sampling channel ensures error scenarios are not missed.

Configuration Example

window.DATAFLUX_RUM &&
  window.DATAFLUX_RUM.init({
    applicationId: "<APPLICATION_ID>",
    site: "<PUBLIC_OPENWAY_URL>",
    clientToken: "<CLIENT_TOKEN>",
    sessionSampleRate: 100,
    sessionReplaySampleRate: 0,
    sessionReplayOnErrorSampleRate: 100
  })

window.DATAFLUX_RUM && window.DATAFLUX_RUM.startSessionReplayRecording()

Notes

  • Session Replay does not record iframe, video, or audio playback content. Canvas is not collected by default and requires configuring replayCanvasEnabled separately. WebGL/WebGL2 is available starting from SDK 3.3.7, requires RUM main package version >= 3.3.7, and also requires installing and registering a compatible browser-rum-webgl plugin. It is recommended that the plugin and the main package use the same SDK release version. For details, see Canvas Recording Manual;
  • To ensure static resources (such as fonts and images) can be accessed normally during replay, you may need to configure CORS policies;
  • Ensure that CSS rules are accessible through the CSSStyleSheet interface to support CSS styles and mouse hover events.

Verify Recording Status

Call window.DATAFLUX_RUM.isRecording() to check whether the current page is recording, and confirm in the Session Replay Explorer that the corresponding Session has produced replay data. Then adjust sessionReplaySampleRate in production according to business requirements.