Skip to content

The only tool you need to know what is happening and how to fix it.

6.2 KB
Raw Blame
# TracewayProvider

The `TracewayProvider` component initializes Traceway and provides context to child components.

## Basic Usage

```jsx
import { TracewayProvider } from "@tracewayapp/react";

function App() {
  return (
    <TracewayProvider connectionString="your-token@https://traceway.example.com/api/report">
      <YourApp />
    </TracewayProvider>
  );
}
```

## Props

| Prop | Type | Required | Description |
|------|------|----------|-------------|
| `connectionString` | `string` | Yes | Your Traceway connection string |
| `options` | `object` | No | Configuration options |
| `children` | `ReactNode` | Yes | Child components |

## Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `debug` | `boolean` | `false` | Log SDK problems to the console: failed uploads, `beforeCapture` throwing, and errors dropped by `ignoreErrors` / `beforeCapture`. Captured events themselves are not logged |
| `debounceMs` | `number` | `1500` | Batch delay in milliseconds |
| `retryDelayMs` | `number` | `10000` | Retry delay for failed uploads |
| `version` | `string` | `undefined` | Your application version |
| `ignoreErrors` | `Array<string \| RegExp>` | `DEFAULT_IGNORE_PATTERNS` | Error patterns to ignore. Pass `[]` to capture all errors. See [Error Filtering](/client/js-sdk/initialization#error-filtering) |
| `beforeCapture` | `(exception) => boolean` | `undefined` | Return `false` to suppress an error. See [Error Filtering](/client/js-sdk/initialization#error-filtering) |
| `sessionRecording` | `boolean` | `true` | Enable the rrweb session recorder |
| `sessionRecordingSegmentDuration` | `number` | `30000` | rrweb segment length in ms |
| `recordAllSessions` | `boolean` | `false` | Always-on session recording. See [Sessions](/learn/sessions) |
| `captureLogs` | `boolean` | `true` | Mirror `console.*` calls into the rolling log buffer |
| `captureNetwork` | `boolean` | `true` | Record `fetch` / `XHR` calls as network actions |
| `captureNavigation` | `boolean` | `true` | Record History API push / replace / pop transitions |
| `eventsWindowMs` | `number` | `10000` (`30000` w/ `recordAllSessions`) | Rolling log/action buffer window |
| `eventsMaxCount` | `number` | `200` (`600` w/ `recordAllSessions`) | Hard cap on log/action buffer entries |
| `captureHttpServerErrors` | `boolean` | `false` | Report every `fetch` response with status >= 500 as a synthetic exception. 4xx is never included, and it is wired into the `fetch` wrapper only, so `XMLHttpRequest` (including browser Axios) does not trigger it |

## Custom Attributes

Use `<TracewayAttributes>` or the `useTracewayAttributes` hook to bind a reactive map of attributes (`userId`, `tenant`, feature flags, etc.) to the SDK's global scope. The hook diffs against the previous map on every render and pushes only the deltas; on unmount, every key it currently owns is removed.

```jsx
import { TracewayAttributes, useTracewayAttributes } from "@tracewayapp/react";

// As a component:
<TracewayAttributes attributes={user ? { userId: user.id, tenant: org.id } : null} />

// Or as a hook:
function App() {
  useTracewayAttributes({ userId: user?.id, tenant: org?.id });
  return <Routes />;
}
```

Both accept `null` / `undefined` as "empty map", which is useful while user data loads or after logout. New object reference with the same content does not trigger SDK calls.

For imperative use (background workers, init scripts), the same primitives are exported as plain functions:

```javascript
import { setAttribute, setAttributes, removeAttribute, clearAttributes } from "@tracewayapp/react";

setAttribute("build_channel", import.meta.env.VITE_CHANNEL ?? "dev");
setAttributes({ tenant: "acme", plan: "pro" });
clearAttributes(); // on logout
```

Layering on each event: **defaults < global scope < per-call**. See [Sessions](/learn/sessions) for the full attribute model.

## Example with Options

```jsx
<TracewayProvider
  connectionString="your-token@https://traceway.example.com/api/report"
  options={{
    debug: process.env.NODE_ENV === "development",
    version: process.env.REACT_APP_VERSION,
    debounceMs: 1000,
  }}
>
  <YourApp />
</TracewayProvider>
```

## Capture All Errors

By default, 4xx HTTP errors, network errors, and timeouts are ignored. To capture everything:

```jsx
<TracewayProvider
  connectionString="your-token@https://traceway.example.com/api/report"
  options={{ ignoreErrors: [] }}
>
  <YourApp />
</TracewayProvider>
```

## Environment-Specific Setup

```jsx
function App() {
  const connectionString = process.env.NODE_ENV === "production"
    ? process.env.REACT_APP_TRACEWAY_PROD
    : process.env.REACT_APP_TRACEWAY_DEV;

  return (
    <TracewayProvider connectionString={connectionString}>
      <YourApp />
    </TracewayProvider>
  );
}
```

## Placement

Place `TracewayProvider` as high as possible in your component tree, typically in your root `App` component or `index.js`:

```jsx
// index.js
import React from "react";
import ReactDOM from "react-dom/client";
import { TracewayProvider } from "@tracewayapp/react";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <TracewayProvider connectionString="your-token@...">
      <App />
    </TracewayProvider>
  </React.StrictMode>
);
```

### A note on StrictMode

`TracewayProvider` initializes the SDK in its constructor, and StrictMode double-invokes constructors in development. Two clients get created, so every uncaught error is reported twice and two batches are uploaded. Production builds do not double-invoke, so live counts are correct. If the doubled counts get in the way while you develop, mount the provider outside `<StrictMode>`:

```jsx
root.render(
  <TracewayProvider connectionString="your-token@...">
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </TracewayProvider>
);
```

## TracewayContext

For advanced use cases, you can access the context directly:

```jsx
import { TracewayContext } from "@tracewayapp/react";
import { useContext } from "react";

function MyComponent() {
  const traceway = useContext(TracewayContext);
  // Use traceway.captureException, etc.
}
```

However, the `useTraceway` hook is preferred for most use cases.