Skip to content

Web Application Access


By collecting metrics data from web applications, application performance can be analyzed visually.

Prerequisites (Datakit Access)

Start Access

  1. Enter User Access Monitoring > Create Application > Web.
  2. Enter the application name.
  3. Enter the application ID.
  4. Select the application access method:

  5. Public DataWay: Directly receives RUM data without installing the DataKit collector.

  6. Local Environment Deployment: Receives RUM data after meeting the prerequisites.

Access Methods

  1. Ensure DataKit is installed and configured to be publicly accessible with the IP geolocation database installed.
  2. Obtain parameters such as applicationId, env, version from the console, then start accessing the application.
  3. When integrating the SDK, set datakitOrigin to the DataKit domain or IP.

  1. Obtain parameters such as applicationId, clientToken, site from the console, then start accessing the application.
  2. No need to configure datakitOrigin when integrating the SDK. Data will be sent to the public DataWay by default.

SDK Configuration

Access Method
Description
NPM Bundles the SDK code into the frontend project, ensuring frontend performance is not affected. May miss requests and errors before SDK initialization.
CDN Asynchronous Loading Asynchronously loads the SDK script via CDN, without affecting page load performance. May miss requests and errors before initialization.
CDN Synchronous Loading Synchronously loads the SDK script via CDN, enabling full collection of all errors and performance metrics. However, it may affect page load performance.

NPM Access

Install and import the SDK in the frontend project:

npm install @truewatchtech/browser-rum

Initialize the SDK in the project:

import { datafluxRum } from "@truewatchtech/browser-rum"
datafluxRum.init({
  applicationId: "<Application ID>",
  site: "http://172.16.212.186:9529",
  clientToken: "a993f53a8ea04bc6b9350e5e670a3a3b",
  env: "production",
  version: "1.0.0",
  service: "browser",
  sessionSampleRate: 100,
  sessionReplaySampleRate: 70,
  compressIntakeRequests: true,
  trackInteractions: true,
  traceType: "ddtrace", // Optional, defaults to ddtrace. Currently supports 6 types: ddtrace, zipkin, skywalking_v3, jaeger, zipkin_single_header, w3c_traceparent
  allowedTracingOrigins: ["https://api.example.com", /https:\/\/.*\.my-api-domain\.com/], // Optional, a list of all requests allowed to inject the header required by the trace collector. Can be the origin of the request or a regular expression.
})
datafluxRum.startSessionReplayRecording()

CDN Synchronous Loading

Add the script in the 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: "http://172.16.212.186:9529",
      clientToken: "a993f53a8ea04bc6b9350e5e670a3a3b",
      env: "production",
      version: "1.0.0",
      service: "browser",
      sessionSampleRate: 100,
      sessionReplaySampleRate: 70,
      compressIntakeRequests: true,
      trackInteractions: true,
      traceType: "ddtrace", // Optional, defaults to ddtrace. Currently supports 6 types: ddtrace, zipkin, skywalking_v3, jaeger, zipkin_single_header, w3c_traceparent
      allowedTracingOrigins: ["https://api.example.com", /https:\/\/.*\.my-api-domain\.com/], // Optional, a list of all requests allowed to inject the header required by the trace collector. Can be the origin of the request or a regular expression.
    })
  window.DATAFLUX_RUM && window.DATAFLUX_RUM.startSessionReplayRecording()
</script>

CDN Asynchronous Loading

Add the script in the 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: "http://172.16.212.186:9529",
      clientToken: "a993f53a8ea04bc6b9350e5e670a3a3b",
      env: "production",
      version: "1.0.0",
      service: "browser",
      sessionSampleRate: 100,
      sessionReplaySampleRate: 70,
      compressIntakeRequests: true,
      trackInteractions: true,
      traceType: "ddtrace", // Optional, defaults to ddtrace. Currently supports 6 types: ddtrace, zipkin, skywalking_v3, jaeger, zipkin_single_header, w3c_traceparent
      allowedTracingOrigins: ["https://api.example.com", /https:\/\/.*\.my-api-domain\.com/], // Optional, a list of all requests allowed to inject the header required by the trace collector. Can be the origin of the request or a regular expression.
    })
    window.DATAFLUX_RUM && window.DATAFLUX_RUM.startSessionReplayRecording()
  })
</script>

Parameter Configuration

Initialization Parameters

