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

# Web SDK Integration Guide

> Learn how to integrate Web RUM SDK in Web applications, including NPM, CDN async, and CDN sync methods

<Info>
  RUM SDK supports multiple integration methods. Choose the one that best fits your project requirements.
</Info>

## Integration Methods

We provide three integration methods:

| Method        | Recommended For          | Features                                           |
| ------------- | ------------------------ | -------------------------------------------------- |
| **NPM**       | Modern web apps          | Bundled with frontend code, no impact on page load |
| **CDN Async** | Performance-focused apps | Async loading, doesn't affect page performance     |
| **CDN Sync**  | Complete data collection | Sync loading, captures all events                  |

<Warning>
  NPM and CDN async methods may miss errors, resources, and user actions triggered before SDK initialization. Use CDN sync for complete collection.
</Warning>

## Integration Code

<Tabs>
  <Tab title="NPM Package">
    Add `@flashcatcloud/browser-rum` to your `package.json`:

    ```bash theme={null}
    npm install @flashcatcloud/browser-rum
    ```

    Then initialize in your app entry file:

    ```javascript theme={null}
    import { flashcatRum } from "@flashcatcloud/browser-rum";

    flashcatRum.init({
      applicationId: "<YOUR_APPLICATION_ID>",
      clientToken: "<YOUR_CLIENT_TOKEN>",
      service: "<SERVICE_NAME>",
      env: "<ENV_NAME>",
      version: "1.0.0",
      sessionSampleRate: 100
    });
    ```
  </Tab>

  <Tab title="CDN Async">
    Add the following code snippet to the `<head>` tag of each HTML page you want to monitor:

    ```html theme={null}
    <script>
      (function (h, o, u, n, d) {
        h = h[d] = h[d] || {
          q: [],
          onReady: function (c) {
            h.q.push(c);
          },
        };
        d = o.createElement(u);
        d.async = 1;
        d.src = n;
        n = o.getElementsByTagName(u)[0];
        n.parentNode.insertBefore(d, n);
      })(
        window,
        document,
        "script",
        "https://static.flashcat.cloud/browser-sdk/v0/flashcat-rum.js",
        "FC_RUM"
      );
      window.FC_RUM.onReady(function () {
        window.FC_RUM.init({
          applicationId: "<YOUR_APPLICATION_ID>",
          clientToken: "<YOUR_CLIENT_TOKEN>",
          service: "<SERVICE_NAME>",
          env: "<ENV_NAME>",
          version: "1.0.0",
          sessionSampleRate: 100
        });
      });
    </script>
    ```
  </Tab>

  <Tab title="CDN Sync">
    Add the following code snippet at the very beginning of the `<head>` tag (before any other `<script>` tags):

    ```html theme={null}
    <script
      src="https://static.flashcat.cloud/browser-sdk/v0/flashcat-rum.js"
      type="text/javascript"
    ></script>
    <script>
      window.FC_RUM &&
        window.FC_RUM.init({
          applicationId: "<YOUR_APPLICATION_ID>",
          clientToken: "<YOUR_CLIENT_TOKEN>",
          service: "<SERVICE_NAME>",
          env: "<ENV_NAME>",
          version: "1.0.0",
          sessionSampleRate: 100
        });
    </script>
    ```

    <Tip>
      You can use `window.FC_RUM` to check if the SDK loaded successfully, allowing you to handle load failures.
    </Tip>
  </Tab>
</Tabs>

## Initialization Parameters

### Required Parameters

<ParamField body="applicationId" type="string" required>
  Application ID, obtained from the application management page
</ParamField>

<ParamField body="clientToken" type="string" required>
  Client Token, obtained from the application management page
</ParamField>

<ParamField body="service" type="string" required>
  Service name, used to distinguish different services
</ParamField>

### Optional Parameters

<ParamField body="env" type="string">
  Environment identifier, such as `production`, `staging`, etc.
</ParamField>

<ParamField body="version" type="string">
  Application version number
</ParamField>

<ParamField body="sessionSampleRate" type="number" default="100">
  Percentage of sessions to track: 100 for all, 0 for none
</ParamField>

<ParamField body="sessionReplaySampleRate" type="number" default="0">
  Percentage of sessions with [Session Replay](/en/rum/session-replay/overview) enabled
