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

# Connect a Next.js application to BugByBug

> Learn how to connect BugByBug to a NextJS project

This guide walks you through connecting a Next.js application to BugByBug using OpenTelemetry.

The integration captures browser errors and sends them to BugByBug through a Next.js API route. Your API key stays on the server, while the browser communicates only with your application's `/api/traces` endpoint.

This approach uses the Next.js App Router and keeps authentication out of the client-side code.

The request flow looks like this:

```text theme={null}
Browser
   |
   | POST /api/traces
   v                                Server request or server error 
Next.js API route                      | 
   |                                   |   Sent directly by the Next.js server
   | Adds x-api-key                    |
   v                                   |
BugByBug ----------------------------+ |
```

You'll create a server-side route to forward telemetry and a client component to capture browser errors.

## 1. Get your BugByBug API key

First, create a project in [BugByBug](https://bugbybug.com/) and retrieve its API key. You'll use this key to authenticate requests sent from your Next.js application to BugByBug.

Keep the key private. Unlike a browser-based integration that exposes its key in the frontend bundle, this setup stores the key in a server-side environment variable.

## 2. Install the OpenTelemetry packages

Install the packages needed to initialize browser tracing and export traces using OTLP/HTTP.

Run the following command from your Next.js project directory:

```bash theme={null}
npm install @opentelemetry/api@1.10.0 @opentelemetry/sdk-trace@3.0.0
npm install @opentelemetry/exporter-trace-otlp-http@0.300.0 @opentelemetry/sdk-node@0.300.0
```

* `@opentelemetry/api`: this is the shared opentelemetry interface.
* `@opentelemetry/sdk-trace`: this creates spans and passes them to the exporter.
* `@opentelemetry/exporter-trace-otlp-http`: this sends spans over HTTP in the format BugByBug needs to analyze the bugs.
* `@opentelemetry/sdk-node`: this is the official OpenTelemetry SDK for Node.js that collects the trace data Next.js creates for every
  request.

## 3. Configure environment variables

Next, configure the BugByBug endpoint and API key in your project's `.env.local` file.

```env theme={null}
OTEL_EXPORTER_OTLP_ENDPOINT="https://nexus.bugbybug.com"
BBB_API_KEY="bbb_your_key_here"
```

Replace the placeholder with your actual BugByBug API key.

> [!TIP]
>
> Do not prefix these variables with `NEXT_PUBLIC_`. Next.js exposes variables with that prefix to browser code. Keeping these variables server-side ensures that your private API key is not included in the frontend bundle.

If you're using a staging environment, configure the corresponding staging endpoint instead. Add the same two variables to your hosting provider's environment settings when deploying the application.

## 4. Create a config helper

Next, you would need to create a function that lets BugByBug read your project settings

`src/app/utils/otel.ts`

```typescript theme={null}
// Reads the BugByBug settings from server-side env vars, at call time.
// Returns undefined when either one is missing, so callers can skip safely.
export const getOtlpConfig = () => {
const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT?.replace(/\/+$/, '')
const apiKey = process.env.BBB_API_KEY
if (!endpoint || !apiKey) return undefined
return { endpoint, tracesUrl: `${endpoint}/v1/traces`, apiKey }
}
```

The files needed for proxy route, server tracing and server error reporting each have their own vars and
could easily read through each vars hence the helper to keep them in sync.

## 5. Create the API proxy route

The browser tracing component will send telemetry to `/api/traces`. You need a Next.js API route to receive that request and forward it to BugByBug.

With the App Router, create the following file:

`src/app/api/traces/route.ts`

Add the following code:

```typescript theme={null}
import { getOtlpConfig } from '@/app/utils/otel'

export async function POST(req: Request) {
  const config = getOtlpConfig()
  if (!config) {
    console.error('[api/traces] OTEL_EXPORTER_OTLP_ENDPOINT or BBB_API_KEY is not set')
    return new Response(null, { status: 500 })
  }
  try {
    const res = await fetch(config.tracesUrl, {
    method: 'POST',
    headers: {
    'content-type': req.headers.get('content-type') ?? 'application/json',
    'x-api-key': config.apiKey
    },
    body: await req.arrayBuffer()
    })
    return new Response(null, { status: res.status })
  } catch (e) {
    // BugByBug unreachable: 502 tells the browser exporter it may retry
    console.error('[api/traces] failed to reach BugByBug', e)
    return new Response(null, { status: 502 })
    }
}
```

This route handles incoming trace requests from the browser and forwards them to BugByBug.

Here's what happens when a request reaches the endpoint:

1. If the endpoint or key is missing, the route answers 500 and logs which setting is missing. It never calls
   BugByBug with a broken URL.
2. Otherwise it forwards the body unchanged, keeps the original content type and adds x-api-key.
   Connect a Next.js application to BugByBug Page 4
3. It returns BugByBug’s status code to the browser, with an empty body, so nothing about BugByBug or
   your key leaks back.
4. If BugByBug can’t be reached, it answers 502 instead of crashing.

**Check your authentication middleware**

If your application uses authentication middleware in `middleware.ts` or `proxy.ts`, make sure `/api/traces` is not redirected to your login page.

This endpoint needs to accept telemetry requests from the browser, including requests made on public pages. Redirecting it to login prevents those requests from reaching BugByBug.

## 6. Create the browser tracing component

With the API route in place, you can configure the browser to capture errors and send them to your Next.js endpoint.

Create the following file:

`src/components/BrowserTracing.tsx`

Add the tracing implementation:

```tsx theme={null}
'use client'

import { useEffect } from 'react'
import { TracerProvider, SimpleSpanProcessor } from '@opentelemetry/sdk-trace'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
import { SpanStatusCode } from '@opentelemetry/api'

export default function BrowserTracing() {
  useEffect(() => {
    const provider = new TracerProvider({
      spanProcessors: [
        new SimpleSpanProcessor({
          exporter: new OTLPTraceExporter({ url: '/api/traces' }),
        }),
      ],
    })

    // Tracer comes straight from this provider instead of a global registration,
    // so React StrictMode's mount -> unmount -> mount always uses the live provider.
    const tracer = provider.getTracer('web-frontend')

    const onError = (e: ErrorEvent) => {
      const span = tracer.startSpan('browser-error')
      span.recordException(e.error || e.message)
      span.setStatus({ code: SpanStatusCode.ERROR, message: e.message })
      span.end()
    }

    const onRejection = (e: PromiseRejectionEvent) => {
      const span = tracer.startSpan('unhandled-promise-rejection')
      span.recordException(e.reason)
      span.setStatus({ code: SpanStatusCode.ERROR, message: String(e.reason) })
      span.end()
    }

    window.addEventListener('error', onError)
    window.addEventListener('unhandledrejection', onRejection)

    return () => {
      window.removeEventListener('error', onError)
      window.removeEventListener('unhandledrejection', onRejection)
      provider.shutdown()
    }
  }, [])

  return null
}
```

The component uses React's `useEffect` hook to initialize OpenTelemetry when the component mounts.

It registers two browser event listeners:

* **`error`:** Captures uncaught JavaScript errors.
* **`unhandledrejection`:** Captures rejected promises that do not have a rejection handler.

**Why must this be a Client Component?**

The code above uses `window` and `useEffect`, which only exist in the browser. App Router components are Server Components by default, and putting this code directly in layout.tsx fails with
ReferenceError: window is not defined. The `use client` directive makes it run in the right place.

## 7. Mount the tracing component in the root layout

Creating the tracing component isn't enough; it also needs to be included in your application.

Import `BrowserTracing` into your root layout and render it inside the body element.

`src/app/layout.tsx`

Update the layout:

```tsx theme={null}
import BrowserTracing from '@/components/BrowserTracing'

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <BrowserTracing />
        {children}
      </body>
    </html>
  )
}
```

Placing `BrowserTracing` in the root layout makes it available across your application. You don't need to add the component to individual pages.

The tracing component returns `null`, so it doesn't render any visible UI. Its purpose is to initialize error monitoring and register the browser event listeners.

## 8. Create a server-side tracing and error reporting

Next, you would need to create a server-side tracing and error reporting route. You can do this through src/instrumentation.ts because next.js automatically loads this file when a server starts.
Two exports in that file cover the server side, plus one helper file for the Node SDK.

### First, trace every request

Start with register(). It loads the tracing setup, but only on the Node.js runtime:

`src/instrumentation.ts`

```typescript theme={null}
import type { Instrumentation } from 'next'
import { getOtlpConfig } from '@/app/utils/otel'

// Server request tracing. The Node SDK can't run on the Edge runtime; Next.js inlines
// NEXT_RUNTIME, so the Edge build drops this import entirely.
export async function register() {
  if (process.env.NEXT_RUNTIME === 'nodejs') {
    const { startTracing } = await import('./instrumentation.node')
    startTracing()
  }
}
```

Then create the file that starts the SDK.
`src/instrumentation.node.ts`

```typescript theme={null}
import { NodeSDK } from '@opentelemetry/sdk-node'
import { BatchSpanProcessor, type SpanProcessor } from '@opentelemetry/sdk-trace'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
import { getOtlpConfig } from '@/app/utils/otel'

export const startTracing = () => {
  const config = getOtlpConfig()
  if (!config) return

  const batch = new BatchSpanProcessor({
    exporter: new OTLPTraceExporter({
      url: config.tracesUrl,
      headers: { 'x-api-key': config.apiKey },
    }),
  })

  // Drops the span Next.js creates for our own calls to BugByBug (/api/traces
  // forwarding browser errors), so each browser error doesn't add a useless span
  const bugByBugUrl = `${config.endpoint}/`
  const skipBugByBugCalls: SpanProcessor = {
    onStart: (span, context) => batch.onStart(span, context),
    onEnd: (span) => {
      if (!String(span.attributes['http.url'] ?? '').startsWith(bugByBugUrl)) {
        batch.onEnd(span)
      }
    },
    forceFlush: () => batch.forceFlush(),
    shutdown: () => batch.shutdown(),
  }

  new NodeSDK({
    serviceName: 'web-server',
    spanProcessors: [skipBugByBugCalls],
    // Without these, NodeSDK builds its own metrics and logs exporters from
    // OTEL_EXPORTER_OTLP_ENDPOINT, which send to BugByBug without the x-api-key header
    metricReaders: [],
    logRecordProcessors: [],
    // Don't attach host name, OS user and process command line to every span
    autoDetectResources: false,
  }).start()
}
```

### What does the code above do?

| Setting | What it does | Purpose |
| - | - | - |
| NEXT\_RUNTIME === `nodejs` | Loads the SDK only on the Node.js runtime. | The Node SDK can’t run on the lighter Edge runtime and would break the Edge build. |
| serviceName: `web-server` | Labels everything the server sends. | Lets you tell server data apart from browser data (web-frontend) in BugByBug. |
| BatchSpanProcessor + exporter | Sends traces in batches, with your API key. | BugByBug needs the key on every request. The browser path adds it in the proxy route; here the server adds it itself. |
| skipBugByBugCalls | Drops spans for calls to BugByBug itself. | Otherwise every browser error forwarded by `/api/traces` creates an extra, useless server span. It matches `<endpoint>/` exactly, so look-alike hosts aren’t dropped. |
| metricReaders: \[] logRecordProcessors: \[] | Turns off the SDK’s automatic metrics and logs exporters. | When `OTEL_EXPORTER_OTLP_ENDPOINT` is set, the SDK quietly creates its own metrics and logs exporters for the same address, without your API key. We found this while testing. |
| autoDetectResources: false | Skips automatic host and process details. | Keeps your server’s host name, OS user name and command line out of every span. |
| if (!config) return | Skips setup when env vars are missing. | The app keeps working (for example on a developer machine without a key) instead of failing at startup. |

### Next, report uncaught server errors.

Add this to `src/instrumentation.ts`, below `register()`. Next.js calls `onRequestError` whenever a Server
Component, Route Handler, Server Action or your middleware throws an error that nothing caught:

```typescript theme={null}
const hex = (bytes: number) =>
  Array.from(crypto.getRandomValues(new Uint8Array(bytes)), (b) =>
    b.toString(16).padStart(2, '0')
  ).join('')
const str = (key: string, value: string) => ({ key, value: { stringValue: value } })
export const onRequestError: Instrumentation.onRequestError = async (
  err,
  request,
  context
) => {
  const config = getOtlpConfig()
  if (!config) return

  const error = err instanceof Error ? err : new Error(String(err))
  const digest = (err as { digest?: unknown } | null)?.digest
  const now = `${Date.now()}000000` // ms -> ns

  // Request headers are deliberately not sent: they carry auth cookies
  const attributes = [
    str('http.request.method', request.method),
    str('url.path', request.path),
    str('next.route', context.routePath),
    str('next.route_type', context.routeType),
    str('next.router_kind', context.routerKind),
    ...(typeof digest === 'string' ? [str('next.error_digest', digest)] : []),
  ]

  const span = {
    traceId: hex(16),
    spanId: hex(8),
    name: 'server-error',
    kind: 2, // SERVER
    startTimeUnixNano: now,
    endTimeUnixNano: now,
    attributes,
    events: [
      {
        name: 'exception',
        timeUnixNano: now,
        attributes: [
          str('exception.type', error.name),
          str('exception.message', error.message),
          ...(error.stack ? [str('exception.stacktrace', error.stack)] : []),
        ],
      },
    ],
    status: { code: 2, message: error.message }, // ERROR
  }

  try {
    await fetch(config.tracesUrl, {
      method: 'POST',
      headers: { 'content-type': 'application/json', 'x-api-key': config.apiKey },
      body: JSON.stringify({
        resourceSpans: [
          {
            resource: { attributes: [str('service.name', 'web-server')] },
            scopeSpans: [{ scope: { name: 'web-server' }, spans: [span] }],
          },
        ],
      }),
    })
  } catch (e) {
    console.error('[instrumentation] failed to report error to BugByBug', e)
  }
}
```

## 9. Verify the connection

After completing the setup, run your Next.js application and generate a test error to confirm that telemetry reaches BugByBug.

### Browser Errors

1. Restart your development server. Environment variable changes require a restart.

2. Open your application in the browser.

3. Open the browser developer console and run:

   ```javascript theme={null}
   setTimeout(() => { throw new Error('BugByBug test error') })
   ```

4. Open the browser's **Network** tab and look for a `POST` request to `/api/traces`.

5. Confirm that the request returns a `200` response and that the test error appears in your BugByBug dashboard.

Also check that the browser request does not contain your API key or the BugByBug ingestion URL. The browser should communicate only with your own `/api/traces` endpoint.

### Server errors and request traces

You could add a temporary route that always fails:

```typescript theme={null}
// TEMPORARY: delete after testing
export const GET = () => {
throw new Error('server test')
}
```

This code would live within your `src/app/api/boom/route.ts` file. Once added, go ahead and test it:

* Open [http://localhost:3000/api/boom](http://localhost:3000/api/boom). It returns 500, and the terminal shows Error: server test.
* Wait about 5 seconds. Server traces are sent in batches, not one by one.
* In BugByBug, filter by the service web-server.

You should see spans like:

* `server-error`: this will be an onRequestError with a message "server test" with its stack trace.
* GET `/api/boom`: this will be the request trace, marked as an error.
* executing api route (app) `/api/boom`: this will be the Route Handler that threw, with the exception attached.
* middleware GET: this will be your middleware or proxy.ts, if you have one.

## Troubleshooting

If the test error doesn't appear in BugByBug, check the request in your browser's Network tab and review the following common issues.

| Symptom | Possible cause / fix |
| - | - |
| npm install fails with ERESOLVE | OpenTelemetry packages from different releases are mixed. Install the exact versions from step 2 and remove `@opentelemetry/sdk-trace-web`. |
| `window is not defined` | Tracing code is running in a Server Component. Move it into the `BrowserTracing` Client Component described in Step 5. |
| `/api/traces` returns 401/403 | Check that `BBB_API_KEY` is configured correctly. Restart the application after editing environment variables. |
| `/api/traces` returns 500 | An env var is missing. The server log says which one. |
| `/api/traces` returns 502 | The server can’t reach BugByBug. Check OTEL\_EXPORTER\_OTLP\_ENDPOINT and outbound network access. |
| Request goes to `undefined/v1/traces` | `OTEL_EXPORTER_OTLP_ENDPOINT` is missing or not configured correctly. |
| `/api/traces` redirects to `/login` | Exclude `/api/traces` from your authentication middleware or proxy rules. |
| No error appears in the dashboard, but the route returns 200 | Check that the configured endpoint points to the correct environment (production or staging). |
| Browser errors stop arriving in development after a reload | The component registers its provider globally. Use provider.getTracer() as in step 6, not provider.register(). |
| Requests to /v1/metrics or /v1/logs rejected with 401 | metricReaders: \[] and logRecordProcessors: \[] are missing from NodeSDK (step 8). |
| An extra span for every browser error | The skipBugByBugCalls filter is missing from instrumentation.node.ts (step 8). |
| No request traces for one route | The route runs on the Edge runtime, which the Node SDK can’t trace. Its errors are still reported. |
| Too many traces or a high bill | Every request is traced. Keep a sample, for example 10%, with OTEL\_TRACES\_SAMPLER=traceidratio and OTEL\_TRACES\_SAMPLER\_ARG=0.1. |

## Security considerations

The proxy route keeps your BugByBug API key on the server, but the `/api/traces` endpoint is publicly reachable by nature. Keep the following precautions in place:

* **Keep your API key server-side.** Store it in `.env.local` and your hosting provider's server-side environment settings. Never expose it through a `NEXT_PUBLIC_` variable.
* **Rotate exposed keys.** If a key has ever been committed to source control or included in a client bundle, rotate it.
* **Protect the proxy endpoint.** Consider checking the request origin, limiting request body size, and applying rate limiting to reduce unwanted traffic.

Once you've verified that errors are arriving in BugByBug, your Next.js application is connected.

## What's next?

* [React integration](https://docs.bugbybug.com/reactjs-guide.md)
* [OpenTelemetry and BugByBug](https://docs.bugbybug.com/opentelemetry.md)
* [Troubleshooting](https://docs.bugbybug.com/faq/troubleshooting.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.