@dynatrace/rum-javascript-sdk
v1.329.6
Published
JavaScript API for Real User Monitoring (RUM)
Readme
@dynatrace/rum-javascript-sdk
A JavaScript API for interacting with the Dynatrace Real User Monitoring (RUM) JavaScript. This package provides both synchronous and asynchronous wrappers for the Dynatrace RUM API, along with TypeScript support and testing utilities.
Installation
npm install @dynatrace/rum-javascript-sdkOverview
This package provides two main API approaches for interacting with the Dynatrace RUM JavaScript, as well as types and a Playwright testing framework:
- Synchronous API: Safe wrapper functions that gracefully handle cases where the RUM JavaScript is not available
- Asynchronous API: Promise-based functions that wait for the RUM JavaScript to become available
- User Actions API: Manual control over user action creation and lifecycle (see USERACTIONS.md)
- TypeScript Support: Comprehensive type definitions for all RUM API functions
- Testing Framework: Playwright-based utilities for testing RUM integration
Quick Start
Synchronous API (Recommended for most use cases)
import { sendEvent, identifyUser } from '@dynatrace/rum-javascript-sdk/api';
// Send a custom event - safely handles cases where RUM JavaScript is not loaded
sendEvent({
'event_properties.component_name': 'UserProfile',
'event_properties.action': 'view'
});
// Identify the current user
identifyUser('[email protected]');Asynchronous API (When you need to ensure RUM JavaScript is available)
import { sendEvent, identifyUser } from '@dynatrace/rum-javascript-sdk/api/promises';
try {
// Wait for RUM JavaScript to be available (with 10s timeout by default)
await sendEvent({
'event_properties.component_name': 'UserProfile',
'event_properties.action': 'view'
});
await identifyUser('[email protected]');
} catch (error) {
console.error('RUM JavaScript not available:', error);
}API Reference
Synchronous API (@dynatrace/rum-javascript-sdk/api)
The synchronous API provides safe wrapper functions that gracefully handle cases where the Dynatrace RUM JavaScript is not available. These functions will execute as no-ops if the JavaScript is not loaded, making them safe to use in any environment.
sendEvent(fields, eventContext?): void
Sends a custom event to Dynatrace RUM.
Parameters:
fields: ApiCreatedEventPropertiesEvent- Event properties object. Must be serializable JSON with properties prefixed withevent_properties., plus optionaldurationandstart_timeproperties.eventContext?: unknown- Optional context for event modification callbacks.
Example:
import { sendEvent } from '@dynatrace/rum-javascript-sdk/api';
sendEvent({
'event_properties.page_name': 'checkout',
'event_properties.step': 'payment',
'event_properties.amount': 99.99,
'duration': 1500,
'start_time': Date.now()
});addEventModifier(eventModifier): Unsubscriber | undefined
Registers a function to modify events before they are sent to Dynatrace.
Parameters:
eventModifier: (jsonEvent: Readonly<JSONEvent>, eventContext?: EventContext) => JSONEvent | null- Function that receives an event and returns a modified version or null to cancel the event.
Returns:
Unsubscriber | undefined- Function to remove the modifier, or undefined if the RUM JavaScript is not available.
Example:
import { addEventModifier } from '@dynatrace/rum-javascript-sdk/api';
const unsubscribe = addEventModifier((event, context) => {
// Add user context to all events
return {
...event,
'event_properties.user_tier': 'premium'
};
});
// Later, remove the modifier
unsubscribe?.();runHealthCheck(config?): Promise<unknown[] | undefined> | undefined
Runs a health check on the RUM JavaScript to diagnose potential issues.
Parameters:
config?: HealthCheckConfig- Optional configuration object:logVerbose?: boolean- Include verbose information in the health checkreturnDiagnosticData?: boolean- Return diagnostic data as array instead of just loggingrunDetailedOverrideCheck?: boolean- Log additional information about overridden native APIs
Returns:
Promise<unknown[] | undefined> | undefined- Promise resolving to diagnostic data (if requested), or undefined if the RUM JavaScript is not available.
Example:
import { runHealthCheck } from '@dynatrace/rum-javascript-sdk/api';
const diagnostics = await runHealthCheck({
logVerbose: true,
returnDiagnosticData: true
});
if (diagnostics) {
console.log('RUM Health Check Results:', diagnostics);
}identifyUser(value): void
Associates the current session with a specific user identifier.
Parameters:
value: string- User identifier (name, email, user ID, etc.)
Example:
import { identifyUser } from '@dynatrace/rum-javascript-sdk/api';
// Identify user after login
identifyUser('[email protected]');sendSessionPropertyEvent(fields): void
Sends session-level properties that will be attached to all subsequent events in the session.
Parameters:
fields: ApiCreatedSessionPropertiesEvent- Session properties object. All keys must be prefixed withsession_properties.and follow naming conventions (lowercase, numbers, underscores, dots).
Example:
import { sendSessionPropertyEvent } from '@dynatrace/rum-javascript-sdk/api';
sendSessionPropertyEvent({
'session_properties.user_type': 'premium',
'session_properties.subscription_tier': 'gold',
'session_properties.region': 'us_east'
});sendExceptionEvent(error, fields?): void
Sends an exception event. Marks the exception event with characteristics.is_api_reported and error.source = api to make it clear on DQL side where errors are coming from.
Only available if the Errors module is enabled.
Parameters:
error: Error- The error object to report. Must be an instance of the standard JavaScriptErrorclass.fields: ApiCreatedEventPropertiesEvent- Optional Event properties object. Must be serializable JSON with properties prefixed withevent_properties., plus optionaldurationandstart_timeproperties.
Example:
import { sendExceptionEvent } from '@dynatrace/rum-javascript-sdk/api';
const yourError = new Error("Your Error Message");
sendExceptionEvent(yourError);import { sendExceptionEvent } from '@dynatrace/rum-javascript-sdk/api';
const yourError = new Error("Your Error Message");
sendExceptionEvent(yourError, { "event_properties.component": "myExampleComponent" });Asynchronous API (@dynatrace/rum-javascript-sdk/promises)
The asynchronous API provides Promise-based functions that wait for the Dynatrace RUM JavaScript to become available. These functions will throw a DynatraceError if the RUM JavaScript is not available within the specified timeout. This is useful for scenarios where you don't want to
enable the RUM JavaScript before the user gives their consent.
sendEvent(fields, eventContext?, timeout?): Promise<void>
Async wrapper for sending custom events, with automatic waiting for RUM JavaScript availability.
Parameters:
fields: ApiCreatedEventPropertiesEvent- Event properties objecteventContext?: unknown- Optional context for event modification callbackstimeout?: number- Timeout in milliseconds to wait for RUM JavaScript (default: 10,000)
Throws:
DynatraceError- If RUM JavaScript is not available within timeout
Example:
import { sendEvent } from '@dynatrace/rum-javascript-sdk/api/promises';
try {
await sendEvent({
'event_properties.conversion': 'purchase',
'event_properties.value': 149.99
}, undefined, 15000); // 15 second timeout
} catch (error) {
console.error('Failed to send event:', error.message);
}addEventModifier(eventModifier, timeout?): Promise<Unsubscriber>
Async wrapper for registering event modifiers, with automatic waiting for RUM JavaScript availability.
Parameters:
eventModifier: (jsonEvent: Readonly<JSONEvent>, eventContext?: EventContext) => JSONEvent | null- Event modifier functiontimeout?: number- Timeout in milliseconds to wait for RUM JavaScript (default: 10,000)
Returns:
Promise<Unsubscriber>- Promise resolving to unsubscriber function
Example:
import { addEventModifier } from '@dynatrace/rum-javascript-sdk/api/promises';
const unsubscribe = await addEventModifier((event) => ({
...event,
'event_properties.environment': 'production'
}));runHealthCheck(config?, timeout?): Promise<unknown[] | undefined>
Async wrapper for running health checks, with automatic waiting for RUM JavaScript availability.
Parameters:
config?: HealthCheckConfig- Optional health check configurationtimeout?: number- Timeout in milliseconds to wait for RUM JavaScript (default: 10,000)
Returns:
Promise<unknown[] | undefined>- Promise resolving to diagnostic data
identifyUser(value, timeout?): Promise<void>
Async wrapper for user identification, with automatic waiting for RUM JavaScript availability.
Parameters:
value: string- User identifiertimeout?: number- Timeout in milliseconds to wait for RUM JavaScript (default: 10,000)
sendSessionPropertyEvent(fields, timeout?): Promise<void>
Async wrapper for sending session properties, with automatic waiting for RUM JavaScript availability.
Parameters:
fields: ApiCreatedSessionPropertiesEvent- Session properties objecttimeout?: number- Timeout in milliseconds to wait for RUM JavaScript (default: 10,000)
sendExceptionEvent(error, fields?): void
Async wrapper for sending an exception event, with automatic waiting for RUM JavaScript availability.
Marks the exception event with characteristics.is_api_reported and error.source = api to make it clear on DQL side where errors are coming from.
Only available if the Errors module is enabled.
Parameters:
error: Error- The error object to report. Must be an instance of the standard JavaScriptErrorclass.fields: ApiCreatedEventPropertiesEvent- Optional Event properties object. Must be serializable JSON with properties prefixed withevent_properties., plus optionaldurationandstart_timeproperties.
User Actions API
Both synchronous and asynchronous wrappers are available for the User Actions API. For detailed documentation and examples, see USERACTIONS.md.
Synchronous API:
import {
createUserAction,
subscribeToUserActions,
setAutomaticUserActionDetection,
getCurrentUserAction
} from '@dynatrace/rum-javascript-sdk/api';
// Create a manual user action
const userAction = createUserAction({ autoClose: false });
// perform work
userAction?.finish();Asynchronous API:
import { createUserAction } from '@dynatrace/rum-javascript-sdk/api/promises';
const userAction = await createUserAction({ autoClose: false });
// perform work
userAction.finish();Error Handling
DynatraceError
Both APIs export a DynatraceError class for handling RUM-specific errors:
import { sendEvent, DynatraceError } from '@dynatrace/rum-javascript-sdk/promises';
try {
await sendEvent({ 'event_properties.test': 'value' });
} catch (error) {
if (error instanceof DynatraceError) {
console.error('RUM API Error:', error.message);
// Handle RUM-specific error
} else {
console.error('Unexpected error:', error);
}
}TypeScript Support
For detailed type information and usage examples, see types.md.
import type {
ApiCreatedEventPropertiesEvent,
ApiCreatedSessionPropertiesEvent,
HealthCheckConfig,
JSONEvent,
EventContext
} from '@dynatrace/rum-javascript-sdk/types';Testing
For testing applications that use this RUM API, see the testing framework documentation in testing.md.
The testing framework provides Playwright fixtures for:
- Waiting for and validating RUM events
- Asserting on specific event properties
- Testing RUM integration in end-to-end scenarios
Best Practices
When to Use Synchronous vs Asynchronous API
Use Synchronous API when:
- You want graceful degradation when the RUM JavaScript is not available
- You're instrumenting existing code and don't want to change control flow
- You're okay with events being dropped if the RUM JavaScript isn't loaded
Use Asynchronous API when:
- You need to ensure events are actually sent
- You want to handle RUM JavaScript availability errors explicitly
- You're building critical instrumentation that must not fail silently
Event Property Naming
Follow prefix custom event properties with event_properties.:
// ✅ Good - properties with prefix are accepted
sendEvent({
'event_properties.action': 'login',
'event_properties.method': 'oauth',
'event_properties.page_name': 'dashboard',
'event_properties.load_time': 1234
});
// ❌ Avoid - properties without prefix are ignored
sendEvent({
'action': 'click',
'data': 'some_value'
});Session Properties
Use session properties for data that applies to the entire user session:
// Set once per session
sendSessionPropertyEvent({
'session_properties.subscription_type': 'premium',
'session_properties.region': 'europe',
'session_properties.app_version': '2.1.0'
});