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.
npm install @dynatrace/rum-javascript-sdk
This package provides two main API approaches for interacting with the Dynatrace RUM JavaScript, as well as types and a Playwright testing framework:
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('user@example.com');
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('user@example.com');
} catch (error) {
console.error('RUM JavaScript not available:', error);
}
@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?): voidSends a custom event to Dynatrace RUM.
Parameters:
fields: ApiCreatedEventPropertiesEvent - Event properties object. Must be serializable JSON with properties prefixed with event_properties., plus optional duration and start_time properties.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 | undefinedRegisters 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> | undefinedRuns 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 APIsReturns:
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): voidAssociates 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('john.doe@example.com');
sendSessionPropertyEvent(fields): voidSends 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 with session_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?): voidSends 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 JavaScript Error class.fields: ApiCreatedEventPropertiesEvent - Optional Event properties object. Must be serializable JSON with properties prefixed with event_properties., plus optional duration and start_time properties.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" });
@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 timeoutExample:
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 functionExample:
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 dataidentifyUser(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?): voidAsync 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 JavaScript Error class.fields: ApiCreatedEventPropertiesEvent - Optional Event properties object. Must be serializable JSON with properties prefixed with event_properties., plus optional duration and start_time properties.Both synchronous and asynchronous wrappers are available for the User Actions API. For detailed documentation and examples, see User Actions API.
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();
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);
}
}
For detailed type information and usage examples, see Dynatrace Api Types.
import type {
ApiCreatedEventPropertiesEvent,
ApiCreatedSessionPropertiesEvent,
HealthCheckConfig,
JSONEvent,
EventContext
} from '@dynatrace/rum-javascript-sdk/types';
This package includes a Playwright testing framework for validating RUM integration. See Testing with Playwright for complete documentation including:
Use Synchronous API when:
Use Asynchronous API when:
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'
});
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'
});