Web Application Setup¶
After completing the configuration on this page, the Browser RUM SDK automatically collects page Views, resource requests, frontend errors, and user actions, and reports the data to TrueWatch.
Choose an Integration Path¶
First, select the entry point based on the application type to avoid duplicate View configurations or accessing browser APIs during server-side rendering.
| Application Type | Recommended Entry | Description |
|---|---|---|
| Uses Webpack, Vite, Rollup, etc. | NPM Setup | Recommended for version management and on-demand bundling |
| No frontend build process | CDN Asynchronous Loading | Does not block page parsing, but may miss requests and errors before initialization |
| Must capture the earliest errors and requests on the page | CDN Synchronous Loading | Initializes as early as possible, but may impact page load time |
| Needs only basic RUM and cares about bundle size | Slim RUM SDK | Retains standard RUM collection, without Session Replay and upload compression |
| React, Vue, Angular SPA | Frontend Framework Plugin Setup | Automatically manages Router View and framework errors |
| Next.js, Nuxt | SSR Framework Setup | Distinguishes server and browser environments to avoid duplicate Views |
| Electron | Electron App Setup | Initialize only in the renderer process |
Prepare Integration Information¶
- Go to RUM > Application List > New Application > Web.
- Create an application and obtain the
applicationId,env,version, and other configurations generated by the console. -
Choose the data reporting method:
-
Public OpenWay: Obtain
siteandclientToken; no need to deploy DataKit. - DataKit Direct Connection: Prepare
datakitOrigin; DataKit must enable the RUM collector and be configured to be publicly accessible with 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 Method¶
Integrate the SDK¶
Integration Method |
Description |
|---|---|
| NPM | Bundles the SDK code into the frontend project for version locking. May miss requests and errors before SDK initialization. |
| CDN Asynchronous Loading | Asynchronously loads the SDK script via CDN, does not affect page load performance. May miss requests and errors before initialization. |
| CDN Synchronous Loading | Synchronously loads the SDK script via CDN, capable of capturing all errors and performance metrics. May impact page load performance. |
NPM Setup¶
Install and import the SDK in the frontend project:
Initialize the SDK in the 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 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: "<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 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: "<PUBLIC_OPENWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
service: "web-app",
env: "production",
version: "1.0.0",
sessionSampleRate: 100,
trackUserInteractions: true
})
})
</script>
The examples above use the Public OpenWay. For DataKit direct connection, remove site and clientToken and configure datakitOrigin instead.
Slim RUM SDK¶
The Slim RUM SDK is available starting from SDK version 3.3.3. It 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 Setup¶
Replace the standard RUM package with the slim package of the same version:
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 Setup¶
The synchronous or asynchronous loading method is the same as the full version; just replace the script file name with the slim version. Below is a synchronous loading example:
<script
src="https://static.truewatch.com/browser-sdk/v3/truewatch-rum-slim.js"
type="text/javascript"
></script>
<script>
window.TRUEWATCH_RUM &&
window.TRUEWATCH_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 from the Full Version¶
The slim version does not include the following capabilities:
- Session Replay, and the recording APIs
startSessionReplayRecording(),stopSessionReplayRecording(),isRecording(); - Canvas 2D, WebGL/WebGL2 recording, and Canvas APIs such as
snapshotCanvas(); compressIntakeRequestsupload compression and its associated Worker.
The slim version forces sessionReplaySampleRate, sessionReplayOnErrorSampleRate, and replayCanvasEnabled to be disabled, and forces compressIntakeRequests to false. Do not pass these configurations during integration, and do not set workerUrl or replayCanvasWorkerUrl. If you later need session replay, Canvas recording, or compressed upload, switch the NPM package or CDN file back to the full version; other basic initialization parameters can be reused.
Verify Integration¶
- Open a page that has integrated the SDK and perform a page navigation, a button click, and an API request.
- In the browser developer tools Network tab, filter for
/v1/write/rumand confirm successful reporting requests. - Check the Console for initialization errors such as
Application ID is not configuredordatakitOrigin or site is not configured. - Go to RUM > Application List, open the corresponding Web application, filter by
service,env, andversionin the Explorer, and confirm that View, Resource, or Action data exists.
Seeing View data indicates basic integration is successful
Error, Resource, and Action data appear only after the corresponding events actually occur on the page. If no data is present, first check whether the current session falls within sessionSampleRate, then refer to the FAQ.
Common Optional Configurations¶
After basic data is confirmed successful, enable other capabilities as needed:
| Goal | Configuration or API | Documentation |
|---|---|---|
| Correlate frontend and backend traces | allowedTracingUrls, traceType |
Tracing Configuration |
| Control collection sampling | sessionSampleRate, startSession() |
Sampling Configuration |
| Enable Session Replay | startSessionReplayRecording() |
Web Session Replay |
| Automatically manage SPA Router View | plugins |
Frontend Framework Plugin Setup |
| Record WebGL/WebGL2 | plugins, Canvas auto recording |
Canvas Recording Manual |
| Identify logged-in users | setUser() |
Custom User Identification |
| Add business fields or events | Global Context, addAction(), addError() |
Custom Data and Events |
Tracing Configuration (Optional)¶
When using 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 is still "ddtrace". CDN integration does not have module imports; use the corresponding runtime string when explicitly configuring. After enabling tracing, you also need to allow the corresponding Trace Header on the API server side. For details, refer to How APM Correlates with RUM.
If a regular session is not sampled 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 Trace Headers only for XHR and Fetch requests that match allowedTracingUrls. This configuration does not create or force-enable a RUM Session, nor does it report View, Error, Resource, or Action data for unsampled sessions. The API service must still allow the request headers corresponding to the selected traceType; cross-origin requests also require proper CORS configuration.
Parameter Configuration¶
Initialization Parameters¶
| Parameter | Type |
Required |
Default |
Description |
|---|---|---|---|---|
applicationId |
String | Yes | The application ID created from TrueWatch. | |
datakitOrigin |
String | Required for DataKit direct connection | DataKit data reporting address, format: protocol (including ://) + domain or IP + optional port, e.g., https://datakit.example.com. |
|
clientToken |
String | Required for Public OpenWay | Public OpenWay data reporting token, obtained from the TrueWatch console. | |
site |
String | Required for Public OpenWay | Public OpenWay data reporting URL, obtained from the TrueWatch console. | |
env |
String | No | The current environment of the Web application, e.g., prod: production; gray: canary; pre: pre-release; common: daily; local: local. | |
version |
String | No | The version number of the Web application. | |
service |
String | No | The service name of the current application, defaults to browser, supports custom configuration. |
|
sessionSampleRate |
Number | No | 100 |
Percentage of data collection: 100 means full collection; 0 means no collection. |
sessionOnErrorSampleRate |
Number | No | 0 |
Compensation sampling rate for error sessions: when a session is not sampled by sessionSampleRate, if an error occurs during the session, it is collected at this rate. Such sessions 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 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 the session cache across subdomains of the same domain. |
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 sending RUM events over insecure (non-HTTPS) connections. |
traceType |
TraceType |
No | TraceType.DDTRACE (runtime value ddtrace) |
Configures the tracing tool type. NPM integration uses the TraceType enum; CDN integration uses the corresponding runtime string. Currently supports 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 zipkin_single_header, w3c_traceparent, zipkin, and jaeger.2. This configuration depends on allowedTracingUrls.3. When configuring the corresponding type, the API service must set the appropriate Access-Control-Allow-Headers. For details, refer to How APM Correlates with RUM. |
traceId128Bit |
Boolean | No | false |
Whether to generate traceID in 128-bit mode, corresponding to traceType. Currently supports zipkin and jaeger. |
allowedTracingUrls |
Array | No | [] |
List of request URL matchers allowed to inject Trace Headers. Array items can be full URLs, regular expressions, matching functions, or objects containing match and traceType. 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 RUM Session is not sampled. Enabling this does not create a Session or report RUM data for unsampled sessions. |
allowedTracingOrigins |
Array | No | [] |
Deprecated, kept only for backward compatibility. For new integrations, use allowedTracingUrls. When both are configured, allowedTracingUrls overrides this configuration. |
trackUserInteractions |
Boolean | No | false |
Whether to enable user action collection. |
trackViewsManually |
Boolean | No | false |
Whether to disable automatic View tracking and let the application call startView() to manually start a View. Framework Router plugins manage this configuration automatically; business applications do not need to set it. Details |
plugins |
Array | No | [] |
Register RUM plugins, must be passed during init(). Framework plugins can collect Router Views and framework errors for React, Vue, Angular, Next.js, and Nuxt. SDK version requirement >= 3.3.6. For details, see Frontend Framework Plugin Setup. WebGL Replay is available from SDK 3.3.7, requires RUM main package version >= 3.3.7, and recommends using the same SDK release version for the plugin and the main package. For details, see Canvas Recording Manual. |
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. Add a custom attribute to elements to specify the action name. For usage details, see Tracking User Actions. |
|
beforeSend |
Function(event, context):Boolean | No | Version requirement: >3.1.2. Intercept and modify data. Details |
|
storeContextsToLocal |
Boolean | No | Version requirement: >3.1.2. Whether to cache user custom data to local storage, e.g., data added via setUser, addGlobalContext APIs. |
|
storeContextsKey |
String | No | Version requirement: >3.1.18. Define the key for storing data in local storage. Default is auto-generated if not set. This parameter is primarily used to distinguish sharing of the 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 reduce the number of request packets. Compression is performed in a Web Worker. 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 performed in Web Worker threads. By default, when CSP security is enabled, worker-src blob:; must be allowed. This configuration allows specifying a self-hosted worker URL. For CSP security policies, refer to CSP Security. SDK version requirement >= 3.2.0. |
|
remoteConfiguration |
Boolean | No | Whether to enable remote configuration for data collection. Default is disabled. Remote configuration allows dynamically modifying data collection parameters without releasing a new version. For example, you can modify the sampling rate or enable/disable user action collection remotely. Remote configuration requires enabling environment variable settings in the TrueWatch console. SDK version requirement >= 3.2.20. DataKit version requirement >= 1.60. How to enable environment variables in the TrueWatch console. |
|
replayCanvasWorkerUrl |
string |
No | Canvas snapshot encoding dedicated worker URL, does not replace workerUrl. This configuration allows specifying a self-hosted worker URL. For CSP security policies, refer to CSP Security. SDK version requirement >= 3.3.0. |
|
replayCanvasEnabled |
boolean |
No | false |
Whether to enable Canvas recording. If disabled, Canvas will not be captured. SDK version requirement >= 3.3.0. |
replayCanvasMode |
'manual' \| 'auto' |
No | auto |
Canvas recording mode. manual requires manually calling snapshotCanvas(canvas); auto enables automatic recording. |
replayCanvasSampling |
number \| 'all' |
No | 2 |
Only takes effect when replayCanvasMode: 'auto'. A positive number selects the automatic snapshot path; it is recommended to start from 2. The value itself does not control the collection frequency of Canvas 2D. 'all' makes Canvas 2D attempt higher fidelity command capture, but complex scenes may still fall back to snapshot. The WebGL plugin always uses budgeted pixel snapshots. |
replayCanvasAutoInterval |
number |
No | 250 |
Target interval for automatic snapshot of each Canvas, in milliseconds. Multiple Canvases are fairly rotated, but the actual pace is also limited by cooldown, backoff, page visibility, and global runtime budget. |
replayCanvasQuality |
'low' \| 'medium' \| 'high' \| number |
No | 0.4 |
Canvas snapshot encoding quality. String presets also adjust sampling and auto-scheduling budget. To only change image quality, pass a number between 0 and 1. |
replayCanvasAutoCooldown |
number |
No | 250 |
Minimum cooldown time for automatic snapshot of the same Canvas, in milliseconds. |
replayCanvasAutoUnchangedBackoff |
number |
No | 3000 |
Interval to trigger the next full encoding check when the lightweight signature remains unchanged, in milliseconds. During this period, changes are still detected at a bounded, adaptive rate. |
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: trueauto: false |
Whether to flush immediately after a Canvas frame successfully enters the replay. |
silentMultipleInit |
boolean |
No | Whether to silently ignore duplicate initialization. |
When not using the low, medium, high string presets, the Canvas auto-scheduling baseline is: sampling 2, target interval 250 ms per Canvas, cooldown 250 ms, unchanged backoff 3000 ms, failure backoff 5000 ms, and a maximum of 2 Canvases per round. String presets replace these budgets and encoding quality simultaneously. Multiple Canvases are also subject to fair rotation and global collection budget constraints. Explicit per-parameter configurations override the corresponding values in the preset. For the full preset matrix, see the Canvas Recording Manual.
The high-frequency scheduling baseline above is for Canvas 2D. When the WebGL plugin does not have explicit interval/cooldown configurations, it continues to use a more conservative GPU readback pace. Explicit per-parameter configurations override these separately.
site Parameter Handling¶
| Node Name | Address |
|---|---|
| US Region 1 (Oregon) | https://us1-openway.truewatch.com |
| EU Region 1 (Frankfurt) | https://eu1-openway.truewatch.com |
| APAC Region 1 (Singapore) | https://ap1-openway.truewatch.com |
| Africa Region 1 (South Africa) | https://za1-openway.truewatch.com |
| Indonesia Region 1 (Jakarta) | https://id1-openway.truewatch.com |
Runtime Session Control¶
RUM SDK 3.3.6 introduces 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:
You can also override the runtime sessionSampleRate:
The sampling rate must be between 0 and 100. The override value is used for this and subsequent auto-renewed sessions. Both the full RUM package and the slim RUM package support this API. For detailed semantics and use cases, see Runtime Restart Session.
Enable Advanced Capabilities as Needed¶
Collect Only Error Session Events¶
Version Requirements
SDK version requirement >= 3.2.19.
When an error is triggered on the page, the SDK automatically performs the following:
- Continuous recording: From the moment the error is triggered, the SDK records the full lifecycle data of the session.
- Precise compensation: Through an independent sampling channel, ensures no error scenarios are 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 the Public OpenWay. For DataKit direct connection, replace the reporting address fields as per the basic integration example.
Data Compression¶
When collecting a large number of static resources (e.g., JS, CSS, images) and enabling full collection, the SDK may generate a large amount of data after initialization, causing request queuing and potentially impacting the application thread state.
Setting compressIntakeRequests: true enables the SDK to compress reported data using deflate in a Web Worker, reducing request size and count.
Configuration Example¶
window.DATAFLUX_RUM &&
window.DATAFLUX_RUM.init({
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_OPENWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
compressIntakeRequests: true
})
Notes¶
- Data compression logic is executed in a Web Worker. If CSP security policies are enabled, you must allow
blob:in theworker-srcdirective. For more information, see CSP Security Policy. - The SDK supports specifying a self-hosted worker URL via the
workerUrlconfiguration option. - SDK version must be >= 3.2 to use this feature.
Custom Data and Events¶
This basic integration page does not repeat all common APIs. Navigate to the corresponding page based on your business goal to see CDN, NPM, and full parameter examples:
- Tracking User Actions: Automatically collect clicks, define Action names, add custom Actions.
- Custom User Identification: Set user after login, clear user on logout or account switch.
- Global Context: Add stable business dimensions to all subsequent RUM events.
- Add Custom Action: Record business operations that cannot be expressed through page clicks.
- Report Custom Error: Report already caught or business-identified exceptions.
Web Session Replay¶
Prerequisites
Use the full RUM package that includes Session Replay; the slim RUM package does not include session replay capability.
Start Recording¶
After SDK initialization, call the startSessionReplayRecording() method to start session replay recording. You can start recording under specific conditions, such as after user login. Start Session Recording.
Collect Only Error-Related Session Replay Data¶
Version Requirements
SDK version requirement >= 3.2.19.
When an error occurs on the page, the SDK automatically performs the following:
- Retroactive capture: Records a full page snapshot of the 1 minute before the error.
- Continuous recording: Continues recording from the error occurrence until the session ends.
- Intelligent compensation: Ensures no error scenarios are missed through an independent sampling channel.
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 captured by default and requires separate configuration of
replayCanvasEnabled. WebGL/WebGL2 recording is available from SDK3.3.7, requires RUM main package version>= 3.3.7, and an additional compatiblebrowser-rum-webglplugin must be installed and registered. It is recommended to use the same SDK release version for the plugin and the main package. For details, see Canvas Recording Manual. - To ensure static resources (e.g., fonts, images) are accessible during replay, you may need to configure CORS policies.
- Ensure that CSS rules are accessible via the
CSSStyleSheetinterface to support CSS styles and hover events.
Verify Recording Status¶
Call window.DATAFLUX_RUM.isRecording() to check whether the current page is recording, and confirm in the session replay viewer that the corresponding session has generated replay data. In production, adjust sessionReplaySampleRate according to business requirements.