Parameter
Type
Required
Default
Description
applicationId String Yes The application ID created from TrueWatch.
datakitOrigin String Yes DataKit data reporting origin note:
Protocol (including //), domain (or IP address) [and port number]
For example:
https://www.datakit.com;
http://100.20.34.3:8088.
clientToken String Yes The data reporting token in openway mode, obtained from the TrueWatch console. Required (public openway access).
site String Yes The data reporting address in public openway mode, obtained from the TrueWatch console. Required (public openway access).
env String No The current environment of the web application, e.g., 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, customizable.
sessionSampleRate Number No 100 Percentage of metrics data collection:
100 means full collection; 0 means no collection.
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, it will be collected at this rate. Such sessions will start recording events when the error occurs and continue until the session ends. SDK version requirement >= 3.2.19.
sessionReplaySampleRate Number No 100 Session Replay data collection percentage:
100 means full collection; 0 means no collection.
sessionReplayOnErrorSampleRate Number No 0 Session Replay compensatory sampling rate for error session replay: when a session is not sampled by sessionReplaySampleRate, if an error occurs during the session, it will be collected at this rate. Such replays will record events up to one minute before the error and continue until the session ends. SDK version requirement >= 3.2.19.
trackSessionAcrossSubdomains Boolean No false Share cache across subdomains of the same domain.
usePartitionedCrossSiteSessionCookie Boolean No false Enable partitioned secure cross-site session cookies details.
useSecureSessionCookie Boolean No false Use secure session cookies. This will disable RUM events sent over insecure (non-HTTPS) connections.
traceType Enum No ddtrace Configure the trace tool type. If not configured, defaults to ddtrace. Currently supports 6 data types: ddtrace, zipkin, skywalking_v3, jaeger, zipkin_single_header, w3c_traceparent.

❗️
1. opentelemetry supports 4 types: zipkin_single_header, w3c_traceparent, zipkin, jaeger.
2. This configuration depends on the allowedTracingOrigins configuration item.
3. Configuring the corresponding traceType requires the corresponding API service. For setting different Access-Control-Allow-Headers, refer to How APM associates with RUM.
traceId128Bit Boolean No false Whether to generate traceID in 128 bytes. Corresponds to traceType. Currently supports types zipkin, jaeger.
allowedTracingOrigins Array No [] A list of all requests allowed to inject the header required by the trace collector. Can be the origin of the request or a regular expression. Origin: Protocol (including //), domain (or IP address) [and port number]. _For example:
["https://api.example.com", /https:\\/\\/._\\.my-api-domain\\.com/]. *
allowedTracingUrls Array No [] A list of URL matching patterns for requests associated with Apm. Can be the request URL, a regular expression, or a match function. For example: ["https://api.example.com/xxx", /https:\/\/.*\.my-api-domain\.com\/xxx/, function(url) {if (url === 'xxx') { return false} else { return true }}]. This parameter is an extension of the allowedTracingOrigins configuration. Either one can be configured.
trackUserInteractions Boolean No false Enable user interaction collection.
trackViewsManually Boolean No false Disable automatic View tracking by the SDK and manually start View using startView(). The framework Router plugin will automatically manage this configuration. No need to set it again in the business. Details.
plugins Array No [] Register RUM framework plugins. Supports route View and framework error collection for React, Vue, Angular, Next.js, and Nuxt. SDK version requirement >= 3.3.6. Details.
enableExperimentalFeatures Array No [] Enable experimental features. Configure ["track_websockets"] to collect native WebSocket connection-level Resources. SDK version requirement >= 3.3.6. Details.
actionNameAttribute String No Version requirement: >3.1.2. Specify the action name by adding a custom attribute to the element. For details, refer to.
beforeSend Function(event, context):Boolean No Version requirement: >3.1.2. Data interception and modification. Details.
storeContextsToLocal Boolean No Version requirement: >3.1.2. Whether to cache user-defined custom data to local storage, such as custom data added via setUser, addGlobalContext APIs.
storeContextsKey String No Version requirement: >3.1.18. Define the key for storing in local storage. If not filled, automatically generated. This parameter is mainly used to distinguish the issue of shared store across different sub-paths under the same domain.
compressIntakeRequests Boolean No Compress RUM data request content to reduce bandwidth usage when sending large amounts of data, and also reduce the number of sent requests. Compression is done in a Web Worker thread. For CSP security policies, refer to CSP security. SDK version requirement >= 3.2.0. Datakit version requirement >= 1.60. Deployment plan requirement >= 1.96.178.
workerUrl String No Session replay and compressIntakeRequests data compression are both done in a Web Worker thread. Therefore, by default, when CSP security access is enabled, worker-src blob:; must be allowed. This configuration allows adding a self-hosted worker address. For CSP security policies, refer to CSP security. SDK version requirement >= 3.2.0.
remoteConfiguration Boolean No Enable remote configuration for data collection. Disabled by default. The remote configuration feature allows dynamically modifying data collection configuration items without releasing a new version. For example, the sampling rate or whether to enable user interaction collection can be modified remotely. The remote configuration feature requires enabling environment variable settings in the TrueWatch console. SDK version requirement >= 3.2.20. Datakit version requirement >= 1.60. How to enable the environment variable feature in the TrueWatch console.
replayCanvasWorkerUrl string No Canvas snapshot encoding dedicated worker URL, does not replace workerUrl. This configuration allows adding a self-hosted worker address. For CSP security policies, refer to CSP security. SDK version requirement >= 3.3.0.
replayCanvasEnabled boolean No false Enable canvas recording. If disabled, canvas will not be collected. SDK version requirement >= 3.3.0.
replayCanvasMode 'manual' \| 'auto' No auto Canvas recording mode. manual requires manually calling snapshotCanvas(canvas); auto is automatic recording.
replayCanvasSampling number \| 'all' No Only effective when replayCanvasMode: 'auto'.
If a number: automatic snapshot sampling. The smaller the value, the more frequent the sampling and the higher the encoding and reporting cost. It is recommended to start from 2.
If 'all': higher fidelity automatic recording, trying to preserve the drawing process. In complex scenarios, it may still automatically fall back to snapshot.
replayCanvasQuality 'low' \| 'medium' \| 'high' \| number No Canvas snapshot encoding quality.
silentMultipleInit boolean No Silently ignore repeated initialization.

site Parameter Handling

Node Name Address
International Zone 1 (Oregon) https://us1-openway.truewatch.com
European Zone 1 (Frankfurt) https://eu1-openway.truewatch.com
Asia Pacific Zone 1 (Singapore) https://ap1-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 will immediately end the current Session and restart 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:

datafluxRum.startSession({
  sessionSampleRate: 100,
})

The sampling rate must be between 0 and 100. This override value will be used for the current and subsequent auto-renewed Sessions. Both the full RUM package and the slim RUM package support this API. For detailed semantics and usage scenarios, see Restart Session at Runtime.

Use Cases

Collect Only Error Session Events

Prerequisite

SDK version requirement: 3.2.19 or above.

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

  • Continuous recording: From the moment the error is triggered, fully record the session lifecycle data.
  • Precise compensation: Ensure no error scenarios are missed through an independent sampling channel.

Configuration

<script
  src="https://static.truewatch.com/browser-sdk/v3/dataflux-rum.js"
  type="text/javascript"
></script>
<script>
// Core configuration initialization
window.DATAFLUX_RUM && window.DATAFLUX_RUM.init({

   ...
   // Precise collection strategy
   sessionSampleRate: 0,             // Disable regular session collection
   sessionOnErrorSampleRate: 100, // Full collection of error sessions

});

</script>

Data Compression

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

To address this situation, the following optimization measures can reduce the impact:

  • Delayed reporting: Use asynchronous mode or NPM access to delay the collection timing, avoiding excessive requests during the initialization phase.
  • Data compression: Use the zlib algorithm to compress the collected data before reporting, effectively reducing the request size and number.

Data compression is performed in a Web Worker, which will not block or affect the browser main thread performance.


Configuration Example

Enable compression by setting compressIntakeRequests: true in the initialization configuration:

<script
  src="https://static.truewatch.com/browser-sdk/v3/dataflux-rum.js"
  type="text/javascript"
></script>
<script>
  window.DATAFLUX_RUM && window.DATAFLUX_RUM.init({
    ...
    compressIntakeRequests: true, // Enable data compression
  });
</script>

Notes

  1. Data compression logic is executed in a Web Worker. If CSP security policy is enabled, worker-src must allow blob:;. For more information, refer to CSP Security Policy Description.
  2. The SDK supports specifying a self-hosted Worker address via the workerUrl configuration item.
  3. The SDK version for using this feature must be >= 3.2.

Custom Data Tags

Use the setGlobalContextProperty or setGlobalContext API to add custom tags to all RUM events.

// Use setGlobalContextProperty to add a single TAG
window.DATAFLUX_RUM && window.DATAFLUX_RUM.setGlobalContextProperty("userName", "Zhang San")

// Use setGlobalContext to add multiple TAGs
window.DATAFLUX_RUM &&
  window.DATAFLUX_RUM.setGlobalContext({
    userAge: 28,
    userGender: "Male",
  })

Track User Actions

Control Whether to Enable Action Collection

Control whether to collect user click behavior through the trackUserInteractions initialization parameter.

Custom Action Name

  • Customize the action name by adding the data-guance-action-name attribute or data-custom-name (depending on the actionNameAttribute configuration) to the clickable element.

Use the addAction API to Customize Actions

// CDN synchronous loading
window.DATAFLUX_RUM &&
  window.DATAFLUX_RUM.addAction("cart", {
    amount: 42,
    nb_items: 2,
    items: ["socks", "t-shirt"],
  })

// CDN asynchronous loading
window.DATAFLUX_RUM.onReady(function () {
  window.DATAFLUX_RUM.addAction("cart", {
    amount: 42,
    nb_items: 2,
    items: ["socks", "t-shirt"],
  })
})

// NPM
import { datafluxRum } from "@truewatchtech/browser-rum"
datafluxRum &&
  datafluxRum.addAction("cart", {
    amount: 42,
    nb_items: 2,
    items: ["socks", "t-shirt"],
  })

Custom Error

Use the addError API to add custom Error metrics data Add Custom Error.

// CDN synchronous loading
const error = new Error("Something wrong occurred.")
window.DATAFLUX_RUM && DATAFLUX_RUM.addError(error, { pageStatus: "beta" })

// CDN asynchronous loading
window.DATAFLUX_RUM.onReady(function () {
  const error = new Error("Something wrong occurred.")
  window.DATAFLUX_RUM.addError(error, { pageStatus: "beta" })
})

// NPM
import { datafluxRum } from "@truewatchtech/browser-rum"
const error = new Error("Something wrong occurred.")
datafluxRum.addError(error, { pageStatus: "beta" })

Custom User Identity

Use the setUser API to add identity attributes (such as ID, name, email) for the current user Add Custom User Information.

// CDN synchronous loading
window.DATAFLUX_RUM &&
  window.DATAFLUX_RUM.setUser({
    id: "1234",
    name: "John Doe",
    email: "john@doe.com",
  })

// CDN asynchronous loading
window.DATAFLUX_RUM.onReady(function () {
  window.DATAFLUX_RUM.setUser({ id: "1234", name: "John Doe", email: "john@doe.com" })
})

// NPM
import { datafluxRum } from "@truewatchtech/browser-rum"
datafluxRum.setUser({ id: "1234", name: "John Doe", email: "john@doe.com" })

Web Session Replay

Prerequisite

Ensure the SDK version you are using supports the session replay feature (usually version > 3.0.0).

Enable Recording

After SDK initialization, call the startSessionReplayRecording() method to enable session replay recording. You can choose to enable it under specific conditions, such as after user login Enable Session Recording.

Prerequisite

SDK version requirement: 3.2.19 or above.

When an error occurs on the page, the SDK will automatically perform the following:

  • Retrospective collection: Record a complete page snapshot from 1 minute before the error.
  • Continuous recording: Continue recording from the moment the error occurs until the session ends.
  • Intelligent compensation: Ensure no error scenarios are missed through an independent sampling channel.

Configuration Example

<script
  src="https://static.truewatch.com/browser-sdk/v3/dataflux-rum.js"
  type="text/javascript"
></script>
<script>
// Initialize SDK core configuration
window.DATAFLUX_RUM && window.DATAFLUX_RUM.init({
   ....

   // Sampling strategy configuration
   sessionSampleRate: 100,          // Full basic session collection (100%)
   sessionReplaySampleRate: 0,       // Disable regular screen recording sampling
   sessionReplayOnErrorSampleRate: 100, // 100% sampling for error scenarios

});

// Force enable the screen recording engine (must be called)
window.DATAFLUX_RUM && window.DATAFLUX_RUM.startSessionReplayRecording();
</script>

Notes

  • Session replay does not cover the playback of iframes, videos, audio, and canvas elements.
  • To ensure static resources (such as fonts, images) can be accessed normally during replay, CORS policies may need to be configured.
  • Ensure CSS rules can be accessed via the CSSStyleSheet interface to support CSS styles and mouse hover events.

Debugging and Optimization

  • Use the SDK's built-in logging and monitoring tools for debugging and improving application performance.
  • Adjust the sessionSampleRate and sessionReplaySampleRate parameters according to business needs.