Nextjs is a production-ready React framework for building single-page web applications. It enables you to build fast and user-friendly static websites, as well as web applications using Reactjs. Using OpenTelemetry Nextjs libraries, you can set up end-to-end tracing for your Nextjs applications.
![Cover Image](/_next/image/?url=%2Fimg%2Fblog%2F2022%2F04%2Fopentelemetry_nextjs_cover.webp&w=3840&q=75)
Nextjs has its own monitoring feature, but it is only limited to measuring the metrics like core web vitals and real-time analytics of the application. It doesn’t have end-to-end tracing, monitoring the database calls, etc. That’s where OpenTelemetry comes in.
OpenTelemetry is an open-source standard under Cloud Native Computing Foundation (CNCF) used for instrumenting applications for generating telemetry data. You can monitor your Nextjs application using OpenTelemetry and a tracing backend of your choice.
What is OpenTelemetry Nextjs instrumentation? Instrumentation is the process of enabling your application code to generate telemetry data like logs, metrics, and traces. Using OpenTelemetry Nextjs client libraries, you can generate end-to-end tracing data from your Nextjs application.
OpenTelemetry provides client libraries to take care of instrumentation. You then need to send the collected data to an analysis backend. In this tutorial, we will be using SigNoz to store and visualize the telemetry data collected by OpenTelemetry from the sample Nextjs application
Before we demonstrate how to implement the OpenTelemetry Nextjs libraries, let’s have a brief overview of OpenTelmetry.
What is OpenTelemetry?
OpenTelemetry is an open-source vendor-agnostic set of tools, APIs, and SDKs used to instrument applications to create and manage telemetry data(logs, metrics, and traces). It aims to make telemetry data(logs, metrics, and traces) a built-in feature of cloud-native software applications.
The telemetry data is then sent to an observability tool for storage and visualization.
![How opentelemetry fits with an application](/img/blog/2022/04/how_opentelemetry_fits.webp)
OpenTelemetry is the bedrock for setting up an observability framework. It also provides you the freedom to choose a backend analysis tool of your choice. You will never get locked in with any vendor if you use OpenTelemetry for your instrumentation layer.
OpenTelemetry and SigNoz
In this tutorial, we will use SigNoz as our backend analysis tool. SigNoz is a full-stack open-source APM tool that can be used for storing and visualizing the telemetry data collected with OpenTelemetry. It is built natively on OpenTelemetry and works on the OTLP data formats.
SigNoz provides query and visualization capabilities for the end-user and comes with out-of-box charts for application metrics and traces.
![Application metrics charts on SigNoz dashboard](/img/blog/common/signoz_charts_application_metrics.webp)
Now let’s get down to how to implement OpenTelemetry Nextjs libraries for a sample Nextjs application and then visualize the collected data in SigNoz.
Running a Nextjs application with OpenTelemetry
First of all, we need to install SigNoz for data collection then this data will be sent to OpenTelemetry for storage and visualization
Installing SigNoz
First, you need to install SigNoz so that OpenTelemetry can send the data to it.
SigNoz cloud is the easiest way to run SigNoz. Sign up for a free account and get 30 days of unlimited access to all features.
You can also decide to self-host SigNoz. It can be installed on macOS or Linux computers in just three steps by using a simple install script. The install script automatically installs Docker Engine on Linux. However, on macOS, you must manually install Docker Engine before running the install script.
git clone -b main https://github.com/SigNoz/signoz.git
cd signoz/deploy/
./install.sh
You can visit our documentation for instructions on how to install SigNoz using Docker Swarm and Helm Charts.
When you are done installing SigNoz, you can access the UI at http://localhost:3301
Creating a sample Nextjs application
To install and run a Nextjs application you need to have Nodejs 12.22.0 or later. You can also check the sample application at this GitHub repo.
Download the latest version of NodejsTo create a new Nextjs app, you can use create-next-app
which sets up everything automatically for you.
Steps to get the app set up and ready:
Step 1: Create a project using any of these commands
npx create-next-app@latest
OR
yarn create next-app
OR
pnpm create next-app
Step2: Check if the application is running
Start the development server.
npm run dev
OR
yarn dev
OR
pnpm dev
You can check if your app is up and running on http://localhost:3000
![Nextjs app running in your local](/img/blog/2022/04/nextjs_app_running.webp)
Instrumenting the Nextjs application with OpenTelemetry
Step 1: Install OpenTelemetry packages
You will need the following OpenTelemetry packages for this sample application.
npm i @opentelemetry/sdk-node
npm i @opentelemetry/auto-instrumentations-node
npm i @opentelemetry/exporter-trace-otlp-http
npm i @opentelemetry/resources
npm i @opentelemetry/semantic-conventions
You can use yarn or npm as per the package manager that you’re using for the project
Step 2. Update next.config.mjs
to include instrumentationHook
/** @type {import('next').NextConfig} */
const nextConfig = {
// include instrumentationHook experimental feature
experimental: {
instrumentationHook: true,
},
};
export default nextConfig;
Step 3. Create instrumentation.ts
file
export async function register() {
if (process.env.NEXT_RUNTIME === 'nodejs') {
await import('./instrumentation.node')
}
}
Step 4. Create instrumentation.node.ts
file
You need to configure the endpoint for SigNoz cloud in this file.
'use strict'
import process from 'process';
import {NodeSDK} from '@opentelemetry/sdk-node';
import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node';
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
import { Resource } from '@opentelemetry/resources'
import { SEMRESATTRS_SERVICE_NAME } from '@opentelemetry/semantic-conventions'
// Add otel logging when debugging
// import { diag, DiagConsoleLogger, DiagLogLevel } from '@opentelemetry/api';
// diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG);
const exporterOptions = {
url: 'https://ingest.[region].signoz.cloud:443/v1/traces', // Use your own data region or set to http://localhost:4318/v1/traces if using selfhost SigNoz
headers: { 'signoz-access-token': 'SIGNOZ_INGESTION_KEY' }, // Use if you are using SigNoz Cloud
}
const traceExporter = new OTLPTraceExporter(exporterOptions);
const sdk = new NodeSDK({
traceExporter,
instrumentations: [getNodeAutoInstrumentations()],
resource: new Resource({
[SEMRESATTRS_SERVICE_NAME]: 'SigNoz-Nextjs-Example',
}),
});
// initialize the SDK and register with the OpenTelemetry API
// this enables the API to record telemetry
sdk.start()
// gracefully shut down the SDK on process exit
process.on('SIGTERM', () => {
sdk.shutdown()
.then(() => console.log('Tracing terminated'))
.catch((error) => console.log('Error terminating tracing', error))
.finally(() => process.exit(0));
});
Step 5: Run the server and monitor the application
Run the application, and your application should be available on http://localhost:8080 .
Hit the URL a couple of times to generate some dummy data and wait for the SigNoz-Nextjs-Example
application to be visible on the SigNoz dashboard.
![Sample Nextjs app being monitored on SigNoz dashboard](/img/blog/2022/04/sample_nextjs_signoz_dashboard.webp)
You can use the dashboard to see application metrics like application latency, requests per sec, and error percentage.
![Nextjs application metrics captured with OpenTelemetry and visualized on SigNoz dashboard](/img/blog/2022/04/otel_nextjs_metrics.webp)
OpenTelemetry captures tracing data from your Nextjs application as well. Tracing data can help you visualize how user requests perform across services in a multi-service application.
In the Traces
tab of SigNoz, you can analyze the tracing data using filters based on tags, status codes, service names, operations, etc.
![Traces tab on SigNoz dashboard](/img/blog/2022/04/nextjs_traces_tab.webp)
You can also visualize the tracing data with the help of flamegraphs and Gantt charts. These visualizations makes it easier for users to see how requests performed acrosee different services in a multi-service application.
![Sample Nextjs app being monitored on SigNoz dashboard](/img/blog/2022/04/otel_nextjs_signoz_dashboard.webp)
Conclusion
Using OpenTelemetry libraries, you can instrument your Nextjs applications for end-to-end tracing. You can then use an open-source APM tool like SigNoz to ensure the smooth performance of your Nextjs application.
OpenTelemetry is the future for setting up observability for cloud-native apps. It is backed by a huge community and covers a wide variety of technology and frameworks. Using OpenTelemetry, engineering teams can instrument polyglot and distributed applications and be assured about compatibility with a lot of technologies.
SigNoz is an open-source observability tool that comes with a SaaS-like experience. You can check out SigNoz by visiting its GitHub repo 👇
If you are someone who understands more from video, then you can watch the below video tutorial on the same with SigNoz.
If you face any issues while trying out SigNoz, you can reach out with your questions in #support channel 👇
Further Reading
Implementing OpenTelemetry in Angular application
Monitor your Nodejs application with OpenTelemetry and SigNoz