> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kubiks.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Next.js Setup

> Send traces and logs from Next.js apps using OpenTelemetry HTTP exporter

## Overview

Connect your Next.js application to Kubiks using the Vercel OpenTelemetry SDK with HTTP exporters. This setup works for any deployment platform (not just Vercel) and provides complete observability for your app.

## Installation

Install the required OpenTelemetry packages:

<CodeGroup>
  ```bash npm theme={null}
  npm install @vercel/otel @opentelemetry/api @opentelemetry/api-logs
  ```

  ```bash pnpm theme={null}
  pnpm add @vercel/otel @opentelemetry/api @opentelemetry/api-logs
  ```

  ```bash yarn theme={null}
  yarn add @vercel/otel @opentelemetry/api @opentelemetry/api-logs
  ```
</CodeGroup>

## Environment Variables

Add these environment variables to your deployment configuration:

```bash .env.local theme={null}
# Required: Your Kubiks API key (get this from kubiks.app/connect)
KUBIKS_API_KEY=your_api_key_here

# Required: OTLP endpoint
OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.kubiks.app

# Optional: Set service name (defaults to your app name)
OTEL_SERVICE_NAME=my-nextjs-app

# Optional: Environment (production, staging, development)
OTEL_ENVIRONMENT=production
```

## Configuration

Create an `instrumentation.ts` file in your **project root** (same level as `app/` or `pages/`):

```typescript instrumentation.ts theme={null}
import { OTLPHttpProtoTraceExporter, registerOTel } from '@vercel/otel';

export function register() {
  registerOTel({
    serviceName: process.env.OTEL_SERVICE_NAME || 'nextjs-app',
    traceExporter: new OTLPHttpProtoTraceExporter({
      url: "https://ingest.kubiks.app/v1/traces",
      headers: {
        "X-Kubiks-Key": process.env.KUBIKS_API_KEY!,
      },
    }),
  });
}
```

<Note>
  Next.js automatically loads `instrumentation.ts` when the application starts. No additional imports needed!
</Note>

## Environment-Specific Configuration

Set environment variables based on your deployment platform:

<Tabs>
  <Tab title="Vercel">
    Add environment variables in your Vercel project settings:

    1. Go to **Settings** → **Environment Variables**
    2. Add `KUBIKS_API_KEY` with your API key
    3. Add `OTEL_EXPORTER_OTLP_ENDPOINT` with value `https://ingest.kubiks.app`
    4. Add `OTEL_SERVICE_NAME` with your app name
    5. Deploy your application
  </Tab>

  <Tab title="Docker">
    Pass environment variables when running your container:

    ```bash theme={null}
    docker run \
      -e KUBIKS_API_KEY=your_api_key \
      -e OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.kubiks.app \
      -e OTEL_SERVICE_NAME=my-nextjs-app \
      -p 3000:3000 \
      your-image
    ```

    Or use a `.env` file with docker-compose:

    ```yaml docker-compose.yml theme={null}
    services:
      app:
        build: .
        ports:
          - "3000:3000"
        env_file:
          - .env
    ```
  </Tab>

  <Tab title="Railway / Render">
    Add environment variables in your platform's dashboard:

    **Railway:**

    1. Go to your project → **Variables**
    2. Add `KUBIKS_API_KEY`, `OTEL_EXPORTER_OTLP_ENDPOINT`, and `OTEL_SERVICE_NAME`

    **Render:**

    1. Go to your web service → **Environment**
    2. Add the same environment variables
  </Tab>

  <Tab title="Self-Hosted">
    Export environment variables before starting your app:

    ```bash theme={null}
    export KUBIKS_API_KEY=your_api_key
    export OTEL_EXPORTER_OTLP_ENDPOINT=https://ingest.kubiks.app
    export OTEL_SERVICE_NAME=my-nextjs-app

    npm run start
    ```

    Or add them to your process manager config (PM2, systemd, etc.).
  </Tab>
</Tabs>

## Get Your API Key

