APItoolkit full color logo
Sign Up

NextJs Integration Guide

APIToolkit Next.js Middleware allows you to monitor HTTP requests in your Next.js applications. It builds upon OpenTelemetry instrumentation to create custom spans for each request, capturing key details such as request and response bodies, headers, and status codes. Additionally, it offers robust support for monitoring outgoing requests and reporting errors automatically.

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.

Installation

Run the command below to install the APIToolkit nextJs sdk and Open telemetery API, SDK, and auto instrumentation tools.

npm install --save apitoolkit-next @opentelemetry/api @vercel/otel

Setup Open Telemetry

Setting up open telemetry allows you to send traces, metrics and logs to the APIToolkit platform. Add the following environment variables to your .env file:

OTEL_EXPORTER_OTLP_ENDPOINT="http://otelcol.apitoolkit.io:4318"
OTEL_SERVICE_NAME="my-service" # Specifies the name of the service.
OTEL_RESOURCE_ATTRIBUTES="at-project-key={YOUR_API_KEY}" # Adds your API KEY to the resource.
OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf" #Specifies the protocol to use for the OpenTelemetry exporter.

Add the following to your intrumentation.ts|js file:

You can create the intrumentation.ts|js in the src directory of your project or root directory if you're not using a src directory.

import { registerOTel } from "@vercel/otel";

export function register() {
  registerOTel("");
}

HTTP Requests Monitoring

After setting up open telemetry. You can monitor http requests using APIToolkit's next middleware, this allows you to monitor all your http requests. including headers, response time, response status code, request body, response body, etc.

To monitor http requests, wrap your routes with the withAPItoolkitAppRouter function if you're using the app router or withAPItoolkitPagesRouter if you're using the pages router.

App Router Example

import { withAPItoolkitAppRouter } from "apitoolkit-next";
import { NextRequest, NextResponse } from "next/server";
async function handleRequest(req: NextRequest) {
  return NextResponse.json({ message: "hello world" });
}

// Optional configuration
const config = {
  captureResponseBody: true,
  serviceName: "my-service",
}
export const GET = withAPItoolkitAppRouter(handleRequest, config);

Pages Router Example

import type { NextApiRequest, NextApiResponse } from "next";
import { withAPItoolkitPagesRouter } from "apitoolkit-next";

function handler(req: NextApiRequest, res: NextApiResponse) {
  res.status(200).json({ message: "Hello from Next.js!" });
}

// Optional configuration
const config = {
  captureResponseBody: true,
  serviceName: "my-service",
}

export default withAPItoolkitPagesRouter(handler, config);

Quick overview of the configuration parameters

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

OptionDescription
debugSet to true to enable debug mode.
serviceNameA defined string name of your application.
tagsA list of defined tags for your services (used for grouping and filtering data on the dashboard).
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.

Reporting errors to APIToolkit

APIToolkit detects a lot of API issues automatically, but it's also valuable to report and track errors. This helps you associate more details about the backend with a given failing request. If you've used sentry, or rollback, or bugsnag, then you're likely aware of this functionality.

To report errors to APIToolkit, you can use the reportError function.

import { NextRequest, NextResponse } from "next/server";
import { withAPItoolkitAppRouter, reportError } from "apitoolkit-next";
async function handleRequest(req: NextRequest) {
  try {
    throw new Error("Something went wrong");
  } catch (e) {
    // reportError will send the error to APIToolkit
    reportError(e);
  }

  return NextResponse.json({ message: "hello world" });
}

export const GET = withAPItoolkitAppRouter(handler);

Monitoring Axios requests

APIToolkit supports monitoring outgoing HTTP requests made using libraries like Axios. To monitor a specific Axios request, you can use the observeAxios function provided by the SDK.

import { NextRequest, NextResponse } from "next/server";
import { withAPItoolkitAppRouter, observeAxios } from "apitoolkit-next";

async function handleRequest(req: NextRequest) {
  // Observe an Axios request
  const response = await observeAxios({
    urlWildcard: "/todos/:id",
  }).get("https://jsonplaceholder.typicode.com/todos/1");

  return NextResponse.json({ data: response.data });
}

export const GET = withAPItoolkitAppRouter(handler);

The urlWildcard parameter is used for urls that contain dynamic path parameters. This helps APIToolkit to identify request to the same endpoint but with different parameters.

All observeAxios options

Below is the full list of options for the observeAxios function:

OptionDescription
urlWildcardoptional The route pattern of the url if it has dynamic path parameters.
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.