This guide connects Datadog browser RUM and server APM in a self-hosted Next.js App Router app and shows which settings change your Datadog usage. The examples use @datadog/browser-rum 7.19.0, @datadog/browser-rum-nextjs 7.19.0, dd-trace 6.27.0 and Next.js 16.4.6, which are the current npm versions on 1 December 2026.
Install the packages:
npm install @datadog/browser-rum @datadog/browser-rum-nextjs dd-trace
Set up browser RUM with the Next.js plugin
Datadog publishes an official Next.js integration, @datadog/browser-rum-nextjs. The integration is in Preview, so its features and configuration can change, and it requires Next.js 15.3 or later because it uses the instrumentation-client file convention.
The plugin detects route changes in the App Router and normalises view names, so that /users/123 becomes /users/[id].
Initialise the SDK in instrumentation-client.ts
Create instrumentation-client.ts in the project root or in src. Next.js runs this file after the HTML document loads and before React hydration starts, so keep it small: in development, Next.js warns when the file takes longer than 16 ms.
import { datadogRum } from '@datadog/browser-rum'
import { nextjsPlugin, onRouterTransitionStart } from '@datadog/browser-rum-nextjs'
export { onRouterTransitionStart }
datadogRum.init({
applicationId: process.env.NEXT_PUBLIC_DD_APPLICATION_ID ?? '',
clientToken: process.env.NEXT_PUBLIC_DD_CLIENT_TOKEN ?? '',
site: 'datadoghq.eu', // your Datadog site
service: 'shop-browser',
env: process.env.NEXT_PUBLIC_DD_ENV,
version: process.env.NEXT_PUBLIC_DD_VERSION,
sessionSampleRate: 100,
sessionReplaySampleRate: 5,
defaultPrivacyLevel: 'mask',
allowedTracingUrls: [`${window.location.origin}/api/`],
traceSampleRate: 10,
traceContextInjection: 'sampled',
plugins: [nextjsPlugin()],
})
The settings do the following:
service,envandversionare the Unified Service Tagging values for the browser app, and RUM needs an explicitserviceto connect to traces.sessionSampleRateis the percentage of sessions that the SDK collects.sessionReplaySampleRateis the percentage of collected sessions that also record a replay.defaultPrivacyLevel: 'mask'masks all text, inputs, images and links in replays, and you can use thedata-dd-privacyattribute to change the level for one element. Replays always maskpassword,emailandtelinputs.
Next.js inlines NEXT_PUBLIC_ variables at build time, so if env differs per environment, you need to build one image per environment.
Mount the router component in the root layout
Render DatadogAppRouter in app/layout.tsx:
import type { ReactNode } from 'react'
import { DatadogAppRouter } from '@datadog/browser-rum-nextjs'
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>
<DatadogAppRouter />
{children}
</body>
</html>
)
}
The published package marks DatadogAppRouter with 'use client', so the root layout can stay a Server Component.
Report errors from error boundaries
Call addNextjsError in each error.tsx file:
'use client'
import { useEffect } from 'react'
import { addNextjsError } from '@datadog/browser-rum-nextjs'
export default function RouteError({ error, retry }: { error: unknown; retry: () => void }) {
useEffect(() => {
if (error instanceof Error) {
addNextjsError(error)
}
}, [error])
return <button onClick={() => retry()}>Try again</button>
}
Next.js passes error as unknown, so narrow the value with instanceof Error before you call addNextjsError. Do not name the component Error, because that name hides the global Error class.
Add the same call to app/global-error.tsx. This file replaces the root layout, so it must render its own html and body tags.
Connect browser requests to APM traces
allowedTracingUrls lists the request URLs that receive trace headers. A string matches URLs that start with that string, while a RegExp matches any substring of the URL, so anchor a RegExp with ^. The example adds headers only to same-origin /api/ requests.
The trace headers are not CORS-safelisted. A cross-origin API must therefore allow them and accept preflight OPTIONS requests, and a pattern that is too broad can cause CORS errors.
traceSampleRate is the percentage of matched requests for which the browser keeps the backend trace. It defaults to 100 and does not change session sampling.
traceContextInjection: 'sampled' is the default. For requests that the browser does not sample, the SDK sends no sampling decision, so the backend tracer applies its own sampling. In the Datadog example, a 20% browser rate and a 40% backend rate together keep 52% of traces.
Tracing does not cover the initial HTML document or requests sent before the SDK initialises.
Datadog states that this connection uses APM paid data in RUM, which can change your APM billing.
Set up server APM with dd-trace
Preload the tracer
Datadog recommends loading dd-trace before Next.js starts, using the --require flag in NODE_OPTIONS:
{
"scripts": {
"start": "NODE_OPTIONS='--require dd-trace/init' ./node_modules/.bin/next start"
}
}
NODE_OPTIONS also applies to child Node.js processes.
Do not start dd-trace in instrumentation.ts
Next.js documents instrumentation.ts for monitoring tools and calls its register() function once when a server instance starts. The Next.js docs guard Node.js code in register() with process.env.NEXT_RUNTIME === 'nodejs'.
Datadog states that loading the tracer in application code is not effective for Next.js, because the framework can load modules first. Use the preload for dd-trace and keep register() for other server setup.
Turbopack builds
Turbopack is the default bundler in Next.js 16, and when a bundler includes third-party libraries in the bundle, dd-trace does not intercept their calls. For Next.js 15.5 or later with Turbopack, wrap the config with withDatadogTurbopack:
import type { NextConfig } from 'next'
import { withDatadogTurbopack } from 'dd-trace/next'
const nextConfig: NextConfig = {
reactStrictMode: true,
}
export default withDatadogTurbopack(nextConfig)
You must still preload dd-trace/init. The wrapper instruments CommonJS dependencies in Node.js bundles, but it does not instrument client or edge bundles.
dd-trace and pino are on the automatic serverExternalPackages list of Next.js, so you do not need to add them.
Configure the container
Set DD_ENV, DD_SERVICE and DD_VERSION on the container and add the matching com.datadoghq.tags Docker labels. The tracer sends spans to the Agent at DD_AGENT_HOST, port 8126.
services:
web:
image: registry.example.com/shop-server:1.4.2
environment:
NODE_OPTIONS: "--require dd-trace/init"
DD_ENV: production
DD_SERVICE: shop-server
DD_VERSION: "1.4.2"
DD_AGENT_HOST: datadog-agent
DD_LOGS_INJECTION: "true"
DD_TRACE_SAMPLING_RULES: '[{"service":"shop-server","sample_rate":0.2}]'
labels:
com.datadoghq.tags.env: production
com.datadoghq.tags.service: shop-server
com.datadoghq.tags.version: "1.4.2"
Use the same env and version values in the browser and on the server.
Datadog lists the App Router and standalone output as supported. In standalone mode, Next.js copies only the files that the server needs into .next/standalone, and because the preload is not an application import, you should check that this folder contains dd-trace.
Correlate logs and traces
dd-trace can inject trace IDs into logs from bunyan, pino and winston, but only for logs in JSON format. Set DD_LOGS_INJECTION=true to make the setting explicit.
Edge runtime and Proxy
The Datadog compatibility table lists Next.js Middleware as not traced. Next.js 16 renamed Middleware to Proxy, which now uses the Node.js runtime by default, while the Edge runtime does not support all Node.js APIs. Do not expect dd-trace spans from Proxy or from routes that use the Edge runtime.
Sampling and cost dimensions
This section gives no prices, so check the Datadog pricing page and your contract.
What Datadog bills
- RUM sessions: Datadog bills RUM per 1,000 sessions, where a session expires after 15 minutes of inactivity and lasts 4 hours at most.
- RUM plans: The pricing page splits RUM into RUM Measure, which covers every collected session, and RUM Investigate, which covers the sessions that you retain.
- Session Replay: Session Replay is an add-on to RUM Investigate, so when a retention filter keeps a session with a replay, Datadog bills both the session and the replay.
- APM hosts: In a container environment outside Fargate, Datadog bills the underlying host that runs the Agent.
- Ingested spans: Datadog meters ingested spans by volume in GB.
- Indexed spans: Datadog bills indexed spans per million.
Each APM host includes 150 GB of ingested spans and 1 million indexed spans per month. The allotment is summed across all APM hosts, and with on-demand billing, Datadog meters it per hour. (Datadog pricing page, read 1 December 2026.)
Three control points
- Head-based sampling at the source: The browser SDK applies
sessionSampleRate,sessionReplaySampleRateandtraceSampleRate, and the tracer appliesDD_TRACE_SAMPLING_RULESorDD_TRACE_SAMPLE_RATE. Without these settings, the Agent sets rates that target 10 traces per second per Agent. Head-based settings change both ingested sessions and ingested spans. - Ingestion controls: The Ingestion Control page shows monthly ingestion and a month-end projection. With
dd-trace5.16.0 or later, you can set service and resource rates there, and these remote rates override local configuration. - Retention filters: RUM retention filters decide which collected sessions Datadog keeps for 30 days, and APM retention filters decide which ingested spans Datadog indexes for 15 days. Retention filters do not change ingestion.
Note these points:
- APM metrics use all traces, so ingestion controls do not change them.
- When you set SDK sampling rules for a service, the error and rare samplers ignore that service.
- Spans from the intelligent retention filter do not count towards indexed span usage.
- Cross-product retention filters can index the APM traces of retained RUM sessions, which can increase indexed APM volume.
RUM without Limits
RUM without Limits separates session ingestion from session retention, and for new applications Datadog recommends sessionSampleRate: 100 with retention filters in the UI.
The browser SDK can override backend sampling decisions, so more collected sessions can mean more ingested spans. If you raise sessionSampleRate, set traceSampleRate to the old session rate: for example, change 10% sessions with 100% traces to 100% sessions with 10% traces.
Worked example
The traffic numbers below are assumptions, not measurements:
- 200,000 sessions per month.
- 12 browser requests to
/api/per session. - 8 spans per backend trace.
The settings come from the examples above: 100% sessions, 5% replays, 10% browser traces and a 0.2 backend rule.
Collected RUM sessions 200,000 x 100% = 200,000
Sessions with a replay 200,000 x 5% = 10,000
Browser /api/ requests 200,000 x 12 = 2,400,000
Traces kept by browser 2,400,000 x 10% = 240,000
Requests left to backend 2,400,000 - 240,000 = 2,160,000
Traces kept by backend 2,160,000 x 20% = 432,000
Ingested traces 240,000 + 432,000 = 672,000
Ingested spans 672,000 x 8 = 5,376,000
With the default traceSampleRate of 100, all 2,400,000 requests keep their trace, which comes to 19,200,000 ingested spans.
Retention filters then decide how many of the 200,000 sessions and 10,000 replays Datadog retains and bills.
Requests outside allowedTracingUrls carry no browser trace headers, so the backend rule alone samples them and you should estimate them separately.
Datadog meters ingested spans in GB, not in spans, so deploy the settings to a test environment first. Then use the datadog.estimated_usage.apm.ingested_bytes metric to convert the span count into GB.
Checklist
- Initialise RUM with
nextjsPlugin()ininstrumentation-client.ts. - Render
DatadogAppRouterin the root layout. - Call
addNextjsErrorinerror.tsxandglobal-error.tsx. - Set the same
envandversionin the browser and on the server. - Limit
allowedTracingUrlsto your own API URLs. - Set
traceSampleRateand keeptraceContextInjection: 'sampled'. - Preload
dd-trace/initwithNODE_OPTIONS. - Use
withDatadogTurbopackfor Turbopack builds. - Set
DD_TRACE_SAMPLING_RULESper service. - Review the RUM and APM retention filters.
- Check the Ingestion Control page after each change.
For a review of an existing setup, see the frontend observability assessment.
Sources
- Datadog: RUM Next.js integration
- npm: @datadog/browser-rum-nextjs
- npm: @datadog/browser-rum
- Datadog: Browser monitoring client-side setup
- Datadog: Session Replay privacy options
- Datadog: Connect RUM and traces
- Datadog: Browser RUM and Session Replay sampling
- Datadog: RUM without Limits
- Datadog: RUM retention filters
- Datadog: RUM and Session Replay billing
- Datadog: APM billing
- Datadog: Pricing
- Datadog: Tracing Node.js applications
- Datadog: Node.js compatibility requirements
- Datadog: Configuring the Node.js tracing library
- Datadog: Unified Service Tagging
- Datadog: Correlating Node.js logs and traces
- Datadog: Ingestion mechanisms
- Datadog: Ingestion controls
- Datadog: Trace retention
- Datadog: APM usage metrics
- npm: dd-trace
- Next.js: instrumentation-client
- Next.js: Instrumentation guide
- Next.js: error.js file convention
- Next.js: serverExternalPackages
- Next.js: Turbopack
- Next.js: output
- Next.js: Environment variables
- Next.js: Edge runtime
- Next.js: proxy.js file convention