> ## 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 React application to BugByBug

> Learn how to connect BugByBug to a ReactJS project

This guide walks you through connecting a React application to BugByBug using OpenTelemetry. Once configured, your application can send browser errors to BugByBug, where you can review and investigate them.

The integration works with React applications built using Vite or Create React App (CRA).

Because React runs in the browser, any configuration included in your frontend bundle can be inspected by visitors. This is particularly important when handling API keys. BugByBug provides two ways to send telemetry, depending on whether you have a backend available.

| Integration method | How it works | Recommended for |
| - | - | - |
| Backend proxy | Your React app sends telemetry to your backend, which forwards it to BugByBug using your API key. | Applications with an existing backend |
| Direct browser export | Your React app sends telemetry directly to BugByBug using a browser-ingestion key. | Applications without a backend proxy |

We recommend the backend proxy because it keeps your private API key on the server.

## 1. Get your BugByBug API key

Before configuring OpenTelemetry, create a project in [BugByBug](https://bugbybug.com/) and retrieve its API key. You'll need this key to authenticate telemetry requests.

Keep the key somewhere secure. If you're using the backend proxy, configure it on your server. If you're exporting directly from the browser, use only a key specifically intended for browser ingestion. Never expose an admin or private server key in your React application.

## 2. Install the OpenTelemetry packages

BugByBug uses OpenTelemetry to receive application telemetry. For this integration, you'll need the OpenTelemetry API, browser tracing SDK, and OTLP/HTTP trace exporter.

Run the following command from your React project directory:

```bash theme={null}
npm install @opentelemetry/api @opentelemetry/sdk-trace-web @opentelemetry/exporter-trace-otlp-http
```

With these packages installed, you can configure your application to create and export traces from the browser.

## 3. Choose how to export telemetry

Before initializing OpenTelemetry, decide how your application will send traces to BugByBug. The tracing implementation is the same for both approaches; the main difference is the destination configured for the exporter and where the API key is stored.

### Option A: Forward telemetry through your backend (recommended)

If your application already has a backend, you can use it as an intermediary between React and BugByBug.

The browser sends telemetry to an endpoint on your backend, and your backend forwards the request to BugByBug with the required authentication header. This keeps your private API key out of the frontend bundle.

Your backend should provide a `POST /api/traces` endpoint that:

1. Accepts incoming trace requests from the React application.
2. Forwards the request body unchanged to `{OTEL_EXPORTER_OTLP_ENDPOINT}/v1/traces`.
3. Preserves the incoming `Content-Type` header.
4. Adds the `x-api-key` authentication header using your BugByBug API key.
5. Returns the status code received from BugByBug.

Limit the request body size (for example, 1 MB) and apply rate limiting to the endpoint.

Configure these environment variables on your backend:

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

**Configure the Vite development proxy**

During local development, your React application needs to reach the backend endpoint. If you're using Vite, configure its development server to forward requests beginning with `/api` to your backend.

In `vite.config.ts`:

```typescript theme={null}
export default defineConfig({
  plugins: [react()],
  server: {
    proxy: {
      '/api': 'http://localhost:4000'
    }
  }
})
```

Replace the port number, `4000` with the port your backend uses.

This proxy configuration is for local development. Your deployed application must also be configured to route `/api/traces` requests to the backend endpoint.

### Option B: Send telemetry directly to BugByBug

If you don't have a backend proxy, you can configure the browser exporter to send traces directly to BugByBug.

This approach requires a browser-ingestion key. Since frontend environment variables are included in the application bundle, the key will be visible to anyone inspecting the application. Never use an admin key or private server key for this setup.

Add the correct environment variable to your project.

For Vite:

```env theme={null}
VITE_BBB_API_KEY="bbb_your_key_here"
```

For Create React App:

```env theme={null}
REACT_APP_BBB_API_KEY="bbb_your_key_here"
```

Treat this key as public. Rotate it if it is abused or exposed unintentionally.

## 4. Create the tracing module

Once you've selected an export method, create a file named `src/tracing.ts`.

This file contains the OpenTelemetry configuration for your React application. It initializes the browser tracer, configures the exporter, and registers listeners for two types of browser errors:

* Uncaught errors, such as JavaScript errors that aren't handled by your application.
* Unhandled promise rejections, which occur when a rejected promise has no rejection handler.

Create `src/tracing.ts`:

```typescript theme={null}
import { WebTracerProvider, SimpleSpanProcessor } from '@opentelemetry/sdk-trace-web'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-http'
import { trace, SpanStatusCode } from '@opentelemetry/api'

export function initTracing() {
  const exporter = new OTLPTraceExporter(
    // Setup A (proxy):
    { url: '/api/traces' }

    // Setup B (direct), use this instead:
    // {
    //   url: 'https://nexus.bugbybug.com/v1/traces',
    //   headers: { 'x-api-key': import.meta.env.VITE_BBB_API_KEY }
    // }
  )

  const provider = new WebTracerProvider({
    spanProcessors: [new SimpleSpanProcessor(exporter)]
  })

  provider.register()
  const tracer = trace.getTracer('web-frontend')

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

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

The exporter configuration depends on the method you selected in Step 3:

* **Backend proxy:** Use the `/api/traces` URL. The backend handles authentication and forwards the request.
* **Direct browser export:** Use the BugByBug endpoint and provide your browser-ingestion key in the request headers.

Keep only the configuration you're using. Both approaches use the same tracing initialization and error listeners.

## 5. Initialize tracing in your React application

After creating the tracing module, import and initialize it before rendering your React application.

This ensures that the browser error listeners are registered early, so errors occurring after initialization can be captured.

In `src/main.tsx`:

```tsx theme={null}
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import { initTracing } from './tracing'

initTracing()

ReactDOM.createRoot(document.getElementById('root')!).render(<App />)
```

Call `initTracing()` once at the application entry point rather than from an individual component. This prevents the tracing setup and event listeners from being registered repeatedly as components render.

## 6. Capture React rendering errors (optional but recommended)

The browser event listeners in the tracing module capture uncaught JavaScript errors and unhandled promise rejections. However, React handles errors caught by its Error Boundaries differently.

To capture errors that occur while React components render, you can add an Error Boundary to your application.

React Error Boundaries are class components. The following implementation records the error and its component stack through OpenTelemetry.

Create `src/AppErrorBoundary.tsx`:

```tsx theme={null}
import { Component, type ErrorInfo, type ReactNode } from 'react'
import { trace, SpanStatusCode } from '@opentelemetry/api'

export class AppErrorBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
  state = { failed: false }

  static getDerivedStateFromError() {
    return { failed: true }
  }

  componentDidCatch(error: Error, info: ErrorInfo) {
    const span = trace.getTracer('web-frontend').startSpan('react-render-error')
    span.recordException(error)
    span.setAttribute('react.component_stack', info.componentStack ?? '')
    span.setStatus({ code: SpanStatusCode.ERROR, message: error.message })
    span.end()
  }

  render() {
    return this.state.failed ? <p>Something went wrong.</p> : this.props.children
  }
}
```

Wrap your application with the Error Boundary:

```tsx theme={null}
<AppErrorBoundary>
  <App />
