Next.js - Using OpenTelemetry



What is OpenTelemetry?

OpenTelemetry is an open source framework used to collect and analyze telemetry data of applications. It works by providing a set of APIs and SDKs that are used to instrument and collect telemetry data. OpenTelemetry is standardized tool that supports multiple languages, frameworks, and backends.

Why it is used?

  • When the application become more complex, it will be difficult to identify and diagnose issues that may arise. OpenTelemetry provides observability tools to track and gain insights into the application's behavior.
  • Next.js supports OpenTelemetry instrumentation out of the box, which means that Next.js itself already instrumented in OpenTelemetry.

Setting Up OpenTelemetry in Next.js

Setting up OpenTelemetry in directly Next.js is quite difficult. So, Next.js provides a package '@vercel/otel' that helps to simplify the setup process. See the steps below.

Step 1: Install the Package

To install the package, run the following command in your Next.js application directory.

npm install @vercel/otel @opentelemetry/sdk-logs @opentelemetry/api-logs @opentelemetry/instrumentation

Step 2: Setup Instrumentation File

Next step is to create a custom instrumentation.ts (or .js) file in the root directory of the project. This file will contain the instrumentation code that will be used to instrument the application. See the code below.

// /instrumentation.ts

import { registerOTel } from '@vercel/otel'
 
export function register() {
  registerOTel({ serviceName: 'next-app' })
}

Step 3: Test Instrumentation

To test the instrumentation, you should have a OpenTelemetry collector with a compatible backend. You can use the OpenTelemetry Collector for Node.js, which is a lightweight, open source, and production-ready collector. We have use docker-compose to run the collector in our application in this repository. It produced following metrics.

Next.js OpenTelemetry Metrics

Create Spans For Instrumentation

In OpenTelemetry, a span is a unit of work or operation in the application that can be traced. In other words, it is a timed operation that can be used to track the performance of the application. Spans can be created using the OpenTelemetry API. Consider the following code snippet.

trace.getTracer('nextjs-example')
.startActiveSpan('fetchGithubStars', async (span) => {
    try {
    return await getValue()
    } finally {
    span.end()
    }
})
  • This will create a span with the name 'fetchGithubStars'.
  • The span will start when the function begins and ends when either the operation completes or fails
  • This will measure how long it took to fetch GitHub stars
Advertisements