APItoolkit full color logo
Sign Up

FastifyJs Integration Guide

APIToolkit Fastify Middleware allows you to monitor HTTP requests in your Fastify 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 fastify sdk and Open telemetery API, SDK, and auto instrumentation tools.

npm install --save apitoolkit-fastify @opentelemetry/api @opentelemetry/auto-instrumentations-node

Open Telemetery 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.

# Specifies the endpoint URL for the OpenTelemetry collector.
export OTEL_EXPORTER_OTLP_ENDPOINT="http://otelcol.apitoolkit.io:4317"
# Specifies the name of the service.
export OTEL_SERVICE_NAME=""
# Adds your API KEY to the resource.
export OTEL_RESOURCE_ATTRIBUTES=at-project-key="z6BJfZVEOSozztMfhqZsGTpG9DiXT9Weurvk1bpe9mwF8orB"
# Specifies the protocol to use for the OpenTelemetry exporter.
export OTEL_EXPORTER_OTLP_PROTOCOL="grpc"

export NODE_OPTIONS="--require @opentelemetry/auto-instrumentations-node/register"
node server.js

Setup APIToolkit Fastify Middleware For HTTP Request Monitoring

APIToolkit Fastify Middleware is a middleware that can be used to monitor HTTP requests. It provides additional functionalities on top of the open telemetry instrumentation which creates a custom span for each request capturing details about the request including request and response bodies.

import fastify from "fastify";
import { APIToolkit } from "apitoolkit-fastify";
import axios from "axios";

const fastifyServer = fastify({});
const apitoolkitClient = APIToolkit.NewClient({
  fastify: fastifyServer, // Required: The Fastify server instance
  monitorAxios: axios, // Optional: Use this to monitor Axios requests
});

apitoolkitClient.initializeHooks();

fastifyServer.get("/", async (request, reply) => {
  const response = await axios.get("https://api.github.com/users/octocat");
  return response.data;
});

fastifyServer.listen({ port: 3000 });

Quick overview of the configuration parameters

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

OptionDescription
fastifyThe Fastify server instance.
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.

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.

The Fastify SDK automatically reports uncaught server errors to APIToolkit. But you can also manually report errors.

import fastify from "fastify";
import { APIToolkit, reportError } from "apitoolkit-fastify";
import axios from "axios";

const fastifyServer = fastify({});
const apitoolkitClient = APIToolkit.NewClient({
  fastify: fastifyServer,
});
apitoolkitClient.initializeHooks();

fastifyServer.get("/", async (request, reply) => {
  try {
    throw new Error("Something went wrong");
    return { message: "Hello World" };
  } catch (error) {
    // Manually report the error to APIToolkit
    reportError(error);
    return { message: "Something went wrong" };
  }
});
fastifyServer.listen({ port: 3000 });

Monitoring Axios requests

APIToolkit supports monitoring outgoing HTTP requests made using libraries like Axios. This can be done either globally or on a per-request basis.

Global monitoring

To monitor all outgoing Axios requests globally, you can use the monitorAxios option when initializing the APIToolkit client.

import { APIToolkit } from "apitoolkit-fastify";
import axios from "axios";
const fastifyServer = fastify({});
const apitoolkitClient = APIToolkit.NewClient({
  fastify: fastifyServer,
  monitorAxios: axios, // Optional: Use this to monitor Axios requests
});

By setting monitorAxios in the client configuration, all axios requests in your server will be monitored by APIToolkit.

Per-request monitoring

To monitor a specific Axios request, you can use the observeAxios function provided by the SDK.

import { APIToolkit, observeAxios } from "apitoolkit-fastify";

const fastifyServer = fastify({});
const apitoolkitClient = APIToolkit.NewClient({ fastify: fastifyServer });
apitoolkitClient.initializeHooks();

fastifyServer.get("/", async (request, reply) => {
  const response = await observeAxios({
    urlWildcard: "/todos/:id",
  }).get("https://jsonplaceholder.typicode.com/todos/1");
  return response.data;
});

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.

Example

import { APIToolkit, observeAxios } from "apitoolkit-fastify";

const fastifyServer = fastify({});
const apitoolkitClient = APIToolkit.NewClient({fastify: fastifyServer});
apitoolkitClient.initializeHooks();

fastifyServer.get("/", async (request, reply) => {
  const response = await observeAxios({
    urlWildcard: "/todos/:id"
    redactHeaders: ["Authorization"],
    redactResponseBody: ["$.credit_card_number"],
    redactRequestBody: ["$.password"]
  }).get("https://jsonplaceholder.typicode.com/todos/1");

  return response.data
})
fastifyServer.listen({ port: 3000 });

Tips

  1. At the moment, only Traces are supported for environment variable configuration. See the open issues for Metrics and Logs to learn more.
  2. 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.