Tutorial: Integrating with Next.js

This tutorial shows you how to integrate AIA with a Next.js application to automatically detect and fix production errors.

#Prerequisites

  • Next.js 14+ application
  • AIA installed and running (Install Guide)
  • GitHub repository for your Next.js app

#Step 1: Install OpenTelemetry

Install the required packages:

Terminal
bun add @opentelemetry/api @opentelemetry/sdk-node \ @opentelemetry/auto-instrumentations-node \ @opentelemetry/exporter-trace-otlp-http

#Step 2: Create Instrumentation File

Create instrumentation.ts in your project root (or src/ directory):

instrumentation.ts
export async function register() { if (process.env.NEXT_RUNTIME === 'nodejs') { const { NodeSDK } = await import('@opentelemetry/sdk-node'); const { OTLPTraceExporter } = await import('@opentelemetry/exporter-trace-otlp-http'); const { getNodeAutoInstrumentations } = await import('@opentelemetry/auto-instrumentations-node'); const sdk = new NodeSDK({ traceExporter: new OTLPTraceExporter({ url: process.env.OTEL_EXPORTER_OTLP_ENDPOINT + '/v1/traces', }), instrumentations: [getNodeAutoInstrumentations()], serviceName: process.env.OTEL_SERVICE_NAME || 'my-nextjs-app', }); sdk.start(); } }

#Step 3: Enable Instrumentation

Update next.config.js:

next.config.js
/** @type {import('next').NextConfig} */ const nextConfig = { experimental: { instrumentationHook: true, }, } module.exports = nextConfig

#Step 4: Configure Environment

Add to .env.local:

.env.local
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 OTEL_SERVICE_NAME=my-nextjs-app

#Step 5: Add Error Boundary (Optional)

Create app/error.tsx for better error handling:

app/error.tsx
'use client' import { useEffect } from 'react' export default function Error({ error, reset, }: { error: Error & { digest?: string } reset: () => void }) { useEffect(() => { // Error is automatically captured by OTEL console.error('Application error:', error) }, [error]) return ( <div> <h2>Something went wrong!</h2> <button onClick={() => reset()}>Try again</button> </div> ) }

#Step 6: Test Integration

Create a test API route that throws an error:

app/api/test-error/route.ts:

app/api/test-error/route.ts
export async function GET() { // This will be caught by OTEL and sent to AIA throw new Error('Test error for AIA demo'); }

#Step 7: Trigger Test Error

Start your Next.js app and trigger the error:

Terminal
# Start Next.js npm run dev # In another terminal, trigger error curl http://localhost:3000/api/test-error

#Step 8: Verify in Dashboard

  1. Open AIA Dashboard: http://localhost:3000
  2. You should see the incident appear
  3. Wait for autopsy analysis (~5-10 seconds)
  4. Check GitHub for the PR

#Step 9: Production Deployment

Vercel

Add environment variables in Vercel dashboard:

Terminal
OTEL_EXPORTER_OTLP_ENDPOINT=https://your-aia-agent.example.com OTEL_SERVICE_NAME=my-nextjs-app

Self-Hosted

Update .env.production:

Terminal
OTEL_EXPORTER_OTLP_ENDPOINT=https://your-aia-agent.example.com OTEL_SERVICE_NAME=my-nextjs-app

#Common Patterns

API Route Error Handling

Terminal
// app/api/users/route.ts export async function GET() { try { const users = await db.query('SELECT * FROM users'); return Response.json(users); } catch (error) { // Error automatically captured by OTEL console.error('Failed to fetch users:', error); return Response.json( { error: 'Failed to fetch users' }, { status: 500 } ); } }

Server Component Error Handling

Terminal
// app/users/page.tsx export default async function UsersPage() { try { const users = await fetchUsers(); return <UserList users={users} />; } catch (error) { // Error captured by OTEL throw error; // Will be caught by error.tsx } }

Client Component Error Handling

Terminal
'use client' import { useEffect } from 'react' export default function ClientComponent() { useEffect(() => { try { // Some client-side code riskyOperation(); } catch (error) { // Client errors won't be captured by OTEL // Send to your error tracking service console.error(error); } }, []); return <div>...</div>; }

#Troubleshooting

No traces received

Check:

  1. OTEL endpoint is correct: http://localhost:4318
  2. AIA Agent is running
  3. Instrumentation hook is enabled in next.config.js
  4. Environment variables are set

Traces sent but no incidents

Check:

  1. Error status code is 500+
  2. Exception is thrown (not just logged)
  3. Check AIA Agent logs

Production deployment issues

Check:

  1. OTEL endpoint is accessible from production
  2. Firewall allows outbound connections
  3. Environment variables are set correctly

#Next Steps