Skip to content

Web Application Integration


Collect metrics data from web applications to analyze application performance visually.

Prerequisites (DataKit Integration)

Start Integration

  1. Navigate to RUM > Create Application > Web.
  2. Enter the application name.
  3. Enter the application ID.
  4. Select the application integration method:

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

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

Integration Methods

  1. Ensure DataKit is installed and configured to be publicly accessible and install the IP Geolocation Database.
  2. Obtain parameters such as applicationId, env, version from the console, and start integrating the application.
  3. When integrating the SDK, set datakitOrigin to the domain name or IP of DataKit.

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

SDK Configuration

Integration Method
Description
NPM Bundles the SDK code into the frontend project, ensuring frontend performance is unaffected. May miss requests and error collection before SDK initialization.
CDN Asynchronous Loading Asynchronously introduces the SDK script via CDN, without affecting page loading performance. May miss requests and error collection before initialization.
CDN Synchronous Loading Synchronously introduces the SDK script via CDN, enabling complete collection of all errors and performance metrics. However, it may affect page loading performance.

NPM Integration

Install and import the SDK in your frontend project:

npm install @cloudcare/browser-rum

Initialize the SDK in your project:

import { datafluxRum } from "@cloudcare/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, list of all requests allowed to inject headers required by the trace collector. Can be request origins or regular expressions.
})
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, list of all requests allowed to inject headers required by the trace collector. Can be request origins or regular expressions.
    })
  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, list of all requests allowed to inject headers required by the trace collector. Can be request origins or regular expressions.
    })
    window.DATAFLUX_RUM && window.DATAFLUX_RUM.startSessionReplayRecording()
  })
</script>

Parameter Configuration

Initialization Parameters

Parameter
Type
Required
Default
Description
applicationId String Yes Application ID created from TrueWatch.
datakitOrigin String Yes DataKit data reporting Origin Note:
Protocol (including ://), domain name (or IP address) [and port number]
For example:
https://www.datakit.com;
http://100.20.34.3:8088.
clientToken String Yes Token for reporting data via openway, obtained from the TrueWatch console, required (for public openway integration).
site String Yes Data reporting address via public openway, obtained from the TrueWatch console, required (for public openway integration).
env String No Current environment of the web application, e.g., prod: production environment; gray: gray environment; pre: pre-release environment; common: daily environment; local: local environment.
version String No Version number of the web application.
service String No Service name of the current application, defaults to browser, supports custom configuration.
sessionSampleRate Number No 100 Percentage of metric data collection:
100 means full collection; 0 means no collection.
sessionOnErrorSampleRate Number No 0 Error session compensation sampling rate: When a session is not sampled by sessionSampleRate, if an error occurs during the session, it is 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 error session replay compensation sampling rate: When a session is not sampled by sessionReplaySampleRate, if an error occurs during the session, it is collected at this rate. Such replays will record up to one minute of events before the error occurs and continue until the session ends. SDK version requirement >= 3.2.19.
trackSessionAcrossSubdomains Boolean No false Share cache across subdomains under the same domain.
usePartitionedCrossSiteSessionCookie Boolean No false Whether to 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 type of tracing tool. 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 takes effect depending on the allowedTracingOrigins configuration item.
3. Configuring the corresponding traceType requires corresponding API services. For setting different Access-Control-Allow-Headers, refer to How APM Associates with RUM.
traceId128Bit Boolean No false Whether to generate traceID in 128-byte format, corresponding to traceType. Currently supports types zipkin, jaeger.
allowedTracingOrigins Array No [] List of all requests allowed to inject headers required by the trace collector. Can be request origins or regular expressions. Origin: Protocol (including ://), domain name (or IP address) [and port number]. _For example:
["https://api.example.com", /https:\\/\\/._\\.my-api-domain\\.com/].*
allowedTracingUrls Array No [] URL matching list for requests associated with Apm. Can be request URLs, regular expressions, or match functions. 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; configuring either one is sufficient.
trackUserInteractions Boolean No false Whether to enable user interaction collection.
actionNameAttribute String No Version requirement: >3.1.2. Add custom attributes to elements to specify action names. For specific usage, refer to details.
beforeSend Function(event, context):Boolean No Version requirement: >3.1.2. Data interception and modification, refer to details.
storeContextsToLocal Boolean No Version requirement: >3.1.2. Whether to cache user-defined data to local localstorage, e.g., custom data added by APIs like setUser, addGlobalContext.
storeContextsKey String No Version requirement: >3.1.18. Define the key for storage in localstorage. Default is empty, automatically generated. This parameter is mainly to distinguish shared store issues under the same domain with different subpaths.
compressIntakeRequests Boolean No Compress RUM data request content to reduce bandwidth usage when sending large amounts of data, while also reducing the number of data sending requests. Compression is completed in the WebWorker thread. For CSP security policy, refer to CSP security. SDK version requirement >= 3.2.0. DataKit version requirement >=1.60. Deployment version requirement >= 1.96.178.
workerUrl Sring No Both sessionReplay and compressIntakeRequests data compression are completed in the webwork thread. Therefore, by default, when CSP security access is enabled, worker-src blob:; needs to be allowed. This configuration allows adding a self-hosted worker address. For CSP security policy, refer to CSP security. SDK version requirement >= 3.2.0.
remoteConfiguration Boolean No Whether to enable the remote configuration function for data collection, not enabled by default. The remote configuration function allows dynamic modification of data collection configuration items without releasing a new version. For example, sampling rates, whether to enable user interaction collection, etc., can be modified in remote configuration. The remote configuration function needs to be enabled in the TrueWatch console environment variable settings. SDK version requirement >= 3.2.20. DataKit version requirement >=1.60. How to enable environment variable function in TrueWatch console.
replayCanvasWorkerUrl string No Dedicated worker address for canvas snapshot encoding, does not replace workerUrl. This configuration allows adding a self-hosted worker address. For CSP security policy, refer to CSP security. SDK version requirement >= 3.3.0.
replayCanvasEnabled boolean No false Whether to enable canvas recording. If not enabled, 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'.
Fill with number: Uses automatic snapshot sampling. Smaller values mean more frequent sampling, with higher encoding and reporting costs; recommended to start from 2.
Fill with 'all': Uses automatic recording with higher fidelity, trying to preserve the drawing process; may still automatically fall back to snapshot in complex scenarios.
replayCanvasQuality 'low' \| 'medium' \| 'high' \| number No Canvas snapshot encoding quality.
silentMultipleInit boolean No Whether to silently ignore duplicate initialization.

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
Africa Zone 1 (South Africa) https://za1-openway.truewatch.com
Indonesia Zone 1 (Jakarta) https://id1-openway.truewatch.com

Use Cases

Collect Only Error Session Events

Prerequisite

SDK version requirement: 3.2.19 or higher.

When a page triggers an error, the SDK will automatically execute:

  • Continuous Recording: Records the full lifecycle data of the session from the moment the error is triggered.
  • Precise Compensation: Ensures 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>
// Core configuration initialization
window.DATAFLUX_RUM && window.DATAFLUX_RUM.init({

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

});

</script>

Data Compression

When collecting a large number of static resources (e.g., JS, CSS, images) and enabling full collection, the SDK may generate a significant amount of data after initialization, causing request backlog and potentially impacting the application thread state.

To mitigate this, the following optimization measures can be taken:

  • Delayed Reporting: Delay the collection timing through asynchronous methods or NPM integration to avoid generating too many requests during the initialization phase.
  • Data Compression: Use the zlib algorithm to compress collected data before reporting, effectively reducing request volume and count.

Data compression operations are performed in a Web Worker and will not block or affect browser main thread performance.


Configuration Example

Enable compressIntakeRequests: true in the initialization configuration to enable compression:

<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, blob:; needs to be allowed in worker-src. For more information, refer to CSP Security Policy Explanation.
  2. The SDK supports specifying a self-hosted Worker address via the workerUrl configuration item.
  3. SDK version >= 3.2 is required to use this feature.

Custom Adding 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",
  })

