Skip to main content

Next.js

Send distributed traces to Last9 from an Next.js app using OpenTelemetry

Introduction

Next.js is a popular React framework that not only helps you generate Server Rendered React applications but also provides a great developer experience writing full-stack applications.

Pre-requisites

  1. You have a Next.js application.

  2. You have signed up for Last9, created a cluster, and obtained the following OTLP credentials:

    1. endpoint - https://otlp.last9.io

    2. auth_header - Obtain it from the Last9 dashboard.

Install OpenTelemetry packages

For instrumentation, Vercel provides a utility that can be used to instrument Next.js application with OpenTelemetry. To install the package, run the following command:

npm install --save @vercel/otel

Setup auto-instrumentation using OpenTelemetry

In your root directory create a file names instrumentation.ts and add the following code:

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

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

The registerOTel function will have all the necessary OpenTelemetry packages and it will automatically instrument your app.

Add environment variables

Add the necessary OpenTelemetry environment variables to your .env.local file:

OTEL_SERVICE_NAME=nextjs-app-service
OTEL_EXPORTER_OTLP_ENDPOINT=https://otlp.last9.io
OTEL_EXPORTER_OTLP_HEADERS="Authorization=Basic <BASIC_AUTH_HEADER>"
OTEL_TRACES_EXPORTER=otlp

If you don't have a .env.local file, create one using the following command in the root directory:

touch .env.local

Start the application

Start the Next.js application:

npm run dev

Visualize the traces in Last9

Once the application runs with the above code, it will start pushing traces to Last9. You can see the result in action by looking at the APM dashboard in Last9.

image

Troubleshooting

Please get in touch with us on Discord or Email if you have any questions.