npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

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

Overview

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

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

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

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

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 configuration
  • timeout?: 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 identifier
  • timeout?: 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 object
  • timeout?: 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 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.

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