Tracking User Actions

Control Whether to Enable Action Collection

Control whether to collect user click behavior via 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 actionNameAttribute configuration) to clickable elements.

Use 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 "@cloudcare/browser-rum"
datafluxRum &&
  datafluxRum.addAction("cart", {
    amount: 42,
    nb_items: 2,
    items: ["socks", "t-shirt"],
  })

Custom Adding Errors

Use the addError API to custom add Error metric 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 "@cloudcare/browser-rum"
const error = new Error("Something wrong occurred.")
datafluxRum.addError(error, { pageStatus: "beta" })

Custom User Identification

Use the setUser API to add identification attributes (e.g., 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 "@cloudcare/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 (typically version > 3.0.0).

Start Recording

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

Prerequisite

SDK version requirement: 3.2.19 or higher.

When a page error occurs, the SDK will automatically perform the following operations:

  • Retrospective Collection: Records a complete page snapshot from up to 1 minute before the error.
  • Continuous Recording: Continuously records from the moment the error occurs until the session ends.
  • Intelligent Compensation: Ensures 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 baseline session collection (100%)
   sessionReplaySampleRate: 0,       // Disable regular screen recording sampling
   sessionReplayOnErrorSampleRate: 100, // 100% sampling for error scenarios

});

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

Notes

  • The session replay feature does not cover playback of iframes, videos, audio, and canvas elements.
  • To ensure static resources (e.g., fonts, images) are accessible during replay, CORS policy configuration may be required.
  • Ensure CSS rules are accessible via the CSSStyleSheet interface to support CSS styles and mouse hover events.

Debugging and Optimization

  • Utilize the logs and monitoring tools provided by the SDK for debugging to improve application performance.
  • Adjust the sessionSampleRate and sessionReplaySampleRate parameters according to business needs.