Skip to Content
KubeSense

Browser RUM Integration

This guide walks through adding Real User Monitoring (RUM) to a browser application using the Kubesense SDK. It covers installation, initialization, and every instrumentation API available.

It describes SDK version 2.0.0. If you are upgrading from 1.x, read Upgrading from 1.x first — several defaults changed.


1. Prerequisites

Before integrating, obtain the following from your Kubesense workspace:

ValueWhere to find it
applicationIdSettings → RUM Application Management → your application → View Details
clientTokenSettings → RUM Application Management → your application → View Details

2. Installation

Full SDK (includes Session Replay):

npm install @kubesense/kubesense-browser-rum
# or
yarn add @kubesense/kubesense-browser-rum

Slim SDK (no Session Replay, smaller bundle):

npm install @kubesense/kubesense-browser-rum-slim
# or
yarn add @kubesense/kubesense-browser-rum-slim

Option B — CDN (script tag)

Add this script in the <head> of your HTML, before any other scripts:

<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','<CDN_URL>/kubesense-rum.js','KUBESENSE_SDK')
</script>

note: Replace <CDN_URL> with the URL provided by your Kubesense account team.


3. Initialization

Call init() once, as early as possible in your application's entry point. All API calls made before init() are queued and replayed automatically.

npm / ES Module

import { kubesenseSdk } from '@kubesense/kubesense-browser-rum'

kubesenseSdk.init({
  applicationId: '<YOUR_APPLICATION_ID>',
  clientToken: '<YOUR_CLIENT_TOKEN>',
  kubesenseRumEndpoint: 'app.kubesense.ai',
  service: 'my-web-app',
  env: 'production',
  version: '1.0.0',
  sessionSampleRate: 100,
  trackUserInteractions: true,
  trackResources: true,
  trackLongTasks: true,
  firstPartyDomains: [
    "api.kubesense.ai",                   // exact hostname
    /\.kubesense\.ai/,                    // all subdomains via regex
    (host) => host.endsWith(".internal"), // custom function
  ],
})

CDN

window.KUBESENSE_SDK.onReady(function() {
  window.KUBESENSE_SDK.init({
    applicationId: '<YOUR_APPLICATION_ID>',
    clientToken: '<YOUR_CLIENT_TOKEN>',
    kubesenseRumEndpoint: 'app.kubesense.ai',
    service: 'my-web-app',
    env: 'production',
    version: '1.0.0',
    sessionSampleRate: 100,
    trackUserInteractions: true,
    trackResources: true,
    trackLongTasks: true,
    firstPartyDomains: [
      "api.kubesense.ai",
      /\.kubesense\.ai/,
      (host) => host.endsWith(".internal"),
    ],
  })
})

React (App.tsx / main.tsx)

import { kubesenseSdk } from '@kubesense/kubesense-browser-rum'

kubesenseSdk.init({
  applicationId: '<YOUR_APPLICATION_ID>',
  clientToken: '<YOUR_CLIENT_TOKEN>',
  kubesenseRumEndpoint: 'app.kubesense.ai',
  service: 'my-react-app',
  env: process.env.NODE_ENV,
  version: process.env.REACT_APP_VERSION,
  sessionSampleRate: 100,
  trackUserInteractions: true,
  trackResources: true,
  trackLongTasks: true,
  firstPartyDomains: [
    "api.kubesense.ai",
    /\.kubesense\.ai/,
    (host) => host.endsWith(".internal"),
  ],
})

function App() { /* ... */ }
export default App

4. Configuration Reference

Required

OptionTypeDescription
applicationIdstringYour RUM application ID
clientTokenstringYour client authentication token

Common Options

OptionTypeDefaultDescription
kubesenseRumEndpointstring—Your Kubesense RUM endpoint hostname
servicestringapplication idService name for this application
envstring—Deployment environment (production, staging, etc.)
versionstring—Application version (e.g. 1.2.3)
sessionSampleRatenumber100Percentage of sessions to collect (0–100)
enableRemoteSdkConfigurationbooleanfalseLet settings be managed from the Kubesense dashboard. Fetched settings are cached and applied on the next page load; until then, and for any setting the dashboard does not set, the init() values apply

Tracking Behaviour

