πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
import { type ErrorEvent } from "@sentry/nextjs";
/**
* High-frequency poll / health endpoints whose transient 5xx responses are
* expected background noise rather than actionable client-side errors.
*
* `Sentry.httpClientIntegration()` reports EVERY 5xx fetch/XHR the browser
* observes as an unhandled `HTTP Client Error with status code: N`. The worst
* offender by far is NextAuth's session poll: `SessionProvider` in `_app.tsx`
* refetches `/api/auth/session` every 5 minutes AND on every window focus, for
* every signed-in user. Its callback runs a heavy nested Prisma query, so any
* transient DB blip, slow response, or pod restart momentarily 5xxes here and is
* amplified across thousands of browsers into huge false-positive Sentry issues.
*
* Matched by URL path SUFFIX so an optional `NEXT_PUBLIC_BASE_PATH` prefix
* (e.g. `/self-hosted/api/auth/session`) still matches.
*/
const HTTP_CLIENT_NOISE_PATHS = [
"/api/auth/session", // NextAuth session poll (5-min interval + on window focus)
// The two probes below are defensive/inert: they are only fetched by infra
// liveness/readiness checks, never by the browser, so they cannot actually
// match a client-side httpClient event. Only /api/auth/session suppresses
// real browser noise today; the probes are listed to be safe if a browser
// ever starts polling them.
"/api/public/health", // liveness probe (infra-only)
"/api/public/ready", // readiness probe (infra-only)
] as const;
function isHttpClientIntegrationEvent(event: ErrorEvent): boolean {
const mechanismType = event.exception?.values?.[0]?.mechanism?.type;
return (
typeof mechanismType === "string" &&
mechanismType.startsWith("auto.http.client")
);
}
/**
* True only for events created by `httpClientIntegration` (exception mechanism
* `auto.http.client.fetch` / `auto.http.client.xhr`) whose request URL targets
* one of the poll/health endpoints in {@link HTTP_CLIENT_NOISE_PATHS}.
*
* Deliberately narrow. It keys on the Sentry-set exception mechanism, so it can
* never drop:
* - a genuine thrown exception or a captured console error (different / no
* mechanism), or
* - an application 5xx (HTTP 500, etc.) on a real API/tRPC endpoint β
* `/api/trpc/...`, `/api/public/traces`, `/api/public/ingestion`. Gateway
* statuses 502/503/504 on those same URLs are dropped by
* {@link isNoisyHttpClientGatewayEvent}, not this poll-path filter.
*
* This does not hide real outages: a genuine `/api/auth/session` 5xx is still
* observable server-side via request tracing/APM spans and application logs, and
* via the health-check system β and the frontend already treats the session poll
* as non-fatal. This filter only removes the redundant client-side amplification
* of that same failure across thousands of browsers.
*/
export function isNoisyHttpClientPollEvent(event: ErrorEvent): boolean {
if (!isHttpClientIntegrationEvent(event)) return false;
const requestUrl = event.request?.url;
if (typeof requestUrl !== "string") return false;
// Reduce to a path so origin/query string don't affect matching. Fall back to
// the raw string if the URL cannot be parsed (httpClient URLs are absolute, so
// this is effectively unreachable, but we stay defensive).
let path = requestUrl;
try {
path = new URL(requestUrl, "http://localhost").pathname;
} catch {
// keep raw requestUrl
}
return HTTP_CLIENT_NOISE_PATHS.some((noisePath) => path.endsWith(noisePath));
}
/**
* Proxy / load-balancer statuses that mean the browser reached an edge (ALB,
* nginx, Cloudflare) which could not get a response from our app: Bad Gateway,
* Service Unavailable, Gateway Timeout. Our tRPC handlers do not produce these
* β application failures serialize as JSON with HTTP 500 (`INTERNAL_SERVER_ERROR`).
*
* `httpClientIntegration` still reports them as unhandled
* `HTTP Client Error with status code: N`. The tRPC seam already treats the
* matching HTML-body parse failure as transport noise
* (`isTrpcResponseParseError` in `api.ts`); this predicate drops the duplicate
* httpClient copy so one LB blip does not mint a Sentry issue.
*
* URL-scoped like {@link isNoisyHttpClientPollEvent}: only same-origin URLs,
* {@link HTTP_CLIENT_NOISE_PATHS}, and `/api/trpc/...` paths. Third-party
* httpClient 502/503/504 (e.g. S3/GCS presigned uploads) are KEPT β those are
* not our edge and are often the only Sentry signal for a failed upload.
*
* True only for `auto.http.client.*` events whose status is 502, 503, or 504
* AND whose request URL is app-owned. Never drops:
* - a genuine thrown exception or console error (different / no mechanism);
* - an application HTTP 500 (or any non-gateway 5xx) on tRPC or the public API
* β those still flow, and JSON 5xx are also captured at `handleTrpcError`;
* - a gateway status on a third-party origin (storage, analytics, β¦).
*
* Real outages remain observable server-side via request tracing/APM spans and
* logs. This only removes the client-side amplification of our own edge.
*/
const HTTP_CLIENT_GATEWAY_STATUSES: ReadonlySet<number> = new Set([
502, 503, 504,
]);
const HTTP_CLIENT_STATUS_MESSAGE =
/^HTTP Client Error with status code: (\d+)$/;
/** Path segment for tRPC routes, matched with an optional base-path prefix. */
const HTTP_CLIENT_TRPC_PATH_RE = /(?:^|\/)api\/trpc(?:\/|$)/;
function readHttpClientStatus(event: ErrorEvent): number | undefined {
const responseContext = event.contexts?.response;
if (
responseContext &&
typeof responseContext === "object" &&
"status_code" in responseContext &&
typeof responseContext.status_code === "number"
) {
return responseContext.status_code;
}
const text =
event.exception?.values?.[0]?.value ??
event.message ??
event.logentry?.message;
if (typeof text !== "string") return undefined;
const match = HTTP_CLIENT_STATUS_MESSAGE.exec(text.trim());
if (!match) return undefined;
return Number(match[1]);
}
/**
* True when the request URL targets our app (LB noise on our edge) rather than
* a third-party origin. Matches same-origin, {@link HTTP_CLIENT_NOISE_PATHS},
* or a `/api/trpc` path (including behind `NEXT_PUBLIC_BASE_PATH`).
*/
function isHttpClientAppOwnedRequestUrl(requestUrl: string): boolean {
let parsed: URL;
try {
const base =
typeof window !== "undefined" && typeof window.location?.href === "string"
? window.location.href
: "http://localhost";
parsed = new URL(requestUrl, base);
} catch {
return false;
}
const path = parsed.pathname;
if (HTTP_CLIENT_NOISE_PATHS.some((noisePath) => path.endsWith(noisePath))) {
return true;
}
if (HTTP_CLIENT_TRPC_PATH_RE.test(path)) {
return true;
}
if (
typeof window !== "undefined" &&
typeof window.location?.origin === "string" &&
window.location.origin !== "null" &&
parsed.origin === window.location.origin
) {
return true;
}
return false;
}
export function isNoisyHttpClientGatewayEvent(event: ErrorEvent): boolean {
if (!isHttpClientIntegrationEvent(event)) return false;
const status = readHttpClientStatus(event);
if (status === undefined || !HTTP_CLIENT_GATEWAY_STATUSES.has(status)) {
return false;
}
const requestUrl = event.request?.url;
if (typeof requestUrl !== "string") return false;
return isHttpClientAppOwnedRequestUrl(requestUrl);
}
/**
* Browser/transport messages that mean the client could not complete a network
* request at the transport layer: offline, flaky wifi, a throttled/backgrounded
* tab, a CORS rejection, or a proxy/infra 5xx that returned an HTML page. Each
* is just one engine's name for "the fetch never completed" β none is Langfuse
* application logic.
*
* Matched as the WHOLE (normalized) exception message, never as a substring: a
* genuine failure does not surface as one of these bare strings. Real API
* failures surface server-side (request tracing / logs) and, on the client, as
* a *handled* error carrying the server's real message (e.g. `UNAUTHORIZED`).
* App code that merely quotes a phrase β e.g. `Failed to fetch created model`,
* `Failed to fetch channels. Please check your Slack connection` β is longer
* than the bare string and is therefore KEPT. See the negative fixtures in
* `sentryFilters.clienttest.ts`.
*/
const TRANSPORT_FAILURE_MESSAGES: readonly string[] = [
"Failed to fetch", // Chrome / Chromium fetch network failure
"NetworkError when attempting to fetch resource", // Firefox fetch network failure
"Load failed", // Safari / WebKit fetch network failure
];
/**
* Browser-extension URL protocols already listed in `denyUrls`
* (`web/instrumentation-client.ts`). `denyUrls` matches stack-frame filenames;
* keep this list in sync so the message-level fallback covers the same origins.
*/
const BROWSER_EXTENSION_MODULE_URL_RE =
/^(?:chrome-extension|moz-extension|safari-extension|safari-web-extension|ms-browser-extension):\/\//i;
/**
* Chrome's exact wording when a dynamic `import()` fails to load. Combined
* with {@link BROWSER_EXTENSION_MODULE_URL_RE} so a first-party chunk-load
* failure (`https://β¦/_next/static/chunks/β¦`) is NOT dropped.
*/
const DYNAMIC_IMPORT_FAILURE_MARKER =
"Failed to fetch dynamically imported module:";
/**
* True when Chrome reported a failed dynamic `import()` whose MODULE URL
* (the text immediately after {@link DYNAMIC_IMPORT_FAILURE_MARKER}) uses a
* browser-extension protocol. Anchored to that URL so a first-party chunk
* failure that merely mentions `chrome-extension://` in a query, fragment, or
* trailing console text is KEPT.
*/
function isBrowserExtensionDynamicImportFailure(text: string): boolean {
const markerIndex = text.indexOf(DYNAMIC_IMPORT_FAILURE_MARKER);
if (markerIndex === -1) return false;
const failedModule = text
.slice(markerIndex + DYNAMIC_IMPORT_FAILURE_MARKER.length)
.trimStart();
return BROWSER_EXTENSION_MODULE_URL_RE.test(failedModule);
}
/**
* Message prefixes emitted by non-Langfuse code (framework / vendor). These are
* unambiguous, vendor-namespaced strings that our own code cannot produce, so
* matching them by prefix cannot swallow a real app error.
*/
const NOISE_MESSAGE_PREFIXES: readonly string[] = [
// NextAuth's client `SessionProvider` logs this via `console.error` (picked up
// by `captureConsoleIntegration`) when its 5-min / on-focus session poll fails
// transiently β same transient root as the httpClient poll already filtered by
// `isNoisyHttpClientPollEvent`. The `[next-auth]` namespace can only come from
// the library, never from app code.
"[next-auth][error][CLIENT_FETCH_ERROR]",
// PostHog analytics SDK notices / client-side rate-limit logs. Third-party.
"[PostHog.js]",
// Cloudflare / Cursor Kitesurf console-errors its own localhost CORS probe
// with this unbracketed prefix (LANGFUSE-610). Distinct from bracketed
// `[kitesurf]` listener wraps β those go through {@link isKitesurfInternalEvent}.
"kitesurf:",
// `Response.json()` on a non-JSON body (a 5xx / HTML proxy page returned where
// JSON was expected). This is the response not being ours-as-JSON, i.e. a
// transport/infra artifact, not app logic.
"Failed to execute 'json' on 'Response'",
// `@sentry/nextjs`'s own pages-router `_error` instrumentation calls
// `captureException(err || `_error.js called with falsy error (${err})`)`, so
// the fallback message always STARTS with this literal (`(undefined)`,
// `(null)`, ...). It is a framework artifact with no real error attached.
"_error.js called with falsy error",
];
/**
* The Sentry SDK synthesizes this exact prefix (global `onunhandledrejection`
* handler) when a promise rejects with a non-`Error` value. These events carry
* NO stack, so Sentry groups them by the stringified value β every new value
* mints a new fingerprint.
*/
const NON_ERROR_REJECTION_PREFIX =
"Non-Error promise rejection captured with value: ";
/**
* Known-benign non-Error rejection values, each traced to a non-app source
* from real events. ONLY these exact values (plus the prefixes below) are
* dropped β an unknown value could be a real rejection from our code or a
* bundled dependency and is KEPT, as is the object-shaped
* `Object captured as promise rejection with keys: β¦` variant, which has
* carried real failures (e.g. `code, message, stack` payloads).
*/
const BENIGN_NON_ERROR_REJECTION_VALUES: readonly string[] = [
// Browser-extension shim (wallet/provider extensions no-op on unsupported
// platforms and reject with this bare string). Observed with no stack and no
// app frames (LANGFUSE-5T9).
"Not implemented on this platform",
// `Promise.reject()` / `reject(undefined)`: zero diagnostic content β no
// stack, no message, no value. Nobody can act on it (LANGFUSE-5TA).
"undefined",
];
/**
* Prefix-matched benign rejection values whose tail varies per occurrence
* (which is exactly what shatters grouping).
*/
const BENIGN_NON_ERROR_REJECTION_VALUE_PREFIXES: readonly string[] = [
// Microsoft Outlook SafeLinks / email-scanner artifact: the crawler injects
// scripts that reject with `Object Not Found Matching Id:<n>, MethodName:β¦`.
// Industry-known scanner noise, never a browser session (LANGFUSE-11Z).
"Object Not Found Matching Id:",
];
/**
* Chromium Android WebView wording when a host-app `@JavascriptInterface`
* method fails. The method name is a Java identifier; the suffix is fixed.
* Observed: LANGFUSE-60G (`Error invoking batch: Java bridge method
* invocation error`).
*/
const ANDROID_WEBVIEW_JAVA_BRIDGE_ERROR_RE =
/^Error invoking [A-Za-z_][\w$]*: Java bridge method invocation error$/;
/**
* Chromium wording when `new URL(input, base)` rejects the base. A `data:`
* document URL cannot resolve a path-absolute URL, so Next.js App Router's
* `new URL(canonicalUrl, window.location.href)` throws during hydrate.
* Observed: LANGFUSE-60K (Electron health probe loading the app HTML as a
* `data:` URL; stack is Next.js `Router` only, 0 users).
*/
const CHROMIUM_INVALID_URL_CONSTRUCTOR_MESSAGE =
"Failed to construct 'URL': Invalid URL";
/**
* Firefox wording for the same `new URL` rejection (`URL constructor: <x>
* is not a valid URL`).
*/
const FIREFOX_INVALID_URL_CONSTRUCTOR_RE =
/^URL constructor: .+ is not a valid URL\.?$/;
function isInvalidUrlConstructorMessage(value: string): boolean {
return (
value === CHROMIUM_INVALID_URL_CONSTRUCTOR_MESSAGE ||
FIREFOX_INVALID_URL_CONSTRUCTOR_RE.test(value)
);
}
/**
* True when the event's page URL is a `data:` document. Checks `request.url`
* first, then `tags.url` β Sentry's transaction/culprit often strips the
* `data:` scheme, so those fields are not used.
*/
function isDataDocumentUrl(event: ErrorEvent): boolean {
const requestUrl = event.request?.url;
if (typeof requestUrl === "string" && requestUrl.startsWith("data:")) {
return true;
}
const taggedUrl = event.tags?.url;
return typeof taggedUrl === "string" && taggedUrl.startsWith("data:");
}
/**
* Chrome's exact `chrome.runtime.sendMessage` / `chrome.runtime.connect`
* lastError when the extension background or content-script port is gone.
* Extensions inject this into the page; Langfuse never calls `chrome.runtime`.
* Observed as an unhandled rejection with no stack (LANGFUSE-614), so
* `denyUrls` cannot match. Whole-message only β an app error that merely
* quotes the phrase is longer and is KEPT.
*
* Stored without a trailing period because {@link coreMessage} strips one.
*/
const CHROME_EXTENSION_PORT_MESSAGES: readonly string[] = [
"Could not establish connection. Receiving end does not exist",
"The message port closed before a response was received",
];
/**
* Chromium wording when Next.js Pages Router `initialize()` does
* `window.__NEXT_DATA__ = initialData` and that Window property is
* getter-only. Observed: LANGFUSE-61R (`/auth/sign-up`, us-prod, 0 users,
* stack is only Next.js `client/index.tsx` + turbopack). Langfuse never
* assigns this property. A page-world extension / SES lockdown / named
* Window property made it a getter; we cannot make it writable after
* `initialize` has thrown.
*
* Whole-message only β an app error that quotes the phrase is longer
* and is KEPT. Stored without a trailing period because
* {@link coreMessage} strips one.
*/
const CHROMIUM_GETTER_ONLY_WINDOW_NEXT_DATA_MESSAGE =
"Cannot set property __NEXT_DATA__ of #<Window> which has only a getter";
/**
* Safari / WebKit wording when injected password-manager or autofill JS
* does `addMore.click()` and `addMore` is undefined. WebKit uniquely
* includes the expression in the TypeError. Langfuse has no `addMore`
* identifier. Observed as a global-handler TypeError with
* document-attributed frames β `denyUrls` cannot match.
*
* Whole-message only. An app error that quotes the phrase is longer
* and is KEPT.
*/
const SAFARI_ADDMORE_CLICK_RE =
/^(?:undefined|null) is not an object \(evaluating 'addMore\.click(?:\(\))?'\)$/;
/**
* Match {@link SAFARI_ADDMORE_CLICK_RE} without {@link coreMessage}.
* `coreMessage` strips a trailing `(β¦)` parenthetical β that clause *is*
* WebKit's signature here, so stripping it would miss the real event.
*/
function isSafariAddMoreClickMessage(value: string): boolean {
return SAFARI_ADDMORE_CLICK_RE.test(value.trim().replace(/\.$/, "").trim());
}
/**
* True when any stack frame is a first-party Next.js chunk. Used as a
* negative guard so a future first-party throw that happens to share
* WebKit's wording still reaches Sentry.
*/
function hasFirstPartyChunkFrame(event: ErrorEvent): boolean {
const frames = event.exception?.values?.[0]?.stacktrace?.frames;
if (!frames || frames.length === 0) return false;
return frames.some(
(frame) =>
typeof frame?.filename === "string" && frame.filename.includes("/_next/"),
);
}
/**
* A `TRPCClientError` re-wraps its cause's message. Depending on capture path
* the Sentry `value` may be the bare cause message (`Failed to fetch`) or carry
* the wrapper prefix (`TRPCClientError: Failed to fetch`). We strip ONLY this
* one known wrapper prefix and match the inner phrase, because the raw
* `TRPCClientError:` prefix also fronts real, must-keep errors.
*/
const TRPC_CLIENT_ERROR_PREFIX = "TRPCClientError: ";
function coreMessage(value: string): string {
const withoutWrapper = value.startsWith(TRPC_CLIENT_ERROR_PREFIX)
? value.slice(TRPC_CLIENT_ERROR_PREFIX.length)
: value;
// Strip engine-specific decorations so the whole-message comparison stays
// exact yet engine-agnostic:
// - a trailing ` (host)` parenthetical Chrome appends, e.g.
// `Failed to fetch (cloud.langfuse.com)` -> `Failed to fetch`;
// - a single trailing period Firefox appends to its transport message.
// Only a WHOLE trailing parenthetical/period is removed, so a real app error
// that merely quotes a phrase (`Failed to fetch created model`) is untouched
// and still fails the exact-equality match.
return withoutWrapper
.trim()
.replace(/\s*\([^()]*\)$/, "")
.replace(/\.$/, "")
.trim();
}
/**
* True for React DevTools' internal probes against React's private fiber
* properties (`__reactContextDevtoolDebugId` and similar). These are benign:
* DevTools reads properties React does not guarantee exist, and the resulting
* failure is DevTools' own instrumentation, not a Langfuse app bug β it fires
* only when the extension is attached and installs its own probes.
*
* Matched against ALL text fields (exception value, message-event text, and
* the `logentry` fallback) because these can arrive as either an exception or
* a message event depending on how DevTools triggers the failure.
*/
/**
* The event's first NON-EMPTY text field β the exception value, else the
* message-event text, else the `logentry` fallback. An empty-string exception
* value is treated as absent (not nullish, so `??` alone would keep it), so a
* "mixed" event β empty exception value but real text on `message` β still
* matches on the message rather than being silently skipped.
*/
function eventText(event: ErrorEvent): string {
const exceptionValue = event.exception?.values?.[0]?.value;
return (
(typeof exceptionValue === "string" && exceptionValue.length > 0
? exceptionValue
: undefined) ??
event.message ??
event.logentry?.message ??
""
);
}
export function isReactDevtoolsInternalEvent(event: ErrorEvent): boolean {
return eventText(event).includes("__reactContextDevtoolDebugId");
}
/**
* True for known-benign CLIENT-side noise that cannot be a real Langfuse app
* bug: browser-level network/transport failures, transient framework/vendor
* poll logs, expected browser-permission / cancellation artifacts, and
* native HTMLMediaElement codec failures. Returning `true` drops the event
* in `beforeSend`.
*
* Design rule (safety first): only signatures that CANNOT represent a real app
* error are listed, each keyed on an unambiguous signature (whole-message match,
* vendor-namespaced prefix, or exception `type` + a required message guard) so a
* real error that merely quotes a phrase still flows to Sentry. When in doubt, a
* signature is left out. Real outages behind these client amplifications remain
* observable server-side (request tracing / logs).
*
* Event shape: message-signature rules are checked against the exception value
* AND the message-event fields (`event.message` / `event.logentry.message`),
* because console-origin noise (NextAuth `CLIENT_FETCH_ERROR`, PostHog notices,
* the Next.js `_error.js` artifact) is captured by `captureConsoleIntegration`
* as a MESSAGE event with NO `event.exception` (no stacktrace is attached by
* default). The `type`-guarded rules stay exception-only β message events carry
* no exception `type`, and those artifacts always arrive as thrown exceptions.
*
* DELIBERATELY NOT dropped here (needs separate, verified handling β do not add
* without confirming the real error is still captured elsewhere):
* - the generic prod error-boundary string `A client-side exception has
* occurred` β it aggregates real exceptions with no stack; hard-dropping it
* could blind us if the underlying exceptions are not captured separately.
* - `OAuthCallback` sign-in errors β could be a genuine auth-config break.
* - auth/permission (`UNAUTHORIZED`, not-a-member), query-timeout, and Sentry
* perf detectors / third-party scripts β handled as UX or in Sentry project
* settings, not by a blind client-side drop.
* - the chunk-load / stale-deploy `SyntaxError` family β GROUPED (not dropped)
* via {@link isStaleChunkParseErrorEvent} so a genuinely broken deploy still
* surfaces as a spike on one issue.
* - first-party `Failed to fetch dynamically imported module` of a
* `/_next/static/chunks/` URL β same Chrome wording as the extension
* family, but our chunks (stale tab / CDN); kept and GROUPED via
* {@link isStaleChunkLoadErrorEvent}.
* - an UNCAUGHT `window.__NEXT_DATA__` getter-only TypeError (global
* `onerror`) β Next.js Pages Router failed to boot; kept as a diagnostic.
* Only the console-captured sibling is dropped (LANGFUSE-61R).
*/
export function isDenylistedNoiseEvent(event: ErrorEvent): boolean {
const exception = event.exception?.values?.[0];
const exceptionType = exception?.type;
const exceptionValue = exception?.value;
// Message-signature rules run against the first non-empty text field
// (exception value β message β logentry); `eventText` treats an empty
// exception value as absent so mixed events still match on the message.
const messageText = eventText(event);
if (messageText.length > 0) {
const core = coreMessage(messageText);
// --- A. Transport / connectivity (whole-message match after unwrapping) ---
if (TRANSPORT_FAILURE_MESSAGES.includes(core)) return true;
// --- A + B + C. Unambiguous framework/vendor/transport prefixes (incl.
// NextAuth, PostHog, non-JSON Response.json(), and the Next.js `_error.js`
// falsy-error artifact). Anchored with startsWith, never a loose includes. ---
if (NOISE_MESSAGE_PREFIXES.some((prefix) => core.startsWith(prefix))) {
return true;
}
// --- A. Browser-extension dynamic import() failure (LANGFUSE-5ZS). ---
// Chrome logs `Failed to fetch dynamically imported module: <url>` when
// an extension's own `import()` fails. `denyUrls` already lists these
// protocols, but this family has no stack frames, so denyUrls never
// matches and captureConsoleIntegration mints a new issue per
// extension-id + hashed asset. The protocol is required on the FAILED
// module URL (not anywhere in the event text); a first-party
// `/_next/static/chunks/` URL is a real stale-chunk / CDN failure and
// is KEPT.
if (isBrowserExtensionDynamicImportFailure(messageText)) {
return true;
}
// --- A. Server returned an HTML error page where JSON was expected. ---
// Requires the JSON-parse signature (`is not valid JSON`) AND an HTML body
// marker, so it stays a "parsed an HTML error page as JSON" transport
// artifact and does NOT overlap the chunk-load / stale-deploy `SyntaxError`
// family (script parsing an HTML page), which is handled separately.
if (
messageText.includes("Unexpected token '<'") &&
messageText.includes("<html") &&
messageText.includes("is not valid JSON")
) {
return true;
}
}
// --- C. `type`-guarded rules β exception events only (message events carry
// no exception `type`; these artifacts always arrive as thrown exceptions). ---
if (typeof exceptionValue === "string") {
// Expected clipboard permission denial (we already fall back). The generic
// `NotAllowedError` type (autoplay, fullscreen, ...) REQUIRES a clipboard
// marker alongside it.
if (
exceptionType === "NotAllowedError" &&
(exceptionValue.includes("Clipboard") ||
exceptionValue.includes("writeText"))
) {
return true;
}
// Intentional request cancellation (nav away / superseded query).
if (
exceptionType === "AbortError" &&
(exceptionValue.includes("signal is aborted") ||
exceptionValue.includes("The operation was aborted"))
) {
return true;
}
// Browser cannot decode an <audio>/<video> resource (codec missing, empty
// source list). Firefox and Chromium reject HTMLMediaElement resource
// selection / autoplay as an unhandled NotSupportedError with no app
// stack. Onboarding splash videos and inline media players already hide
// or fall back in the UI; this is an expected capability gap, not an
// application bug. Guarded to the global handler so an app-captured
// NotSupportedError with the same wording is KEPT. Other
// NotSupportedError families (WebGL, WebRTC, "The operation is not
// supported.") have different messages and are KEPT.
if (
isGlobalHandlerUnsupportedMediaResourceEvent(
exceptionType,
exceptionValue,
exception?.mechanism?.type,
)
) {
return true;
}
// Known-benign non-Error promise rejections. The `UnhandledRejection`
// exception type is SDK-synthesized (a real `Error` rejection keeps its own
// type, e.g. `TypeError`), and the value denylist is exact/prefix-anchored:
// an unknown rejection value still flows to Sentry. See
// BENIGN_NON_ERROR_REJECTION_VALUES for per-value provenance.
if (
exceptionType === "UnhandledRejection" &&
exceptionValue.startsWith(NON_ERROR_REJECTION_PREFIX)
) {
const rejectionValue = exceptionValue.slice(
NON_ERROR_REJECTION_PREFIX.length,
);
if (
BENIGN_NON_ERROR_REJECTION_VALUES.includes(rejectionValue) ||
BENIGN_NON_ERROR_REJECTION_VALUE_PREFIXES.some((prefix) =>
rejectionValue.startsWith(prefix),
)
) {
return true;
}
}
// Environmental storage-access denial: browsers throw a `SecurityError`
// DOMException on the `window.localStorage` property GETTER itself when
// storage is blocked (third-party iframe, privacy mode). The message is
// browser-generated β app logic cannot produce it. Stacks point at
// per-deploy hashed chunks, so each occurrence minted a new fingerprint
// (LANGFUSE-5TC/5TD/5TE/5TF).
//
// Guarded to the `capture_console` mechanism: only instances our own code
// already CAUGHT and logged (e.g. the useLocalStorage / useSessionStorage
// fallback paths) are dropped. An UNCAUGHT storage SecurityError β e.g. a
// bare storage read during render crashing the page β arrives via the
// global `onerror` handler and is KEPT, as are other `SecurityError`s
// (e.g. cross-origin frame access).
if (
exceptionType === "SecurityError" &&
exception?.mechanism?.type === "auto.core.capture_console" &&
/^Failed to read the '(localStorage|sessionStorage)' property from 'Window':/.test(
exceptionValue,
)
) {
return true;
}
// Android WebView `@JavascriptInterface` methods only accept primitives.
// Chromium throws `Error invoking <method>: Java bridge method invocation
// error` when an injected host-app bridge fails β typically on `unload`,
// after the Java side is already torn down. Sentry's addEventListener wrap
// then captures the HOST APP's listener, not Langfuse code. We have no
// Java bridge (LANGFUSE-60G: Chrome Mobile WebView, anonymous `batch`
// frames only).
//
// Chrome extension port lastError (LANGFUSE-614) is the same class of
// injected-browser artifact: Chromium's exact `chrome.runtime` wording,
// no stack, `denyUrls` cannot match. Sibling message is the other
// documented lastError for a torn-down extension port.
//
// Safari password-manager `addMore.click` is the same class: WebKit's
// exact TypeError for an injected `addMore` that is undefined. Stack is
// document-attributed global code, not a chunk.
//
// All three are anchored to a Sentry browser-API / global-handler
// mechanism so an app-captured exception that merely quotes the
// phrase is KEPT.
const mechanismType = exception?.mechanism?.type;
if (
typeof mechanismType === "string" &&
mechanismType.startsWith("auto.browser.")
) {
if (ANDROID_WEBVIEW_JAVA_BRIDGE_ERROR_RE.test(exceptionValue)) {
return true;
}
if (
CHROME_EXTENSION_PORT_MESSAGES.includes(coreMessage(exceptionValue))
) {
return true;
}
if (
exceptionType === "TypeError" &&
isSafariAddMoreClickMessage(exceptionValue) &&
!hasFirstPartyChunkFrame(event)
) {
return true;
}
}
// Next.js App Router hydrates with
// `new URL(canonicalUrl, window.location.href)`. A `data:` document is
// not a valid base for a path-absolute canonical URL, so Chromium throws
// TypeError. Observed only from third-party Electron probes that load the
// app HTML as a data: URL (LANGFUSE-60K) β 0 users, Next.js frames only.
// We cannot fix Next.js here, and the page is not a real session.
//
// Requires TypeError + exact constructor wording + a data: page URL +
// a Sentry browser/global-handler mechanism so:
// - the same TypeError on an https:// page is KEPT (real app bug);
// - an app-captured exception that merely quotes the phrase is KEPT.
if (
exceptionType === "TypeError" &&
typeof mechanismType === "string" &&
mechanismType.startsWith("auto.browser.") &&
isInvalidUrlConstructorMessage(exceptionValue) &&
isDataDocumentUrl(event)
) {
return true;
}
// Next.js Pages Router boots with `window.__NEXT_DATA__ = initialData`
// (`next/src/client/index.tsx`). When that Window property is
// getter-only, Chromium throws TypeError. Observed as a console
// capture (LANGFUSE-61R): extra args are `Error was not caught` +
// the TypeError (that wrapper string is not in Next.js 16.3.3 β
// page-world). We never assign `__NEXT_DATA__` ourselves.
//
// Guarded to `capture_console` so an UNCAUGHT throw (page failed to
// hydrate via global onerror) is KEPT β that is a real diagnostic.
// An app-captured exception that merely quotes the phrase (`generic`)
// is also KEPT.
if (
exceptionType === "TypeError" &&
mechanismType === "auto.core.capture_console" &&
coreMessage(exceptionValue) ===
CHROMIUM_GETTER_ONLY_WINDOW_NEXT_DATA_MESSAGE
) {
return true;
}
}
return false;
}
/**
* Exact browser-generated HTMLMediaElement messages. Whole-string match only:
* an app error that quotes a phrase is longer and is therefore KEPT.
*/
const UNSUPPORTED_MEDIA_RESOURCE_MESSAGES: readonly string[] = [
// Firefox
"The media resource indicated by the src attribute or assigned media provider object was not suitable.",
// Chromium / WebKit
"Failed to load because no supported source was found.",
];
/**
* True for a native HTMLMediaElement NotSupportedError delivered by the
* browser global handlers (`onunhandledrejection` / `onerror`). See the
* call site in {@link isDenylistedNoiseEvent} for why this is dropped.
*/
function isGlobalHandlerUnsupportedMediaResourceEvent(
exceptionType: string | undefined,
exceptionValue: string,
mechanismType: string | undefined,
): boolean {
if (exceptionType !== "NotSupportedError") return false;
if (
typeof mechanismType !== "string" ||
!mechanismType.startsWith("auto.browser.global_handlers")
) {
return false;
}
return UNSUPPORTED_MEDIA_RESOURCE_MESSAGES.includes(exceptionValue);
}
/**
* Fingerprint used to collapse all stale-chunk parse errors into ONE Sentry
* issue (see {@link isStaleChunkParseErrorEvent}).
*/
export const STALE_CHUNK_PARSE_FINGERPRINT = "stale-chunk-parse-error";
/**
* Fingerprint used to collapse first-party chunk LOAD failures into ONE Sentry
* issue (see {@link isStaleChunkLoadErrorEvent}). Separate from the parse
* fingerprint: a 404/network miss is not the same signal as an unparsable body.
*/
export const STALE_CHUNK_LOAD_FINGERPRINT = "stale-chunk-load-error";
const NEXT_STATIC_CHUNK_PATH = "/_next/static/";
const FAILED_TO_LOAD_SCRIPT_MARKER = "Failed to load script:";
/**
* True for a browser-level parse failure of a Next.js chunk: the global
* `onerror` handler caught a `SyntaxError` whose entire stack is ONE anonymous
* frame at a `/_next/static/chunks/β¦` script β the shape a browser produces
* when a script's CONTENT fails to parse (truncated download, or a stale
* client fetching a chunk that no longer exists and receiving garbage after a
* deploy). Chunk filenames are content-hashed, so Sentry minted a new
* fingerprint per chunk per deploy (LANGFUSE-5WH/5WG/5WD/5S7 and the 1-event
* long tail). The reload banner (#15279) is the mitigation for the cause.
*
* These events are GROUPED under {@link STALE_CHUNK_PARSE_FINGERPRINT} in
* `beforeSend`, NOT dropped: if a deploy ever ships a genuinely unparsable
* chunk to everyone, the single grouped issue spikes and stays visible.
*
* Cannot catch a user-authored or app-code `SyntaxError`:
* - the evals code editor reports user-code syntax errors via
* `console.error` (mechanism `auto.core.capture_console`) with app frames
* (`web/src/features/evals/β¦`) β different mechanism, multi-frame stack;
* - a runtime `SyntaxError` thrown by app code (e.g. `JSON.parse`) carries
* its throwing function and callers β more than one frame / a named
* function.
*/
export function isStaleChunkParseErrorEvent(event: ErrorEvent): boolean {
const exception = event.exception?.values?.[0];
if (exception?.type !== "SyntaxError") return false;
if (exception.mechanism?.type !== "auto.browser.global_handlers.onerror") {
return false;
}
const frames = exception.stacktrace?.frames;
if (!frames || frames.length !== 1) return false;
const frame = frames[0];
// Parse errors carry no function name β the SDK synthesizes the frame with
// its UNKNOWN_FUNCTION placeholder `"?"` on the wire (`beforeSend` runs
// BEFORE server-side normalization turns that into `null`). A real function
// name means runtime code threw.
if (frame?.function && frame.function !== "?") return false;
return (
typeof frame?.filename === "string" &&
frame.filename.includes("/_next/static/chunks/")
);
}
/**
* True for a first-party Next.js chunk that failed to LOAD (not parse):
* Pages Router `route-loader` `script.onerror` (`Failed to load script:
* <hashed /_next/static/β¦ URL>`) or Chrome's dynamic
* `import()` of the same path. Chunk filenames are content-hashed, so Sentry
* minted a new issue per chunk per deploy. The one-shot reload in
* `reloadOnStaleChunk` is the user-facing recovery; these events are GROUPED
* under {@link STALE_CHUNK_LOAD_FINGERPRINT} in `beforeSend`, NOT dropped β
* a CDN/deploy that 404s a chunk for everyone still spikes on one issue.
*
* Cannot catch:
* - a third-party `Failed to load script:` (no `/_next/static/` path);
* - UI copy such as `Failed to load evaluators:` (no chunk URL);
* - worker `importScripts` failures (different message family);
* - browser-extension `import()` (extension protocol, already denylisted).
*/
export function isStaleChunkLoadErrorEvent(event: ErrorEvent): boolean {
const text = eventText(event);
if (!text.includes(NEXT_STATIC_CHUNK_PATH)) return false;
return (
text.includes(FAILED_TO_LOAD_SCRIPT_MARKER) ||
text.includes(DYNAMIC_IMPORT_FAILURE_MARKER)
);
}
/**
* PostHog's lazily-loaded session-replay recorder script. Older posthog-js
* served `/static/posthog-recorder.js?v=<version>`; 1.417+ serves
* `/static/<version>/posthog-recorder.js`. Match the filename as a path
* segment so both layouts (and a query string) count.
*/
function isPosthogRecorderFilename(path: string): boolean {
return (
path === "posthog-recorder.js" || path.endsWith("/posthog-recorder.js")
);
}
/**
* Frames that carry no attribution: browser-native/eval frames, and the Sentry
* SDK's own wrapper frames (its `wrap()` helper sits at the outer edge of
* every instrumented listener stack). The `@sentry` path shape only occurs in
* dev / source-mapped stacks β in a prod bundle the wrapper lives in an app
* chunk, which this predicate deliberately does NOT allow (see the coverage
* gap note on {@link isPosthogRecorderInternalEvent}).
*/
function isOpaqueOrSdkFrame(filename: string): boolean {
return (
filename === "<anonymous>" ||
filename === "[native code]" ||
(filename.includes("node_modules") && filename.includes("@sentry"))
);
}
/**
* True for errors thrown wholly INSIDE PostHog's session-replay recorder:
* every attributable stack frame lives in the recorder script (plus at most
* browser-native and Sentry-SDK wrapper frames). rrweb's DOM serialization
* throws on exotic page content (observed: `SyntaxError: Invalid or unexpected
* token` from `processMutations` / `onRRwebEmit`, LANGFUSE-5VY/5VX; later
* `TypeError: string "" is not a function` from `onRRwebEmit` under the
* path-versioned script, LANGFUSE-621/620), and each throw site mints a new
* fingerprint per recorder version. The recorder filename may sit at
* `/static/posthog-recorder.js` or `/static/<version>/posthog-recorder.js`.
*
* Safe to drop: an error thrown by OUR code always carries at least one app
* chunk frame (the throwing frame), which fails this check. Errors with no
* app frame are the vendor recorder failing internally β not a Langfuse app
* bug, and not actionable in Sentry (session replay is best-effort telemetry;
* a broken recorder shows up as missing recordings in PostHog, not here).
* Same posture as the browser-extension `denyUrls` entries, expressed as a
* testable predicate because the crash frame is often `<anonymous>`, which
* `denyUrls` skips inconsistently.
*
* Known coverage gap (deliberate): the `addEventListener`-wrapped variant
* (LANGFUSE-5VY) carries the Sentry SDK's `wrap()` frame, which in a prod
* bundle is an app-chunk filename indistinguishable from app code β those
* events are KEPT. Allowing chunk frames here would risk masking real app
* listener errors, so only the all-recorder shape (LANGFUSE-5VX) is dropped.
*/
export function isPosthogRecorderInternalEvent(event: ErrorEvent): boolean {
const frames = event.exception?.values?.[0]?.stacktrace?.frames;
if (!frames || frames.length === 0) return false;
let sawRecorderFrame = false;
for (const frame of frames) {
const filename = frame?.filename;
// A frame with no filename has no attribution β treat like <anonymous>.
if (typeof filename !== "string" || filename.length === 0) continue;
// Strip query/fragment (older `?v=` layout) before matching the filename.
const path = filename.split(/[?#]/)[0];
if (isPosthogRecorderFilename(path)) {
sawRecorderFrame = true;
continue;
}
if (isOpaqueOrSdkFrame(filename)) continue;
// Any other frame (app chunk, other vendor) β not recorder-internal.
return false;
}
return sawRecorderFrame;
}
/**
* Kitesurf's injected page-world scripts. Served as root-relative paths on our
* origin (`/__ks_user_classic_regular.js`), so `denyUrls` never matches them.
*/
const KITESURF_USER_SCRIPT_RE = /(?:^|\/)__ks_user[^/]*\.js$/i;
const KITESURF_DOM_SHIM_RE = /(?:^|\/)dom-shim\.js$/i;
/**
* Bare `page.js` as Sentry reports Kitesurf's page controller. Must NOT match
* a Next.js `/_next/.../page.js` β basename-only matching is intentional.
*/
function isKitesurfPageControllerFilename(path: string): boolean {
return path === "page.js" || path === "/page.js";
}
function isKitesurfVendorFilename(path: string): boolean {
return KITESURF_USER_SCRIPT_RE.test(path) || KITESURF_DOM_SHIM_RE.test(path);
}
/**
* True for Kitesurf (Cursor / Cloudflare agent-browser) internals that mint
* production Sentry noise without involving Langfuse app code:
*
* 1. Console: `[kitesurf] β¦` via `captureConsoleIntegration` (LANGFUSE-60W).
* Dropped only when the text has no `/_next/` chunk β a wrap of a real
* app listener throw usually quotes our chunk and is KEPT.
* 2. Stack: every attributable frame in `__ks_user_*.js` / `dom-shim.js`
* (plus opaque / bare `page.js` controller frames). Covers
* `ReferenceError: DOMRect is not defined` (LANGFUSE-60Z) and the
* iframe-load `Proxy` TypeError (LANGFUSE-60X).
*
* Unbracketed `kitesurf:` CORS probes are handled by
* {@link NOISE_MESSAGE_PREFIXES} (LANGFUSE-610).
*
* Same posture as {@link isPosthogRecorderInternalEvent}.
*/
export function isKitesurfInternalEvent(event: ErrorEvent): boolean {
const text = eventText(event);
if (text.length > 0) {
const core = coreMessage(text);
if (core.startsWith("[kitesurf]") && !text.includes("/_next/")) {
return true;
}
}
const frames = event.exception?.values?.[0]?.stacktrace?.frames;
if (!frames || frames.length === 0) return false;
let sawKitesurfVendorFrame = false;
for (const stackFrame of frames) {
const filename = stackFrame?.filename;
if (typeof filename !== "string" || filename.length === 0) continue;
const path = filename.split(/[?#]/)[0];
if (isKitesurfVendorFilename(path)) {
sawKitesurfVendorFrame = true;
continue;
}
if (isOpaqueOrSdkFrame(filename)) continue;
// Bare `page.js` is Kitesurf's controller only when a vendor script is
// also on the stack. An all-`page.js` stack is kept.
if (isKitesurfPageControllerFilename(path)) continue;
return false;
}
return sawKitesurfVendorFrame;
}