Skip to content

Instantly share code, notes, and snippets.

@WomB0ComB0
Created September 19, 2025 11:20
Show Gist options
  • Select an option

  • Save WomB0ComB0/23fdf655bb146c661ba3f9cec7405a37 to your computer and use it in GitHub Desktop.

Select an option

Save WomB0ComB0/23fdf655bb146c661ba3f9cec7405a37 to your computer and use it in GitHub Desktop.
datadog-init - Enhanced with AI-generated documentation
'use client';
import { datadogRum } from '@datadog/browser-rum';
import type { RumInitConfiguration } from '@datadog/browser-rum-core';
import app from 'next/app';
import { cache, memo, useEffect } from 'react';
/**
* Type declaration extending the global Window interface to include Datadog initialization flag
* @interface Window
* @property {boolean} __datadogRumInitialized - Flag indicating whether Datadog RUM has been initialized
*/
declare global {
interface Window {
__datadogRumInitialized?: boolean;
}
}
/**
* Initializes the Datadog Real User Monitoring (RUM) client with configuration settings.
* This function is cached to prevent multiple initializations.
*
* @function initDatadog
* @description Sets up Datadog RUM with application monitoring configurations including:
* - Application and client identification
* - Environment and version tracking
* - Session sampling and replay settings
* - User interaction and resource tracking
* - Privacy and security settings
*
* @returns {void}
*
* @example
* ```ts
* initDatadog(); // Initializes Datadog RUM with predefined configuration
* ```
*
* @remarks
* - Only initializes in browser environment
* - Prevents multiple initializations using window.__datadogRumInitialized flag
* - Configures session replay and tracking settings
* - Sets up URL allowlist for tracing
*/
const initDatadog = cache(() => {
if (typeof window !== 'undefined' && !window.__datadogRumInitialized) {
datadogRum.init({
applicationId: process.env.NEXT_PUBLIC_DATADOG_APPLICATION_ID,
clientToken: process.env.NEXT_PUBLIC_DATADOG_CLIENT_TOKEN,
site: process.env.NEXT_PUBLIC_DATADOG_SITE as Extract<RumInitConfiguration['site'], string>,
service: app.name,
env: process.env.NODE_ENV,
version: process.env.NEXT_PUBLIC_APP_VERSION,
sessionSampleRate: 100,
sessionReplaySampleRate: 33,
trackUserInteractions: true,
trackResources: true,
trackLongTasks: true,
defaultPrivacyLevel: 'mask-user-input',
allowedTracingUrls: [/https:\/\/.*\.<domain>\.org/],
} satisfies RumInitConfiguration);
datadogRum.startSessionReplayRecording();
window.__datadogRumInitialized = true;
}
});
/**
* Memoized React component that handles Datadog RUM initialization.
*
* @component DatadogInit
* @description A null-rendering component that initializes Datadog RUM on mount.
* Uses useEffect to ensure browser-only execution and memo for performance optimization.
*
* @returns {null} Component renders nothing, only handles initialization
*
* @example
* ```tsx
* // In your app's root component:
* function App() {
* return (
* <>
* <DatadogInit />
* </>
* );
* }
* ```
*
* @remarks
* - Should be placed high in the component tree
* - Only initializes in browser environment
* - Memoized to prevent unnecessary re-renders
*/
export const DatadogInit = memo((): null => {
useEffect(() => {
if (typeof window !== 'undefined') {
initDatadog();
}
}, []);
return null;
});
/**
* Error handler function that reports errors to Datadog RUM.
*
* @function datadogErrorHandler
* @description Captures and reports errors to Datadog RUM for monitoring and debugging.
*
* @param {Error} error - The error object containing information about the error that occurred
* @param {React.ErrorInfo} errorInfo - React-specific error information including component stack trace
* @returns {void}
*
* @example
* ```tsx
* class ErrorBoundary extends React.Component {
* componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
* datadogErrorHandler(error, errorInfo);
* }
* }
* ```
*
* @remarks
* - Should be used within error boundaries or global error handlers
* - Automatically adds error context to Datadog RUM
* - Preserves original error information while adding it to monitoring
*/
export const datadogErrorHandler = (error: Error, errorInfo: React.ErrorInfo): void => {
datadogRum.addError(error, { errorInfo });
};

datadog-init.tsx

File Type: TSX
Lines: 130
Size: 4 KB
Generated: 9/19/2025, 7:20:37 AM


Code Analysis: datadog-init.tsx

This file initializes and configures the Datadog Real User Monitoring (RUM) client for a Next.js application. It focuses on setting up Datadog for front-end monitoring, including error tracking, performance metrics, and session replay.

