Skip to content

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

7.5 KB
Raw Blame
# jQuery Quick Start

Integrate Traceway into your jQuery application with the `@tracewayapp/jquery` package.

## Installation

### Via npm

```bash
npm install @tracewayapp/jquery jquery
```

```javascript
import $ from "jquery";
import { init } from "@tracewayapp/jquery";

// The AJAX hook binds to the global jQuery, so publish it before init().
window.jQuery = window.$ = $;

init("your-token@https://cloud.tracewayapp.com/api/report");
```

`init()` binds `$(document).ajaxError()` on `window.jQuery` (or `window.$`). If jQuery is only a bundled module and never lands on `window`, uncaught errors and `captureException()` still work but AJAX errors are silently skipped. Call `init()` after jQuery is on the page. If jQuery already comes from a `<script>` tag, it is global already and you can drop the two jQuery lines above.

Session recording is on by default. The last ~30s of DOM events ship with every captured exception.

### Via CDN

No build step needed. Add two script tags after jQuery:

```html
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tracewayapp/jquery@1/dist/traceway-jquery.iife.global.js"></script>
<script>
  TracewayJQuery.init("your-token@https://cloud.tracewayapp.com/api/report");
</script>
```

The CDN build exposes everything on the `TracewayJQuery` global: `TracewayJQuery.captureException`, `TracewayJQuery.captureMessage`, `TracewayJQuery.setAttribute`, `TracewayJQuery.flush`, and so on. The `import` examples below are for the npm build, so prefix them with `TracewayJQuery.` when you use the CDN.

## What It Does

Once initialized, the SDK automatically:

- Captures uncaught JavaScript errors and unhandled promise rejections
- Captures jQuery AJAX errors via `$(document).ajaxError()`
- Injects `traceway-trace-id` headers into same-origin `$.ajax()` requests
- Injects `traceway-trace-id` headers into same-origin `fetch()` requests

## AJAX Error Capture

jQuery AJAX errors are captured automatically. When `$.ajax()` fails, Traceway records the URL, HTTP method, status code, and error message.

```javascript
// This error is captured automatically
$.ajax({
  url: "/api/users",
  method: "GET",
  error: function (jqXHR, textStatus, errorThrown) {
    // Your error handling; Traceway also captures this
  },
});
```

## Manual Error Capture

Capture errors explicitly in try/catch blocks:

```javascript
import { captureException } from "@tracewayapp/jquery";

try {
  riskyOperation();
} catch (error) {
  captureException(error);
}
```

## With Options

```javascript
import { init } from "@tracewayapp/jquery";

init("your-token@https://cloud.tracewayapp.com/api/report", {
  debug: true,
  version: "1.0.0",
});
```

### Options Reference

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `debug` | `boolean` | `false` | Log filtered-out events and failed uploads to the browser console. Successful captures 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 window the log and action buffers retain |
| `eventsMaxCount` | `number` | `200` (`600` w/ `recordAllSessions`) | Hard cap on entries kept independently in the log and action buffers |
| `captureHttpServerErrors` | `boolean` | `false` | Report every `fetch` response with status >= 500 as a synthetic exception. It is wired into the `fetch` wrapper only, so `$.ajax()` does not trigger it. Use the `ajaxError` capture below for jQuery requests |

## Error Filtering

By default, 4xx AJAX errors (e.g., 401, 422), network errors, and timeouts are **not** captured. This means `$.ajax()` calls that return 4xx status codes will not appear in your Traceway dashboard unless you opt in.

To capture all AJAX errors including 4xx:

```javascript
init("your-token@https://cloud.tracewayapp.com/api/report", {
  ignoreErrors: [],
});
```

The jQuery SDK records HTTP status codes as attributes on captured errors. You can use `beforeCapture` to selectively filter by status:

```javascript
init("your-token@https://cloud.tracewayapp.com/api/report", {
  ignoreErrors: [],
  beforeCapture: (exception) => {
    // Only capture 5xx server errors from AJAX
    const status = Number(exception.attributes?.status);
    if (status >= 400 && status < 500) return false;
    return true;
  },
});
```

## Custom Attributes

Attach app-level identifiers (`userId`, `tenant`, feature flags, etc.) to every session and exception:

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

setAttribute("userId", "u_42");
setAttributes({ tenant: "acme", plan: "pro" });

// On logout / tenant switch:
clearAttributes();
```

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

## Distributed Tracing

The SDK automatically instruments both `XMLHttpRequest` (used by `$.ajax()`) and `fetch` to propagate a `traceway-trace-id` header on same-origin requests. This links frontend errors to the backend requests that caused them.

The backend has to hold up its end: it must set the incoming header on its server span as the `traceway.distributed_trace_id` attribute. The Symfony bundle does this for you, everything else needs one small middleware. See [Distributed Tracing](/client/js-sdk/distributed-tracing#backend-setup).

### With Symfony + OpenTelemetry

If your backend uses the [Symfony OpenTelemetry Bundle](/client/otel/symfony), distributed tracing works out of the box. The bundle reads the `traceway-trace-id` header from incoming requests and attaches it as a span attribute, linking your jQuery frontend errors to Symfony backend traces.

```javascript
// Frontend: trace header is injected automatically
$.post("/api/orders", { item: "widget" });
```

```php
// Backend: the bundle reads traceway-trace-id automatically
// No extra configuration needed in your Symfony controllers
```

## Test Your Integration

```javascript
import { captureException } from "@tracewayapp/jquery";

$("#test-button").on("click", function () {
  captureException(new Error("Test error from jQuery"));
});
```

On the CDN build, call `TracewayJQuery.captureException(new Error("Test error from jQuery"))` instead.

Click the button and check your Traceway dashboard to verify the error appears.

## Next Steps

- [Distributed Tracing](/client/js-sdk/distributed-tracing): Frontend ↔ backend correlation
- [JS SDK Reference](/client/js-sdk): Full API reference