Skip to content

Web Application Integration


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 Guance.

Choose an Integration Path

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

Application Type Recommended Entry Description
Using build tools such as Webpack, Vite, Rollup NPM Integration Recommended for version management and on-demand integration
No frontend build process CDN Asynchronous Loading Does not block page parsing, but may miss requests and errors that occur before initialization
Must collect errors and requests from the earliest stage of the page 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 standard RUM collection but does not include Session Replay or intake compression
React, Vue, Angular single-page applications Frontend Framework Plugin Integration Automatically manages Router Views and framework errors
Next.js, Nuxt Integration in SSR Frameworks Distinguishes server-side from browser environments to avoid duplicate Views
Electron Electron Application Integration Initializes only in the renderer process

Prepare Integration Information

  1. Go to RUM > Application List > Create Application > Web.
  2. Create an application and obtain the applicationId, env, version, and other configuration generated by the console.
  3. Choose the data ingestion method:

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

  5. DataKit direct connection: Prepare datakitOrigin; DataKit needs the RUM collector enabled, and must be configured to be publicly accessible with the IP geolocation database installed.
Do not configure both ingestion methods at the same time

Public OpenWay uses site and clientToken; DataKit direct connection uses datakitOrigin. Keep only the fields required by the integration method you choose.

Ingestion Method

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

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

Integrate the SDK

Integration Method
Description
NPM Bundles the SDK code into your frontend project, making it easy to lock versions. May miss requests and errors that occur before SDK initialization.
CDN Asynchronous Loading Loads the SDK script asynchronously via CDN without affecting page load performance. May miss request and error collection that occurs before initialization.
CDN Synchronous Loading Loads the SDK script synchronously via CDN, enabling complete collection of all errors and performance metrics. However, it may affect page load performance.

NPM Integration

Install and import the SDK in your frontend project:

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

Initialize the SDK in your project:

import { datafluxRum } from "@cloudcare/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 following script to your HTML file:

<script
  src="https://static.guance.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 following script to your HTML file:

