> ## Documentation Index
> Fetch the complete documentation index at: https://docs.molesignal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Browser RUM SDK

> Install and configure the MoleSignal Browser RUM SDK, identify users, add custom events, and verify intake.

The MoleSignal Browser RUM SDK collects browser sessions, page views, user interactions,
frontend errors, Web Vitals, network resources, and trace correlation context.

## Prerequisites

* the MoleSignal deployment URL;
* a stable application identifier, such as `checkout-web`;
* a dedicated token authorized to send RUM data into the target workspace.

<Warning>
  `clientToken` is included in browser code and is visible to users. Never use an owner, administrator,
  or personal token. Use the application-bound `msrum_` client token created by the data-source guide.
</Warning>

## Install and initialize

<Steps>
  <Step title="Install the package">
    ```bash theme={null}
    npm install @molesignal/browser-rum
    ```
  </Step>

  <Step title="Initialize the SDK once">
    ```ts theme={null}
    import { initRum } from '@molesignal/browser-rum';

    const rum = initRum({
      applicationId: 'checkout-web',
      clientToken: 'msrum_your_client_token',
      site: 'https://molesignal.example.com',
      service: 'web-frontend',
      env: 'production',
      version: 'v1.4.0',
      sessionSampleRate: 100,
      trackUserInteractions: true,
    });
    ```

    Initialize the SDK before the application router mounts to capture the first page view.
    Importing and initializing the package during server-side rendering is safe; browser instrumentation
    starts only when browser APIs exist.
  </Step>

  <Step title="Verify the first session">
    Open **RUM → Overview** and select a time range that includes the current time. Confirm that the
    application appears, then open **Sessions** to inspect the first session.
  </Step>
</Steps>

The `site` value can be a MoleSignal origin, `/api` base, or `/api/v1` base. The SDK normalizes the value and
sends data to the RUM endpoints beneath `/api/v1/rum`.

## Identify users and add context

Provide the user during initialization when possible so the first session carries the correct identity.

```ts theme={null}
const rum = initRum({
  applicationId: 'checkout-web',
  clientToken: 'msrum_your_client_token',
  site: 'https://molesignal.example.com',
  user: { id: currentUser.id, plan: currentUser.plan },
  globalContext: { region: 'eu-west-1' },
});

rum.setUser({ id: 'user-42', plan: 'enterprise' });
rum.setGlobalContextProperty('feature_flags', ['new-checkout']);
```

When no user is provided, the SDK creates a stable anonymous identifier in `localStorage`. Set
`trackAnonymousUser: false` when privacy policy does not allow persistent anonymous identity.

## Add custom actions, errors, and views

```ts theme={null}
rum.addAction('Checkout submitted', {
  cart_size: 3,
  payment_method: 'card',
});

try {
  await submitOrder();
} catch (error) {
  rum.addError(error, { component: 'CheckoutForm' });
}

// Use this when trackViewsManually is true.
rum.startView('Order confirmation');
```

Call `rum.flush()` before a controlled navigation or shutdown to wait for queued events.
Call `rum.stop()` to remove instrumentation and flush the client.

## Automatic collection defaults

| Data                            | Option                    | Default                                  |
| ------------------------------- | ------------------------- | ---------------------------------------- |
| Page views                      | `trackViewsManually`      | Automatic History API tracking (`false`) |
| Fetch, XHR, and resource timing | `trackResources`          | `true`                                   |
| Long tasks                      | `trackLongTasks`          | `true`                                   |
| Web Vitals                      | `trackWebVitals`          | `true`                                   |
| Clicks and form submissions     | `trackUserInteractions`   | `false`                                  |
| Rage and dead clicks            | `trackFrustrations`       | Same as interaction tracking             |
| Runtime errors                  | built in                  | Enabled                                  |
| `console.error`                 | `trackConsoleErrors`      | `false`                                  |
| DOM session replay              | `sessionReplaySampleRate` | `0`                                      |

## Connect browser requests to traces

The fetch and XMLHttpRequest integrations read W3C `traceparent` from the outgoing request, response,
or a `Server-Timing` entry named `traceparent`. For cross-origin APIs, expose the response headers and
allow the origin explicitly:

```http theme={null}
Access-Control-Expose-Headers: traceparent, server-timing
```

```ts theme={null}
allowedTracingUrls: [
  'https://api.example.com',
  /^https:\/\/edge-\w+\.example\.com\//,
]
```

## Next steps

<CardGroup cols={2}>
  <Card title="Data sampling" icon="sliders" href="/en-US/rum/sampling">
    Control session and replay volume independently.
  </Card>

  <Card title="Privacy" icon="shield" href="/en-US/rum/privacy">
    Keep sensitive values on the user's device.
  </Card>

  <Card title="Session replay" icon="video" href="/en-US/rum/session-replay">
    Record and replay DOM changes safely.
  </Card>

  <Card title="Source maps & symbols" icon="file-code" href="/en-US/rum/source-maps">
    Restore minified browser stacks and review the unified artifact workflow.
  </Card>
</CardGroup>
