RUM JavaScript API - 1.333.0
    Preparing search index...

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

    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:

    • 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 User Actions API)
    • TypeScript Support: Comprehensive type definitions for all RUM API functions
    • Testing Framework: Playwright-based utilities for testing RUM integration
    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);
    }

    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.

    Sends 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()
    });

    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?.();

    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 check
      • returnDiagnosticData?: boolean - Return diagnostic data as array instead of just logging
      • runDetailedOverrideCheck?: 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);
    }

    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('john.doe@example.com');

    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 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'
    });

    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 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" });

    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.

    Async wrapper for sending custom events, with automatic waiting for RUM JavaScript availability.

    Parameters:

    • fields: ApiCreatedEventPropertiesEvent - Event properties object
    • eventContext?: unknown - Optional context for event modification callbacks
    • timeout?: 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);
    }

    Async wrapper for registering event modifiers, with automatic waiting for RUM JavaScript availability.

    Parameters:

    • eventModifier: (jsonEvent: Readonly<JSONEvent>, eventContext?: EventContext) => JSONEvent | null - Event modifier function
    • timeout?: 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'
    }));

    Async wrapper for running health checks, with automatic waiting for RUM JavaScript availability.

    Parameters:

    • config?: HealthCheckConfig - Optional health check configuration
    • timeout?: number - Timeout in milliseconds to wait for RUM JavaScript (default: 10,000)

    Returns:

    • Promise<unknown[] | undefined> - Promise resolving to diagnostic data

    Async wrapper for user identification, with automatic waiting for RUM JavaScript availability.

    Parameters:

    • value: string - User identifier
    • timeout?: number - Timeout in milliseconds to wait for RUM JavaScript (default: 10,000)

    Async wrapper for sending session properties, with automatic waiting for RUM JavaScript availability.

    Parameters:

    • fields: ApiCreatedSessionPropertiesEvent - Session properties object
    • timeout?: number - Timeout in milliseconds to wait for RUM JavaScript (default: 10,000)

    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 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:

    • Setup and configuration
    • Fixture usage and ordering
    • Event assertion methods
    • Troubleshooting guide

    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

    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'
    });