Amazon CloudWatch RUM Web Client

repository·main·Indexed 40 days ago

https://github.com/aws-observability/aws-rum-web

A JavaScript library for real user monitoring (RUM) that captures web vitals, JavaScript errors, HTTP requests, and session replays. It provides multiple distribution options including a full build (aws-rum-web) and a lightweight build (@aws-rum/web-slim), supporting both NPM bundling and CDN snippet patterns for MPAs. Version 3.2.1 features a plugin-based architecture for telemetry groups such as errors, performance, http, interaction, and replay.

Tokens
43.1K
Snippets
109
Records
183
Agent score
94%

What's inside CloudWatch RUM

  1. Overview of CloudWatch RUM Web Client

    main

    The CloudWatch RUM Web Client is a JavaScript library designed for real user monitoring on web applications. It captures various telemetry data including:

    • Page load timing
    • Web Vitals
    • JavaScript errors
    • HTTP requests
    • Session replays
    • Custom events

    All captured data is shipped to Amazon CloudWatch RUM for analysis.

  2. Choose the right AWS RUM Web package

    main

    The AWS RUM Web client is distributed via three npm packages. Most users should use aws-rum-web.

    • aws-rum-web: The full distribution. It includes the slim core plus Cognito authentication, SigV4 signing, the default telemetry group (errors, performance, http, replay), and remote configuration. This is the recommended default.
    • @aws-rum/web-slim: An imperative distribution designed for minimal bundle size. It does not include Cognito, default telemetries, or built-in signing. You must manually wire up plugins via eventPluginsToLoad and configure authentication/signing yourself.
    • @aws-rum/web-core: Contains the engine and plugin types. This is intended for developers building custom distributions or writing new plugins; it is not a standalone SDK.
  3. Use @aws-rum/web-slim for a lightweight RUM client

    main

    The @aws-rum/web-slim package provides a smaller, imperative distribution of the Amazon CloudWatch RUM web client. It uses the same AwsRum class and public API as the full aws-rum-web package but excludes bundled Cognito auth, default telemetries, remote config, and SigV4 signing. This allows you to manually wire up only the features you need, reducing bundle size.

    Size Comparison:

    • CDN bundle (minified): ~32 KB (vs ~162 KB for full)
    • CDN bundle (gzipped): ~10 KB (vs ~50 KB for full)
  4. Caveats for sharing user identity across contexts

    main

    When implementing manual user identity synchronization, be aware of the following constraints:

    • Silent Seeding: There is no user_start event for seeded IDs, so there is no suppression flag available for followers; the initial seed is always silent.
    • Sticky Manual Mode: Once an instance has a userId seeded via configuration or pinUserId(), it enters a 'sticky' manual mode. The SDK will never fall back to cookies or mint a new UUID for that instance, even if allowCookies is changed or cookies are cleared.
    • NPM vs CDN Availability: pinUserId() is available in both NPM and CDN builds. However, getUserId() is NPM-only. If you use the CDN, you cannot retrieve the ID from the leader to broadcast it.
    • No Built-in Transport: The SDK does not provide the mechanism to move data between instances. The developer is responsible for the broadcasting logic (e.g., via postMessage).
    • No Change Callbacks: The SDK does not currently provide a callback to notify instances when a user ID has changed; instances must be updated via the host's communication channel.
  5. Configure the Telemetry Config Array

    main

    The telemetries configuration is an array that defines which categories of data the RUM client records. Each entry in the array can be either a simple string (using default settings) or an array containing the telemetry name and a configuration object.

    Available Telemetry Names:

    • errors: Records JavaScript errors (unhandled by default).
    • http: Records HTTP requests (failed requests by default). Required for X-Ray tracing.
    • interaction: Records DOM events (must be configured to record specific events).
    • performance: Records page load timing, web vitals, and resource load timing.
    • replay: Records a session replay using rrweb (text/input content is masked by default).

    Examples:

    Using default configurations:

    telemetries: ['errors', 'performance', 'http'];

    Providing partial configurations:

    telemetries: [
        ['errors', { stackTraceLength: 500 }],
        'performance',
        ['http', { stackTraceLength: 500, addXRayTraceIdHeader: true }]
    ];
  6. Manage user identity and manual mode

    main

    The web client persists an anonymous user ID in the cwr_u cookie for userIdRetentionDays (default 30).

    Manual Mode for User Identity

    You can take ownership of the user identity by seeding userId during construction or calling pinUserId(id) at runtime. Once engaged, manual mode is sticky for the life of the instance:

    • getUserId() returns the host-supplied ID even if allowCookies: false or userIdRetentionDays: 0.
    • No user_start event is emitted.

    Use this when the host already knows the identity (e.g., a signed-in account ID or a stable device ID).

  7. How plugins work in AWS RUM Web Client

    main

    In the AWS RUM Web Client, every piece of instrumentation is a plugin. A plugin is a module that observes a specific part of the web environment (such as the DOM, fetch calls, or the Performance API) and emits RUM events to CloudWatch.

    Plugins are categorized by their telemetry group (e.g., errors, performance, http) and the specific event types they emit.

  8. How sessions and sampling work in CloudWatch RUM

    main

    A session is a period of activity by a single anonymous user. Every RUM event is tagged with a session ID so CloudWatch RUM can compute sessionized metrics (e.g., errors per session).

    Session Lifecycle

    1. Initialization: The client calls getSession().
    2. Reuse: If a valid session exists in the cwr_s cookie (and allowCookies is true), it is reused.
    3. Creation: If no session exists, a new UUID v4 is generated, a sampling decision is made, and a com.amazon.rum.session_start_event is emitted.
    4. Expiration: Sessions expire after sessionLengthSeconds (default 1800s / 30 min) of inactivity. The next getSession() call rotates it.

    Sampling Logic

    sessionSampleRate (default 1) determines the probability that a session's events are recorded. Sampling is decided once per session, not per event.

    • 1: Record every session.
    • 0.1: Record 10% of sessions.
    • 0: Record no sessions (useful as a kill-switch).

    Once a session is selected for recording, all its events are captured up to the sessionEventLimit (default 200). Set sessionEventLimit: 0 to remove this cap.

  9. Compare @aws-rum/web-core vs @aws-rum/web-slim

    main

    The web-slim package is a lightweight distribution that provides the same API surface as the full package but excludes several heavy features:

    • No Cognito auth: identityPoolId and guestRoleArn do not work. You must use setAwsCredentials with a custom provider.
    • No built-in SigV4: You must manually opt-in using setSigningConfigFactory(createSigningConfig) from @aws-rum/web-core.
    • No Remote config: The u field in the CDN snippet is unavailable.
    • No automatic telemetries: You must load plugins explicitly via eventPluginsToLoad.
  10. How plugins and telemetries work in AWS RUM

    main

    The AWS RUM web client's instrumentation is organized into plugins. Most plugins are grouped into logical telemetries (such as errors, performance, http, interaction, and replay).

    To enable a group of related plugins, you configure the telemetries array in your configuration. For example, adding errors to the telemetries array will enable the JsErrorPlugin.

    Some plugins are always on (like PageViewPlugin), while others are opt-in via specific configuration keys (like TTIPlugin via eventPluginsToLoad).

  11. Manage event flushing on page hide

    main

    To prevent data loss when a user leaves a page, the client automatically flushes the event cache when the page is hidden (visibilitychange → hidden or pagehide).

    Beacon vs Fetch

    The method used for this flush depends on the useBeacon configuration:

    • useBeacon: true (default): Attempts to use navigator.sendBeacon, falling back to fetch. This is the safest method for ensuring delivery after a page is gone, but it cannot include custom headers.
    • useBeacon: false: Attempts to use fetch, falling back to sendBeacon. Use this setting if you are using custom headers.

    Manual Flushing

    You can manually trigger a flush using the following methods:

    • awsRum.dispatch(): Uses fetch.
    • awsRum.dispatchBeacon(): Uses sendBeacon, falling back to fetch on failure.
    // Manual flush using fetch
    awsRum.dispatch(); 
    
    // Manual flush using sendBeacon (safer for page exit)
    awsRum.dispatchBeacon();
  12. Understand payload compression

    main

    By default, the client uses gzip compression to reduce payload size.

    • Activation: Compression is enabled when compressionStrategy.enabled is true (default).
    • Threshold: Payloads larger than approximately 2KB are considered for compression.
    • Efficiency Check: Compression is only applied if it achieves a $\ge$ 20% reduction in size. If the reduction is less than 20%, the raw payload is sent instead.
    • Header: Compressed requests include the Content-Encoding: gzip header. RUM JSON payloads typically see a 60–80% reduction.