</ParamField>

<ParamField body="trackingConsent" type="'granted' | 'not-granted'" default="granted">
  Initial user tracking consent state, see [User Tracking Consent](/en/rum/sdk/web/advanced-config#user-tracking-consent)
</ParamField>

<ParamField body="trackViewsManually" type="boolean" default="false">
  Whether to manually control view creation, see [Override Default View Names](/en/rum/sdk/web/advanced-config#override-default-rum-view-names)
</ParamField>

<ParamField body="trackUserInteractions" type="boolean" default="true">
  Whether to automatically collect user interactions
</ParamField>

<ParamField body="trackResources" type="boolean" default="true">
  Whether to enable resource event collection
</ParamField>

<ParamField body="trackLongTasks" type="boolean" default="true">
  Whether to enable long task event collection
</ParamField>

<ParamField body="trackAnonymousUser" type="boolean" default="true">
  Whether to enable cross-session anonymous user ID collection
</ParamField>

<ParamField body="sessionReplayPrivacyLevel" type="'allow' | 'mask-user-input' | 'mask'" default="mask-user-input">
  Session replay privacy policy: `allow` collects all data except passwords, `mask-user-input` hides user input field content, and `mask` hides all text
</ParamField>

<ParamField body="allowedTracingUrls" type="array">
  List of request URLs for injecting tracing headers, see [Integrate RUM with Distributed Tracing](/en/rum/sdk/web/advanced-config#integrate-rum-with-distributed-tracing)
</ParamField>

<ParamField body="traceSampleRate" type="number" default="100">
  Percentage of requests to trace
</ParamField>

<ParamField body="proxy" type="string">
  Optional proxy URL, e.g., `https://www.proxy.com/path`
</ParamField>

<ParamField body="compressIntakeRequests" type="boolean" default="false">
  Whether to compress requests sent to Flashduty, done in Worker thread
</ParamField>

<ParamField body="storeContextsAcrossPages" type="boolean" default="false">
  Whether to store context in localStorage for cross-page persistence
</ParamField>

## Use Cases

### Custom User Identification

Use `flashcatRum.setUser()` to add identification attributes for the current user:

```javascript theme={null}
flashcatRum.setUser({
  id: '1234',
  name: 'John Doe',
  email: 'john@doe.com',
  plan: 'premium'
});
```

### Adding Custom Tags

After initializing RUM, use the `setGlobalContextProperty` API to add additional tags to all RUM events:

```javascript theme={null}
import { flashcatRum } from "@flashcatcloud/browser-rum";

flashcatRum.setGlobalContextProperty('activity', {
  hasPaid: true,
  amount: 23.42
});
```

### Sending Custom Actions

Use the `addAction` API to create RUM actions with context attributes:

```javascript theme={null}
import { flashcatRum } from "@flashcatcloud/browser-rum";

function onCheckoutButtonClick(cart) {
  flashcatRum.addAction("checkout", {
    value: cart.value,
    items: cart.items
  });
}
```

### Custom Error Reporting

You can attach local context to error objects via the `dd_context` property:

```javascript theme={null}
const error = new Error("Something went wrong");
error.dd_context = { component: "Menu", param: 123 };
throw error;
```

## Verification

<Steps>
  <Step title="Check Network Requests">
    Open browser developer tools and check if there are data upload requests to `https://browser.flashcat.cloud/api/v2/rum` in the Network panel.
  </Step>

  <Step title="View Console Data">
    Access the Flashduty console to verify that RUM application data is displaying correctly.
  </Step>

  <Step title="Trigger User Interactions">
    Trigger some user interactions on the page (clicks, scrolls, etc.) to verify data collection is working.

    <Check>
      Data typically appears in the console within 2-5 minutes.
    </Check>
  </Step>
</Steps>

## Next Steps

<CardGroup cols={3}>
  <Card title="Advanced Configuration" icon="sliders" href="/en/rum/sdk/web/advanced-config">
    Learn about advanced SDK configuration features
  </Card>

  <Card title="Data Collection" icon="database" href="/en/rum/sdk/web/data-collection">
    Learn about data types collected by the SDK
  </Card>

  <Card title="Insights" icon="chart-line" href="/en/rum/analytics/web">
    View and analyze RUM data
  </Card>
</CardGroup>
