Web App Integration¶
After completing the configuration on this page, the Browser RUM SDK automatically collects page Views, resource requests, frontend errors, and user interactions, and reports the data toTrueWatch.
For WebView pages in an App, first read WebView Page Integration, and select the initialization method based on the page's scope of use.
For first-time integration, complete "Define Application → Select Integration Method → Integration Configuration" in the console, then verify data reporting. After basic data reporting succeeds, you can adjust sampling, Distributed Tracing, and Session Replay as needed.
Define Application¶
- Go to "RUM > Application List", click "Create Application", and select "Web" as the application type.
- In "Define Application", enter the application name and application ID. After the application is created, the system automatically generates a Client Token for client-side data reporting.
- In "Select Integration Method", choose one of the methods in the table below, then complete the corresponding operations in "Integration Configuration".
For an existing application, go directly to its configuration page, verify the application information, and continue integration.
Select Integration Method¶
| Integration Method | Use Cases | Entry Point |
|---|---|---|
| Agent Auto Integration | Want a coding assistant to analyze the project and complete SDK integration | Copy the prompt generated by the console and provide it to the coding assistant in the application code repository |
| Manual Integration | Want to modify business code yourself, choose how to import the SDK, and configure parameters | First select the data reporting method, then integrate the SDK according to the application type |
| Automatic Server Integration | Host a website on Nginx, IIS, or Tomcat and want to inject the SDK through the server | Configure collection parameters in the console and run the integration command on the target server |
Choose one integration method per page. For pages that already have the RUM SDK, verify the existing configuration first to avoid duplicate initialization or duplicate collection.
Agent Auto Integration¶
- On the application configuration page, select "Agent Auto Integration".
- Copy the full prompt from "Integration Configuration". It contains integration information such as the current application ID, DataWay URL, and temporary authorization code.
- Open the coding assistant in the application code repository and paste the prompt. Based on the integration guide, the Agent analyzes the project structure, reuses existing configuration, and completes the required SDK integration and validation.
- Follow Verify Integration to check actual data reporting and ingestion.
The integration guide in the prompt describes the runtime environment and specific steps. If integration information is not ready, handle it as follows:
- Personal API Key not generated yet: Click "Generate API Key", and copy the prompt again after completion. If you do not have the required permissions, contact the Workspace administrator to enable it.
- Temporary authorization code not ready: You can let the Agent analyze the project first, complete the required information, and then continue integration.
Manual Integration¶
Manual integration has two steps: first select the data reporting method, then select an SDK import method such as NPM or CDN.
| Data Reporting Method | Recommended Use Cases | Initialization Parameters |
|---|---|---|
| Use Public DataWay | Usually preferred; TrueWatch provides the data receiving service | applicationId, site, clientToken |
| Local Environment Deployment | You need to deploy and manage DataKit yourself, or the current Workspace does not provide a Public DataWay URL | applicationId, datakitOrigin |
Choose only one of the two reporting methods. site and clientToken are used for Public DataWay, and datakitOrigin is used for local environment deployment. Do not specify both in the same initialization configuration.
Prepare Reporting Configuration¶
- Under "Manual Integration", select "Use Public DataWay".
- Copy
applicationId,site, andclientTokenfrom the current application's integration configuration. Use the current site URL provided by the console. Do not use the console login URL or addresses of other sites assite. - Keep the following configuration when integrating the SDK. You do not need to install DataKit or separately configure the RUM collector.
- Install DataKit and enable the RUM collector.
- Ensure the network where the user's browser is located can access DataKit's data reporting URL, and optionally install the IP geolocation database to resolve geolocation information corresponding to user IPs.
- Under "Manual Integration", select "Local Environment Deployment", and configure
datakitOriginas the actual DataKit receiving URL. HTTPS pages should use an accessible HTTPS receiving URL to avoid requests being blocked by the browser. - When integrating the SDK, remove
siteandclientTokenand use the following configuration.
Automatic Server Integration¶
Inject the RUM SDK into website HTML pages through Nginx, IIS, or Tomcat. This does not require modifying application code, but you need configuration and command execution permissions on the target server.
Prerequisites¶
- A Web app has been created, and you have configuration and command execution permissions on the target server.
- The page contains an injectable
<head>tag. Keep only one RUM SDK integration method per page to avoid duplicate collection. - The browser can access SDK resources and the data reporting URL. When using CSP, configure the allowed scope according to CSP Security Policy.
| Server | Environment Requirements and Operational Impact |
|---|---|
| Nginx | Linux Nginx 1.9.4+, http_sub_module, Bash, and curl; run as root or with sudo. Integration configuration changes reload Nginx |
| IIS | 64-bit Windows, IIS 7.5+, URL Rewrite 2.x, static content read permission, and a dedicated application pool; run PowerShell 5.1+ as administrator. Enabling, disabling, updating, and rolling back recycle the application pool, and in-process sessions may be lost |
| Tomcat | Applies to complete HTML pages returned by JSP or Servlet. Before installation, check the Tomcat and JDK versions and restart requirements listed in "Installation Environment" |
Configure Integration¶
- On the Web app configuration page, in "Select Integration Method", select "Automatic Server Integration".
- In "Connect Application", select OpenWay or DataKit, and verify the reporting URL, service name, environment, and application version. The application version marks the business version and does not upgrade the SDK.
- In "SDK Source and Loading", verify the resource source and loading method.
- In "Collection Content", set the session sample rate, error session compensation sampling rate, and user interaction collection. Enable Session Replay as needed, and configure the replay sample rate, error replay compensation sampling rate, and privacy level. Replay first passes session sampling, then replay sampling.
- In "Installation Environment", select Nginx, IIS, or Tomcat, and verify the environment requirements. For Tomcat, in "Advanced Integration Settings" you can specify the deployment path of the target Web app, and page paths to include or exclude. Rumable only injects the SDK into complete HTML pages matching the rules; pages already integrated with RUM are skipped automatically.
- In "Run Installation Command", copy the command generated from the current configuration and run it on the target server. When using auto-discover sites, select the sites to integrate as prompted by the terminal.
The command already includes the configuration; no separate file download is required. If you need to archive it or update manually, you can download rumable.toml. The command and configuration contain the Client Token; keep them secure.
Verify and Update¶
After running the command, check the server execution result and visit the target page. For Tomcat, select a page where both the deployment path and page path match the injection rules. Follow Verify Integration to confirm that the current RUM application has received data for this visit.
If no data is received, check whether you accessed an enabled site and path, whether the SDK is blocked by CSP, whether the reporting URL is reachable, and whether the session is sampled. If the page already integrates the SDK through NPM or CDN, handle duplicate integration first.
After modifying collection parameters, regenerate the integration command and run it on the target server. Saving or copying the configuration only in the console does not automatically update the injection configuration on the server; after modifying the downloaded rumable.toml, you also need to reapply it on the server.
For SDK parameter meanings, see Parameter Configuration. For sampling rules, see Sampling Configuration.
Manually Integrate SDK¶
The following examples use Public DataWay by default. For local environment deployment, replace the reporting parameters as described in Prepare Reporting Configuration.
Select the integration entry point in the following table based on the application type. NPM and CDN determine how the SDK is loaded on the page; Public DataWay and local DataKit determine where data is reported. Configure them separately.
| Application Type | Recommended Entry Point | Description |
|---|---|---|
| Using build tools such as Webpack, Vite, or Rollup | NPM Integration | Recommended; facilitates version management and on-demand integration, but may miss requests and errors before initialization |
| No frontend build process | CDN Asynchronous Loading | Does not block page parsing, but may miss requests and errors before initialization |
| Need to collect page errors and requests as early as possible | CDN Synchronous Loading | Initializes as early as possible, but adds to page load time |
| Only need basic RUM and care about frontend bundle size | Slim RUM SDK | Retains regular RUM collection and does not include Session Replay or intake compression |
| React, Vue, or Angular single-page applications | Frontend Framework Plugin Integration | Automatically manages Router View and framework errors |
| Next.js, Nuxt | Integration under SSR Frameworks | Distinguishes server-side and browser environments to avoid duplicate Views |
| Electron | Electron App Integration | Initialize only in the renderer process |
| WebView pages in an App | WebView Page Integration | Distinguishes regular integration from App-embedded-only scenarios; configure the Bridge on the host side for each platform |
NPM Integration¶
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_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
service: "web-app",
env: "production",
version: "1.0.0",
sessionSampleRate: 100,
trackUserInteractions: true
})
CDN Synchronous Loading¶
Add the scripts 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_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
service: "web-app",
env: "production",
version: "1.0.0",
sessionSampleRate: 100,
trackUserInteractions: true
})
</script>
CDN Asynchronous Loading¶
Add the scripts 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_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
service: "web-app",
env: "production",
version: "1.0.0",
sessionSampleRate: 100,
trackUserInteractions: true
})
})
</script>
DOM-Only Session Replay¶
Starting from Browser SDK 3.3.25, when a page needs RUM events and DOM replay, you can self-host bundle/truewatch-rum-dom.js in the @truewatchtech/browser-rum package.
To record Canvas 2D or WebGL, use the full RUM script. Load only one entry point per page; initialization and replay sampling configuration are the same as the full version.
Slim RUM SDK¶
Starting from RUM SDK 3.3.3, a slim version is available. The slim version uses the same initialization method as the full version and supports regular 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 same version of the slim package:
import { truewatchRum } from "@truewatchtech/browser-rum-slim"
truewatchRum.init({
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
service: "web-app",
env: "production",
version: "1.0.0",
sessionSampleRate: 100,
trackUserInteractions: true
})
CDN Integration¶
Synchronous or asynchronous loading is the same as the full version; just replace the script file name with the file corresponding to 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_DATAWAY_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 recording APIs such as
startSessionReplayRecording(),stopSessionReplayRecording(), andisRecording(); - Canvas 2D and WebGL/WebGL2 recording, and Canvas APIs such as
snapshotCanvas(); compressIntakeRequestsintake compression and the corresponding Worker.
The slim version forces sessionReplaySampleRate, sessionReplayOnErrorSampleRate, and replayCanvasEnabled to off, and forces compressIntakeRequests to false. Do not pass these configurations during integration, and you do not need to set workerUrl or replayCanvasWorkerUrl. If you later need Session Replay, Canvas recording, or compressed reporting, switch the NPM package or CDN file back to the full version; other basic initialization parameters can continue to be used.
Verify Integration¶
The following steps are for standalone Web SDK reporting; for App WebView Bridge mode, see WebView Data Verification.
- Open a page with the SDK integrated, and perform a page navigation, button click, and API request.
- Filter
/v1/write/rumin the Network panel of browser developer tools, and confirm that a successful reporting request exists. - Check the Console and confirm that there are no initialization errors such as
Application ID is not configuredordatakitOrigin or site is not configured. - Go to "RUM > Application List", open the corresponding Web app, filter by
service,env, andversionfrom the integration configuration in the Explorer, and confirm that View, Resource, or Action data has been received.
Seeing View data means basic integration is successful
Error, Resource, and Action appear only after the corresponding events actually occur on the page. If there is no data, first check whether the current Session matches sessionSampleRate, then see FAQ.
Get SDK Initialization Result¶
Both the Web RUM full and slim versions support initialization callbacks starting from Browser SDK 3.3.25.
Configure onInitSuccess and onInitError in the existing init() call. For CDN asynchronous loading, call init() in onReady().
After the SDK completes configuration validation and necessary session storage checks, it calls onInitSuccess. If remote configuration (remoteConfiguration) is enabled, the SDK processes remote configuration first. When compressed reporting is enabled in the full version, the success callback also waits for the compression Worker to be ready. Automatically collected Views may be generated before the callback. The slim version and the full version using JSON reporting do not need to wait for the compression Worker.
The following example uses Public DataWay. Pass initOptions to the current RUM instance's init(initOptions).
const initOptions = {
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
remoteConfiguration: true,
onInitSuccess(result) {
console.log("RUM 初始化成功", result.remoteConfiguration)
if (result.remoteConfiguration === "fallback") {
console.warn("RUM 已使用本地配置启动", result.remoteConfigurationError.code)
}
},
onInitError(error) {
console.error("RUM 初始化失败", error.code, error.message)
}
}
result.remoteConfiguration |
Meaning |
|---|---|
disabled |
Remote configuration is disabled, and the SDK completes initialization with local configuration. |
applied |
The SDK has processed a valid remote response. If an empty configuration is returned, the local configuration still takes effect. |
fallback |
Remote request or response parsing fails, and the SDK completes initialization with local configuration. remoteConfigurationError contains code and message; HTTP errors also contain status. |
The remote request timeout is 10 seconds. Timeouts, network errors, non-200 responses, or malformed responses all trigger fallback to local configuration. If the local configuration also cannot start the SDK, this call only triggers onInitError.
Each init() call triggers at most one result callback. init() returns undefined, and the callback may execute synchronously before it returns. If you manage views manually, you can call startView() in onInitSuccess to create the first view. For standalone Web SDK reporting, check browser requests according to Verify Integration, and check Views in the corresponding Web app. When App WebView Bridge is enabled, data is reported by the App SDK; follow WebView Data Verification to check Views in the corresponding App.
error.code |
Handling |
|---|---|
invalid_configuration, invalid_plugins |
Check parameters and plugin settings after local or remote overrides, correct them, and call init() again. |
storage_unavailable |
Check browser cookie, localStorage, and session storage configuration. Restore storage and retry. |
worker_initialization_failed |
The compression Worker in the full version failed to start or timed out. The SDK notifies once through onInitError. Check error.message, and follow the prompt to check the Worker URL (workerUrl), network connection, or Content Security Policy (CSP). After correction, refresh the page to reinitialize. Subsequent init() calls on the current page are ignored. |
already_initialized |
This call is rejected; the first call retains its callback. silentMultipleInit only controls console messages. |
initialization_ignored |
The current instance delegates initialization to the instance injected by Synthetics. |
sdk_disabled, initialization_failed |
An exception occurred during SDK construction or startup. Investigate and fix the cause, then refresh the page. |
Common Optional Configurations¶
After basic data is confirmed successfully, enable other capabilities as needed:
| Goal | Configuration or API | Documentation |
|---|---|---|
| Correlate frontend and backend traces | allowedTracingUrls, traceType |
Distributed Tracing Configuration |
| Limit API request rate per anonymous visitor | visitorId, resetVisitorId() |
Visitor ID |
| Control collection ratio | sessionSampleRate, startSession() |
Sampling Configuration |
| Collect only error session events | sessionOnErrorSampleRate |
Error Session Compensation Sampling |
| Enable Session Replay | startSessionReplayRecording() |
Web Session Replay |
| Compress reported data | compressIntakeRequests |
Data Compression |
| Automatically manage SPA Router View | plugins |
Frontend Framework Plugin Integration |
| Record WebGL/WebGL2 | plugins, Canvas automatic recording |
Canvas Recording Guide |
| 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)¶
For NPM + TypeScript integration, 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_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
allowedTracingUrls: ["https://api.example.com"],
traceType: TraceType.DDTRACE
})
The runtime value of TraceType.DDTRACE is still "ddtrace". CDN integration has no module import; when configuring explicitly, use the corresponding runtime string. 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 sampled but you still need to pass Trace Headers to the backend, you can explicitly enable allowTraceHeaderWithoutSession:
datafluxRum.init({
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
sessionSampleRate: 0,
sessionOnErrorSampleRate: 0,
allowedTracingUrls: ["https://api.example.com"],
allowTraceHeaderWithoutSession: true
})
When enabled, the SDK still injects Trace Headers only into XHR and Fetch requests matching allowedTracingUrls. This configuration does not create or force-enable a RUM Session, and it does not report View, Error, Resource, or Action data for unsampled Sessions. The API service still needs to 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 | Application ID created in TrueWatch. | |
datakitOrigin |
String | Required for local environment deployment | DataKit data reporting URL in the format protocol (including ://) + domain or IP + optional port, for example https://datakit.example.com. |
|
clientToken |
String | Required for Public DataWay | Public DataWay data reporting token, obtained from the TrueWatch console. | |
site |
String | Required for Public DataWay | Public DataWay data reporting URL, obtained from the TrueWatch console. | |
env |
String | No | Current environment of the Web app, such as prod: production environment; gray: canary environment; pre: staging environment; common: daily environment; local: local environment. | |
version |
String | No | Version number of the Web app. | |
service |
String | No | Service name of the current application. Defaults to browser and supports custom configuration. |
|
sessionSampleRate |
Number | No | 100 |
Percentage of metric data to collect:100 collects all; 0 collects none. |
sessionOnErrorSampleRate |
Number | No | 0 |
Error session compensation sampling rate: If a session is not sampled by sessionSampleRate but an error occurs during the session, collect it at this rate. Such sessions start recording events when the error occurs and continue recording until the session ends. Requires SDK version >= 3.2.19 |
sessionReplaySampleRate |
Number | No | 100 |
Session Replay data collection percentage: 100 collects all; 0 collects none. |
sessionReplayOnErrorSampleRate |
Number | No | 0 |
Session Replay error session replay compensation sampling rate: If a session is not sampled by sessionReplaySampleRate but an error occurs during the session, collect it at this rate. Such replays record up to one minute of events before the error and continue recording until the session ends. Requires SDK version >= 3.2.19 |
trackSessionAcrossSubdomains |
Boolean | No | false |
Share cache among 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 disables RUM events sent over insecure (non-HTTPS) connections |
traceType |
TraceType |
No | TraceType.DDTRACE (runtime value ddtrace) |
Configures the Distributed 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 4 types: zipkin_single_header, w3c_traceparent, zipkin, and jaeger.2. This configuration takes effect only when allowedTracingUrls is configured.3. When configuring the corresponding type, you need to set the corresponding Access-Control-Allow-Headers for the API service. For details, see How APM correlates with RUM. |
traceId128Bit |
Boolean | No | false |
Whether to generate traceID in 128-bit mode. This corresponds to traceType; currently supports zipkin and jaeger. |
allowedTracingUrls |
Array | No | [] |
List of request URL matches allowed to inject Trace Headers. Array items can be a full URL, regular expression, match function, or an object 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 matching 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; retained only for compatibility with older configurations. For new integrations, use allowedTracingUrls; when both are configured, allowedTracingUrls overrides this configuration. |
trackUserInteractions |
Boolean | No | false |
Whether to enable user interaction collection. |
enablePrivacyForActionName |
Boolean | No | false |
Whether automatic Action names follow the DOM privacy level. When enabled, masked names use a fixed placeholder, and clicks in hidden elements do not generate automatic Actions; explicitly configured Action name attributes remain available. Requires SDK version >= 3.3.14. See Protect Automatic Action Names. |
trackViewsManually |
Boolean | No | false |
Whether to disable automatic SDK Views and have the application call startView() to start Views manually. Framework Router plugins manage this configuration automatically; business code does not need to set it again. Details |
plugins |
Array | No | [] |
Register RUM plugins; must be passed during init(). Framework plugins can collect route Views and framework errors for React, Vue, Angular, Next.js, and Nuxt. Requires SDK version >= 3.3.6. For details, see Frontend Framework Plugin Integration. WebGL Replay is available from SDK 3.3.7, requires RUM main package version >= 3.3.7, and it is recommended that the plugin and main package use the same SDK release version. For details, see Canvas Recording Guide. |
enableExperimentalFeatures |
Array | No | [] |
Enable experimental features. Configure ["track_websockets"] to collect native WebSocket connection-level Resources. Requires SDK version >= 3.3.6. Details |
actionNameAttribute |
String | No | Version requirement: >3.1.2. Add a custom attribute to an element to specify the operation name. For usage, see Details. |
|
beforeSend |
Function(event, context):Boolean | No | Version requirement: >3.1.2. Data interception and data modification. Details |
|
storeContextsToLocal |
Boolean | No | Version requirement: >3.1.2. Whether to cache user-defined data in local localstorage, such as custom data added by the setUser and addGlobalContext APIs. |
|
storeContextsKey |
String | No | Version requirement: >3.1.18. Defines the key stored in localstorage. If left blank, it is generated automatically. This parameter mainly distinguishes the store shared by different subpaths under the same domain. For user identity and session boundary configuration, see Page Refresh and Local Storage. |
|
compressIntakeRequests |
Boolean | No | Compress RUM data request content to reduce bandwidth usage when sending large amounts of data and reduce the number of data requests. Compression is performed in a WebWorker thread. For CSP security policy, see CSP Security. Requires SDK version >= 3.2.0. Requires DataKit version >=1.60. Deployment Plan requires >= 1.96.178 |
|
workerUrl |
String | No | Session Replay and compressIntakeRequests data compression are both performed in WebWorker threads. Therefore, by default, when CSP secure access is enabled, you need to allow worker-src blob:;. This configuration allows adding a self-hosted Worker URL. For CSP security policy, see CSP Security. Requires SDK version >= 3.2.0. |
|
remoteConfiguration |
Boolean | No | Whether to enable remote configuration for data collection. Disabled by default. Remote configuration can dynamically modify data collection configuration items without releasing a new version. For example, you can modify the sample rate or whether to enable user interaction collection in remote configuration. Remote configuration requires enabling environment variable settings in the TrueWatch console. Requires SDK version >= 3.2.20. Requires DataKit version >=1.60. How to enable environment variables in the TrueWatch console |
|
onInitSuccess |
function |
No | Supported in SDK 3.3.25 and later. Called when initialization succeeds; the parameter contains the remote configuration processing result. See Initialization Result. |
|
onInitError |
function |
No | Supported in SDK 3.3.25 and later. Triggered when this initialization fails or the call is rejected; the parameter contains code and message. See Error Codes. |
|
replayCanvasWorkerUrl |
string |
No | Worker URL dedicated to Canvas snapshot encoding; does not replace workerUrl. This configuration allows adding a self-hosted Worker URL. For CSP security policy, see CSP Security. Requires SDK version >= 3.3.0. |
|
replayCanvasEnabled |
boolean |
No | false |
Whether to enable Canvas recording. If not enabled, Canvas is not collected. Requires SDK version >= 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 | 2 |
Only effective 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 Canvas 2D collection frequency. 'all' makes Canvas 2D attempt higher-fidelity command capture; complex scenarios may still fall back to snapshots. The WebGL plugin always uses budgeted pixel snapshots. |
replayCanvasAutoInterval |
number |
No | 250 |
Target interval for automatic snapshots of each Canvas, in milliseconds. Multiple Canvases rotate fairly; the actual pace is also limited 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 automatic scheduling budgets at the same time; if you only want to change image quality, pass a number between 0 and 1. |
replayCanvasAutoCooldown |
number |
No | 250 |
Minimum cooldown time for automatic snapshots of the same Canvas, in milliseconds. |
replayCanvasAutoUnchangedBackoff |
number |
No | 3000 |
Interval before triggering the next full encoding check when the lightweight signature remains unchanged, in milliseconds; during this period, changes are still detected with a bounded, adaptive pace. |
replayCanvasAutoFailureBackoff |
number |
No | 5000 |
Backoff time after automatic collection fails, 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 prioritize flushing after a Canvas frame successfully enters replay. |
silentMultipleInit |
boolean |
No | Whether to disable console messages for duplicate initialization. A configured onInitError still receives already_initialized. |
When the low, medium, or high string preset is not used, the Canvas automatic scheduling baseline is: sampling 2, target interval 250 ms per Canvas, cooldown 250 ms, unchanged backoff 3000 ms, failure backoff 5000 ms, and at most 2 Canvases per run. String presets replace these budgets and the encoding quality at the same time; multiple Canvases are also subject to fair rotation and the global collection budget. Explicit individual configurations override the corresponding values in the preset. For the full preset matrix, see Canvas Recording Guide.
The high-frequency scheduling baseline above applies to Canvas 2D. When interval/cooldown is not explicitly configured, the WebGL plugin continues to use a more conservative GPU readback pace; only explicit individual configurations override them separately.
Public DataWay Site URLs¶
site specifies the public data receiving URL. Prefer to copy the URL from the current application's integration configuration. The table below is for verifying sites; for local environment deployment, configuring datakitOrigin is sufficient.
| Node Name | URL |
|---|---|
| International 1 (Oregon) | https://us1-openway.truewatch.com |
| Europe 1 (Frankfurt) | https://eu1-openway.truewatch.com |
| Asia Pacific 1 (Singapore) | https://ap1-openway.truewatch.com |
| Asia Pacific 2 (Singapore) | https://ap2-openway.truewatch.com |
| Africa 1 (South Africa) | https://za1-openway.truewatch.com |
| Indonesia 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 restarts the Session according to the current sampling configuration, without waiting for the next user interaction:
You can also override the runtime sessionSampleRate at the same time:
The sample rate must be between 0 and 100. This override applies to this Session and subsequent automatically continued Sessions. Both the full RUM package and the slim RUM package support this API. For detailed semantics and use cases, see Restart Session at Runtime.
Enable Advanced Capabilities as Needed¶
Collect Only Error Session Events¶
Version Requirement
Requires SDK version >= 3.2.19.
sessionOnErrorSampleRate compensates for error sessions that miss regular sampling. When an error occurs in a session and the compensation sampling is matched, the SDK starts recording events from the time of the error and continues until the session ends.
The following example disables regular session sampling and sets the error session compensation sampling rate to 100%.
Configuration Example¶
window.DATAFLUX_RUM &&
window.DATAFLUX_RUM.init({
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
sessionSampleRate: 0,
sessionOnErrorSampleRate: 100
})
The example above uses Public DataWay. For local environment deployment, replace the reporting address field according to the basic integration example.
Data Compression¶
When a page contains many static resources (such as JS, CSS, and images) or the sample rate is high, it may generate a large amount of RUM reporting data.
After setting compressIntakeRequests: true, the SDK uses deflate in a Web Worker to compress reported data, reducing request size and request count.
Configuration Example¶
window.DATAFLUX_RUM &&
window.DATAFLUX_RUM.init({
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
compressIntakeRequests: true
})
Notes¶
- Data compression logic runs in a Web Worker. If a CSP security policy is enabled, you need to allow
blob:inworker-src. For more information, see CSP Security Policy. - The SDK supports specifying a self-hosted Worker URL through the
workerUrlconfiguration item. - The SDK version using this feature must be >= 3.2.
Custom Data and Events¶
Select the corresponding API based on your business goal, and view CDN and NPM integration examples and parameter descriptions:
- Track User Actions: Automatically collect clicks, define Action names, and add custom Actions.
- Custom User Identity: Set the user after login, and clear the user when logging out or switching accounts.
- Global Context: Add stable business dimensions to all subsequent RUM events.
- Add Custom Action: Record business operations that cannot be expressed by page clicks.
- Report Custom Error: Report exceptions that have been captured or actively identified by the business.
Web Session Replay¶
Prerequisites
Use the full RUM package that includes Session Replay; the slim RUM package does not include Session Replay capabilities.
Start Recording¶
After SDK initialization, call the startSessionReplayRecording() method to start Session Replay recording. You can choose to start it under specific conditions, such as starting session recording after user login.
Collect Only Error-Related Session Replay Data¶
Version Requirement
Requires SDK version >= 3.2.19.
sessionReplayOnErrorSampleRate compensates for error sessions that miss regular replay sampling. When an error occurs in a session and compensation sampling is matched, up to 1 minute of replay data before the error can be captured, and recording continues until the session ends.
The following example collects all RUM sessions, disables regular replay sampling, sets the error session replay compensation sampling rate to 100%, and calls the recording API. Session Replay is still constrained by the RUM session sampling result. For specific rules, see Sampling Configuration.
Configuration Example¶
window.DATAFLUX_RUM &&
window.DATAFLUX_RUM.init({
applicationId: "<APPLICATION_ID>",
site: "<PUBLIC_DATAWAY_URL>",
clientToken: "<CLIENT_TOKEN>",
sessionSampleRate: 100,
sessionReplaySampleRate: 0,
sessionReplayOnErrorSampleRate: 100
})
window.DATAFLUX_RUM && window.DATAFLUX_RUM.startSessionReplayRecording()
Notes¶
- Session Replay does not record playback content of iframes, videos, or audio; Canvas is not collected by default and requires separate
replayCanvasEnabledconfiguration. WebGL/WebGL2 is available from SDK3.3.7, requires RUM main package version>= 3.3.7, and requires additional installation and registration of a compatiblebrowser-rum-webglplugin; it is recommended that the plugin and main package use the same SDK release version. For details, see Canvas Recording Guide; - To ensure static resources (such as fonts and images) can be accessed normally during replay, you may need to configure CORS policies;
- Ensure CSS rules are accessible through the CSSStyleSheet API 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 generated replay data. In production, adjust sessionReplaySampleRate according to business needs.