# RUM Script Installation



The VitalSentinel RUM (Real User Monitoring) script collects Core Web Vitals and performance metrics from your actual visitors. It's lightweight (\~13KB gzipped) and non-blocking.

## Basic Installation [#basic-installation]

Add this script to the `<head>` section of your HTML:

```html
<script
  src="https://rum.vitalsentinel.com/rum.js"
  data-key="YOUR_TRACKING_ID"
  async
></script>
```

<Callout type="info">
  Find your tracking ID in **Domain Settings** → &#x2A;*Real User Monitoring (RUM)**.
</Callout>

## Configuration Options [#configuration-options]

Customize the script behavior using `data-*` attributes:

| Attribute                  | Type    | Default   | Description                                                           |
| -------------------------- | ------- | --------- | --------------------------------------------------------------------- |
| `data-key`                 | string  | required  | Your unique tracking ID                                               |
| `data-sample-rate`         | number  | 1.0       | Sampling rate (0.0-1.0)                                               |
| `data-debug`               | boolean | false     | Enable console logging                                                |
| `data-engagement`          | boolean | true      | Track clicks, scroll depth, time on page, and form interactions       |
| `data-mask-text`           | boolean | false     | Redact text content                                                   |
| `data-mask-selectors`      | boolean | false     | Redact CSS selectors                                                  |
| `data-filter-query-params` | boolean | false     | Remove query parameters                                               |
| `data-batch-size`          | number  | (default) | How many events to buffer before sending                              |
| `data-flush-interval`      | number  | (default) | Longest time to wait, in milliseconds, before sending buffered events |

### Tuning Batching [#tuning-batching]

Most sites should leave `data-batch-size` and `data-flush-interval` at their defaults - they're tuned for typical traffic patterns. Adjust them only if you have a specific reason:

* **Very high traffic** - increasing the batch size reduces the number of network requests per visitor.
* **Long-lived single-page apps** - setting a flush interval sends events periodically even when the user stays on one route for a long time. By default, events are sent when the page is hidden or unloaded.
* **Debugging** - a small flush interval and batch size make events show up in your network panel almost immediately.

### Example with Options [#example-with-options]

```html
<script
  src="https://rum.vitalsentinel.com/rum.js"
  data-key="abc123"
  data-sample-rate="0.5"
  data-debug="true"
  data-engagement="true"
  async
></script>
```

## What Data is Collected [#what-data-is-collected]

### Core Web Vitals [#core-web-vitals]

The script automatically tracks all Core Web Vitals:

* **LCP (Largest Contentful Paint)** - Loading performance
* **FCP (First Contentful Paint)** - Initial render time
* **CLS (Cumulative Layout Shift)** - Visual stability
* **INP (Interaction to Next Paint)** - Interactivity
* **TTFB (Time to First Byte)** - Server response time

### Navigation Timing [#navigation-timing]

* DNS lookup time
* TCP connection time
* Request/response time
* DOM load time
* Full page load time

### User Engagement [#user-engagement]

When enabled (default), tracks:

* Scroll depth milestones (25%, 50%, 75%, 90%, 100%)
* Time on page and active time
* Page visibility changes
* Click tracking and rage click detection
* Form engagement (focus, changes, submissions, abandonment)

### Error Tracking [#error-tracking]

* JavaScript errors with stack traces
* Unhandled promise rejections
* Resource loading failures (images, scripts, stylesheets)

### Device Information [#device-information]

* Screen size and device pixel ratio
* Device memory and CPU cores
* Effective network connection type (slow-2g, 2g, 3g, or 4g) and downlink estimate
* Touch capability

## Platform-Specific Installation [#platform-specific-installation]

### WordPress [#wordpress]

Use a header scripts plugin, or add to your theme's `functions.php`:

```php
function vitalsentinel_rum_script() {
    ?>
    <script src="https://rum.vitalsentinel.com/rum.js" data-key="YOUR_TRACKING_ID" async></script>
    <?php
}
add_action('wp_head', 'vitalsentinel_rum_script');
```

See [Platform Guides](/installation/platforms) for the `wp_enqueue_script` alternative.

### Shopify [#shopify]

1. Go to **Online Store** → **Themes**
2. Click &#x2A;*...** → **Edit code** on your active theme
3. Open `theme.liquid` in the Layout folder
4. Add the script before `</head>`

### Next.js [#nextjs]

Using the Script component in your root layout (`app/layout.tsx`):

```jsx
import Script from 'next/script';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        {children}
        <Script
          src="https://rum.vitalsentinel.com/rum.js"
          data-key="YOUR_TRACKING_ID"
          strategy="afterInteractive"
        />
      </body>
    </html>
  );
}
```

### React (Create React App) [#react-create-react-app]

Add to `public/index.html`:

```html
<script
  src="https://rum.vitalsentinel.com/rum.js"
  data-key="YOUR_TRACKING_ID"
  async
></script>
```

### Vue.js [#vuejs]

Add to `public/index.html` or your main template.

### Nuxt.js [#nuxtjs]

In `nuxt.config.js`:

```js
export default {
  head: {
    script: [
      {
        src: 'https://rum.vitalsentinel.com/rum.js',
        'data-key': 'YOUR_TRACKING_ID',
        async: true
      }
    ]
  }
}
```

## SPA Support [#spa-support]

The RUM script automatically detects Single Page Application navigation using the History API. For manual control:

```javascript
// Trigger navigation tracking manually
window.VitalSentinelRUM.startSoftNavigation();
```

This is useful for:

* Custom routing implementations
* Hash-based navigation
* Complex state transitions

## API Methods [#api-methods]

The script exposes methods for custom tracking via `window.VitalSentinelRUM` (or the shorter alias `window.VSRUM`):

### Track Custom Events [#track-custom-events]

```javascript
window.VitalSentinelRUM.trackCustomEvent('purchase', {
  productId: '12345',
  value: 99.99,
  currency: 'USD'
});
```

### Mark Points in Time [#mark-points-in-time]

```javascript
// Mark points in time
window.VitalSentinelRUM.mark('hero-start');
window.VitalSentinelRUM.mark('hero-loaded');

// Measure time between two marks
window.VitalSentinelRUM.measure('hero-time', { start: 'hero-start', end: 'hero-loaded' });
```

### Add Custom Data [#add-custom-data]

```javascript
// Add data to all subsequent events
window.VitalSentinelRUM.addData('userId', 'user-123');
window.VitalSentinelRUM.addData('plan', 'premium');
```

### Event Hooks [#event-hooks]

```javascript
// Listen to RUM events
window.VitalSentinelRUM.on('mark', (eventType, data) => {
  console.log('Mark created:', data.name, data.startTime);
});

window.VitalSentinelRUM.on('measure', (eventType, data) => {
  console.log('Measure recorded:', data.name, data.duration);
});

window.VitalSentinelRUM.on('soft_navigation', (eventType, data) => {
  console.log('SPA navigation:', data);
});
```

### Force Send Data [#force-send-data]

```javascript
// Send all queued events immediately
window.VitalSentinelRUM.forceFlush();
```

### Get Debug Info [#get-debug-info]

```javascript
const debug = window.VitalSentinelRUM.getDebug();
console.log(debug);
// Returns: {
//   sessionId: string,
//   eventQueue: number,
//   marks: Array,
//   customData: Array,
//   hooks: string[],
//   navigationCount: number
// }
```

## Command Queue [#command-queue]

The script installs its own command queue as soon as it loads. Once the tag is on the page, queue commands with `cmd()`:

```javascript
// Queue commands with cmd()
window.VitalSentinelRUM.cmd(['mark', 'app-start']);

// trackCustomEvent isn't queueable - call it directly
window.VitalSentinelRUM.trackCustomEvent('page_intent', { category: 'pricing' });
```

## Privacy & Consent [#privacy--consent]

### Privacy by Default [#privacy-by-default]

The RUM script is designed with privacy in mind:

* No persistent cookies by default
* No cross-site tracking
* Session IDs regenerate on page refresh (no persistent identifiers)
* URL sanitization available via `data-filter-query-params`

### Privacy Options [#privacy-options]

Enable additional privacy features:

```html
<script
  src="https://rum.vitalsentinel.com/rum.js"
  data-key="YOUR_TRACKING_ID"
  data-mask-text="true"
  data-mask-selectors="true"
  data-filter-query-params="true"
  async
></script>
```

* `data-mask-text` - Redacts text content in engagement events
* `data-mask-selectors` - Masks CSS selectors in click/form tracking
* `data-filter-query-params` - Removes query parameters from tracked URLs

### Opt-Out Support [#opt-out-support]

Respect user preferences:

```javascript
// Check Do Not Track
if (navigator.doNotTrack === '1') {
  // Don't load the script
}
```

### GDPR Compliance [#gdpr-compliance]

The RUM script is designed to be GDPR-friendly by default (no cookies, no persistent identifiers). For additional compliance:

1. **Delay loading** until consent is given
2. **Use sampling** (`data-sample-rate`) to reduce data collection
3. **Enable privacy options** (`data-mask-text`, `data-mask-selectors`, `data-filter-query-params`)

## Troubleshooting [#troubleshooting]

### Script Not Loading [#script-not-loading]

1. Check browser console for errors
2. Verify the tracking ID is correct
3. Ensure no ad blocker is blocking the script
4. Check Content Security Policy headers

### No Data Appearing [#no-data-appearing]

1. Wait 15-30 minutes for initial data
2. Check sample rate is greater than 0
3. Verify the domain matches your configured domain
4. Enable debug mode to see console logs

### Debug Mode [#debug-mode]

Enable debug logging:

```html
<script
  src="https://rum.vitalsentinel.com/rum.js"
  data-key="YOUR_TRACKING_ID"
  data-debug="true"
  async
></script>
```

Then check your browser console for `[VitalSentinel RUM]` messages.

## Browser Compatibility [#browser-compatibility]

The RUM script supports:

* Chrome/Edge 90+
* Firefox 89+
* Safari 15+
* Opera 76+

Older browsers will gracefully degrade without causing errors.

## Related [#related]

<Cards>
  <Card title="RUM Monitoring" href="/features/rum-monitoring">
    Learn about the metrics and insights available from RUM data
  </Card>

  <Card title="Performance Thresholds" href="/features/performance-thresholds">
    Understand what good, needs improvement, and poor metrics look like
  </Card>

  <Card title="Data & Privacy" href="/others/data-privacy">
    Details on data collection, storage, and GDPR compliance
  </Card>

  <Card title="Troubleshooting" href="/help/troubleshooting">
    Solutions to common installation and tracking issues
  </Card>
</Cards>