<script>
  ;(function (h, o, u, n, d) {
    h = h[d] = h[d] || {
      q: [],
      onReady: function (c) {
        h.q.push(c)
      },
    }
    d = o.createElement(u)
    d.async = 1
    d.src = n
    n = o.getElementsByTagName(u)[0]
    n.parentNode.insertBefore(d, n)
  })(
    window,
    document,
    "script",
    "https://static.guance.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 example above uses Public OpenWay. For DataKit direct connection, remove site and clientToken and configure datakitOrigin instead.

Slim RUM SDK

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

NPM Integration

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

npm install @cloudcare/browser-rum-slim @cloudcare/browser-core
import { datafluxRum } from "@cloudcare/browser-rum-slim"

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 Integration

Synchronous and asynchronous loading are the same as with the full version; simply replace the script file name with the corresponding slim file. A synchronous loading example follows:

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

Capability Differences from the Full Version

The slim version does not include the following capabilities:

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

The slim version forces sessionReplaySampleRate, sessionReplayOnErrorSampleRate, and replayCanvasEnabled off, and forces compressIntakeRequests to false. Do not pass these configurations when integrating, and you do not need to set workerUrl or replayCanvasWorkerUrl. If you later need Session Replay, Canvas recording, or compressed intake, switch the NPM package or CDN file back to the full version. Your other basic initialization parameters can continue to be used.

Verify the Integration

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

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

Common Optional Configurations

After confirming that the basic data is successfully collected, enable other capabilities as needed:

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

Distributed Tracing Configuration (Optional)

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

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

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

The runtime value of TraceType.DDTRACE remains "ddtrace". CDN integration does not involve module imports; when configuring explicitly, use the corresponding runtime string. After enabling distributed tracing, you also need to allow the corresponding Trace headers on your 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_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 into 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 server still needs to allow the headers for the selected traceType; cross-origin requests also require correct CORS configuration.

Parameter Configuration

Initialization Parameters

Parameter
Type
Required
Default
Description
applicationId String Yes The application ID created in Guance.
datakitOrigin String DataKit direct connection The DataKit ingestion URL, in the format protocol (including ://) + domain or IP + optional port, for example https://datakit.example.com.
clientToken String Public OpenWay The Public OpenWay ingestion token, obtained from the Guance console.
site String Public OpenWay The Public OpenWay ingestion URL, obtained from the Guance console.
env String No The current environment of the web application. For example, 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; custom configuration is supported.
sessionSampleRate Number No 100 Percentage of session data to collect:
100 means collect all; 0 means collect none.
sessionOnErrorSampleRate Number No 0 Compensatory sampling rate for error sessions: when a session is not sampled by sessionSampleRate, if an error occurs during the session, the session is collected 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 Percentage of Session Replay data to collect:
100 means collect all; 0 means collect none.
sessionReplayOnErrorSampleRate Number No 0 Compensatory sampling rate for Session Replay in error sessions: when a session is not sampled by sessionReplaySampleRate, if an error occurs during the session, the replay is collected at this rate. Such replays record up to one minute of events before the error occurs and continue recording until the session ends. Requires SDK version >= 3.2.19.
trackSessionAcrossSubdomains Boolean No false Subdomains under the same domain share the cache.
usePartitionedCrossSiteSessionCookie Boolean No false Whether to enable partitioned secure cross-site session cookies. Details
useSecureSessionCookie Boolean No false Use a secure session cookie. This disables sending RUM events 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 only takes effect with allowedTracingUrls.
3. When configuring a corresponding type, set the matching 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. Corresponds to traceType; currently supports zipkin and jaeger.
allowedTracingUrls Array No [] A list of request URL matchers allowed to have Trace headers injected. Array items can be full URLs, regular expressions, matching functions, or objects containing match and traceType. For example: ["https://api.example.com/xxx", /https:\/\/.*\.my-api-domain\.com\/xxx/, (url) => url.includes("/api/")].
allowTraceHeaderWithoutSession Boolean No false Whether to still inject Trace headers into XHR and Fetch requests 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. Use allowedTracingUrls for new integrations. When both are configured, allowedTracingUrls overrides this setting.
trackUserInteractions Boolean No false Whether to enable user interaction collection.
enablePrivacyForActionName Boolean No false Whether automatic Action names should follow DOM privacy levels. When enabled, masked names use fixed placeholders, 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 turn off automatic Views in the SDK and have the application start a View manually by calling startView(). Framework router plugins manage this configuration automatically; applications do not need to set it again. See details.
plugins Array No [] Registers RUM plugins; must be passed in 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. 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 the main package use the same SDK release version. See Canvas Recording User Guide.
enableExperimentalFeatures Array No [] Enable experimental features. Configuring ["track_websockets"] collects connection-level Resources for native WebSocket. Requires SDK version >= 3.3.6. See details.
actionNameAttribute String No Requires version >3.1.2. Add a custom attribute to elements to specify the name of the Action. For usage details, see Tracking User Actions.
beforeSend Function(event, context):Boolean No Requires version >3.1.2. Intercept and modify data. See details.
storeContextsToLocal Boolean No Requires version >3.1.2. Whether to cache user-defined data to local localStorage, such as custom data added via the setUser and addGlobalContext APIs.
storeContextsKey String No Requires version >3.1.18. Defines the key used for localStorage storage. If left empty, it is generated automatically. This parameter is mainly used to distinguish shared stores across different subpaths under the same domain.
compressIntakeRequests Boolean No Compresses the content of RUM data requests to reduce bandwidth usage when sending large amounts of data, and also reduces the number of requests. Compression is performed in a Web Worker thread. For CSP security policies, see CSP Security. Requires SDK version >= 3.2.0 and DataKit version >= 1.60. Deployment Plan requires >= 1.96.178.
workerUrl String No Session Replay and compressIntakeRequests data compression are both completed in Web Worker threads. Therefore, by default, when CSP secure access is enabled, worker-src blob: must be allowed. This setting allows you to specify a self-hosted Worker URL. For CSP security policies, 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 lets you dynamically modify data collection settings without releasing a new version. For example, you can modify the sampling rate or whether user interaction collection is enabled through remote configuration. Enabling remote configuration requires turning on the environment variable setting in the Guance console. Requires SDK version >= 3.2.20 and DataKit version >= 1.60. How to enable the environment variable feature in the Guance console.
replayCanvasWorkerUrl string No The dedicated Worker URL for Canvas snapshot encoding; does not replace workerUrl. This setting allows you to specify a self-hosted Worker URL. For CSP security policies, see CSP Security. Requires SDK version >= 3.3.0.
replayCanvasEnabled boolean No false Whether to enable Canvas recording. When disabled, Canvas is not collected. Requires SDK version >= 3.3.0.
replayCanvasMode 'manual' \| 'auto' No auto Canvas recording mode. In manual mode, you need to manually call snapshotCanvas(canvas); auto records automatically.
replayCanvasSampling number \| 'all' No 2 Only takes effect when replayCanvasMode: 'auto' is set. Positive numbers select 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 scenes may still fall back to snapshot. The WebGL plugin always uses budgeted pixel snapshots.
replayCanvasAutoInterval number No 250 The target interval in milliseconds for automatic snapshots of each Canvas. Multiple Canvases are fairly rotated; the actual cadence is also constrained 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 automatic scheduling budgets; pass a number between 0 and 1 if you only want to change image quality.
replayCanvasAutoCooldown number No 250 The minimum cooldown time in milliseconds between automatic snapshots of the same Canvas.
replayCanvasAutoUnchangedBackoff number No 3000 The interval in milliseconds before the next full encoding check is triggered when the lightweight signature remains unchanged. During this period, changes are still probed at a bounded, adaptive cadence.
replayCanvasAutoFailureBackoff number No 5000 The backoff time in milliseconds after an automatic collection failure.
replayCanvasAutoMaxPerRun number No 2 The maximum number of Canvases processed in a single automatic scheduling run.
replayCanvasFlushImmediately boolean No manual: true
auto: false
Whether to prioritize flushing after Canvas frames successfully enter the replay.
silentMultipleInit boolean No Whether to silently ignore repeated initialization.

When the low, medium, or high string presets are not used, the automatic scheduling baseline for Canvas is: sampling 2, a target interval of 250 ms per Canvas, cooldown 250 ms, unchanged backoff 3000 ms, failure backoff 5000 ms, and a maximum of 2 Canvases per run. String presets replace both these budgets and the encoding quality. Multiple Canvases are also subject to fair rotation and global collection budget limits. Explicit per-item configuration overrides the corresponding value in the preset. See the full preset matrix in Canvas Recording User Guide.

The high-frequency scheduling baseline above applies to Canvas 2D. When the WebGL plugin does not explicitly configure interval/cooldown, it continues to use a more conservative GPU readback cadence; only explicit per-item configuration overrides these individually.

site Parameter Handling

Node Name Address
China Zone 1 (Hangzhou) https://rum-openway.guance.com
China Zone 2 (Ningxia) https://aws-openway.guance.com
China Zone 4 (Guangzhou) https://cn4-openway.guance.com
China Zone 6 (Hong Kong) https://cn6-openway.guance.one
International Zone 1 (Oregon) https://us1-openway.guance.com
Europe Zone 1 (Frankfurt) https://eu1-openway.guance.one
Asia-Pacific Zone 1 (Singapore) https://ap1-openway.guance.one
Africa Zone 1 (South Africa) https://za1-openway.guance.com
Indonesia Zone 1 (Jakarta) https://id1-openway.guance.com

Runtime Session Control

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

datafluxRum.startSession()

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

datafluxRum.startSession({
  sessionSampleRate: 100,
})

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

Enable Advanced Capabilities as Needed

Collect Only Error Session Events

Version Requirements

Requires SDK version >= 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 full lifecycle data of the session is recorded.
  • Precise compensation: an independent sampling channel ensures error scenarios are not missed.

Configuration

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

The example above uses Public OpenWay. For DataKit direct connection, replace the ingestion URL fields with those from the basic integration example.

Data Compression

When collecting large numbers 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 backlog and potentially affecting the application thread state.

Setting compressIntakeRequests: true makes the SDK compress ingestion data using deflate in a Web Worker, reducing request size and the number of requests.

Configuration Example

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

Notes

  1. The data compression logic runs in a Web Worker. If a CSP security policy is enabled, you need to allow blob: in worker-src. For more information, see CSP Security Policy Documentation.
  2. The SDK supports specifying a self-hosted Worker URL through the workerUrl configuration option.
  3. The SDK version used with this feature must be >= 3.2.

Custom Data and Events

The basic integration page no longer expands all public APIs. Go to the corresponding page for your business goal to get CDN, NPM, and full parameter examples:

  • Track User Actions: automatically collect clicks, define Action names, and add custom Actions.
  • Custom User Identification: 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 Actions: record business operations that cannot be expressed through page clicks.
  • Report Custom Errors: report exceptions that have already been caught or are proactively identified by the business.

Web Session Replay

Prerequisites

Use the full RUM package, which includes Session Replay. The slim RUM package does not include Session Replay capabilities.

Enable Recording

After the SDK is initialized, call startSessionReplayRecording() to start Session Replay recording. You can choose to enable it under specific conditions, such as after user login. See Enable Session Recording.

Version Requirements

Requires SDK version >= 3.2.19.

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

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

Configuration Example

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

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

Notes

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

Verify Recording Status

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

Feedback

Is this page helpful?