( DOCUMENTATION )Developer Reference

TraceMole Docs

SDK Integration/Next.js Integration Guide

Next.js Integration Guide

Integrate query explain telemetry into Next.js using OpenTelemetry and TraceMole listeners.

Integrating TraceMole into your Next.js application requires installing a few instrumentation packages, configuring an OpenTelemetry SDK hook, and wrapping your database client setup. Follow these steps to get started:

Official Example Application

To speed up your implementation, you can clone and run our working demo app on GitHub: TraceMole Next.js Example App

1. Install Required Packages Install

Install the OpenTelemetry SDK packages, the MongoDB driver instrumentation, and the TraceMole explain listener helper inside your Next.js project folder:

npm install @opentelemetry/sdk-node @opentelemetry/exporter-trace-otlp-http @opentelemetry/auto-instrumentations-node @opentelemetry/instrumentation-mongodb @tracemole/nextjs-mongodb-explain mongodb

2. Configure OpenTelemetry (`instrumentation.ts`) Create / Add

Create an `instrumentation.ts` (or `src/instrumentation.ts` if using a `src/` directory) file at the root of your Next.js project to initialize the OTel NodeSDK:

export async function register() {
  if (process.env.NEXT_RUNTIME === "nodejs") {
    const { NodeSDK } = await import("@opentelemetry/sdk-node");
    const { OTLPTraceExporter } = await import(
      "@opentelemetry/exporter-trace-otlp-http"
    );
    const { getNodeAutoInstrumentations } = await import(
      "@opentelemetry/auto-instrumentations-node"
    );
    const { MongoDBInstrumentation } = await import(
      "@opentelemetry/instrumentation-mongodb"
    );
    const apiKey = process.env.TRACE_MOLE_API_KEY;

    const sdk = new NodeSDK({
      serviceName: process.env.OTEL_SERVICE_NAME ?? "my-next-app",
      traceExporter: new OTLPTraceExporter({
        url:
          process.env.TRACEMOLE_OTLP_TRACES_ENDPOINT ??
          "http://localhost:4318/v1/traces",
        headers: apiKey ? { "x-api-key": apiKey } : {},
      }),

      instrumentations: [
        getNodeAutoInstrumentations({
          // Disable default mongodb instrumentation bundled in auto-instrumentations
          "@opentelemetry/instrumentation-mongodb": { enabled: false },
        }),
        new MongoDBInstrumentation({ requireParentSpan: false }),
      ],
    });

    sdk.start();
  }
}

3. Enable Instrumentation in Next.js config Modify Config

Next.js Version Compatibility:

  • Next.js 15+ (Newer): The instrumentation hook is enabled by default. You can completely skip this step!
  • Next.js 13 & 14 (Older): You must explicitly enable `experimental.instrumentationHook` in your configuration file.

If you are running Next.js 13 or 14, modify your `next.config.ts` or `next.config.js` to enable the experimental hook:

const nextConfig = {
  experimental: {
    instrumentationHook: true,
  },
};

export default nextConfig;

4. Create MongoDB Connector (`lib/mongodb.ts`) Create / Modify

Initialize your MongoClient. This template is based on the official MongoDB Next.js integration docs, updated to include `monitorCommands: true` and register the TraceMole query explain listener:

import { MongoClient } from "mongodb";
import { registerTraceMoleListener } from "@tracemole/nextjs-mongodb-explain";

if (!process.env.MONGODB_URI) {
  throw new Error('Invalid/Missing environment variable: "MONGODB_URI"');
}

const uri = process.env.MONGODB_URI;
const options = {
  monitorCommands: true, // required for command listener
};

let client: MongoClient;
let clientPromise: Promise<MongoClient>;

if (process.env.NODE_ENV === "development") {
  // In development mode, use a global variable so that the value
  // is preserved across module reloads caused by HMR (Hot Module Replacement).
  const globalWithMongo = global as typeof globalThis & {
    _mongoClientPromise?: Promise<MongoClient>;
  };

  if (!globalWithMongo._mongoClientPromise) {
    client = new MongoClient(uri, options);
    
    // Register TraceMole listener to trace explain stats
    registerTraceMoleListener(client, {
      slowThreshold: 50, // ms — explain queries slower than 50ms
    });
    
    globalWithMongo._mongoClientPromise = client.connect();
  }
  clientPromise = globalWithMongo._mongoClientPromise;
} else {
  // In production mode, it's best to not use a global variable.
  client = new MongoClient(uri, options);
  
  // Register TraceMole listener to trace explain stats
  registerTraceMoleListener(client, {
    slowThreshold: 50, // ms
  });
  
  clientPromise = client.connect();
}

export default clientPromise;

5. Configure Environment Variables (`.env.local`) Modify Config

Add the TraceMole API Key and your MongoDB connection URL to your local environment file:

TRACE_MOLE_API_KEY=your_api_key_here
TRACEMOLE_OTLP_TRACES_ENDPOINT=https://your-endpoint/v1/traces