Skip to content

adham90/opentrace_browser

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

2 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

OpenTrace JS

Lightweight browser error tracking client for OpenTrace. Captures JavaScript errors and forwards them to your OpenTrace server via POST /api/logs.

  • Zero dependencies — vanilla JS, no polyfills
  • 3.1 KB gzipped — won't bloat your bundle
  • Never throws — all internal errors swallowed, safe for production
  • Auto-capturewindow.onerror and unhandled promise rejections
  • Error grouping — stable fingerprinting for server-side dedup
  • Request correlation — ties browser errors to the server request via request_id
  • Breadcrumbs — click, navigation, and fetch tracking for error context

Quick Start

Add this to your HTML <head>:

<script src="https://your-opentrace-server.com/static/opentrace.min.js"></script>
<script>
  OpenTrace.init({
    endpoint: "https://your-opentrace-server.com/api/logs",
    apiKey: "your-api-key",
    service: "my-app-frontend",
  });
</script>

Or find a pre-filled snippet on your OpenTrace server at Settings > Setup > Browser Error Tracking.

Request ID Correlation

To correlate browser errors with the server request that rendered the page, add a meta tag to your layout:

<!-- Rails -->
<meta name="opentrace-rid" content="<%= request.request_id %>">

<!-- Express -->
<meta name="opentrace-rid" content="<%= req.id %>">

The JS client reads this automatically and includes it as request_id on every log entry.

API

OpenTrace.init(options)

Initialize the client. Must be called before any other method.

Option Type Default Description
endpoint string required OpenTrace server URL (e.g. https://host/api/logs)
apiKey string required API key for authentication
service string required Service name (e.g. "my-app-frontend")
environment string "" Environment tag (production, staging, etc.)
commitHash string "" Git commit hash for release tracking
requestIdMeta string "opentrace-rid" <meta> tag name to read request ID from
sampleRate number 1.0 Fraction of errors to capture (0.0–1.0)
beforeSend function null Hook to modify/filter events. Return null to drop.
maxQueueSize number 50 Max buffered events before forced flush
flushInterval number 5000 Flush interval in milliseconds
enabled boolean true Kill switch
debug boolean false Log internal state to console

OpenTrace.captureError(error, metadata?)

Manually capture a caught error with optional metadata.

try {
  riskyOperation();
} catch (e) {
  OpenTrace.captureError(e, { userId: 42, page: "/checkout" });
}

OpenTrace.log(level, message, metadata?)

Send a manual log entry.

OpenTrace.log("warn", "Payment retry attempted", { orderId: 123 });

OpenTrace.setContext(ctx)

Set global context merged into every event.

OpenTrace.setContext({ userId: 42, plan: "pro" });

OpenTrace.addBreadcrumb(crumb)

Add a manual breadcrumb for error context.

OpenTrace.addBreadcrumb({ type: "checkout", data: { step: "payment" } });

OpenTrace.flush()

Flush pending events immediately.

OpenTrace.shutdown()

Flush and tear down all hooks.

How It Works

  1. Auto-capture hooks window.onerror and unhandledrejection to catch uncaught errors
  2. Breadcrumbs automatically track clicks, navigation (History API), and fetch requests
  3. Fingerprinting generates a stable hash from exception class + message + source file for server-side error grouping
  4. Batching queues events in memory and flushes on interval or when the queue is full
  5. Page unload uses navigator.sendBeacon to flush remaining events when the tab is hidden
  6. Deduplication throttles identical errors (same fingerprint) to 1 per 5 seconds
  7. Retry on network failure or rate limiting with exponential backoff (max 3 attempts)

PII Scrubbing

Use the beforeSend hook to strip sensitive data before it leaves the browser:

OpenTrace.init({
  // ...
  beforeSend(event) {
    delete event.metadata.user_agent;
    event.message = event.message.replace(/email=\S+/g, "email=[REDACTED]");
    return event; // return null to drop the event entirely
  },
});

Development

npm install
npm test          # run tests (vitest)
npm run build     # build dist/ (rollup)

Project Structure

src/
  index.js          # entry point, public API
  capture.js        # window.onerror, unhandledrejection hooks
  transport.js      # batching, flush, sendBeacon, retry
  fingerprint.js    # error fingerprinting
  breadcrumbs.js    # click, navigation, fetch tracking
  utils.js          # truncation, hashing, selectors
test/
  index.test.js     # integration tests
  capture.test.js   # auto-capture tests
  transport.test.js # batching and network tests
  fingerprint.test.js
  breadcrumbs.test.js
  utils.test.js

Build Outputs

File Format Size
dist/opentrace.js IIFE (unminified) 19 KB
dist/opentrace.min.js IIFE (minified) 7.4 KB
dist/opentrace.esm.js ES module 18 KB

Browser Support

ES2015+ (all modern browsers). No IE11 support.

License

MIT

About

Lightweight browser error tracking client for OpenTrace. Captures JS errors, unhandled rejections, and manual logs — 3.1KB gzipped, zero dependencies.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors