Want to see the complete code? Check out our Next.js + Gentrace
example on GitHub.
Prerequisites
- Next.js 14.0.0+ (with App Router)
- Node.js 18.17.0+
- A Gentrace API key
Installation
It’s critical to use
@opentelemetry/sdk-trace-node
v1 (not v2) due
to functionality and type compatibility issues with v2.Configuration
Next.js requires a two-part setup to avoid conflicts between OpenTelemetry configurations.Step 1: Create instrumentation.ts
Create aninstrumentation.ts
file in your project root:
instrumentation.ts
Next.js automatically runs
instrumentation.ts
during server
startup. No additional configuration is needed.Step 2: Initialize Gentrace SDK
In your API routes, initialize Gentrace withotelSetup: false
:
app/api/your-route/route.ts
Always set
otelSetup: false
in Next.js to avoid conflicts between
Gentrace’s OpenTelemetry setup and Vercel’s.Usage Example
Here’s a complete example of an API route with Gentrace tracing:app/api/completion/route.ts
Environment Variables
Add these to your.env.local
:
.env.local
Streaming Support
Next.js with Vercel AI SDK supports streaming responses. Gentrace automatically traces streaming interactions:Using with Sentry
If you’re using Sentry in your Next.js application, the standardinstrumentation.ts
approach won’t work due to conflicts between Sentry’s OpenTelemetry configuration and the default setup. Sentry overrides many of the default OpenTelemetry SDK configurations, which can prevent traces from being sent to Gentrace.
Important Version Compatibility:
- Sentry SDK versions ≤9.x use OpenTelemetry v1
- Sentry SDK versions 10.0.0+ use OpenTelemetry v2
openTelemetrySpanProcessors
option:
Configuration
Create or update your Sentry configuration files:sentry.server.config.ts
Do not use both the
instrumentation.ts
approach and the Sentry
configuration approach simultaneously. This will cause conflicts and
may result in missing or duplicated traces.Checking Your Sentry Version
To check which version of Sentry you’re using:- For Sentry ≤9.x: Use
@opentelemetry/sdk-trace-base@^1
- For Sentry 10.0.0+: Use
@opentelemetry/sdk-trace-base@^2
Additional Resources
Related Resources
- Installation Guide - General SDK setup
- Initialization Reference - Detailed init() options
- OpenTelemetry Setup - Understanding OTEL configuration