Observability for Next.js
Instrument your Next.js app based on App Router with Laminar
Overview
Next.js is a popular React framework for building web applications.
For a full example app, see the Next.js guide and the Next.js + AI SDK guide.
Getting Started
1. Install Laminar
2. Update your next.config.ts
Add the following to your next.config.ts
file:
This is because Laminar depends on OpenTelemetry, which uses some Node.js-specific functionality, and we need to inform Next.js about it. Learn more in the Next.js docs.
3. Initialize Laminar
To instrument your entire Next.js app, place Laminar initialization in instrumentation.{ts,js}
file. Learn more about instrumentation.{ts,js}
here.
instrumentation.ts
is experimental in Next.js < 15.
If you use Next.js < 15, add the following to your next.config.js
:
4. Patch LLM SDKs
AI SDK is already instrumented implicitly, but you need to direct it to use Laminar tracer.
AI SDK is already instrumented implicitly, but you need to direct it to use Laminar tracer.
Usually, Laminar initialize can patch the LLM SDKs automatically. However, in Next.js, the imports
that happen in instrumentation.{ts,js}
file are not visible to the rest of the app.
So, you need to manually patch the LLM SDKs using Laminar.patch
function.
For example, if you initialize your LLM SDKs in lib/llm-clients.ts
file, you can patch them like this:
5. Grouping traces within one route
If your app makes multiple LLM calls within one route, you may want to group them together.
You might get this functionality by default, if your app is instrumented with OpenTelemetry and
some Next.js instrumentation, e.g. @vercel/otel
or @sentry/nextjs
.
Otherwise, you can achieve this by using observe
function wrapper, e.g. something like
Learn more about observe
function wrapper here.