---
title: Monitor Your Next.js App With RUM
description: Guide for monitoring Next.js applications with RUM.
breadcrumbs: >-
  Docs > RUM & Session Replay > Real User Monitoring & Session Replay Guides >
  Monitor Your Next.js App With RUM
---

# Monitor Your Next.js App With RUM

## Overview{% #overview %}

[Next.js](https://nextjs.org/) is a JavaScript framework created by [Vercel](https://vercel.com) for building React web applications and Node.js APIs. This guide shows you how to add Datadog RUM to your Next.js application to monitor frontend performance and user behavior.

## Prerequisites{% #prerequisites %}

Create a RUM application in Datadog to get your credentials:

1. Go to [**Digital Experience > Performance Summary**](https://app.datadoghq.com/rum/performance-monitoring).
1. Click **New Application**.
1. Select **JS**, enter an application name, and click **Create Application**.
1. Copy the `applicationId` and `clientToken` values.

{% alert level="info" %}
If you store these in `.env.local`, prefix them with `NEXT_PUBLIC_` to expose them to the browser. See Next.js environment variables.
{% /alert %}

## Install the RUM SDK{% #install-the-rum-sdk %}

For routing setup instructions, see the section that matches your Next.js configuration: App Router or Pages Router.

### App Router{% #app-router %}

**Note:** The [App Router](https://nextjs.org/docs/app) is available in Next.js v13+.

The App Router uses React Server Components by default. Since RUM must run in the browser, initialize it in a [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components).

{% tab title="npm" %}

1. Install the RUM SDK:

   ```bash
   npm install @datadog/browser-rum
   ```

1. Create a client component for RUM initialization:

In the `components/datadog-init.tsx` file:

```tsx
   "use client";

   import { datadogRum } from "@datadog/browser-rum";

   datadogRum.init({
     applicationId: "<YOUR_APPLICATION_ID>",
     clientToken: "<CLIENT_TOKEN>",
     site: "datadoghq.com",
     service: "<SERVICE_NAME>",
     env: "<ENV_NAME>",
     sessionSampleRate: 100,
     sessionReplaySampleRate: 20,
     trackUserInteractions: true,
     trackResources: true,
     trackLongTasks: true,
   });

   export default function DatadogInit() {
     return null;
   }
   
```
Add the component to your [root layout](https://nextjs.org/docs/app/building-your-application/routing/layouts-and-templates):
In the `app/layout.tsx` file:

```tsx
   import DatadogInit from "@/components/datadog-init";

   export default function RootLayout({ children }: { children: React.ReactNode }) {
     return (
       <html lang="en">
         <body>
           <DatadogInit />
           {children}
         </body>
       </html>
     );
   }
   
```

{% /tab %}

{% tab title="CDN async" %}
Use the Next.js `Script` component to load RUM asynchronously:

In the `app/layout.tsx` file:

```tsx
import Script from "next/script";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <Script id="datadog-rum">
        {`
          (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;d.crossOrigin=''
            n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
          })(window,document,'script','https://www.datadoghq-browser-agent.com/us1/v6/datadog-rum.js','DD_RUM')
          window.DD_RUM.onReady(function() {
            window.DD_RUM.init({
              clientToken: '<CLIENT_TOKEN>',
              applicationId: '<YOUR_APPLICATION_ID>',
              site: 'datadoghq.com',
              service: '<SERVICE_NAME>',
              env: '<ENV_NAME>',
              sessionSampleRate: 100,
              sessionReplaySampleRate: 20,
            });
          })
        `}
      </Script>
      <body>{children}</body>
    </html>
  );
}
```

{% /tab %}

{% tab title="CDN sync" %}
Use `strategy="beforeInteractive"` to load RUM synchronously before the page becomes interactive:

In the `app/layout.tsx` file:

```tsx
import Script from "next/script";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <Script
          id="dd-rum-sync"
          src="https://www.datadoghq-browser-agent.com/us1/v6/datadog-rum.js"
          crossOrigin=""
          type="text/javascript"
          strategy="beforeInteractive"
        />
        <Script id="datadog-rum">
          {`
            window.DD_RUM && window.DD_RUM.init({
              clientToken: '<CLIENT_TOKEN>',
              applicationId: '<YOUR_APPLICATION_ID>',
              site: 'datadoghq.com',
              service: '<SERVICE_NAME>',
              env: '<ENV_NAME>',
              sessionSampleRate: 100,
              sessionReplaySampleRate: 20,
            });
          `}
        </Script>
        {children}
      </body>
    </html>
  );
}
```

{% /tab %}

### Pages Router{% #pages-router %}

The [Pages Router](https://nextjs.org/docs/pages) runs on the client, so you can initialize RUM directly in [`_app.tsx`](https://nextjs.org/docs/pages/building-your-application/routing/custom-app).

{% tab title="npm" %}

1. Install the RUM SDK:

   ```bash
   npm install @datadog/browser-rum
   ```

1. Initialize RUM in your custom App component:

In the `pages/_app.tsx` file:

```tsx
   import type { AppProps } from "next/app";
   import { datadogRum } from "@datadog/browser-rum";

   datadogRum.init({
     applicationId: "<YOUR_APPLICATION_ID>",
     clientToken: "<CLIENT_TOKEN>",
     site: "datadoghq.com",
     service: "<SERVICE_NAME>",
     env: "<ENV_NAME>",
     sessionSampleRate: 100,
     sessionReplaySampleRate: 20,
     trackUserInteractions: true,
     trackResources: true,
     trackLongTasks: true,
   });

   export default function App({ Component, pageProps }: AppProps) {
     return <Component {...pageProps} />;
   }
   
```

{% /tab %}

{% tab title="CDN async" %}
Use the Next.js `Script` component to load RUM asynchronously:

In the `pages/_app.tsx` file:

```tsx
import type { AppProps } from "next/app";
import Script from "next/script";

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <Script id="datadog-rum">
        {`
          (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;d.crossOrigin=''
            n=o.getElementsByTagName(u)[0];n.parentNode.insertBefore(d,n)
          })(window,document,'script','https://www.datadoghq-browser-agent.com/us1/v6/datadog-rum.js','DD_RUM')
          window.DD_RUM.onReady(function() {
            window.DD_RUM.init({
              clientToken: '<CLIENT_TOKEN>',
              applicationId: '<YOUR_APPLICATION_ID>',
              site: 'datadoghq.com',
              service: '<SERVICE_NAME>',
              env: '<ENV_NAME>',
              sessionSampleRate: 100,
              sessionReplaySampleRate: 20,
            });
          })
        `}
      </Script>
      <Component {...pageProps} />
    </>
  );
}
```

{% /tab %}

{% tab title="CDN sync" %}
Use `strategy="beforeInteractive"` to load RUM synchronously before the page becomes interactive:

In the `pages/_app.tsx` file:

```tsx
import type { AppProps } from "next/app";
import Script from "next/script";

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <Script
        id="dd-rum-sync"
        src="https://www.datadoghq-browser-agent.com/us1/v6/datadog-rum.js"
        crossOrigin=""
        type="text/javascript"
        strategy="beforeInteractive"
      />
      <Script id="datadog-rum">
        {`
          window.DD_RUM && window.DD_RUM.init({
            clientToken: '<CLIENT_TOKEN>',
            applicationId: '<YOUR_APPLICATION_ID>',
            site: 'datadoghq.com',
            service: '<SERVICE_NAME>',
            env: '<ENV_NAME>',
            sessionSampleRate: 100,
            sessionReplaySampleRate: 20,
          });
        `}
      </Script>
      <Component {...pageProps} />
    </>
  );
}
```

{% /tab %}

## Verify and deploy{% #verify-and-deploy %}

1. Run your app locally and visualize the [data collected](https://docs.datadoghq.com/real_user_monitoring/application_monitoring/browser/data_collected.md) in [dashboards](https://docs.datadoghq.com/real_user_monitoring/platform/dashboards.md) or create a search query in the [RUM Explorer](https://app.datadoghq.com/rum/sessions).
1. Deploy your changes. While doing so, don't forget to change your env and version so you can find your production sessions later.

## Backend monitoring{% #backend-monitoring %}

To connect RUM with your backend traces:

1. Set up [RUM and Traces](https://docs.datadoghq.com/real_user_monitoring/correlate_with_other_telemetry/apm.md?tab=browserrum#setup-rum) to correlate frontend and backend data.
1. Configure [OpenTelemetry support](https://docs.datadoghq.com/real_user_monitoring/correlate_with_other_telemetry/apm.md?tab=browserrum#opentelemetry-support) if using APM.

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

- [Learn about RUM Monitors](https://docs.datadoghq.com/monitors/create/types/real_user_monitoring.md)