OptionTypeDefaultDescription
trackUserInteractionsbooleantrueAuto-collect clicks and user actions
trackResourcesbooleantrueCollect XHR / Fetch resource events
trackLongTasksbooleantrueCollect long task events (>50ms)
trackViewsManuallybooleanfalseDisable automatic view creation (SPA manual control)
trackResourceHeadersboolean | MatchHeader[]falseCapture request/response headers on resource events. true collects a default header set for all URLs; matchers can scope by url, name, location ('request' / 'response') and extractor. Headers whose names look sensitive (token, cookie, authorization, api-key, …) are always dropped
trackAnonymousUserbooleantrueTrack anonymous user identity and extend cookie expiration
actionNameAttributestring—HTML attribute used to name actions (e.g. data-action-name)
excludedActivityUrlsMatchOption[]—Request URLs to ignore for page activity calculation
firstPartyDomainsMatchOption[]—Additional domains to treat as first-party in resource classification
allowedTracingUrlsArray<MatchOption | TracingOption>—URLs to inject distributed trace headers into
allowedGraphQlUrlsArray<MatchOption | GraphQlUrlOption>—GraphQL endpoints to track with operation metadata
trackFeatureFlagsForEventsFeatureFlagsForEvents[][]Attach feature flag evaluations to these event types
allowUntrustedEventsbooleanfalseListen to programmatically dispatched DOM events (useful in automated test environments)
allowedTrackingOriginsMatchOption[]—Origins where the SDK is allowed to run (browser extension use)
betaTrackWebSocketsbooleanfalseBeta. Collect WebSocket resource events. Their beforeSend context is WebSocket-specific — narrow it with isWebSocket before reading XHR/Fetch fields
betaEnableViewUpdatesbooleantrue from the CDN without proxy, else falseBeta. Send only changed fields on intermediate view updates. Off by default with a proxy, which may not forward the view_update event type

note: Back/forward cache restores and requests made before init() are always tracked. The trackBfcacheViews and trackEarlyRequests options from 1.x were removed.

Session Replay & Privacy

OptionTypeDefaultDescription
sessionReplaySampleRatenumber0Percentage of sessions to record (0–100)
startSessionReplayRecordingManuallybooleanfalse if sessionReplaySampleRate > 0, else trueStart recording only when startSessionReplayRecording() is called
sessionReplayRoutes{ include?: MatchOption[], exclude?: MatchOption[] }—Record only on matching routes; recording starts and stops automatically on navigation. See Route-Based Session Replay
sessionReplayCanvasRecording{ enable, quality?, maxFramesPerSecond?, maxImageDimension?, hashingMaxDimension? }disabledCapture <canvas> content (e.g. charts) in Session Replay. See Canvas Recording
defaultPrivacyLevel'mask' | 'mask-user-input' | 'mask-unless-allowlisted' | 'allow''mask-user-input'Default text masking level for session replay
enablePrivacyForActionNamebooleantrueMask action names wherever the element's privacy level masks its text
subdomainstring—Custom subdomain for session replay share links
trackingConsent'granted' | 'not-granted''granted'Initial user tracking consent state

defaultPrivacyLevel values

ValueBehaviour
'mask'All text content and form inputs are replaced with xxx. Static and dynamic text is hidden.
'mask-user-input'Only form inputs (<input>, <textarea>, <select>) are masked. Static text is visible. Default.
'mask-unless-allowlisted'Form inputs are masked, and static text is masked unless it appears in the allowlist (window.$KUBESENSE_ALLOW, a Set of lower-cased strings).
'allow'Nothing is masked. All content is recorded as-is.

warning: The default changed from 'mask' to 'mask-user-input' in 2.0.0. An application that never set defaultPrivacyLevel now records static page text unmasked. Set defaultPrivacyLevel: 'mask' to keep the 1.x behaviour.

Override the privacy level on individual HTML elements using the data-kubesense-privacy attribute (or the equivalent kubesense-privacy-<level> class):

<!-- Force mask a specific element even when the global level is 'allow' -->
<div data-kubesense-privacy="mask">Card number: 4111 1111 1111 1111</div>

<!-- Allow a specific element even when the global level is 'mask' -->
<h1 data-kubesense-privacy="allow">Welcome to the Dashboard</h1>

<!-- Mask only user input within this container -->
<form data-kubesense-privacy="mask-user-input">
  <input type="text" placeholder="Name" />
</form>

Distributed Tracing

OptionTypeDefaultDescription
traceSampleRatenumber100Percentage of requests to trace (0–100)
traceContextInjection'sampled' | 'tracecontext''sampled'When to inject trace context into requests
propagateTraceBaggagebooleantrueInclude user/account IDs in the W3C baggage header