Key Components:

  1. initDatadog (Cached Initialization):

    • This function is the core of the Datadog RUM setup. It's wrapped in cache from React to ensure it's only executed once, preventing multiple initializations of the Datadog RUM client.
    • It checks if it's running in a browser environment (typeof window !== 'undefined') and if Datadog RUM hasn't already been initialized (!window.__datadogRumInitialized). The window.__datadogRumInitialized flag acts as a safeguard against redundant initializations, which could lead to inaccurate data or performance issues.
    • It retrieves configuration parameters from environment variables (e.g., NEXT_PUBLIC_DATADOG_APPLICATION_ID, NEXT_PUBLIC_DATADOG_CLIENT_TOKEN). This allows for different Datadog configurations across environments (development, staging, production). The site property is explicitly typed using Extract to ensure it's a valid value from the RumInitConfiguration type.
    • It configures various RUM features:
      • sessionSampleRate: Controls the percentage of user sessions that are tracked.
      • sessionReplaySampleRate: Determines the percentage of sessions that are recorded for replay.
      • trackUserInteractions: Enables tracking of user interactions like clicks and taps.
      • trackResources: Monitors the loading of resources like images and scripts.
      • trackLongTasks: Identifies long-running tasks that can impact performance.
      • defaultPrivacyLevel: Sets the default privacy level for data collection (e.g., masking user input).
      • allowedTracingUrls: Specifies the URLs for which tracing should be enabled. The example uses a regular expression to match URLs from a specific domain.
    • It starts session replay recording using datadogRum.startSessionReplayRecording().
    • Finally, it sets the window.__datadogRumInitialized flag to true to prevent subsequent initializations.
  2. DatadogInit (React Component):

    • This is a React component responsible for triggering the initDatadog function.
    • It uses useEffect with an empty dependency array ([]) to ensure that initDatadog is called only once when the component mounts. This is crucial for initializing Datadog RUM correctly.
    • It includes a check if (typeof window !== 'undefined') inside the useEffect to ensure that the initialization logic only runs in the browser environment, preventing errors during server-side rendering.
    • It's wrapped in memo to prevent unnecessary re-renders, optimizing performance.
    • It returns null because it's a functional component that only performs side effects (initialization) and doesn't render any UI. This makes it a good candidate for placing high up in the component tree.
  3. datadogErrorHandler (Error Handler):

    • This function is designed to be used within React error boundaries or global error handlers to report errors to Datadog RUM.
    • It takes an Error object and React.ErrorInfo (containing component stack trace) as arguments.
    • It uses datadogRum.addError to report the error to Datadog, including the error information and React-specific context. This provides valuable debugging information, such as the component stack trace, to help identify the source of errors.

Architecture and Design:

  • Initialization Strategy: The code employs a combination of caching and a React component with useEffect to ensure that Datadog RUM is initialized only once in the browser. This is a common and effective pattern for integrating third-party libraries that require initialization.
  • Environment Configuration: The use of environment variables for configuration allows for flexibility and separation of concerns. Different environments can have different Datadog settings without modifying the code.
  • Error Handling: The datadogErrorHandler function provides a centralized way to report errors to Datadog, making it easier to track and debug issues in the application.
  • Privacy and Security: The defaultPrivacyLevel and allowedTracingUrls options demonstrate a focus on privacy and security by controlling the data that is collected and the URLs that are traced.

Practical Usage:

  1. Installation: Install the Datadog RUM browser SDK:

    npm install @datadog/browser-rum
  2. Configuration: Set the required environment variables (e.g., NEXT_PUBLIC_DATADOG_APPLICATION_ID, NEXT_PUBLIC_DATADOG_CLIENT_TOKEN, NEXT_PUBLIC_DATADOG_SITE). These variables should be configured in your hosting environment or in a .env file for local development.

  3. Integration: Place the <DatadogInit /> component high up in your application's component tree (e.g., in your _app.tsx or _app.js file).

    import { DatadogInit } from './datadog-init';
    
    function MyApp({ Component, pageProps }) {
      return (
        <>
          <DatadogInit />
          <Component {...pageProps} />
        </>
      );
    }
    
    export default MyApp;
  4. Error Boundaries: Implement error boundaries using a library like react-error-boundary and use the datadogErrorHandler function to report errors to Datadog.

    import React from 'react';
    import { ErrorBoundary } from 'react-error-boundary';
    import { datadogErrorHandler } from './datadog-init';
    
    function MyComponent() {
      // ... your component logic ...
    }
    
    function ErrorFallback({ error, resetErrorBoundary }) {
      return (
        <div>
          <p>Something went wrong:</p>
          <pre>{error.message}</pre>
          <button onClick={resetErrorBoundary}>Try again</button>
        </div>
      );
    }
    
    function App() {
      return (
        <ErrorBoundary
          FallbackComponent={ErrorFallback}
          onError={(error, errorInfo) => {
            datadogErrorHandler(error, errorInfo);
          }}
        >
          <MyComponent />
        </ErrorBoundary>
      );
    }
    
    export default App;

Potential Improvements:

  • Dynamic Configuration: Consider allowing more dynamic configuration of Datadog RUM settings through props passed to the DatadogInit component. This would allow for more fine-grained control over the RUM configuration.
  • Custom Tracing: Explore the use of custom tracing to track specific user flows or performance bottlenecks in the application.
  • User Identification: Implement user identification to associate RUM data with specific users. This can be done using the datadogRum.setUser method. Be mindful of privacy regulations when collecting user data.
  • Feature Flags: Integrate with a feature flag system to dynamically enable or disable Datadog RUM features based on user segments or other criteria.
  • Typescript Enhancements: Add explicit types for the environment variables used, improving type safety and developer experience.

In summary, this file provides a well-structured and comprehensive solution for integrating Datadog RUM into a Next.js application. It addresses key aspects of RUM setup, including initialization, configuration, error handling, and privacy. The use of React hooks and best practices ensures that Datadog RUM is initialized correctly and efficiently.


Description generated using AI analysis

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment