---
title: Upgrade the RUM Browser SDK
description: >-
  Upgrade guide for migrating between major versions of RUM Browser SDK with
  breaking changes, new features, and compatibility updates.
breadcrumbs: >-
  Docs > RUM & Session Replay > Real User Monitoring & Session Replay Guides >
  Upgrade the RUM Browser SDK
---

# Upgrade the RUM Browser SDK

## Overview{% #overview %}

Follow this guide to migrate between major versions of the Browser RUM and Browser Logs SDKs. See [the SDK documentation](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser.md) for details on its features and capabilities.

## From v6 to v7{% #from-v6-to-v7 %}

The v7 SDK improves privacy defaults, removes deprecated options, and modernizes the SDK internals. Most changes require configuration updates.

Take notice of the below breaking changes as you upgrade your SDK. Changes are grouped by area of impact.
If you use an AI coding assistant that supports agent skills, you can apply the [`upgrade-browser-sdk-v7` skill](https://github.com/DataDog/browser-sdk/blob/main/.claude/skills/upgrade-browser-sdk-v7/SKILL.md) to automate most of the migration steps below.
### Core{% #core %}

#### Session manager rewrite{% #session-manager-rewrite %}

The system that tracks sessions has been rewritten to improve data reliability and reduce billing discrepancies. Depending on your setup, you may notice changes in session counts.

#### Deterministic sampling decisions{% #deterministic-sampling-decisions %}

Previously, the sampling decision was made once at session creation and persisted. In v7, it is computed on demand from the session ID and sample rate, making it consistent regardless of which page initializes the SDK. If you use different sampling rates across pages, those rates are applied consistently.

#### Session store key renamed{% #session-store-key-renamed %}

The session storage key has changed from `_dd_s` to `_dd_s_v2` because the new session manager uses an incompatible storage format. On upgrade, existing sessions are automatically migrated from `_dd_s`.

**Note**: If you roll back to v6 after upgrading, the v6 SDK starts a new session because it does not read the `_dd_s_v2` key. If you have CSP or cookie policies that allowlist specific cookie names, add `_dd_s_v2`.

#### Update the CDN bundle URL{% #update-the-cdn-bundle-url %}

If you load the SDK from the Datadog CDN, update the version segment of the bundle URL from `v6` to `v7`. This applies to all bundles:

| Bundle   | URL                                                                     |
| -------- | ----------------------------------------------------------------------- |
| RUM      | `https://www.datadoghq-browser-agent.com/<SITE>/v7/datadog-rum.js`      |
| RUM Slim | `https://www.datadoghq-browser-agent.com/<SITE>/v7/datadog-rum-slim.js` |
| Logs     | `https://www.datadoghq-browser-agent.com/<SITE>/v7/datadog-logs.js`     |

Replace `<SITE>` with your Datadog site (for example, `us1`, `us3`, `us5`, `eu1`, `ap1`, or `ap2`). See the [setup documentation](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser.md) for the URL for your site.

#### CDN bundles use ESM dynamic imports{% #cdn-bundles-use-esm-dynamic-imports %}

CDN bundles use ESM dynamic imports instead of CommonJS, which reduces webpack overhead and overall bundle size. If you use the CDN snippet, add the `crossorigin` attribute to the script tag:

```html
<script src="https://www.datadoghq-browser-agent.com/..." crossorigin="anonymous"></script>
```

See the [setup documentation](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser.md) for full snippet examples.

#### ES2020 browser baseline{% #es2020-browser-baseline %}

Support for pre-ES2020 browsers has been dropped to remove compatibility shims and polyfills, which reduces bundle size. Minimum supported versions are Chrome 80+, Firefox 78+, and Safari 14+. Estimated impact: ~0.048% less coverage.

To continue supporting older browsers, keep using Browser SDK v6 or earlier.

#### Removed options{% #removed-options %}

| Deprecated option (v6 or earlier) | Replacement (v7)                                       |
| --------------------------------- | ------------------------------------------------------ |
| `betaEncodeCookieOptions`         | Cookie encoding is always enabled.                     |
| `allowFallbackToLocalStorage`     | Use `sessionPersistence: ['cookie', 'local-storage']`. |

### RUM{% #rum %}

#### `propagateTraceBaggage` enabled by default{% #propagatetracebaggage-enabled-by-default %}

The `propagateTraceBaggage` [initialization parameter](https://datadoghq.dev/browser-sdk/interfaces/_datadog_browser-rum.RumInitConfiguration.html) defaults to `true` in v7. Propagating baggage enables tail-based sampling and gives traces access to user and account context.

If you use distributed tracing on cross-origin requests, either set `propagateTraceBaggage: false` or add `baggage` to your `Access-Control-Allow-Headers` response headers:

```
Access-Control-Allow-Headers: traceparent, tracestate, baggage
```

#### New default for `defaultPrivacyLevel`{% #new-default-for-defaultprivacylevel %}

`defaultPrivacyLevel` defaults to `mask-user-input` in v7 (previously `mask`). This provides a privacy default that masks user input without the restrictions of full masking. The new default masks user input while other content is collected.

To preserve full masking, explicitly set `defaultPrivacyLevel: "mask"`.

#### `enablePrivacyForActionName` enabled by default{% #enableprivacyforactionname-enabled-by-default %}

`enablePrivacyForActionName` defaults to `true` in v7. Click action names follow the `defaultPrivacyLevel` setting by default. Set `enablePrivacyForActionName: false` to opt out.

#### `startDurationVital` and `stopDurationVital` API change{% #startdurationvital-and-stopdurationvital-api-change %}

The `DurationVitalReference` object has been replaced by a `vitalKey` string option. This aligns the API with `startResource`/`stopResource` and `startAction`/`stopAction`, and with the Mobile SDK. Multiple concurrent vitals with the same name are still supported:

```js
// Before
const ref = datadogRum.startDurationVital('myVital')
datadogRum.stopDurationVital(ref)

// After
datadogRum.startDurationVital('myVital', { vitalKey: 'uniqueKey' })
datadogRum.stopDurationVital('myVital', { vitalKey: 'uniqueKey' })
```

#### New `session_renewal` view loading type{% #new-session_renewal-view-loading-type %}

When a session expires and is renewed, the new view is created with `@view.loading_type:session_renewal` instead of `route_change`. Update any dashboards or monitors that filter on `@view.loading_type` if they should also include session-renewed views.

#### Document resource uses `PerformanceNavigationTiming`{% #document-resource-uses-performancenavigationtiming %}

The initial document resource event previously used a synthetic timing entry. It uses the browser's native `PerformanceNavigationTiming` directly in v7, which may produce slightly different `resource.duration` values for the document resource. The `initiatorType` for the document resource changes from `initial_document` to `navigation`.

If you use plugins or domain context handlers that inspect `performanceEntry` for document resources, update them to expect a `PerformanceNavigationTiming` instead of `PerformanceResourceTiming`.

#### First Input Delay (FID) removed{% #first-input-delay-fid-removed %}

Google replaced FID with Interaction to Next Paint (INP) as a Core Web Vital. FID has been removed from the SDK to reduce bundle size. Use INP instead.

#### Plugin API: `strategy` removed{% #plugin-api-strategy-removed %}

The `strategy` field has been removed from the plugin API. If you use `rum-react` or other integrations, upgrade them to v7 alongside the core SDK.

#### Improved action name computation{% #improved-action-name-computation %}

In v7, the SDK uses a new strategy for computing action names that considers the DOM structure to apply element privacy levels more precisely and improve handling of shadow DOM content. Action names may change slightly. The `betaTrackActionsInShadowDom` option has been removed.

#### BFCache navigations always tracked{% #bfcache-navigations-always-tracked %}

Back/Forward Cache restores are tracked as distinct views with `@view.loading_type:bf_cache`, including accurate loading time and Core Web Vitals. The `trackBfCacheViews` option has been removed.

#### Early requests always collected{% #early-requests-always-collected %}

Resources and requests that occurred before the SDK initialized are automatically captured. Some of those early resources may be missing properties such as status code. The `trackEarlyRequests` option has been removed.

#### Async chunk file names prefixed with `datadog`{% #async-chunk-file-names-prefixed-with-datadog %}

Async chunk filenames include a `datadog` prefix (for example, `datadog-rum-recorder.js`). If you have CSP or caching rules matching the old names, update them accordingly.

### Logs{% #logs %}

#### Logs require a session manager{% #logs-require-a-session-manager %}

Logs always use a session manager, so Logs events are consistently associated with a session ID. When neither cookies nor local storage are available, the SDK does not send data and logs a warning. Previously, Logs would still start without storage.

To explicitly enable memory-backed sessions, use `sessionPersistence: 'memory'`. In worker environments, this fallback is automatic.

#### `forwardErrorsToLogs` and `forwardConsoleLogs` are independent{% #forwarderrorstologs-and-forwardconsolelogs-are-independent %}

Previously, enabling `forwardErrorsToLogs` also silently forwarded `console.error` calls. In v7, these options are fully independent. You have precise control over what gets forwarded. `forwardErrorsToLogs` controls only unhandled errors.

To preserve the previous behavior, add `error` to your `forwardConsoleLogs` array:

```js
DD_LOGS.init({
  forwardConsoleLogs: ['error', 'warn'],
})
```

#### Network errors for canceled requests are dropped{% #network-errors-for-canceled-requests-are-dropped %}

Requests canceled by the application (aborted fetch or XHR) no longer generate a network error log. This reduces noise in error tracking.

#### Removed options{% #removed-options-1 %}

| Deprecated option (v6 or earlier) | Replacement (v7)                                                                                                                                                                                             |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `usePciIntake`                    | The standard intake is PCI compliant. Update your [CSP](https://docs.datadoghq.com/integrations/content_security_policy_logs.md?tab=firefox#use-csp-with-real-user-monitoring-and-session-replay) if needed. |

### Session Replay{% #session-replay %}

#### New data format{% #new-data-format %}

In v7, session replay uses a new, more compact data format which significantly reduces bandwidth usage. Session replay data is not exposed directly through browser SDK APIs, so no action is required to adopt this change.

## From v5 to v6{% #from-v5-to-v6 %}

The main improvement v6 offers is the bundle size reduction. By dropping support for IE11 and leveraging lazy loading, the size of the RUM bundle has been reduced by 10% and the Logs bundle by nearly 9%. Additionally, we've changed a few default initialization parameters and prepared for future improvements.

Take notice of the below breaking changes as you upgrade your SDK.

### Breaking changes{% #breaking-changes %}

#### Browser support{% #browser-support %}

Support for IE11 and other older browsers has been discontinued. Browsers must now support at least ES2018. To use Datadog on older browsers, you can keep using Browser SDK v5 or earlier.

#### Add tracestate header when using tracecontext propagator{% #add-tracestate-header-when-using-tracecontext-propagator %}

The default `tracecontext` propagator now sends a new `tracestate` header with additional metadata that allows better attribution of your traces. If you are using this propagator, then you need to allow this new header for all traced endpoints, in addition to the existing `traceparent` header:

```
Access-Control-Allow-Headers: traceparent, tracestate
```

#### Strongly type `site` option{% #strongly-type-site-option %}

The `site` option now has a stronger type definition. If you use TypeScript you might have an error if you use a non-standard value. We recommend using [proxy](https://docs.datadoghq.com/real_user_monitoring/guide/proxy-rum-data.md) to send RUM data to a nonstandard URL.

#### Tracking Actions, Resources and LongTask are now enabled by default{% #tracking-actions-resources-and-longtask-are-now-enabled-by-default %}

User interactions, resources, and long tasks are now tracked by default. This change does not impact billing. To opt-out, set `trackUserInteractions`, `trackResources`, and `trackLongTasks` [initialization parameters](https://datadoghq.dev/browser-sdk/interfaces/_datadog_browser-rum.RumInitConfiguration.html) to `false`.

#### Collect Long Animation Frames as Long Tasks{% #collect-long-animation-frames-as-long-tasks %}

On supported Browsers, [Long Animation Frames](https://developer.chrome.com/docs/web-platform/long-animation-frames#long-frames-api) are now collected instead of Long Tasks. The event type in the RUM Explorer is still `long_task`, but they will contain information about the long animation frame.

#### Increased cookies expiration date{% #increased-cookies-expiration-date %}

To support anonymous user tracking, the session cookie (`_dd_s`) expiration is extended to 1 year. To opt-out, set `trackAnonymousUser` [initialization parameters](https://datadoghq.dev/browser-sdk/interfaces/_datadog_browser-rum.RumInitConfiguration.html) to `false`.

#### Removed useCrossSiteSessionCookie initialization parameter{% #removed-usecrosssitesessioncookie-initialization-parameter %}

`useCrossSiteSessionCookie` was deprecated and is now unsupported. Use `usePartitionedCrossSiteSessionCookie` [initialization parameters](https://datadoghq.dev/browser-sdk/interfaces/_datadog_browser-rum.RumInitConfiguration.html) instead.

#### Lazy load Session Replay{% #lazy-load-session-replay %}

Session Replay module is now lazy-loaded using [dynamic imports](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import). This loads the module only for sessions sampled for Session Replay, reducing the bundle size for others.

**If you're using the SDK through NPM**, ensure your bundler supports dynamic imports. Most modern bundlers support this feature out of the box, but some may require configuration changes. Refer to your bundler's documentation for guidance: [Webpack](https://webpack.js.org/guides/code-splitting/#dynamic-imports), [Esbuild](https://esbuild.github.io/api/#splitting), [Rollup](https://rollupjs.org/tutorial/#code-splitting), [Parcel](https://parceljs.org/features/code-splitting).

**If you're using the SDK through a CDN**, there are no breaking changes. However, note that in addition to the main script being loaded (for example, `datadog-rum.js`), the SDK will dynamically load an additional chunk when needed (for example, `recorder-d7628536637b074ddc3b-datadog-rum.js`).

#### Do not inject trace context for non-sampled traces{% #do-not-inject-trace-context-for-non-sampled-traces %}

The default value for the `traceContextInjection` initialization parameter has been updated to `sampled` to ensure backend services' sampling decisions are applied when traces are not sampled in the Browser SDK. See the [Connect RUM and Traces documentation](https://docs.datadoghq.com/real_user_monitoring/correlate_with_other_telemetry/apm.md?tab=browserrum#:~:text=configure%20the%20traceContextInjection) for more information.

**Note**: If you're using a `traceSampleRate` of 100% (default), this change does not have any impact for you.

### Future breaking changes{% #future-breaking-changes %}

#### Enabling compression for Datadog intake requests{% #enabling-compression-for-datadog-intake-requests %}

Compression for Datadog intake requests will be enabled by default in a future major version. Datadog recommends that you opt-in to compression now using the `compressIntakeRequests` [initialization parameter](https://datadoghq.dev/browser-sdk/interfaces/_datadog_browser-rum.RumInitConfiguration.html). Since compression is performed in a Worker thread, configuring the Content Security Policy is necessary. See [CSP guidelines](https://docs.datadoghq.com/integrations/content_security_policy_logs.md?tab=firefox#use-csp-with-real-user-monitoring-and-session-replay) for more information.

## From v4 to v5{% #from-v4-to-v5 %}

V5 introduces the following changes and more:

- New configurations and privacy defaults for Session Replay
- Automatic collection of frustration signals
- Updated performance metrics
- Updated SDK parameters and APIs

Take notice of the below breaking changes as you upgrade your SDK. Changes are grouped by area of impact.

### General{% #general %}

#### SDK initialization parameters{% #sdk-initialization-parameters %}

**Action to take**: Replace the deprecated parameters with the new equivalent parameters in v5. The old parameter names are no longer available in v5.

| Deprecated parameter name (v4 or earlier) | New parameter name (v5) |
| ----------------------------------------- | ----------------------- |
| proxyUrl                                  | proxy                   |
| sampleRate                                | sessionSampleRate       |
| allowedTracingOrigins                     | allowedTracingUrls      |
| tracingSampleRate                         | traceSampleRate         |
| trackInteractions                         | trackUserInteractions   |
| premiumSampleRate                         | sessionReplaySampleRate |
| replaySampleRate                          | sessionReplaySampleRate |

#### Public APIs{% #public-apis %}

**Action to take**: Replace the deprecated APIs with the new equivalent APIs. The old APIs are no longer available in v5.

| Deprecated parameter name (v4 or earlier) | New parameter name (v5)                                                                                                                                                                |
| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| DD_RUM.removeUser                         | [DD_RUM.clearUser](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/advanced_configuration.md?tab=npm#clear-user-session-property)                       |
| DD_RUM.addRumGlobalContext                | [DD_RUM.setGlobalContextProperty](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/advanced_configuration.md?tab=npm#add-global-context-property)        |
| DD_RUM.removeRumGlobalContext             | [DD_RUM.removeGlobalContextProperty](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/advanced_configuration.md?tab=npm#remove-global-context-property)  |
| DD_RUM.getRumGlobalContext                | [DD_RUM.getGlobalContext](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/advanced_configuration.md?tab=npm#read-global-context)                        |
| DD_RUM.setRumGlobalContext                | [DD_RUM.setGlobalContext](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/advanced_configuration.md?tab=npm#replace-global-context)                     |
| DD_LOGS.addLoggerGlobalContext            | [DD_LOGS.setGlobalContextProperty](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/advanced_configuration.md?tab=npm#add-global-context-property)       |
| DD_LOGS.removeLoggerGlobalContext         | [DD_LOGS.removeGlobalContextProperty](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/advanced_configuration.md?tab=npm#remove-global-context-property) |
| DD_LOGS.getLoggerGlobalContext            | [DD_LOGS.getGlobalContext](https://docs.datadoghq.com/api/latest/rum.md)                                                                                                               |
| DD_LOGS.setLoggerGlobalContext            | [DD_LOGS.setGlobalContext](https://docs.datadoghq.com/api/latest/rum.md)                                                                                                               |
| logger.addContext                         | [logger.setContextProperty](https://docs.datadoghq.com/api/latest/rum.md)                                                                                                              |
| logger.removeContext                      | [logger.removeContextProperty](https://docs.datadoghq.com/api/latest/rum.md)                                                                                                           |

#### Intake domains{% #intake-domains %}

V5 sends data to different intake domains than previous versions.

**Action to take**: Update any [Content Security Policy (CSP)](https://docs.datadoghq.com/integrations/content_security_policy_logs.md?tab=firefox#use-csp-with-real-user-monitoring-and-session-replay) `connect-src` entries to use the new domain.

| Datadog site | Domain                                                 |
| ------------ | ------------------------------------------------------ |
| US1          | `connect-src https://browser-intake-datadoghq.com`     |
| US3          | `connect-src https://browser-intake-us3-datadoghq.com` |
| US5          | `connect-src https://browser-intake-us5-datadoghq.com` |
| EU1          | `connect-src https://browser-intake-datadoghq.eu`      |
| US1-FED      | `connect-src https://browser-intake-ddog-gov.com`      |
| US2-FED      | `connect-src https://browser-intake-us2-ddog-gov.com`  |
| AP1          | `connect-src https://browser-intake-ap1-datadoghq.com` |

#### Trusted events{% #trusted-events %}

To avoid collecting incorrect or illegitimate data, v5 only listens to events generated by user actions, ignoring events created by scripts. See [trusted events](https://developer.mozilla.org/en-US/docs/Web/API/Event/isTrusted) for more details.

**Action to take**: If you rely on any programmatic events and want them to be taken into account by the SDK, add the `__ddIsTrusted` attribute to them, like below:

```javascript
const click = new Event('click')
click.__ddIsTrusted = true
document.dispatchEvent(click)
```

**Action to take**: If you rely heavily on programmatic events, such as in an automated UI test environment, for example, you can allow all untrusted events by setting `allowUntrustedEvents: true`.

#### `beforeSend` return type{% #beforesend-return-type %}

`beforeSend` callback functions should return a boolean value:

```javascript
beforeSend(event: any, context?: any) => boolean
```

The implementation has not changed. If no value is returned, the event is not discarded.

**Action to take**: Ensure that `beforeSend` returns `true` to keep the event and `false` to discard it. This resolves related TypeScript compilation errors.

### Session Replay{% #session-replay-1 %}

#### Session Replay masking{% #session-replay-masking %}

The default Session Replay masking setting `defaultPrivacyLevel` has been changed from `mask-user-input` to `mask`. This hides all data in Session Replay recordings by default, making recordings less sensitive to view. For more information, see [Session Replay Browser Privacy Options](https://docs.datadoghq.com/session_replay/browser/privacy_options.md#configuration).

**Action to take**: If you want to see more unmasked data in Session Replay, like non-sensitive HTML content or user-entered text, set `defaultPrivacyLevel` to `mask-user-input` or `allow`.

#### Automatic recording of sessions sampled for Session Replay{% #automatic-recording-of-sessions-sampled-for-session-replay %}

Sessions that are sampled for Session Replay using [`sessionReplaySampleRate`](https://docs.datadoghq.com/real_user_monitoring/guide/sampling-browser-plans.md#setup) are automatically recorded at the start of the session. This means that you don't have to call the [`startSessionReplayRecording()`](https://docs.datadoghq.com/session_replay/browser.md#usage) method to capture a recording. In other words, you won't accidentally miss any recordings.

**Action to take**: If you want to continue using the old recording behavior and customize when your recording starts, set `startSessionReplayRecordingManually` to `true`.

#### Only pay for Session Replay when the session captures a recording{% #only-pay-for-session-replay-when-the-session-captures-a-recording %}

In previous SDK versions, sessions are determined to be Session Replay sessions through the sampling mechanism. In v5, sessions are only counted as Session Replay sessions if a recording is captured during the session. This makes it easier to track your Session Replay usage.

**No action needed**: This behavior automatically takes effect in v5.

#### Default Session Replay sampling rate{% #default-session-replay-sampling-rate %}

In v5, the default `sessionReplaySampleRate` is 0 instead of 100. If you don't include a sampling rate, no replays are recorded.

**Action to take**: To use Session Replay, set a sampling rate explicitly with `sessionReplaySampleRate: 100` (or another sampling rate).

### RUM{% #rum-1 %}

### APM integration{% #apm-integration %}

To promote the support and usage of OpenTelemetry, the default propagator types have been changed to include `tracecontext` in addition to `datadog`.

**Action to take**: If you are not already specifying the desired propagator on the `allowedTracingUrls` initialization parameter, configure your server Access-Control-Allow-Headers to also accept the `traceparent` header. For more information, see [connect RUM and Traces](https://docs.datadoghq.com/real_user_monitoring/correlate_with_other_telemetry/apm.md#opentelemetry-support).

### Session plan field{% #session-plan-field %}

In relation to Session Replay changes, the `session.plan` field is only available for session events.

**Action to take**: Update any monitor or dashboard queries you have saved to exclude the `session.plan` field for non-session events.

#### Frustration signals are collected automatically{% #frustration-signals-are-collected-automatically %}

You only need to set `trackUserInteractions: true` to collect all user interactions, including frustration signals. You no longer need to set the `trackFrustrations` parameter separately.

**Action to take**: To track frustration signals, set `trackUserInteractions: true`. The `trackFrustrations` parameter can be removed.

#### Resource durations are omitted for frozen pages{% #resource-durations-are-omitted-for-frozen-pages %}

Resource collection omits durations of resources that were extended due to the page going into the background, for example, when the user clicks on a separate tab while the page is loading.

**No action needed**: This behavior automatically takes effect in v5.

#### Resources and long task tracking{% #resources-and-long-task-tracking %}

When using `sessionReplaySampleRate` instead of `replaySampleRate` or `premiumSampleRate` (both deprecated), you must configure resources and long tasks explicitly.

**Action to take**: To collect these events, ensure that `trackResources` and `trackLongTasks` are set to `true`.

#### Resource method names are in uppercase{% #resource-method-names-are-in-uppercase %}

In order to avoid having different values for the same method name depending on the case (POST vs post), method names are now consistently sent in uppercase.

**Action to take**: Update monitor or dashboard queries to use the `resource.method` field with uppercase values.

#### `beforeSend` action event{% #beforesend-action-event %}

The `beforeSend` API allows access to contextual information of the collected events (see [Enrich and control RUM data](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/advanced_configuration.md?tab=npm#enrich-and-control-rum-data)).

With the introduction of frustration signals, an action event can be associated with several DOM events.

Along with this update, the `context.event` attribute has been removed in favor of the `context.events` attribute.

**Action to take**: Update `beforeSend` code to use `context.events` instead of `context.event`.

```javascript
beforeSend: (event, context) => {
  if (event.type === 'action' && event.action.type === 'click') {
    // accessing browser events related to the action event
    // before, single event: context.event
    // now, multiple events: context.events
  }
}
```

#### `beforeSend` in foreground periods{% #beforesend-in-foreground-periods %}

The `view.in_foreground_periods` attribute is computed directly from the backend, not sent by the SDK.

**Action to take**: Remove `view.in_foreground_periods` from `beforeSend` code. If you were relying on this attribute for a specific use case, reach out to [Support](https://docs.datadoghq.com/help/) for assistance.

#### `beforeSend` performance entry{% #beforesend-performance-entry %}

The `beforeSend` context `performanceEntry` attribute has been updated from the JSON representation to include the performance entry object directly.

The exported `PerformanceEntryRepresentation` type has been removed in favor of the standard `PerformanceEntry` type.

**Action to take**: In `beforeSend` code, use the `PerformanceEntry` type directly instead of the `PerformanceEntryRepresentation` type.

### Logs{% #logs-1 %}

#### Remove console error prefix{% #remove-console-error-prefix %}

The "`console error:`" prefix in log messages has been removed. This information can be found in the `origin` attribute.

**Action to take**: Update monitor or dashboard queries using the `"console error:"` prefix to use `@origin:console` instead.

#### Remove `error.origin`{% #remove-errororigin %}

Since the introduction of the `origin` attribute on all logs, `error.origin` was redundant and has been removed.

**Action to take**: Update monitor or dashboard queries using `error.origin` to use `origin` instead.

#### Decouple main logger{% #decouple-main-logger %}

When the SDK collects runtime errors or network, report, or console logs, it does not append the context specific to the main logger (`DD_LOGS.logger`), and it does not use the level or handler set for that logger.

**Action to take**: If you relied on the main logger level to exclude non-logger logs, use dedicated initialization parameters instead.

**Action to take**: If you relied on the main logger context to add context to non-logger logs, use global context instead.

## From v3 to v4{% #from-v3-to-v4 %}

Several breaking changes were made to the RUM and Logs Browser SDK with the v4 version.

### Changes{% #changes %}

#### Intake URLs{% #intake-urls %}

The URLs for where the RUM Browser SDK data is sent has changed. Ensure that your [Content Security Policy is up to date](https://docs.datadoghq.com/real_user_monitoring/faq/content_security_policy.md).

#### Minimal Typescript version support{% #minimal-typescript-version-support %}

The RUM Browser SDK v4 is not compatible with TypeScript earlier than v3.8.2. If you use TypeScript, ensure that the version is at least v3.8.2.

#### Tags syntax{% #tags-syntax %}

The `version`, `env`, and `service` initialization parameters are sent as tags to Datadog. The RUM Browser SDK slightly sanitizes them to ensure that they don't generate multiple tags, and prints a warning if those values don't meet the tag requirements syntax.

#### Stricter initialization parameters typing{% #stricter-initialization-parameters-typing %}

TypeScript types representing initialization parameters are stricter and may reject previously accepted unsupported parameters. If you get type-checking errors, ensure you are providing supported initialization parameters.

#### Privacy options precedence{% #privacy-options-precedence %}

When multiple privacy options are specified on the same element, Datadog applies the most restrictive option to avoid unexpectedly leaking sensitive data. For example, if both `dd-privacy-allow` and `dd-privacy-hidden` classes are specified on the same element, it is hidden instead of allowed.

#### Action names computation{% #action-names-computation %}

When computing action names, the RUM Browser SDK removes text of child elements with the `data-dd-action-name` attribute from inner text.

For example, for the following `container` element, where previously the computed action name would be `Container sensitive data`, in v4, the computed action name is `Container`:

```html
<div id="container">
  Container
  <div data-dd-action-name="sensitive">sensitive data</div>
</div>
```

### Removals{% #removals %}

#### XHR `_datadog_xhr` field{% #xhr-_datadog_xhr-field %}

The RUM Browser SDK previously used a `_datadog_xhr` property on `XMLHttpRequest` objects representing its internal state. This property has been removed without replacement as it wasn't intended to be used externally.

#### `proxyHost` initialization parameter{% #proxyhost-initialization-parameter %}

The `proxyHost` initialization parameter has been removed. Use the `proxyUrl` initialization parameter instead.

#### Privacy options support{% #privacy-options-support %}

The privacy options `input-ignored` and `input-masked` are no longer valid. Instead, use the `mask-user-input` privacy option.

Specifically, replace:

- `dd-privacy-input-ignored` and `dd-privacy-input-masked` class names with `dd-privacy-mask-user-input`
- `dd-privacy="input-masked"` and `dd-privacy="input-ignored"` attribute values with `dd-privacy="mask-user-input"`

## From v2 to v3{% #from-v2-to-v3 %}

The Browser SDK v3 introduces [Session Replay](https://docs.datadoghq.com/session_replay.md). With this major version update, several breaking changes were made to the RUM and Logs Browser SDKs.

### Changes{% #changes-1 %}

#### RUM errors{% #rum-errors %}

The RUM Browser SDK no longer issues [RUM errors](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/collecting_browser_errors.md) for failed XHR and Fetch calls. These failed network requests are still collected as [RUM resources](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/monitoring_resource_performance.md), which contain the status code attribute.

To continue seeing the failed network requests as RUM errors, Datadog recommends intercepting the resource with the [beforeSend API](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/advanced_configuration.md?tab=npm#enrich-and-control-rum-data), checking the `status_code` property, and manually sending an error with the [addError API](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/collecting_browser_errors.md?tab=npm#collect-errors-manually).

```javascript
beforeSend: (event) => {
    if (event.type === 'resource' && event.resource.status_code >= 500) {
        datadogRum.addError(`${event.resource.method} ${event.resource.url} ${event.resource.status_code}`); // "GET https://www.example.com/ 504"
    }
}
```

#### RUM error source attribute{% #rum-error-source-attribute %}

The RUM Browser SDK no longer lets you specify the source of an error collected with the [addError API](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/collecting_browser_errors.md?tab=npm#collect-errors-manually). All errors collected with this API have their source attribute set to `custom`. The [addError API](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/collecting_browser_errors.md?tab=npm#collect-errors-manually) accepts a context object as its second parameter, which should be used to pass extra context about the error.

### Removals{% #removals-1 %}

#### RUM API{% #rum-api %}

| Old API       | New API   |
| ------------- | --------- |
| addUserAction | addAction |

#### Initialization options{% #initialization-options %}

| Old options        | New options |
| ------------------ | ----------- |
| publicApiKey       | clientToken |
| datacenter         | site        |
| resourceSampleRate | NONE        |

#### TypeScript types{% #typescript-types %}

| Old types                    | New types                    |
| ---------------------------- | ---------------------------- |
| RumUserConfiguration         | RumInitConfiguration         |
| RumRecorderUserConfiguration | RumRecorderInitConfiguration |
| LogsUserConfiguration        | LogsInitConfiguration        |

## Further Reading{% #further-reading %}

- [Visualize your RUM data in the Explorer](https://docs.datadoghq.com/real_user_monitoring/explorer.md)
- [Use Datadog Session Replay to view real-time user journeys](https://www.datadoghq.com/blog/session-replay-datadog/)
