( 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:

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.OTEL_EXPORTER_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 with `monitorCommands: true` and register the TraceMole query explain listener:

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

const SKIP = process.env.SKIP_MONGO_CONNECT === "true";

let clientPromise: Promise<MongoClient>;

function createClient(uri: string): MongoClient {
  const client = new MongoClient(uri, {
    monitorCommands: true, // required for command listener
    serverApi: {
      version: ServerApiVersion.v1,
      strict: true,
      deprecationErrors: true,
    },
  });

  registerTraceMoleListener(client as any, {
    slowThreshold: 0, // ms — explain all queries
  });

  return client;
}

if (SKIP) {
  clientPromise = Promise.resolve({} as MongoClient);
} else {
  if (!process.env.MONGO_DB_URL) {
    throw new Error("Missing env: MONGO_DB_URL");
  }

  const uri = process.env.MONGO_DB_URL;
  const g = global as any;

  if (process.env.NODE_ENV === "development") {
    if (!g._mongoClientPromise) {
      g._mongoClientPromise = createClient(uri).connect();
    }
    clientPromise = g._mongoClientPromise;
  } else {
    clientPromise = createClient(uri).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
MONGO_DB_URL=mongodb+srv://...