<Steps>
  <Step title="Navigate to Connect Page">
    Go to [kubiks.app/connect](https://kubiks.app/connect) in your dashboard
  </Step>

  <Step title="Create API Key">
    Click **Create API Key** in the OpenTelemetry Ingestion section
  </Step>

  <Step title="Copy the Key">
    Copy the generated API key and add it to your environment variables
  </Step>
</Steps>

## Verify Setup

Once configured, your Next.js app will automatically send traces and logs to Kubiks. To verify:

1. Start your development server or deploy your app
2. Make some requests to your application
3. Check your [Kubiks dashboard](https://kubiks.app) for traces and logs

<Tip>
  Traces appear in real-time. If you don't see data after a few seconds, check your API key and endpoint configuration.
</Tip>

## What Gets Tracked

The `@vercel/otel` package automatically instruments:

<AccordionGroup>
  <Accordion title="HTTP Requests">
    * All incoming HTTP requests
    * Request/response headers
    * Status codes and response times
    * URL paths and query parameters
  </Accordion>

  <Accordion title="Next.js Internals">
    * Server-side rendering (SSR)
    * API routes
    * Server components
    * Middleware
    * Static generation
  </Accordion>

  <Accordion title="External Calls">
    * `fetch()` calls to external APIs
    * Database queries (when instrumented)
    * Third-party service calls
  </Accordion>

  <Accordion title="Performance Metrics">
    * Request duration
    * Time to first byte (TTFB)
    * Server-side rendering time
    * API response times
  </Accordion>
</AccordionGroup>

## Instrument Your Dependencies

Enhance observability by adding Kubiks OpenTelemetry SDKs for popular frameworks:

<CardGroup cols={2}>
  <Card title="Drizzle ORM" icon="database" href="/opentelemetry-integrations/otel-drizzle">
    Trace all database queries and transactions
  </Card>

  <Card title="Better Auth" icon="lock" href="/opentelemetry-integrations/otel-better-auth">
    Monitor authentication flows and sessions
  </Card>

  <Card title="Resend" icon="envelope" href="/opentelemetry-integrations/otel-resend">
    Track email delivery and operations
  </Card>

  <Card title="Upstash QStash" icon="message" href="/opentelemetry-integrations/otel-upstash-queues">
    Monitor message queue operations
  </Card>

  <Card title="Autumn Billing" icon="credit-card" href="/opentelemetry-integrations/otel-autumn">
    Trace billing and payment flows
  </Card>

  <Card title="View All Integrations" icon="grid" href="/opentelemetry-integrations/overview">
    Explore all available SDKs
  </Card>
</CardGroup>

## Troubleshooting

<AccordionGroup>
  <Accordion title="No traces appearing">
    **Check these common issues:**

    1. Verify `KUBIKS_API_KEY` is set correctly
    2. Confirm `OTEL_EXPORTER_OTLP_ENDPOINT` is `https://ingest.kubiks.app`
    3. Ensure `instrumentationHook: true` is in `next.config.ts`
    4. Check that `instrumentation.ts` is in your project root
    5. Restart your development server after config changes
  </Accordion>

  <Accordion title="instrumentation.ts not loading">
    Make sure:

    1. File is named exactly `instrumentation.ts` (or `.js`)
    2. File is in project root (same level as `app/` or `pages/`)
    3. `experimental.instrumentationHook` is enabled in Next.js config
    4. You're using Next.js 13.2 or later
  </Accordion>

  <Accordion title="Invalid API key errors">
    1. Double-check your API key from [kubiks.app/connect](https://kubiks.app/connect)
    2. Ensure no extra spaces or quotes in your `.env.local`
    3. Verify environment variables are loaded (check `process.env.KUBIKS_API_KEY`)
    4. For production, confirm variables are set in your deployment platform
  </Accordion>

  <Accordion title="Only seeing some traces">
    The SDK uses sampling by default. To see all traces in development:

    ```typescript instrumentation.ts theme={null}
    import { registerOTel } from '@vercel/otel';

    export function register() {
      registerOTel({
        serviceName: process.env.OTEL_SERVICE_NAME || 'nextjs-app',
        // Sample all traces in development
        ...(process.env.NODE_ENV === 'development' && {
          tracesSampleRate: 1.0,
        }),
      });
    }
    ```
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="View Traces" icon="chart-line" href="https://kubiks.ai">
    Check your dashboard for real-time traces
  </Card>

  <Card title="Add Database Tracing" icon="database" href="/opentelemetry-integrations/otel-drizzle">
    Instrument your database queries
  </Card>

  <Card title="Vercel Integration" icon="triangle" href="/vercel-integration">
    Using Vercel? Try our native integration
  </Card>

  <Card title="OpenTelemetry Docs" icon="book" href="/opentelemetry-integrations/overview">
    Explore all integrations
  </Card>
</CardGroup>