</AppErrorBoundary>
```

With this in place, errors caught by the boundary can also be recorded and sent through your configured exporter.

## 7. Verify the connection

Once you've completed the configuration, run your React application and send a test error to check that telemetry reaches BugByBug.

1. Restart your development server. This is necessary if you've changed environment variables.

2. Open your React application in a 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 the outgoing telemetry request:
   * **Backend proxy:** Look for a `POST` request to `/api/traces`.
   * **Direct browser export:** Look for a `POST` request to `https://nexus.bugbybug.com/v1/traces`.

5. Check the response status and open your BugByBug dashboard to confirm that the test error has arrived.

If you're using the backend proxy, also check that the browser request does not contain your private BugByBug API key.

## Troubleshooting

If your test error doesn't appear in BugByBug, use the browser's Network tab to check whether the telemetry request was sent and what response it received.

| Symptom | Possible cause / fix |
| - | - |
| `/api/traces` returns 404 in development | Check your Vite proxy configuration and confirm that your backend exposes the expected route. |
| BugByBug returns 401 or 403 | Check that the API key is present, valid, and configured on the correct side of the integration. |
| CORS error with direct export | The BugByBug endpoint must allow requests from your application's origin. Consider using the backend proxy instead. |
| React rendering errors are missing | Add the Error Boundary described in Step 6. |
| Environment variable is undefined | Vite requires the `VITE_` prefix; Create React App requires `REACT_APP_`. Restart the development server after changing environment variables. |

## Security considerations

Keep the following points in mind when deploying the integration:

* **Use the backend proxy when possible.** It keeps your private API key on the server rather than exposing it in the browser.
* **Never expose an admin or private server key.** Frontend environment variables are bundled into the application and should not be treated as secrets.
* **Treat browser-ingestion keys as public.** Use only keys intended for browser ingestion, and rotate them if they are abused.
* **Protect your proxy endpoint.** Apply request-size limits and rate limiting to reduce unwanted traffic.


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