APItoolkit full color logo
Sign Up

NestJs Integration Guide

You can integrate your NestJs application with APIToolkit using OpenTelemetry. This allows you to send logs, metrics, and traces to APIToolkit for monitoring and analytics.

To get started, you'll need the OpenTelemetry Node.js library and some basic configuration.


Prerequisites

Ensure you have completed the first three steps of the onboarding guide{target="\_blank"}.

Installation

Run the command below to install the API, SDK, and Instrumentation tools.


npm install --save @opentelemetry/api \
    @opentelemetry/auto-instrumentations-node

# Or

yarn add @opentelemetry/api @opentelemetry/auto-instrumentations-node

OpenTelemetery Configuration

This module is highly configurable by setting environment variables. So many aspects of the auto instrumentation’s behavior such as Resource detectors, Exporters, Trace context propagation headers, and many more can be configured based on your needs. Add the following environment variables to your .env file:

# Specifies the endpoint URL for the OpenTelemetry collector.
OTEL_EXPORTER_OTLP_ENDPOINT="http://otelcol.apitoolkit.io:4317"
# Specifies the name of the service.
OTEL_SERVICE_NAME="{YOUR_SERVICE_NAME}"
# Adds your API KEY to the resource.
OTEL_RESOURCE_ATTRIBUTES="at-project-key={YOUR_API_KEY}"
# Specifies the protocol to use for the OpenTelemetry exporter.
OTEL_EXPORTER_OTLP_PROTOCOL="grpc"
# disable some auto instrumentation libraries
OTEL_NODE_DISABLED_INSTRUMENTATIONS=net,connect,dns,fs

APIToolkit Middleware for NestJs + Express

If your NestJs app uses the default Express adapter (which is the default unless changed), you can include the APIToolkit Express middleware to capture HTTP request and response details:

Installation

npm install --save apitoolkit-express

in your main.ts file

import "@opentelemetry/auto-instrumentations-node/register"; // IMPORTANT: Do this as early as possible in your server
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { APIToolkit } from "apitoolkit-express";
import axios from "axios";

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  const apitoolkitClient = APIToolkit.NewClient({
    monitorAxios: axios, // Optional: Use this to monitor axios requests
  });

  app.use(apitoolkit.middleware);

  app.get("/", async (req, res) => {
    // This axios request get's monitored and appears in the  APIToolkit explorer
    const response = await axios.get(
      "https://jsonplaceholder.typicode.com/todos/1"
    );
    res.json(response.data);
  });

  // automatically report unhandled errors along with the request data
  app.use(apitoolkitClient.errorMiddleware);

  await app.listen(3000);
}
bootstrap();

APIToolkit Middleware with for NestJs + Fastify

If your NestJS app uses the Fastify adapter, you should follow our Fastify integration fastify guide{target="\_blank"}. for detailed setup instructions.

Quick overview of the configuration parameters

AttributeDescription
OTEL_EXPORTER_OTLP_ENDPOINTSpecifies the endpoint URL for the OpenTelemetry collector. In this case, it's set to "http://otelcol.apitoolkit.io:4317".
OTEL_NODE_RESOURCE_DETECTORSDefines which resource detectors to use. Here, it's set to detect environment variables, host information, and operating system details.
OTEL_SERVICE_NAMESets the name of your service. You should replace "your-service-name" with the actual name of your service.
OTEL_RESOURCE_ATTRIBUTESSpecifies additional resource attributes. In this case, it's setting an API Toolkit project key.
OTEL_EXPORTER_OTLP_PROTOCOLDefines the protocol used for exporting telemetry data. It's set to "grpc" (gRPC protocol).
OTEL_PROPAGATORSSpecifies which context propagators to use. Here, it's set to use both "baggage" and "tracecontext".

Quick overview of the configuration parameters

An object with the following optional fields can be passed to the middleware function to configure it:

OptionDescription
debugSet to true to enable debug mode.
tagsA list of defined tags for your services (used for grouping and filtering data on the dashboard).
serviceNameA defined string name of your application
serviceVersionA defined string version of your application (used for further debugging on the dashboard).
redactHeadersA list of HTTP header keys to redact.
redactResponseBodyA list of JSONPaths from the response body to redact.
redactRequestBodyA list of JSONPaths from the request body to redact.
captureRequestBodydefault false, set to true if you want to capture the request body.
captureResponseBodydefault false, set to true if you want to capture the response body.
monitorAxiosAxios instance to monitor.

<div class="callout"> <p><i class="fa-regular fa-lightbulb"></i> <b>Tips</b></p> <ol> <li> At the moment, only Traces are supported for environment variable configuration. See the open issues for Metrics and Logs to learn more. </li> <li> By default, all SDK resource detectors are enabled. However, you can customize this by setting the OTEL_NODE_RESOURCE_DETECTORS environment variable to activate specific detectors or disable them entirely. </li> </ul>

</div>