Skip to main content
This example demonstrates how to build a Next.js application with OpenAI integration and OpenInference instrumentation.

Prerequisites

  • Node.js 18+
  • OpenAI API key
  • Phoenix or another OpenTelemetry collector

Installation

1

Create Next.js app

2

Install dependencies

3

Set environment variables

Create a .env.local file:

Instrumentation Setup

Next.js requires a specific instrumentation pattern using the instrumentation hook.

Create Root Instrumentation File

Create instrumentation.ts in the root directory:

Create Node.js Instrumentation

Create instrumentation-node.ts:

Enable Instrumentation in Next.js Config

Update next.config.js:

API Route

Create app/api/chat/route.ts:

Streaming API Route

For streaming responses, create app/api/chat/stream/route.ts:

Chat UI Component

Create app/components/chat.tsx:

Main Page

Update app/page.tsx:

Run the Application

Visit http://localhost:3000 to use the chat interface.

Key Features

Automatic Instrumentation

Next.js instrumentation hook automatically initializes tracing before your application code runs.

Server-Side Only

Instrumentation only runs in the Node.js runtime (server-side), not in the browser.

API Routes

Both standard and streaming API routes are automatically traced.

Next Steps