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

# Browser JavaScript

> Instrument a browser JavaScript application with OpenTelemetry and send RUM telemetry to Trace0.

> [!NOTE]
>
> This guide covers browser-side (client) JavaScript — React, Vue, plain DOM apps, anything running in a user's browser. For a Node.js server, see the , see the [Node.js guide](https://docs.trace0hq.com/setup/etup/javascript/containers-and-vms).

## 1. Install the OpenTelemetry Browser SDK

```bash theme={"languages":{"custom":["/languages/trace0ql.tmLanguage.json"]}}
npm install @opentelemetry/browser-sdk @opentelemetry/browser-instrumentation
```

* `@opentelemetry/browser-sdk` is OpenTelemetry's combined SDK for the browser — it wires up a tracer provider, a logger provider, and their exporters in one call.

* `@opentelemetry/browser-instrumentation` provides the individual instrumentations (fetch, user actions, Web Vitals, errors, and more) as subpath exports under `./experimental/*`.

## 2. Initialize the SDK

Create a file (for example `otel.ts`) and import it before any other code runs, so instrumentation is registered before your app makes its first render or network call:

```ts theme={"languages":{"custom":["/languages/trace0ql.tmLanguage.json"]}}
// otel.ts
import { startBrowserSdk } from '@opentelemetry/browser-sdk';
import { FetchInstrumentation } from '@opentelemetry/browser-instrumentation/experimental/fetch';
import { XhrInstrumentation } from '@opentelemetry/browser-instrumentation/experimental/xhr';
import { UserActionInstrumentation } from '@opentelemetry/browser-instrumentation/experimental/user-action';

startBrowserSdk({
  serviceName: 'your-browser-app',
  exportConfig: {
    url: 'https://app.trace0hq.com/api',
    headers: { 'X-API-KEY': 'YOUR_TRACE0_ENV_API_KEY' },
  },
  instrumentations: [
    new FetchInstrumentation(),
    new XhrInstrumentation(),
    new UserActionInstrumentation(),
  ],
});
```

```ts theme={"languages":{"custom":["/languages/trace0ql.tmLanguage.json"]}}
// index.tsx / main.tsx
import './otel';
// ...the rest of your app's entry point
```

A single root-level `exportConfig` is enough here: `startBrowserSdk` sends traces to `.../v1/traces` and logs to `.../v1/logs`, both appended automatically onto the base URL you give it.