Trace sampling is deterministic and derived from the session id, so every request in a session gets the same sampling decision.

Trace headers go only to the URLs in allowedTracingUrls, and service must be set when it is. To link requests to your backend's traces, and for the CORS headers your API must allow, see Backend Traces and Logs in RUM.

Performance & Transport

OptionTypeDefaultDescription
profilingSampleRatenumber0Percentage of users to profile (0–100)
compressIntakeRequestsbooleanfalseCompress payloads sent to the intake (requires workerUrl)
workerUrlstring—URL to the SDK Web Worker file (same origin required)
proxystring | function—Proxy URL or function to route SDK requests through a custom endpoint

Session Persistence & Cookies

OptionTypeDefaultDescription
sessionPersistence'cookie' | 'local-storage' | 'memory', or an array of them'cookie'Storage strategy for sessions. An array is tried in order — ['cookie', 'local-storage'] falls back to local storage when cookies are unavailable (this replaces 1.x's allowFallbackToLocalStorage). 'memory' suits single-page apps only: every page load starts a new session
useSecureSessionCookiebooleanfalseRestrict session cookie to HTTPS connections only
usePartitionedCrossSiteSessionCookiebooleanfalseUse a partitioned cross-site cookie — required when the SDK runs inside an iframe on another domain
trackSessionAcrossSubdomainsbooleanfalseShare the session across all subdomains of the same site
storeContextsAcrossPagesbooleanfalsePersist global context and user context in localStorage across page navigations

note: sessionPersistence, useSecureSessionCookie, usePartitionedCrossSiteSessionCookie, and trackSessionAcrossSubdomains must be set to identical values if you use both the RUM and Logs SDKs on the same page.

Other Options

OptionTypeDefaultDescription
silentMultipleInitbooleanfalseSuppress the error when init() is called more than once on the same page

firstPartyDomains — Detailed

By default, only the current page's hostname is classified as "first-party" in resource and trace attribution. Use firstPartyDomains to declare additional origins you own so they are correctly attributed instead of appearing as third-party.

Accepts strings (exact hostname), regular expressions, or functions:

kubesenseSdk.init({
  // ...
  firstPartyDomains: [
    'api.myapp.com',                        // exact hostname
    /\.myapp\.com$/,                        // all subdomains of myapp.com
    (host) => host.endsWith('.internal'),   // function — matches *.internal
  ],
})

With this configuration, requests to api.myapp.com, cdn.myapp.com, or payments.internal are classified as first-party resources, and distributed trace headers are automatically injected if those origins also appear in allowedTracingUrls.

Callbacks & Plugins

OptionTypeDescription
beforeSend(event, context) => booleanInspect, modify, or discard events before sending. Return false to drop (not applicable to view events).
pluginsRumPlugin[]SDK plugin extensions

beforeSend example — drop health-check errors

kubesenseSdk.init({
  // ...
  beforeSend: (event) => {
    if (event.type === 'error' && event.error.message.includes('health-check')) {
      return false // drop this event
    }
    return true
  },
})

beforeSend example — enrich resource events

kubesenseSdk.init({
  // ...
  beforeSend: (event) => {
    if (event.type === 'resource' && event.resource.url.includes('/api/graphql')) {
      event.context.graphql_operation = getGraphQlOperation(event.resource.url)
    }
    return true
  },
})

5. View Tracking

A view represents a page or screen the user is on. The SDK creates views automatically on URL changes. For Single-Page Apps with custom routing, you may want manual control.

Automatic (default)

Views are created automatically on every history.pushState or hashchange. No code needed.

Manual View Control (SPA)

Set trackViewsManually: true in init(), then call startView() on each route change.

// React Router example
import { useEffect } from 'react'
import { useLocation } from 'react-router-dom'
import { kubesenseSdk } from '@kubesense/kubesense-browser-rum'

function RouteTracker() {
  const location = useLocation()

  useEffect(() => {
    kubesenseSdk.startView({ name: location.pathname })
  }, [location])

  return null
}
// Vue Router example
router.afterEach((to) => {
  kubesenseSdk.startView({ name: to.name ?? to.path })
})

View API

// Start a new view with a name
kubesenseSdk.startView('checkout')

// Start with full options (name, service, version)
kubesenseSdk.startView({ name: 'checkout', service: 'payments', version: '2.1.0' })

// Change the name of the current view after it started
kubesenseSdk.setViewName('checkout-confirmation')

// Attach context to the current view only
kubesenseSdk.setViewContext({ cart_id: 'abc123', item_count: 3 })
kubesenseSdk.setViewContextProperty('experiment_variant', 'B')

// Read current view context
const ctx = kubesenseSdk.getViewContext()

6. User Context

Attach user identity to all events. Call this after login or session restore.

// Set user (id is required)
kubesenseSdk.setUser({
  id: 'usr-1234',
  name: 'Jane Smith',
  email: 'jane@example.com',
  // Any custom properties:
  plan: 'enterprise',
  role: 'admin',
})

// Update a single property
kubesenseSdk.setUserProperty('plan', 'pro')

// Read current user
const user = kubesenseSdk.getUser()

// Remove a property
kubesenseSdk.removeUserProperty('role')

// Clear on logout
kubesenseSdk.clearUser()

note: Calling setUser() with a different id automatically expires the current session to prevent cross-user data contamination on shared devices.


7. Account Context

Attach account/organization information to all events (useful for B2B applications).

kubesenseSdk.setAccount({
  id: 'acct-5678',
  name: 'Acme Corp',
  plan: 'enterprise',
})

// Update a single property
kubesenseSdk.setAccountProperty('plan', 'enterprise-plus')

// Read current account
const account = kubesenseSdk.getAccount()

// Remove a property
kubesenseSdk.removeAccountProperty('plan')

// Clear
kubesenseSdk.clearAccount()

8. Error Tracking

Automatic Error Collection

The SDK automatically captures:

  • Unhandled JavaScript exceptions (window.onerror)
  • Unhandled promise rejections
  • Console errors (console.error)
  • Network errors (for tracked resource URLs)

No code needed for these. Requests your application aborts (for example with AbortController) are not reported as network errors.

Manual Error Reporting

Report handled errors you catch yourself:

try {
  processPayment(order)
} catch (error) {
  kubesenseSdk.addError(error, {
    order_id: order.id,
    amount: order.total,
  })
}
// Report a plain string
kubesenseSdk.addError('Payment failed: insufficient funds', {
  user_id: currentUser.id,
})

React Error Boundary

import { Component } from 'react'
import { kubesenseSdk } from '@kubesense/kubesense-browser-rum'

class ErrorBoundary extends Component {
  componentDidCatch(error: Error, info: React.ErrorInfo) {
    kubesenseSdk.addError(error, {
      component_stack: info.componentStack,
    })
  }

  render() {
    return this.props.children
  }
}

9. Action Tracking

Automatic Action Collection

When trackUserInteractions: true (default), the SDK automatically tracks clicks and names them from:

  1. The element's data-action-name attribute (configure via actionNameAttribute)
  2. The element's aria-label, title, or alt attribute
  3. The element's inner text (truncated)

Custom Actions

// Track a programmatic or non-click action
kubesenseSdk.addAction('export_csv', {
  row_count: 1500,
  format: 'csv',
})

kubesenseSdk.addAction('search', {
  query: searchTerm,
  results_count: results.length,
})

Naming Clicks via HTML Attribute

<!-- Using default attribute (data-action-name) -->
<button data-action-name="Add to cart">+</button>

<!-- Using a custom attribute configured at init -->
<!-- kubesenseSdk.init({ actionNameAttribute: 'data-rum-action' }) -->
<button data-rum-action="checkout">Buy Now</button>

10. Resource & Long Task Tracking

Both are enabled by default. No code needed.

kubesenseSdk.init({
  trackResources: true,  // default: true
  trackLongTasks: true,  // default: true
})

To stop collecting resources or long tasks entirely:

kubesenseSdk.init({
  trackResources: false,
  trackLongTasks: false,
})

11. Custom Timings & Performance Vitals

Custom View Timings

Mark key moments within the current view (e.g. "time to data loaded"):

// After data is fetched and rendered
kubesenseSdk.addTiming('data_ready')

// Pass an explicit timestamp (ms since page load)
kubesenseSdk.addTiming('hero_image_loaded', performance.now())

Timings appear in the view event under view.custom_timings.

Duration Vitals

Measure elapsed time for arbitrary operations:

// Option 1: start and stop by name
kubesenseSdk.startDurationVital('checkout_flow')
// ... user completes checkout ...
kubesenseSdk.stopDurationVital('checkout_flow', {
  context: { steps_completed: 4 },
})

// Option 2: several concurrent vitals with the same name — tell them apart with vitalKey
const key = crypto.randomUUID()
kubesenseSdk.startDurationVital('report_generation', { vitalKey: key })
generateReport().then(() => {
  kubesenseSdk.stopDurationVital('report_generation', { vitalKey: key })
})

// Option 3: add a completed vital with known start/duration
kubesenseSdk.addDurationVital('pdf_render', {
  startTime: renderStartTime,
  duration: renderDuration,
  context: { page_count: 12 },
})

12. Feature Operations

Track multi-step operations (e.g. checkout flows, onboarding) as a series of steps with pass/fail outcomes.

// Start tracking a named operation
kubesenseSdk.startFeatureOperation('onboarding', {
  context: { step: 'profile_setup' },
})

// Mark succeeded
kubesenseSdk.succeedFeatureOperation('onboarding', {
  context: { steps_completed: 3 },
})

// Mark failed with a reason
kubesenseSdk.failFeatureOperation('onboarding', 'profile_incomplete', {
  context: { missing_fields: ['phone'] },
})

13. Global Context

Attach custom properties to every event (views, errors, resources, actions).

// Set at startup
kubesenseSdk.setGlobalContext({
  deployment_region: 'us-east-1',
  feature_set: 'beta',
})

// Add or update a single property at any time
kubesenseSdk.setGlobalContextProperty('ab_test_group', 'variant_B')

// Read current context
const ctx = kubesenseSdk.getGlobalContext()

// Remove one property
kubesenseSdk.removeGlobalContextProperty('feature_set')

// Clear everything
kubesenseSdk.clearGlobalContext()

14. Session Replay

Session Replay records the user's screen so you can replay exactly what happened around an error or frustration signal.

Enable Replay

kubesenseSdk.init({
  // ...
  sessionReplaySampleRate: 20, // record 20% of sessions
})

Manual Recording Control

kubesenseSdk.init({
  // ...
  sessionReplaySampleRate: 100,
  startSessionReplayRecordingManually: true, // don't start automatically
})

// Start recording only for important flows (e.g. after login)
function onUserLoggedIn() {
  kubesenseSdk.startSessionReplayRecording()
}

// Stop recording when leaving a sensitive screen
function onEnterPaymentPage() {
  kubesenseSdk.stopSessionReplayRecording()
}

Privacy Masking

kubesenseSdk.init({
  defaultPrivacyLevel: 'mask', // 'mask' | 'mask-user-input' | 'mask-unless-allowlisted' | 'allow'
})
LevelBehaviour
maskAll text and inputs are masked
mask-user-inputOnly form inputs are masked; static text is visible (default)
mask-unless-allowlistedForm inputs are masked; static text is masked unless allowlisted
allowNothing is masked

Override per element:

<!-- Force masking an element -->
<div data-kubesense-privacy="mask">Sensitive data</div>

<!-- Allow a specific element in a masked view -->
<p data-kubesense-privacy="allow">Public content</p>

Canvas Recording

Charts and other <canvas> content are not captured by default. Enable canvas recording to capture them as image frames:

kubesenseSdk.init({
  // ...
  sessionReplayCanvasRecording: {
    enable: true,
    quality: 'medium',      // 'low' | 'medium' | 'high' — default 'medium'
    maxFramesPerSecond: 1,  // optional override, 0–8
  },
})

Only canvases whose privacy level is allow are captured — mark them (or an ancestor) with data-kubesense-privacy="allow":

<div data-kubesense-privacy="allow">
  <canvas id="revenue-chart"></canvas>
</div>

A frame is captured only when the canvas content changes, and identical frames are uploaded once. maxImageDimension (1–1280) and hashingMaxDimension (1–100) override single values of the chosen quality preset.

const replayUrl = kubesenseSdk.getSessionReplayLink()
// Share or store this URL to view the recording later

15. Distributed Tracing

Correlate frontend RUM events with backend traces by injecting trace headers into outgoing requests.

kubesenseSdk.init({
  // ...
  allowedTracingUrls: [
    'https://api.example.com',               // exact origin
    /https:\/\/.*\.example\.com/,            // regex
    (url) => url.startsWith('https://api.'), // function
  ],
  traceSampleRate: 100, // trace 100% of allowed requests
})

Custom Propagator Format

kubesenseSdk.init({
  allowedTracingUrls: [
    {
      match: 'https://api.example.com',
      propagatorTypes: ['tracecontext', 'kubesense'], // W3C + Kubesense headers
    },
  ],
})

Propagate User/Account in Baggage

kubesenseSdk.init({
  propagateTraceBaggage: true, // includes user.id and account.id in the baggage header
})

If you require explicit consent before collecting data (e.g. GDPR):

kubesenseSdk.init({
  // ...
  trackingConsent: 'not-granted', // start with no collection
})

// After user accepts your consent banner:
kubesenseSdk.setTrackingConsent('granted')

// If user withdraws consent:
kubesenseSdk.setTrackingConsent('not-granted')

Stop a Session

kubesenseSdk.stopSession()
// No new events collected until next page load or user activity

17. Feature Flag Tracking

Track which feature flags were evaluated during a session or action:

// After evaluating a flag
const flagValue = featureFlags.get('new_checkout')
kubesenseSdk.addFeatureFlagEvaluation('new_checkout', flagValue)

To attach flag evaluations to specific event types, configure at init:

kubesenseSdk.init({
  trackFeatureFlagsForEvents: ['action', 'vital', 'long_task', 'resource'],
})

18. GraphQL Tracking

Track GraphQL requests with operation metadata:

kubesenseSdk.init({
  allowedGraphQlUrls: [
    {
      match: 'https://api.example.com/graphql',
      trackPayload: false,       // don't capture request body
      trackResponseErrors: true, // capture GraphQL errors in response
    },
  ],
})

19. TypeScript Support

The SDK ships full TypeScript types. Import them directly:

import type {
  RumInitConfiguration,
  RumEvent,
  RumEventDomainContext,
} from '@kubesense/kubesense-browser-rum'

const config: RumInitConfiguration = {
  applicationId: '<YOUR_APPLICATION_ID>',
  clientToken: '<YOUR_CLIENT_TOKEN>',
  service: 'my-app',
  env: 'production',
  beforeSend: (event: RumEvent, context: RumEventDomainContext): boolean => {
    // type-safe access to event fields
    return true
  },
}

20. Core Web Vitals

The SDK automatically collects Core Web Vitals metrics defined by Google. These metrics help you understand real-world user experience.

Automatically Collected Vitals

VitalDescriptionGoodNeeds ImprovementPoor
LCPLargest Contentful Paint - time to render largest content< 2.5s2.5s - 4s> 4s
INPInteraction to Next Paint - response to all interactions< 200ms200ms - 500ms> 500ms
CLSCumulative Layout Shift - visual stability< 0.10.1 - 0.25> 0.25
FCPFirst Contentful Paint - time to first content< 1.8s1.8s - 3s> 3s
TTFBTime to First Byte - server response time< 800ms800ms - 1800ms> 1800ms

note: First Input Delay (FID) is no longer collected as of 2.0.0. INP, which replaced it as a Core Web Vital, covers all interactions.

Custom Vitals

Track your own performance metrics:

// Add custom timing
kubesenseSdk.addTiming('data_loaded', performance.now())

// Or use duration vitals for complex measurements
kubesenseSdk.startDurationVital('checkout_flow')
// ... user completes checkout ...
kubesenseSdk.stopDurationVital('checkout_flow', { context: { steps_completed: 5 } })

21. Performance & Bundle Size

Bundle Sizes

PackageSize (gzip)Features
@kubesense/kubesense-browser-rum~66KBFull RUM + Session Replay + Profiling (recorder and profiler loaded on demand)
@kubesense/kubesense-browser-rum-slim~51KBRUM only (no replay)
@kubesense/kubesense-browser-logs~22KBLog collection
@kubesense/kubesense-browser-rum-react~5KBReact integration

Lazy Loading Session Replay

Session Replay code is loaded on-demand to reduce initial bundle size. The replay recorder module (~11KB gzip) is only loaded when:

  • sessionReplaySampleRate > 0 AND recording starts
  • startSessionReplayRecording() is called

Optimizing Performance

kubesenseSdk.init({
  sessionSampleRate: 100,       // Adjust based on needs
  sessionReplaySampleRate: 10,  // 10% - replay is expensive
  traceSampleRate: 20,          // 20% - tracing adds overhead
  trackResources: false,        // Disable if not needed
  defaultPrivacyLevel: 'mask-user-input', // Faster than 'mask'
})

22. Troubleshooting

Enable Debug Mode

// Print SDK-internal errors and warnings to the console
kubesenseSdk._setDebug(true)

kubesenseSdk.init({ ... })

Check SDK Status

// Get internal context (current session, view, user)
const context = kubesenseSdk.getInternalContext()
console.log(context)

// Get initialization config
const config = kubesenseSdk.getInitConfiguration()
console.log(config)

Common Issues

No data appearing in dashboard:

  • Verify applicationId and clientToken are correct
  • Check browser console for errors
  • Confirm kubesenseRumEndpoint matches your Kubesense instance

Session Replay not working:

  • Ensure sessionReplaySampleRate > 0
  • If sessionReplayRoutes is set, check that the current path matches include and not exclude
  • Browser supports Session Replay (not IE, not incognito)
  • Check for CSP restrictions blocking worker

High memory usage:

  • Reduce sessionReplaySampleRate
  • Disable trackResources if not needed

23. Route-Based Session Replay

Record only specific pages based on route patterns. Use the sessionReplayRoutes option — recording starts and stops automatically as the user navigates:

kubesenseSdk.init({
  // ...
  sessionReplaySampleRate: 100,
  sessionReplayRoutes: {
    include: ['/checkout', '/signup', /^\/orders\/\d+/],
    exclude: ['/checkout/card'],
  },
})
  • Rules match against the path (pathname + search + hash). Strings match by prefix, so /checkout also covers /checkout/payment; regular expressions and functions are also accepted.
  • exclude takes precedence over include. Omitting include makes every route eligible.
  • Routes only narrow recording: a session not sampled in by sessionReplaySampleRate is never recorded.
  • Privacy is not route-scoped. Use per-element data-kubesense-privacy attributes for page-specific masking.

Manual wiring

If you need logic the route rules cannot express, control recording yourself:

// Initialize with manual start
kubesenseSdk.init({
  startSessionReplayRecordingManually: true,
})

// Define routes to record
const routesToRecord = ['/checkout', '/payment', '/cart', '/dashboard']

// Update recording state based on route
function updateSessionReplay() {
  const shouldRecord = routesToRecord.some(route =>
    window.location.pathname.startsWith(route)
  )
  if (shouldRecord) {
    kubesenseSdk.startSessionReplayRecording()
  } else {
    kubesenseSdk.stopSessionReplayRecording()
  }
}

updateSessionReplay()
window.addEventListener('popstate', updateSessionReplay)

React Router

useEffect(() => {
  const shouldRecord = routesToRecord.some(route =>
    location.pathname.startsWith(route)
  )
  if (shouldRecord) {
    kubesenseSdk.startSessionReplayRecording()
  } else {
    kubesenseSdk.stopSessionReplayRecording()
  }
}, [location.pathname])

24. Geolocation (User Location)

Get accurate user location instead of IP-based GeoIP. Requires user permission.

import { getCurrentPosition, canUseGeoLocation } from '@kubesense/kubesense-browser-core'

if (canUseGeoLocation()) {
  getCurrentPosition((position) => {
    kubesenseSdk.setGlobalContextProperty('geo', {
      latitude: position.latitude,
      longitude: position.longitude,
      accuracy: position.accuracy,
    })
  })
}

Reverse Geocoding (Location Names)

Convert coordinates to location names:

import { getCurrentPosition, reverseGeocodeWithPosition, canUseGeoLocation } from '@kubesense/kubesense-browser-core'

if (canUseGeoLocation()) {
  getCurrentPosition((position) => {
    reverseGeocodeWithPosition(position, (result) => {
      console.log(result.city)      // "San Francisco"
      console.log(result.state)     // "California"
      console.log(result.country)   // "United States of America"
    })
  })
}

25. Custom Events

Track custom business events beyond built-in RUM collection:

// Custom action
kubesenseSdk.addAction('checkout_completed', { cartValue: 99, currency: 'USD' })

// Custom error
kubesenseSdk.addError(new Error('Payment failed'), { source: 'checkout' })

// View context (attached only to current view)
kubesenseSdk.setViewContext({ order_id: '12345' })

Upgrading from 1.x

2.0.0 is a major release. Review these changes before upgrading:

Removed init options — ignored if passed:

RemovedUse instead
allowFallbackToLocalStoragesessionPersistence: ['cookie', 'local-storage']
trackBfcacheViewsNothing — bfcache restores are always tracked
trackEarlyRequestsNothing — requests made before init() are always collected, so expect more resource events if you had it off
usePciIntakeNothing — Kubesense has a single intake
betaEncodeCookieOptionsNothing — cookie options are always encoded
internalAnalyticsSubdomainproxy

Changed defaults and behaviour:

  • defaultPrivacyLevel defaults to 'mask-user-input' (was 'mask'), so static page text is now recorded unmasked in Session Replay. Set 'mask' explicitly to keep the 1.x behaviour.
  • enablePrivacyForActionName defaults to true (was false).
  • propagateTraceBaggage defaults to true (was false).
  • service defaults to the application id when not set. Set it explicitly if your dashboards group by service.
  • FID is no longer collected — use INP.
  • Aborted requests no longer produce network errors, so error counts drop for applications that cancel requests routinely.
  • Trace sampling is deterministic per session.
  • startDurationVital() no longer returns a reference. Stop vitals by name, and use the vitalKey option to tell concurrent vitals with the same name apart.
  • The event tags field read in beforeSend is event.ktags (was event.ddtags).
  • SDK-internal errors all report error.type: 'Error'; filter on the message instead of RateLimitReached / MaxQueueSizeReached.

Sessions: the session is now stored under _kubesense_s_v2. An existing 1.x session is carried over once, but 2.0.0 never writes the old key back. Upgrade the RUM and Logs SDKs together, and upgrade every subdomain that shares a session at the same time — pages still on 1.x next to pages on 2.0.0 run separate sessions. Rolling back to 1.x starts new sessions.

Remote configuration: with enableRemoteSdkConfiguration, the cached dashboard settings are now stored per client token. The first page load after upgrading uses the local init() values; the next one applies the dashboard settings again.

TypeScript: RumFetchResourceEventDomainContext, RumXhrResourceEventDomainContext and RumOtherResourceEventDomainContext were replaced by RumResourceEventDomainContext.


Quick Reference

// Initialization
kubesenseSdk.init({ applicationId, clientToken, /* ... */ })

// Views
kubesenseSdk.startView(name)
kubesenseSdk.setViewName(name)
kubesenseSdk.setViewContext(context)
kubesenseSdk.setViewContextProperty(key, value)

// User & Account
kubesenseSdk.setUser({ id, name, email, /* ...custom */ })
kubesenseSdk.clearUser()
kubesenseSdk.setAccount({ id, name, /* ...custom */ })
kubesenseSdk.clearAccount()

// Global Context
kubesenseSdk.setGlobalContext(context)
kubesenseSdk.setGlobalContextProperty(key, value)
kubesenseSdk.clearGlobalContext()

// Errors & Actions
kubesenseSdk.addError(error, context)
kubesenseSdk.addAction(name, context)

// Timings & Vitals
kubesenseSdk.addTiming(name)
kubesenseSdk.startDurationVital(name)
kubesenseSdk.stopDurationVital(nameOrRef)

// Session Replay
kubesenseSdk.startSessionReplayRecording()
kubesenseSdk.stopSessionReplayRecording()
kubesenseSdk.getSessionReplayLink()

// Consent
kubesenseSdk.setTrackingConsent('granted' | 'not-granted')
kubesenseSdk.stopSession()

On this page

1. Prerequisites2. InstallationOption A — npm / Yarn (recommended)Option B — CDN (script tag)3. Initializationnpm / ES ModuleCDNReact (App.tsx / main.tsx)4. Configuration ReferenceRequiredCommon OptionsTracking BehaviourSession Replay & PrivacydefaultPrivacyLevel valuesDistributed TracingPerformance & TransportSession Persistence & CookiesOther OptionsfirstPartyDomains — DetailedCallbacks & PluginsbeforeSend example — drop health-check errorsbeforeSend example — enrich resource events5. View TrackingAutomatic (default)Manual View Control (SPA)View API6. User Context7. Account Context8. Error TrackingAutomatic Error CollectionManual Error ReportingReact Error Boundary9. Action TrackingAutomatic Action CollectionCustom ActionsNaming Clicks via HTML Attribute10. Resource & Long Task Tracking11. Custom Timings & Performance VitalsCustom View TimingsDuration Vitals12. Feature Operations13. Global Context14. Session ReplayEnable ReplayManual Recording ControlPrivacy MaskingCanvas RecordingGet Replay Link15. Distributed TracingCustom Propagator FormatPropagate User/Account in Baggage16. Privacy & ConsentTracking ConsentStop a Session17. Feature Flag Tracking18. GraphQL Tracking19. TypeScript Support20. Core Web VitalsAutomatically Collected VitalsCustom Vitals21. Performance & Bundle SizeBundle SizesLazy Loading Session ReplayOptimizing Performance22. TroubleshootingEnable Debug ModeCheck SDK StatusCommon Issues23. Route-Based Session ReplayManual wiringReact Router24. Geolocation (User Location)Reverse Geocoding (Location Names)25. Custom EventsUpgrading from 1.xQuick Reference