npm package: @potipher/otel-react
Description: OpenTelemetry instrumentation for React components
Latest version: 1.0.3

# @potipher/otel-react

OpenTelemetry instrumentation for React components with business analytics and error tracking.

## Features

- Component Tracing - Track clicks, changes, focus/blur events automatically
- Business Analytics - Track custom events (purchases, signups, conversions)
- Error Tracking - Manual error capture with context and metadata
- Session Management - Automatic 30-minute session tracking
- Jaeger Integration - View traces in Jaeger UI
- Prometheus Metrics - Auto-convert traces to metrics
- Zero Config - Works out of the box with Next.js

## Installation

```bash
npm install @potipher/otel-react
```

## Quick Start

### 1. Create Client Provider

Create `/components/client-tracing-provider.tsx`:

```tsx
"use client"

import { TracingProvider } from "@potipher/otel-react"

export function ClientTracingProvider({ children }: { children: React.ReactNode }) {
  return (
    <TracingProvider config={{ 
      serviceName: 'my-app',
      apiEndpoint: '/api/traces'  // or https://collector.potipher.com/v1/traces
    }}>
      {children}
    </TracingProvider>
  )
}
```

### 2. Add to Layout

```tsx
// app/layout.tsx
import { ClientTracingProvider } from "@/components/client-tracing-provider"

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <ClientTracingProvider>
          {children}
        </ClientTracingProvider>
      </body>
    </html>
  )
}
```

### 3. Create API Proxy

Create `/app/api/traces/route.ts`:

```ts
export async function POST(request: Request) {
  const body = await request.text()
  
  const response = await fetch('http://localhost:4318/v1/traces', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body,
  })

  return new Response(response.body, {
    status: response.status,
    headers: response.headers,
  })
}
```

### 4. Use Instrumented Components

```tsx
import { ComponentTracer } from '@potipher/otel-react'

// Track custom events
ComponentTracer.trackEvent('purchase_completed', {
  userId: 'user_123',
  value: 99.99,
  currency: 'USD',
  metadata: { items: 3 }
})

// Capture errors
ComponentTracer.captureError(new Error('Payment failed'), {
  componentName: 'checkout',
  userId: 'user_123',
  metadata: { amount: 99.99 }
})

// Track interactions
await ComponentTracer.recordInteraction('buy-button', 'click', {
  product_id: 'SKU-123',
  price: 29.99
})
```

## API Reference

### TracingProvider

```tsx
<TracingProvider config={{
  serviceName: string        // Required: Your app name
  apiEndpoint?: string       // Optional: OTLP endpoint (default: /api/traces)
}}>
```

### ComponentTracer

#### `recordInteraction(componentName, interaction, attributes?, statusCode?)`

Track component interactions:

```ts
await ComponentTracer.recordInteraction(
  'checkout-button',
  'click',
  { product_id: 'SKU-123', price: 99.99 },
  200
)
```

#### `captureError(error, context?)`

Capture errors with context:

```ts
await ComponentTracer.captureError(
  new Error('Payment failed'),
  {
    componentName: 'checkout',
    userId: 'user_123',
    metadata: { amount: 99.99, gateway: 'stripe' }
  }
)
```

#### `trackEvent(eventName, properties?)`

Track business events:

```ts
await ComponentTracer.trackEvent('purchase_completed', {
  userId: 'user_123',
  value: 99.99,
  currency: 'USD',
  metadata: { items: 3, category: 'electronics' }
})
```

#### `startOperation(componentName, interaction, attributes?)`

Start long-running operation:

```ts
const opId = await ComponentTracer.startOperation('checkout-form', 'submit')
// ... do async work
await ComponentTracer.endOperation(opId, 200)
```

### useComponentTrace Hook

```tsx
import { useComponentTrace } from '@potipher/otel-react'

function MyComponent() {
  const { recordClick, recordChange, recordFocus, recordBlur } = 
    useComponentTrace('my-component')
  
  return <button onClick={recordClick}>Click me</button>
}
```

## License

MIT

## Links

- [Documentation](https://potipher.com/docs)
- [GitHub](https://github.com/potipher/otel-react)
- [NPM](https://www.npmjs.com/package/@potipher/otel-react)