Cette page n'est pas encore disponible en français, sa traduction est en cours.
Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.

Overview

Next.js is a JavaScript framework created by Vercel 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

Create a RUM application in Datadog to get your credentials:

  1. Go to Digital Experience > Performance Summary.
  2. Click New Application.
  3. Select JS, enter an application name, and click Create Application.
  4. Copy the applicationId and clientToken values.
If you store these in .env.local, prefix them with NEXT_PUBLIC_ to expose them to the browser. See Next.js environment variables.

Install the RUM SDK

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

App Router

Note: The App Router 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.

  1. Install the RUM SDK:

    npm install @datadog/browser-rum
    
  2. Create a client component for RUM initialization:

components/datadog-init.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;
   }
   
  1. Add the component to your root layout:

app/layout.tsx

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

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

Use the Next.js Script component to load RUM asynchronously:

app/layout.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
            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>
  );
}

Use strategy="beforeInteractive" to load RUM synchronously before the page becomes interactive:

app/layout.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"
          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>
  );
}

Pages Router

The Pages Router runs on the client, so you can initialize RUM directly in _app.tsx.

  1. Install the RUM SDK:

    npm install @datadog/browser-rum
    
  2. Initialize RUM in your custom App component:

pages/_app.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} />;
   }
   

Use the Next.js Script component to load RUM asynchronously:

pages/_app.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
            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} />
    </>
  );
}

Use strategy="beforeInteractive" to load RUM synchronously before the page becomes interactive:

pages/_app.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"
        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} />
    </>
  );
}

Verify and deploy

  1. Run your app locally and visualize the data collected in dashboards or create a search query in the RUM Explorer.
  2. 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

To connect RUM with your backend traces:

  1. Set up RUM and Traces to correlate frontend and backend data.
  2. Configure OpenTelemetry support if using APM.

Further reading

Documentation, liens et articles supplémentaires utiles: