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 that is used to create React.js web pages and Node.js APIs. You can integrate Next.js with RUM to monitor your frontend and backend applications for browser-related metrics that you give insight into performance and user behavior.

Setup

Follow the steps below to set up Datadog RUM browser monitoring.

Create an application

  1. Navigate to Digital Experience > Performance Summary.
  2. Click the New Application button.
  3. Make sure JS is selected, then enter a name for your application and click Create New RUM Application. A clientToken and applicationId are automatically generated for your application.
When using `.env.local`, only variables prefixed with `NEXT_PUBLIC_` are included in the client bundle. See Bundling Environment Variables for the Browser in the Next.js docs.

Instrument your application

  1. Choose your instrumentation type, then copy and paste the code snippet from the Datadog RUM UI into the appropriate file based on the instrumentation type.

    When using npm, you need to make a few small changes to the code snippet from the Datadog RUM UI before pasting it into either the root layout.tsx or custom _app.tsx file (Datadog supports both):

    • If your application relies on the newer Next.js App Router (versions 13+), Datadog recommends using the CDN RUM instrumentation to ensure that the RUM initialization occurs in the client. If you want to use the npm package, the initialization code must run in a client component so RUM can collect telemetry from the client. You can achieve this without making your layout.tsx file itself a client component by following the example below to create an empty <DatadogInit /> component with the RUM initialization code, and then rendering that <DatadogInit /> component in your layout.tsx.
    • If your Next.js application relies on the older Next.js Page Router, you can paste the initialization snippet into the custom _app.tsx file without the "use client" directive and without a separate <DatadogInit /> component.

    datadog-init.tsx

       // Necessary if using App Router to ensure this file runs on the client
       "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>",
          // Specify a version number to identify the deployed version of your application in Datadog
          // version: '1.0.0',
          sessionSampleRate: 100,
          sessionReplaySampleRate: 20,
          trackUserInteractions: true,
          trackResources: true,
          trackLongTasks: true,
          defaultPrivacyLevel: "mask-user-input",
          // Specify URLs to propagate trace headers for connection between RUM and backend trace
          allowedTracingUrls: [
            { match: "https://example.com/api/", propagatorTypes: ["tracecontext"] },
          ],
        });
        
        export default function DatadogInit() {
          // Render nothing - this component is only included so that the init code
          // above will run client-side
          return null;
        }
       
    

    layout.tsx or _app.tsx

        import DatadogInit from "@/components/datadog-init";
    
        export default function RootLayout({
          children,
        }: {
          children: React.ReactNode;
        }) {
          return (
            <html lang="en">
              <body>
                <DatadogInit />
                {children}
              </body>
            </html>
          );
        }
    
       
    

    When using CDN async, you need to make a few small changes to the code snippet from the Datadog RUM UI before pasting it into either the root layout.tsx or custom _app.tsx file (Datadog supports both):

    • If your application relies on the newer Next.js App Router (versions 13+), paste the snippet into the root layout.tsx file.
    • If your Next.js application relies on the older Next.js Page Router, paste the snippet into the custom _app.tsx file.
    • The Next.js external scripts need to be loaded like in this page.

    Note: The Next.js scripts include import and export lines, and includes curly braces and backticks between the Script id, where all instances of Script are in uppercase.

    layout.tsx or _app.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/v5/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: 'next-app-router-rum',
                     env: '<ENV_NAME>',
                     // Specify a version number to identify the deployed version of your application in Datadog
                     // version: '1.0.0',
                     sessionSampleRate: 100,
                     sessionReplaySampleRate: 100,
                     trackUserInteractions: true,
                     trackResources: true,
                     trackLongTasks: true,
                   });
                 })
               `}
             </Script>
             <body>{children}</body>
           </html>
         );
       }
    
       
    

    When using CDN sync, you need to make a few small changes to the code snippet from the Datadog RUM UI before pasting it into either the root layout.tsx or custom _app.tsx file (Datadog supports both):

    • If your application relies on the newer Next.js App Router (versions 13+), paste the snippet into the root layout.tsx file.
    • If your Next.js application relies on the older Next.js Page Router, paste the snippet into the custom _app.tsx file.
    • The Next.js external scripts need to be loaded like in this page.

    Note: The Next.js scripts include import and export lines, and includes curly braces and backticks between the Script id, where all instances of Script are in uppercase.

    layout.tsx or _app.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/v5/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: 'rum-cdn-async',
                     env: '<ENV_NAME>',
                     // Specify a version number to identify the deployed version of your application in Datadog
                     // version: '1.0.0',
                     sessionSampleRate: 100,
                     sessionReplaySampleRate: 100,
                     trackUserInteractions: true,
                     trackResources: true,
                     trackLongTasks: true,
                   });
                 `}
               </Script>
               {children}
             </body>
           </html>
         );
       }
    
       
    
  2. Follow the in-app steps to verify your installation.

  3. Deploy the changes to your application. Once your deployment is live, Datadog collects events from user browsers.

  4. You can visualize the data collected in your Next.js application using dashboards.

Backend monitoring

To start backend monitoring of your Next.js applications:

  1. Follow the browser setup steps for Connecting RUM and Traces.
  2. Follow the browser setup steps for OpenTelemetry support to connect with APM.

Further Reading

Documentation, liens et articles supplémentaires utiles: