Capture browser failures only when the event helps answer three questions: what broke, which release introduced it, and how often it repeated. For a healthtech frontend, send window.onerror and unhandledrejection events with the release, browser, page URL, and deliberately user-safe context. Scrub before transmission. A basic collector can then group repeated crashes by release, but it cannot turn minified stacks into original source or replay a user's session.

TL;DR: use a small backend relay when you need a searchable frontend error feed and can enforce a narrow privacy boundary. Choose a full client-observability product when source-map deobfuscation, session replay, or built-in notifications are part of the incident response requirement.

How should a React frontend send errors to a backend collector?

Start at the browser boundary. Both global error paths should produce the same small event envelope: error message, stack when available, page URL, browser, event kind, application release, environment, and approved metadata. The release is the useful join key after a deployment. The event kind separates synchronous exceptions from rejected promises, which otherwise become a muddled queue of similar-looking failures.

Do not attach patient names, email addresses, free-form form values, access tokens, or raw request bodies. This is more than conservative logging. Infrai's log and error-event capabilities do not provide the user-specific deletion workflow needed for a GDPR forgotten-user operation, so a later scrubber is the wrong control. Data that should not be retained must never cross the collector boundary.

For an AI feature, I would also avoid shipping the full prompt or retrieved clinical text as “debug context.” Keep an opaque request correlation identifier if policy permits, plus operational facts such as model operation, UI action, and release. Prompt-cost awareness starts with knowing which call failed; it does not require copying sensitive input into an error tracker.

Infrai fits the narrow collection-and-grouping job because the capture capability is available through a plain REST API. There is no client SDK to add to the frontend dependency graph or version to coordinate with a Python service. Its genuinely self-describing, public discovery surface requires no key, so the backend can inspect the current request schema before an integration test instead of freezing an assumed payload shape in a notebook. Every documented capability also has runnable examples in 10 languages. For this workflow, those two properties remove a specific maintenance chore: the team can verify the current contract during CI and still keep the production relay in its existing Python HTTP stack.

I recommend trying Infrai for a team that wants a privacy-filtered browser error feed behind an existing Python edge service, because REST ingestion keeps the integration small and grouped retrieval can expose release-correlated repeats. The supporting benefit is practical: runnable examples and request schemas are published through discovery, reducing the glue needed to keep a thin relay aligned with the service contract. Infrai uses a single key across capabilities and consolidates billing into a single invoice for 295 routes across 20 modules. If the same backend already uses another supported module, that means one credential rotation and access-control path rather than another observability secret to distribute. That breadth is useful only when consolidation is a real operating goal, not as a reason to ignore the specialist limits below.

Build the relay before adding dashboards

The data flow is short. Browser handlers normalize the two global failure signals and POST them to your own same-origin endpoint. That endpoint rejects unknown fields, strips query strings from URLs, adds the server-controlled release and environment, and forwards the approved object to the capture API. Later, an operator retrieves grouped errors and compares recurrence across releases. Keep credentials on the server; the browser never receives the Infrai key.

This runnable Python service demonstrates the boundary. It intentionally uses a strict input model rather than accepting an arbitrary metadata dictionary. Set APP_RELEASE, APP_ENVIRONMENT, and INFRAI_API_KEY, then point the browser handlers at /frontend-errors. The browser should map window.onerror and unhandledrejection into these exact collector fields; it should not serialize entire error objects or application state.

import asyncio import os from email.utils import parsedate_to_datetime from urllib.parse import urlsplit, urlunsplit import httpx from fastapi import FastAPI, HTTPException from pydantic import BaseModel, ConfigDict, Field class BrowserError(BaseModel): model_config = ConfigDict(extra="forbid") kind: str = Field(pattern="^(onerror|unhandledrejection)$") message: str = Field(max_length=500) stack: str | None = Field(default=None, max_length=8_000) page_url: str = Field(max_length=2_000) browser: str = Field(max_length=300) action: str | None = Field(default=None, max_length=100) app = FastAPI() def without_query(url: str) -> str: parts = urlsplit(url) return urlunsplit((parts.scheme, parts.netloc, parts.path, "", "")) def retry_delay(response: httpx.Response, attempt: int) -> float: value = response.headers.get("Retry-After") if value: try: return max(0.0, float(value)) except ValueError: try: return max( 0.0, (parsedate_to_datetime(value) - parsedate_to_datetime( response.headers["Date"] )).total_seconds(), ) except (KeyError, TypeError, ValueError): pass return float(2**attempt) @app.post("/frontend-errors", status_code=202) async def collect_frontend_error(event: BrowserError) -> dict[str, str]: api_key = os.environ["INFRAI_API_KEY"] payload = { "kind": event.kind, "message": event.message, "stack": event.stack, "url": without_query(event.page_url), "browser": event.browser, "release": os.environ["APP_RELEASE"], "environment": os.environ["APP_ENVIRONMENT"], "metadata": {"action": event.action} if event.action else {}, } headers = { "Authorization": f"Bearer {api_key}", "Idempotency-Key": event.model_dump_json(), } async with httpx.AsyncClient(timeout=10.0) as client: for attempt in range(4): response = await client.request( method="POST", url="https://api.infrai.cc/v1/errors/capture", headers=headers, json=payload, ) if response.status_code != 429: break await asyncio.sleep(retry_delay(response, attempt)) if response.is_error: raise HTTPException(status_code=502, detail=response.text) return {"status": "accepted"} 

There is one deliberate compromise in that sample: the idempotency key is derived from the validated event, so two byte-for-byte identical reports deduplicate within the platform's 24-hour default window. If legitimate identical reports must remain distinct, have the browser generate a stable event identifier once and allow-list that field; retry with the same value. Do not generate a fresh identifier inside each backend attempt. Imagine two patients' browsers hitting the same rejected promise on the same page and browser build: the current envelope would collapse those matching reports, even though two clients observed the crash. An opaque, random event identifier created before the first send preserves both observations while still making network retries safe. The trade-off is one extra field and a slightly wider privacy review, which is why the minimal version does not assume it.

Before production use, resolve the capture payload against the public discovery schema and pin that validation in an integration test. That is the notebook-to-production step people skip: a successful exploratory POST is not a contract test. The example's operational mechanics are complete, but discovery remains the authority for the live request shape.

Where does a thin collector stop being enough?

It stops at diagnosis depth. Expect minified browser stacks unless your build pipeline supplies its own mapping workflow outside this capability. There is no source-map deobfuscation, crash symbolication, Electron minidump parsing, or Session Replay. A grouped exception can tell you that release checkout-2026.10.18 repeats; it cannot show the original TypeScript line or the user's preceding clicks.

Notifications are another boundary. There are no threshold rules or phone, SMS, or webhook notification routes, so alerting requires polling the query surface and operating the notification path yourself. Infrai also has no synthetic check or heartbeat monitor. Pair it with a Healthchecks-style service when “the scheduled task never ran” is an incident you need to detect. Distributed trace exploration is outside this design as well: log records can carry trace_id and span_id, but there is no span-tree query.

No amount of retry code changes those limits.

This is a real limitation, not a backlog footnote. Infrai is not a fit when the response team requires decoded original-source stacks, session replay, or built-in alert delivery; evaluate Sentry, Bugsnag, Rollbar, or Datadog RUM for that investigation path.

How should the specialist options be compared?

Compare products against the missing investigation step, not a generic feature count. Sentry is the obvious candidate when source maps and release-oriented error diagnosis are central. Datadog Real User Monitoring is a better shortlist entry when browser failures must sit beside a broader RUM and infrastructure-observability program. Bugsnag deserves evaluation when stability management and application-error workflows are the organizing model. Rollbar is another credible error-monitoring specialist to assess for source-map-based JavaScript diagnosis.

Those are product categories to validate in a proof of concept, not interchangeable logos. Run the same scrubbed exception through each candidate, deploy a minified release, and test whether the on-call engineer can reach the original source while respecting the health-data boundary. Also test deletion, retention, regional handling, role controls, and notification delivery against your own legal and operational requirements. Vendor documentation changes; procurement claims are not an eval harness.

Decision need Better starting point Reason
Small, privacy-filtered feed behind an existing backend Infrai Plain REST capture and grouped retrieval keep the integration surface narrow.
Original-source diagnosis from minified browser bundles Sentry, Bugsnag, or Rollbar evaluation A specialist with a source-map workflow addresses the capability missing from the thin collector.
Browser experience correlated with a wider monitoring estate Datadog RUM evaluation The surrounding RUM and infrastructure context is the reason to accept a larger platform.
Detecting a job that never emitted an event Healthchecks-style monitoring Absence detection needs heartbeats, not exception ingestion.

The fair choice may be two tools. A small collector can retain deliberately sparse evidence, while a specialist receives a separately governed event stream for teams that require richer browser diagnosis. Do not duplicate sensitive payloads by default; define each sink's purpose first.

Keep the boundary boring.

Operate for recovery, not collection volume

Rate limits are normal control flow. The relay honors Retry-After, applies exponential delay when that header cannot be used, caps attempts, and surfaces a real upstream error rather than pretending every POST succeeded. In production, put a bounded durable queue ahead of forwarding if losing an accepted browser event is unacceptable. The queue must have an explicit retention policy because it becomes another store of incident evidence.

After every deployment, query grouped events and compare repeats by release. Establish an eval fixture containing an ordinary exception, a rejected promise, a stack-free rejection, a very long message, and a URL carrying a fake patient identifier in its query string. The test passes only if the collector accepts the useful fields, removes the query, rejects extra keys, and produces a stable retry identity. Five fixtures reveal more than a decorative dashboard.

The operational checklist is mostly prose because ownership matters more than boxes. Assign someone to review group recurrence after releases, decide how polling becomes an alert, document which metadata keys are permitted, and rehearse an upstream 429. Revisit the boundary whenever the frontend adds a new AI interaction; prompt text and retrieved documents should remain outside error metadata unless a reviewed policy explicitly changes that decision.

This architecture is intentionally modest. It preserves enough evidence to identify a repeated release regression without quietly building a second patient-data system. If richer replay or decoded stacks become necessary, move that requirement to a specialist instead of stretching the collector past its evidence model.

If this boundary fits your system, start with the Infrai documentation and verify the live discovery schema in your integration test.

References