`FetchInstrumentation`/`XhrInstrumentation` create a span for every outgoing request and inject a `traceparent` header into it, so a backend that extracts that header continues the same trace — see [Trace0 Transaction Detail](https://docs.trace0hq.com/platform/transactions) to see the linked trace once both sides are instrumented. `UserActionInstrumentation` emits a `browser.user_action.click` log event per click, by default.

> [!NOTE]
>
> This configuration exports directly from the browser, which means `YOUR_TRACE0_ENV_API_KEY` ships inside your JS bundle — visible to anyone who views the page's source, inspects network requests, or reads the built bundle. Use a key scoped to a non-production environment, or export through a backend/collector proxy instead if you need to keep the key off the client. It also requires Trace0's ingest endpoint to accept cross-origin browser requests (CORS).

## 3. Turn On Browser Resource Detection

`@opentelemetry/browser-sdk/browser-detector` exports a resource detector that adds browser attributes — the user agent and preferred language always, plus platform, brands, and mobile status when the [UA Client Hints API](https://developer.mozilla.org/en-US/docs/Web/API/User-Agent_Client_Hints_API) is available:

```ts theme={"languages":{"custom":["/languages/trace0ql.tmLanguage.json"]}}
import { browserDetector } from '@opentelemetry/browser-sdk/browser-detector';
import { detectResources } from '@opentelemetry/resources';

// Some of these attributes resolve asynchronously, so wait for them
// before starting the SDK.
const browserResource = detectResources({ detectors: [browserDetector] });
await browserResource.waitForAsyncAttributes?.();

startBrowserSdk({
  serviceName: 'your-browser-app',
  resourceAttributes: { ...browserResource.attributes },
  // ...exportConfig, instrumentations, etc.
});
```

This merges `user_agent.original`, `browser.language`, `browser.platform`, `browser.brands`, and `browser.mobile` into the resource shared by every span and log record your app emits.

## 4. Add the Session Processor

Sessions correlate multiple traces and log records that happen within a given time window — a browser tab being open, roughly. The `@opentelemetry/browser-sdk/session` subpath provides a default implementation:

```ts theme={"languages":{"custom":["/languages/trace0ql.tmLanguage.json"]}}
import { startBrowserSdk } from '@opentelemetry/browser-sdk';
import {
  createDefaultSessionIdGenerator,
  createLocalStorageSessionStore,
  createSessionLogRecordProcessor,
  createSessionManager,
  createSessionSpanProcessor,
} from '@opentelemetry/browser-sdk/session';

const sessionManager = createSessionManager({
  sessionIdGenerator: createDefaultSessionIdGenerator(),
  sessionStore: createLocalStorageSessionStore(),
  maxDuration: 4 * 60 * 60, // 4 hours
  inactivityTimeout: 30 * 60, // 30 minutes
});

// Restore or start the session before any instrumentation runs, so the
// very first span/log already carries the right session.id.
await sessionManager.start();

startBrowserSdk({
  serviceName: 'your-browser-app',
  traces: {
    exportConfig: {
      url: 'https://app.trace0hq.com/api/v1/traces',
      headers: { 'X-API-KEY': 'YOUR_TRACE0_ENV_API_KEY' },
    },
    // Session processors must be registered before any export processor.
    processors: [createSessionSpanProcessor(sessionManager)],
  },
  logs: {
    exportConfig: {
      url: 'https://app.trace0hq.com/api/v1/logs',
      headers: { 'X-API-KEY': 'YOUR_TRACE0_ENV_API_KEY' },
    },
    processors: [createSessionLogRecordProcessor(sessionManager)],
  },
  // ...instrumentations
});
```

`createLocalStorageSessionStore()` persists the session in `localStorage`, so it survives page reloads until it expires (by `maxDuration` or `inactivityTimeout`, whichever comes first).

> [!NOTE]
>
> Once you add any `processors` to `traces` or `logs`, you need to set that signal's `exportConfig` yourself, with the full `/v1/traces` or `/v1/logs` path — the automatic URL-suffixing shown in [step 2](#2-initialize-the-sdk) only applies when you haven't customized `processors` for that signal. Omitting `exportConfig` once you've added `processors` means that signal won't export at all.

## 5. Adding a User ID

There's no built-in user-identity processor, but you simply hold the current user in a module-level variable, and read it from a custom processor registered on both signals.

```ts theme={"languages":{"custom":["/languages/trace0ql.tmLanguage.json"]}}
import type { Span } from '@opentelemetry/api';
import type { SdkLogRecord } from '@opentelemetry/sdk-logs';

// Call setUserId() from your login/logout code.
let currentUserId: string | null = null;
export function setUserId(id: string | null): void {
  currentUserId = id;
}

class UserSpanProcessor {
  onStart(span: Span): void {
    if (currentUserId) span.setAttribute('user.id', currentUserId);
  }
  onEnd(): void {}
  forceFlush(): Promise<void> { return Promise.resolve(); }
  shutdown(): Promise<void> { return Promise.resolve(); }
}

class UserLogRecordProcessor {
  onEmit(logRecord: SdkLogRecord): void {
    if (currentUserId) logRecord.setAttribute('user.id', currentUserId);
  }
  forceFlush(): Promise<void> { return Promise.resolve(); }
  shutdown(): Promise<void> { return Promise.resolve(); }
}
```

Register `UserSpanProcessor`/`UserLogRecordProcessor` in `traces.processors`/`logs.processors`, alongside the session processors from step 4. Then, from your auth code:

```ts theme={"languages":{"custom":["/languages/trace0ql.tmLanguage.json"]}}
// after login:
setUserId('user_123');

// on logout:
setUserId(null);
```

## 6. Web Vitals

```ts theme={"languages":{"custom":["/languages/trace0ql.tmLanguage.json"]}}
import { WebVitalsInstrumentation } from '@opentelemetry/browser-instrumentation/experimental/web-vitals';

new WebVitalsInstrumentation({
  reportAllChanges: false,
  reportSoftNavs: false,
});
```

Add it to `instrumentations` like any other instrumentation. It uses the [`web-vitals`](https://github.com/GoogleChrome/web-vitals) library to emit a log event per Core Web Vital (LCP, CLS, INP, FCP, TTFB) as each is measured.

See the [Web Vitals section](https://github.com/open-telemetry/opentelemetry-browser/blob/main/packages/instrumentation/README.md#web-vitals) of the OpenTelemetry Browser SDK docs for the full option reference.

## 7. Adding Custom Attributes to Log Records

Several instrumentations in this family used to support a per-instrumentation `applyCustomLogRecordData` hook, but it's now deprecated in favor of one general mechanism: register a custom `LogRecordProcessor` with your `LoggerProvider` (or, with `startBrowserSdk`, in `logs.processors`). This applies to every log record from every instrumentation, not just one:

```ts theme={"languages":{"custom":["/languages/trace0ql.tmLanguage.json"]}}
import type { SdkLogRecord } from '@opentelemetry/sdk-logs';

// Holds whatever app-specific state you want attached to telemetry.
// For example, the current route, set from your router on navigation.
let currentRoute: string | undefined;
export function setCurrentRoute(route: string | undefined): void {
  currentRoute = route;
}

class CustomAttributesProcessor {
  onEmit(logRecord: SdkLogRecord): void {
    if (currentRoute) logRecord.setAttribute('app.route.id', currentRoute);
  }
  forceFlush(): Promise<void> { return Promise.resolve(); }
  shutdown(): Promise<void> { return Promise.resolve(); }
}
```

Register it in `logs.processors`, after the session and user processors from steps 4 and 5 (order between these doesn't matter, since none of them depend on each other's output — but all of them need to run before `startBrowserSdk` appends its export processor, which happens automatically as long as they're in this list at all).

`app.route.id` here is the route *template* (e.g. `/users/:id`), not the resolved path — set it from your router on every navigation (for example, React Router's `useMatches()`), not from `location.pathname`.

## 8. Errors

```ts theme={"languages":{"custom":["/languages/trace0ql.tmLanguage.json"]}}
import { ErrorsInstrumentation } from '@opentelemetry/browser-instrumentation/experimental/errors';

new ErrorsInstrumentation({
  applyCustomAttributes: (error) => ({
    'app.error.severity':
      error instanceof Error && error.name === 'ValidationError' ? 'warning' : 'error',
  }),
});
```

Add it to `instrumentations`. It emits an `exception` log event for every uncaught error (`window.addEventListener('error', ...)`) and unhandled promise rejection (`window.addEventListener('unhandledrejection', ...)`) — no manual error-reporting call needed, as long as the error is genuinely uncaught (not swallowed by a `try`/`catch`).

| Attribute | Description |
| - | - |
| `exception.type` | The error's `name` (omitted when the thrown value is a string). |
| `exception.message` | The error's `message`, or the thrown string itself. |
| `exception.stacktrace` | The error's `stack` (omitted when the thrown value is a string). |

> [!NOTE]
>
> `ErrorsInstrumentation` relies on the OpenTelemetry Logs API's standard trace-correlation mechanism: when a log record is emitted while a span is active in context, the SDK automatically stamps it with that span's trace and span IDs. This means an error thrown synchronously while a span is active correlates with that trace automatically — but browsers have no built-in way to keep a span "active" across an `await` (unlike Node's `AsyncLocalStorage`), so an error thrown after awaiting a `fetch()` call generally won't carry its trace ID this way. If you need that correlation, wrap the call in your own span and call `span.recordException(error)` directly inside the `catch`, rather than relying on this instrumentation alone.

## 9. User ID and Session ID in Trace0

Once `user.id` and `session.id` are set via steps 4 and 5, Trace0 automatically surfaces them as [tags](https://docs.trace0hq.com/platform/transactions/tags.md) on the traces and logs that carry them, so no additional Trace0-side configuration needed. Use them to filter the dashboard down to a single user's or session's activity.

## 10. Deploy Your App

Deploy your app and watch traces and logs appear in the [Trace0 dashboard](https://app.trace0hq.com) within seconds.

## Example Service

See our example app for a working React app with Trace0 installed:

| Example | Environment |
| - | - |
| [React Frontend example app](https://github.com/Trace0-HQ/trace0-examples/tree/main/react-frontend) | Browser (React) |

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


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