Answers you can trust, from Codeables
Every page on Codeables is structured and verified — built so people and the AI agents they rely on can trust it. Explore more from the source behind this answer.
Explore CodeablesHow do we set up Datadog RUM + Session Replay for a React app and link sessions to backend traces?
Quick Answer: To set up Datadog RUM + Session Replay for a React app and link sessions to backend traces, you install and configure the
@datadog/browser-rumSDK (with Session Replay enabled), add trace linkage viatrackInteractionsand sampling rules, then instrument your backend with Datadog APM so RUM views and user actions correlate automatically with backend spans and services.
Why This Matters
When you’re on call, “frontend looks slow” isn’t enough. You need to see exactly what the user did, how the page behaved in their browser, and which backend request, query, or dependency caused the slowdown. Datadog RUM plus Session Replay gives you user-level visibility, and linking those sessions to backend traces means you can pivot from a specific frustrated session to the precise span, service, or DB call responsible—in one place and within minutes.
Key Benefits:
- Faster investigations: Pivot from a single RUM session (or Session Replay) to correlated backend traces and logs instead of guessing which request ID is relevant.
- Concrete user impact: See how real users experience errors, layout shifts, and latency, then tie that directly to services, deploys, and queries that changed.
- Lower MTTR with fewer tools: Replace context-switching between browser dev tools, log searches, and APM with a single flow across RUM, Session Replay, and backend tracing.
Core Concepts & Key Points
| Concept | Definition | Why it's important |
|---|---|---|
| RUM (Real User Monitoring) | Datadog product that captures real users’ page views, errors, resources, Core Web Vitals, and custom events from your React app. | Shows actual user experience instead of synthetic or lab-only metrics, and becomes the entry point for troubleshooting frontend issues. |
| Session Replay | Visual replay of a user’s browser session that reconstructs clicks, page transitions, and DOM changes without recording actual video. | Lets you “watch” problem sessions (rage clicks, errors, slow forms) and reproduce issues without asking for screenshots. |
| Trace linkage (RUM ↔ APM) | Datadog’s ability to correlate RUM views and user actions with distributed traces and spans from your backend services. | Enables a direct path from “this user was slow on this page” to “this specific API span and database query caused it,” which is critical for fast root cause analysis. |
How It Works (Step-by-Step)
At a high level, you:
- Configure Datadog RUM in your React app.
- Enable Session Replay and interaction tracking.
- Instrument your backend services with Datadog APM.
- Ensure trace correlation (RUM → backend) is enabled.
- Use Datadog to pivot between RUM sessions, replays, traces, logs, and infrastructure.
Below is a practical, operator-focused walkthrough.
1. Prepare Datadog RUM on your account
Before writing any code:
-
Enable RUM in Datadog:
- In Datadog, go to UX Monitoring → RUM Applications.
- Click New Application, choose Browser, and name it (e.g.,
react-web-app-prod). - Datadog will generate:
clientTokenapplicationId- recommended snippet / SDK usage
site(e.g.,datadoghq.com,datadoghq.eu)
-
Decide environments & sampling:
- Plan to set
envtags (e.g.,production,staging). - Choose initial sampling:
sampleRatefor RUM sessions (e.g., 100 for full capture in staging, maybe 20–50 in prod).sessionReplaySampleRatefor Session Replay (often lower than RUM, e.g., 10–20, to control cost).
- Plan to set
You’ll use these values in your React code.
2. Install Datadog RUM and Session Replay in your React app
If you have a modern React build (Create React App, Next.js, Vite, etc.), the cleanest approach is to install the RUM SDK from npm and initialize it in your app startup.
2.1 Install the SDK
npm install @datadog/browser-rum --save
# or
yarn add @datadog/browser-rum
For Session Replay, you don’t need a separate package—the core RUM SDK supports it.
2.2 Initialize RUM in your React entry point
In your main entry file (e.g., src/index.tsx or src/main.tsx):
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App';
import { datadogRum } from '@datadog/browser-rum';
datadogRum.init({
applicationId: '<YOUR_RUM_APPLICATION_ID>',
clientToken: '<YOUR_CLIENT_TOKEN>',
site: 'datadoghq.com', // or your Datadog site
service: 'react-web-app', // matches your service naming in Datadog
env: process.env.NODE_ENV === 'production' ? 'production' : 'staging',
version: process.env.REACT_APP_VERSION, // optional: app version, commit, etc.
// RUM sampling
sampleRate: 100, // % of sessions to capture with RUM
// Session Replay sampling
sessionReplaySampleRate: 20, // % of sessions that include Session Replay
// Enable automatic tracking
trackInteractions: true, // clicks, taps, etc.
trackResources: true,
trackLongTasks: true,
// Privacy settings—adjust as needed
defaultPrivacyLevel: 'mask-user-input', // or 'mask' / 'allow'
});
datadogRum.startSessionReplayRecording();
const root = ReactDOM.createRoot(
document.getElementById('root') as HTMLElement
);
root.render(<App />);
Key points:
service: Use a consistent name for the frontend service so it aligns with your backend naming in APM.env: Set to match the environment tag used on your backend. RUM-to-APM correlation works best whenserviceandenvare coherent across products.defaultPrivacyLevel: Protects sensitive user data by masking or allowing input fields and text. Keep it conservative in production and only loosen after a formal review.
3. Enhance React integration and user context
Once RUM is initialized, you can provide richer context so individual sessions are more useful during investigations.
3.1 Track navigation in a single-page React app
For typical React Router setups, RUM automatically tracks route changes as views if you initialize it early, but you can explicitly mark views if you have custom navigation logic:
import { datadogRum } from '@datadog/browser-rum';
// Example: if you have manual navigation logic
datadogRum.startView('home', {
viewName: 'HomePage',
});
In most SPA cases, automatic view tracking is enough; you’ll see entries like /products, /checkout in the RUM Explorer.
3.2 Attach user info to RUM sessions
Add user and tenant details so you can find relevant sessions quickly during incidents:
import { datadogRum } from '@datadog/browser-rum';
// After a user logs in or their profile loads:
datadogRum.setUser({
id: user.id, // stable unique identifier
email: user.email, // optional
name: user.name, // optional
plan: user.plan, // custom attribute
accountId: account.id, // custom attribute (multi-tenant)
});
This makes it easy to filter on @user.id:12345 when someone reports “I hit an error on checkout.”
3.3 Record custom actions and events
RUM will auto-capture interactions when trackInteractions: true, but you can create custom actions for key flows such as checkout, file upload, or save operations:
datadogRum.addAction('checkout_submit', {
cartValue: 149.99,
itemsCount: 3,
});
These actions appear in Datadog RUM tied to the same session and can be used in SLOs and dashboards.
4. Enable Session Replay with correct privacy controls
Session Replay lets you visually reconstruct user sessions. For production, you want a strict privacy posture.
You already enabled replay with:
sessionReplaySampleRate: 20,
defaultPrivacyLevel: 'mask-user-input',
Consider further tuning:
-
Mask everything by default, then allow specific areas:
-
Default:
defaultPrivacyLevel: 'mask' -
Use HTML attributes to unmask non-sensitive areas:
<div data-dd-privacy="allow">Product catalog here</div>
-
-
Explicitly mask sensitive components (even if using
mask-user-input):<input type="password" data-dd-privacy="mask" // ... /> -
Exclude entire components from recording if needed:
<div data-dd-privacy="hidden"> {/* Completely excluded from Session Replay */} </div>
Review Datadog’s RUM & Session Replay privacy docs with your security/compliance team, especially if you’re subject to PCI, HIPAA, or similar regimes.
5. Instrument backend services with Datadog APM
To link RUM sessions to backend traces, your backends must:
- Emit traces using Datadog APM.
- Accept and propagate tracing headers from the browser.
- Use coherent
service/envtagging.
Below are common stacks; they all follow the same pattern.
5.1 Install APM in your backend (examples)
Node.js / Express:
npm install dd-trace --save
// tracing.js
const tracer = require('dd-trace').init({
service: 'api-service',
env: process.env.DD_ENV || 'production',
});
// Make sure this is imported before other requires
module.exports = tracer;
// app.js
require('./tracing'); // First import
const express = require('express');
const app = express();
// your routes...
Python / Django or Flask:
pip install ddtrace
DD_SERVICE=api-service DD_ENV=production \
ddtrace-run gunicorn myapp.wsgi:application
Java / Spring Boot (using Java Agent):
java -javaagent:/path/to/dd-java-agent.jar \
-Ddd.service=api-service \
-Ddd.env=production \
-jar myapp.jar
The exact setup differs by language, but the APM docs walk through each runtime. The important part for RUM correlation is that your REST / GraphQL / RPC entrypoints are traced.
6. Ensure RUM-to-trace correlation is enabled
Datadog’s browser RUM SDK adds trace headers to XHR/fetch calls to enable end-to-end tracing, as long as:
- You’ve configured
allowedTracingOriginsorallowedTracingUrlscorrectly. - The backend is instrumented with APM and configured to accept Datadog tracing headers.
- The CORS configuration allows those headers.
6.1 Configure tracing origins in your RUM init
Update your React initialization:
datadogRum.init({
applicationId: '<YOUR_RUM_APPLICATION_ID>',
clientToken: '<YOUR_CLIENT_TOKEN>',
site: 'datadoghq.com',
service: 'react-web-app',
env: 'production',
sampleRate: 100,
sessionReplaySampleRate: 20,
trackInteractions: true,
trackResources: true,
trackLongTasks: true,
// Correlate RUM with backend traces
allowedTracingOrigins: [
'https://api.mycompany.com',
'https://auth.mycompany.com',
],
});
For newer SDKs, allowedTracingUrls may be available for more granular control. The idea is the same: tell RUM which endpoints should get tracing headers.
6.2 Confirm backend accepts Datadog tracing headers
Datadog’s browser SDK will send W3C or Datadog tracing headers such as:
traceparentx-datadog-trace-idx-datadog-parent-idx-datadog-sampling-priority
Make sure your backend:
-
Doesn’t strip these headers.
-
Handles them in CORS configuration:
Access-Control-Allow-Headers: x-datadog-trace-id, x-datadog-parent-id, x-datadog-sampling-priority, traceparent, tracestate, content-type
If you already have Datadog’s APM auto-instrumentation enabled on the backend, it will automatically pick up these headers as the parent trace/span context.
6.3 Validate correlation in Datadog
Once React and the backend are live:
- Trigger a request in the browser (e.g., load
/dashboard). - In UX Monitoring → RUM Explorer, open a view for that page.
- In the right-side panel, you should see:
- Related traces under “Resources” or “Back end” section.
- A link like “View related traces”.
Clicking it should open APM with traces filtered to the ones corresponding to this RUM event.
7. Analyze sessions, replays, and traces together
Once everything is wired, you get a unified workflow:
-
Start from a frontend symptom:
- A spike in RUM error rate or frontend latency on
/checkout. - A user ticket referencing a particular time or user ID.
- A spike in RUM error rate or frontend latency on
-
Open the relevant RUM view/session:
- Filter by
@view.url_path:/checkoutand time window. - Filter by
@user.id:12345if you set user context.
- Filter by
-
Watch the Session Replay:
- Click Play Session Replay to see what the user did.
- Observe UI behavior: button clicked multiple times, slow spinner, form validation oddities.
-
Pivot to backend traces:
- In the same RUM event, click View related traces.
- Datadog APM opens with the relevant trace(s), including:
- Entry span (e.g.,
api-serviceGET /orders). - Downstream services, DB calls, caches, queues.
- Entry span (e.g.,
-
Drill into logs and infrastructure:
- From a span, pivot to Logs if you’re forwarding logs to Datadog Log Management.
- From a service, pivot to Infrastructure or Network for CPU, memory, container restarts, or network health.
- If you use Watchdog Insights or Bits AI SRE Investigations, let them surface anomalies in error patterns or latency during the relevant window.
This gives you a true “overview to deep details, fast” flow: RUM view → Session Replay → trace → logs/infrastructure → root cause.
Common Mistakes to Avoid
-
Mismatch between frontend and backend
env/servicetags:
If your React app is tagged asenv:prodand your backend asenv:production, correlation and dashboards become messy. Standardizeenvandservicenaming across RUM and APM before rollout. -
Not configuring
allowedTracingOrigins/CORS headers:
RUM might be sending trace headers that your API silently drops due to CORS or proxy rules. Always verify the headers in browser dev tools and confirm they survive to your backend before assuming correlation is working.
Real-World Example
At one point, our React-based SaaS started getting tickets about “random” slowdown on the billing page. Metrics looked fine on average, and the usual logs search for ERROR didn’t show anything obvious.
With Datadog RUM and Session Replay in place:
- We filtered RUM views on
/billingand narrowed to the timeframe when tickets were opened. - Session Replay showed users waiting 8–10 seconds after clicking “Update payment,” with repeated clicks and a spinner that never finished.
- From a slow RUM view, we pivoted to related traces and immediately saw a subset of
POST /payment-methodtraces with high latency—only when hitting a particular third-party payment gateway region. - The trace showed:
- Fast app logic.
- Slow external HTTP calls to the gateway.
- From the span, we pivoted to logs and confirmed repeated retries and timeouts tied to specific IP ranges.
We were able to:
- Route those requests to a healthier region.
- Add a circuit breaker and better UX feedback.
- Verify the fix through RUM dashboards and new Session Replays, all without guessing which backend calls were involved.
Pro Tip: During an incident, set up a quick RUM dashboard filtered to the affected endpoint (e.g.,
/billing,/checkout) and break down by@network.client.geo.countryor@browser.name. Combine that with a trace search on the same time window so you can quickly see if the issue is localized to a region, browser, or backend dependency.
Summary
To set up Datadog RUM + Session Replay for a React app and link sessions to backend traces, you:
- Initialize the RUM SDK in your React entry point with
sampleRate,sessionReplaySampleRate,trackInteractions, and strong privacy defaults. - Add user context and key business actions so problematic sessions are easy to find and interpret.
- Instrument your backend with Datadog APM and configure
allowedTracingOrigins/CORS so browser requests carry trace headers into your services. - Use Datadog’s unified platform to pivot from RUM views and Session Replay to backend traces, logs, and infrastructure.
The result is a single investigation path from “this user had a slow page” to “this service, span, and dependency caused it,” which cuts MTTR and reduces the guesswork that usually burns on-call time.