From 7b8fd175b1f68224cd62d1c33fb50ae309fe3e4c Mon Sep 17 00:00:00 2001 From: Omar Zunic Date: Fri, 13 Nov 2026 09:57:51 +0100 Subject: [PATCH 1/5] feat(web): add browser and server diagnostics A production check found three faults that PostHog could not explain: a minified React error #418 with no component name, a Firefox network error with no request, and a server function that hung for 60 s. - Turn on web vitals with attribution and soft navigations in posthog-js. The client value wins over the project's remote setting. - Add src/client.tsx, the default Start client entry plus an onRecoverableError that captures the error with the component stack, the page language and the Chrome translation flag. - Send a server_fn_slow event from the server function middleware for a call of 1 s or more, also when the call throws. - Send a server_fn_network_error event when the fetch of a server function fails before an answer. The error is rethrown unchanged. --- apps/web/CLAUDE.md | 1 + apps/web/src/client.tsx | 42 +++++++++++++++++ apps/web/src/lib/capture-failure.test.ts | 57 +++++++++++++++++++++++- apps/web/src/lib/capture-failure.ts | 56 ++++++++++++++++++----- apps/web/src/lib/posthog-api.ts | 31 +++++++++++++ apps/web/src/lib/posthog-client.ts | 30 +++++++++++++ apps/web/src/start.ts | 19 ++++++-- docs/domains/deployment.md | 4 +- 8 files changed, 222 insertions(+), 18 deletions(-) create mode 100644 apps/web/src/client.tsx diff --git a/apps/web/CLAUDE.md b/apps/web/CLAUDE.md index e5ef11d0..48caa80f 100644 --- a/apps/web/CLAUDE.md +++ b/apps/web/CLAUDE.md @@ -17,6 +17,7 @@ bun run generate-routes # tsr generate — regenerates routeTree.gen.ts - Outside it: `index.tsx` (a redirect into the workspace; the public pages live in `apps/site`, see `docs/domains/deployment.md`), `login.tsx`, `choose-organization.tsx` (the workspace chooser for a link such as `/:org/settings`; see `docs/domains/authentication.md`), `accept-invite/$invitationId.tsx`, `no-access.tsx`, `device.tsx` (approves a CLI login) and `cli/` (the install scripts and binary downloads). - Server routes: `api/auth/$.ts` (better-auth), `api/login.ts`, `api/mcp-login.ts`, `api/github/setup.ts`, `api/slack/callback.ts`, `api/files/$.ts`, `api/assistant/stream.ts`, `api/mcp/$orgSlug.ts`, `[.]well-known/oauth-*.ts`, `api/v1/projects` + `api/v1/time-entries` (cookie-authed REST reads), and `api/v1/{meta,me,session}`, `api/v1/me/devices` (the mobile app's phone, see `docs/domains/mobile.md`) + `api/v1/orgs/$orgSlug/*` (the CLI's API). `api/v1/openapi[.]json.ts` serves the OpenAPI document that `lib/openapi.ts` builds, and `api-docs.tsx` renders it with Scalar. **A new `api/v1` route needs an entry in `OPERATIONS`** — `lib/openapi.test.ts` fails until the two lists match, and each response schema there is checked against its `@farmer/core/api` type at compile time. That API takes two bearer credentials — a device-flow session token and a personal API token (`fmr_…`, Preferences → API tokens, `components/api-tokens-settings.tsx`); `docs/domains/api-tokens.md` has the rules, including the read-only 403 in `serve` and the `session` scheme that lets `/api-docs` send requests as the signed-in reader (`?org=` on the OpenAPI route; never add CORS headers to `api/v1`). All of that auth lives in `server/api-auth.ts` — deliberately NOT `server/auth.ts`, see the client-bundle rule below. - `reports.tsx` is the shell. Its four tabs — Time, Overtime, Tracking (`compliance`) and Absence — are declared in `components/reports/search.ts` and live in `components/reports/`. `periodSearch` there is shared with the project page. +- `src/client.tsx` — the custom client entry that TanStack Start picks up by name. It is the default entry plus an `onRecoverableError` that captures hydration errors in PostHog (see `docs/domains/deployment.md`). - `src/server/` — thin `createServerFn` wrappers, one file per aggregate, mirroring `services/`. **Auth is attached via middleware** (`sessionMiddleware` / `orgMiddleware` / `orgAdminMiddleware` from `server/auth.ts`), read from the handler's `context` — never by calling `requireOrgContext()` inline, so the protection is part of the function's declared shape. `auth.ts` itself is the only place the bare helpers are called, because route `beforeLoad`s need them. `orgMiddleware` re-checks membership inside its `.server()` callback rather than in a shared helper: a top-level function body in `auth.ts` ships to the browser, so a deferred `import("@farmer/core/services")` there becomes a real client chunk. - `src/queries/` — TanStack Query `queryOptions` factories, one per aggregate; loaders prefetch, components read via `useSuspenseQuery`. **Every key names its organization**: factories take the slug first (`timeEntriesRangeQuery(orgSlug, from, to)`) and spread their root from `queryKeys(orgSlug)` in `queries/keys.ts`; invalidations name the same root. Components get the slug from `useOrgSlug()`, loaders from `params.orgSlug`. Never write a bare `queryKey: ["…"]` literal and never drop the org — an org-blind key is an answer from the previous workspace. Server functions are deliberately NOT generated from a shared declaration — see `docs/adr/0001-no-server-function-generator.md`. - `src/components/ui/` — shadcn on **Base UI** (`@base-ui/react`), not Radix (`components.json` style is `base-nova`). Composition uses the `render` prop, not `asChild`. The project picker (grouped by client) and task picker (grouped by `taskGroup`) are in `components/pickers/`. The task picker leaves out the tasks the person switched off (`pickers/your-tasks.tsx`, also Preferences → Your tasks), search included, except the task already chosen and Recent; its grouped list ends in Edit list. diff --git a/apps/web/src/client.tsx b/apps/web/src/client.tsx new file mode 100644 index 00000000..bf93056e --- /dev/null +++ b/apps/web/src/client.tsx @@ -0,0 +1,42 @@ +import { StartClient } from "@tanstack/react-start/client"; +import posthog from "posthog-js"; +import { StrictMode, startTransition } from "react"; +import { type HydrationOptions, hydrateRoot } from "react-dom/client"; + +const TRANSLATED = ["translated-ltr", "translated-rtl"]; + +/** + * Report an error that React recovered from, such as a hydration mismatch + * (React error #418). The production message names no component, so the + * event holds the component stack. Chrome's page translation edits the DOM + * and the `lang` attribute, so the event says if it was on. + * + * Not `reportError`: React's default handler calls it, and the `error` event + * that it fires is already captured by posthog-js. This handler replaces + * the default, so each error is captured one time. + */ +const onRecoverableError: NonNullable< + HydrationOptions["onRecoverableError"] +> = (error, errorInfo) => { + if (posthog.__loaded) { + const classes = document.documentElement.classList; + posthog.captureException(error, { + react_component_stack: errorInfo.componentStack, + html_lang: document.documentElement.lang, + html_translated: TRANSLATED.some((name) => classes.contains(name)), + pathname: location.pathname, + }); + } + console.error(error); +}; + +// The default entry of TanStack Start, plus `onRecoverableError`. +startTransition(() => { + hydrateRoot( + document, + + + , + { onRecoverableError }, + ); +}); diff --git a/apps/web/src/lib/capture-failure.test.ts b/apps/web/src/lib/capture-failure.test.ts index 8080dfe4..18464b0d 100644 --- a/apps/web/src/lib/capture-failure.test.ts +++ b/apps/web/src/lib/capture-failure.test.ts @@ -1,6 +1,9 @@ -import { describe, expect, test } from "bun:test"; +import { describe, expect, spyOn, test } from "bun:test"; -import { captureFailure } from "./capture-failure"; +import { PostHog } from "posthog-node"; + +import { captureFailure, SLOW_SERVER_FN_MS } from "./capture-failure"; +import * as posthogServer from "./posthog-server"; const run = (error: Error) => captureFailure( @@ -26,3 +29,53 @@ describe("captureFailure", () => { expect(await run(error).catch((e) => e)).toBe(error); }); }); + +describe("slow server functions", () => { + /** Run a call that takes `ms` on a fake clock. Resolves with the events + * that PostHog got, after the background report had time to run. */ + const eventsFor = async (ms: number, fails = false) => { + const client = new PostHog("test-token", { disabled: true }); + const capture = spyOn(client, "capture").mockImplementation(() => {}); + const getClient = spyOn(posthogServer, "getPostHogClient").mockReturnValue( + client, + ); + let clock = 0; + try { + await captureFailure( + { + next: () => { + clock += ms; + return fails ? Promise.reject(new Error("x")) : Promise.resolve(1); + }, + serverFnMeta: { name: "fn", filename: "file.ts" }, + }, + () => new Headers(), + () => clock, + ).catch(() => {}); + // The report is a background task, so give it time to finish. + await Bun.sleep(300); + return capture.mock.calls.map(([message]) => message); + } finally { + getClient.mockRestore(); + } + }; + + test("a fast call sends nothing", async () => { + expect(await eventsFor(SLOW_SERVER_FN_MS - 1)).toEqual([]); + }); + + test("a slow call sends one event", async () => { + const events = await eventsFor(SLOW_SERVER_FN_MS); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ + event: "server_fn_slow", + properties: { server_fn_name: "fn", duration_ms: 1000, threw: false }, + }); + }); + + test("a slow call that throws is reported as one that threw", async () => { + const events = await eventsFor(SLOW_SERVER_FN_MS, true); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ properties: { threw: true } }); + }); +}); diff --git a/apps/web/src/lib/capture-failure.ts b/apps/web/src/lib/capture-failure.ts index f4a7d11d..4d98260f 100644 --- a/apps/web/src/lib/capture-failure.ts +++ b/apps/web/src/lib/capture-failure.ts @@ -6,7 +6,8 @@ * it: it runs after the throw and is never awaited. A failure of the capture * is logged and dropped. Only a fault is captured: see `isServerFnFault`. The * person is read from the session because the middleware runs before - * `orgMiddleware`, so it has no `ctx`. + * `orgMiddleware`, so it has no `ctx`. A call that takes `SLOW_SERVER_FN_MS` + * or more is reported the same way, as a `server_fn_slow` event. * * `start.ts` reaches this module with a deferred `import()` inside the * middleware callback, which TanStack strips from the client bundle. A static @@ -21,10 +22,15 @@ export const captureFailure = async ( serverFnMeta: { name: string; filename: string }; }, readHeaders: () => Headers, + now: () => number = () => performance.now(), ): Promise => { + const start = now(); try { - return await next(); + const result = await next(); + reportIfSlow(now() - start, false, serverFnMeta, readHeaders); + return result; } catch (error) { + reportIfSlow(now() - start, true, serverFnMeta, readHeaders); if (error instanceof Error) { reportInBackground(error, serverFnMeta, readHeaders); } @@ -32,22 +38,50 @@ export const captureFailure = async ( } }; -const reportInBackground = ( - error: Error, - meta: { name: string; filename: string }, +/** A call at or over this duration is sent as a `server_fn_slow` event. */ +export const SLOW_SERVER_FN_MS = 1000; + +type FnMeta = { name: string; filename: string }; + +const logCaptureFailure = (captureError: Error) => + console.error("server function capture failed", captureError); + +/** Run a deferred report. It never throws and nothing awaits it. */ +const inBackground = ( readHeaders: () => Headers, + report: ( + posthogApi: typeof import("./posthog-api"), + headers: Headers, + ) => Promise, ): void => { - const fail = (captureError: Error) => - console.error("server function capture failed", captureError); try { // Read at once, while the request context is current. const headers = readHeaders(); void import("./posthog-api") - .then(({ reportServerFnError }) => - reportServerFnError(error, headers, meta), - ) - .catch(fail); + .then((posthogApi) => report(posthogApi, headers)) + .catch(logCaptureFailure); } catch (captureError) { console.error("server function capture failed", captureError); } }; + +const reportInBackground = ( + error: Error, + meta: FnMeta, + readHeaders: () => Headers, +): void => + inBackground(readHeaders, ({ reportServerFnError }, headers) => + reportServerFnError(error, headers, meta), + ); + +const reportIfSlow = ( + durationMs: number, + threw: boolean, + meta: FnMeta, + readHeaders: () => Headers, +): void => { + if (durationMs < SLOW_SERVER_FN_MS) return; + inBackground(readHeaders, ({ reportSlowServerFn }, headers) => + reportSlowServerFn(headers, meta, { durationMs, threw }), + ); +}; diff --git a/apps/web/src/lib/posthog-api.ts b/apps/web/src/lib/posthog-api.ts index fdaab16b..4dfb49ae 100644 --- a/apps/web/src/lib/posthog-api.ts +++ b/apps/web/src/lib/posthog-api.ts @@ -210,6 +210,37 @@ export const reportServerFnError = async ( }); }; +/** + * Report a server function that took long, whether it threw or not. + * + * The caller does not await this and checks the threshold. The person comes + * from the session, as in `reportServerFnError`. + */ +export const reportSlowServerFn = async ( + headers: Headers, + fn: { name: string; filename: string }, + call: { durationMs: number; threw: boolean }, +): Promise => { + const { auth } = await import("@farmer/core/auth"); + const session = await auth.api.getSession({ headers }).catch(() => null); + const userId = session?.user.id ?? null; + const properties = { + organization_id: session?.session.activeOrganizationId ?? null, + server_fn_name: fn.name, + server_fn_file: fn.filename, + duration_ms: Math.round(call.durationMs), + threw: call.threw, + }; + getPostHogClient()?.capture({ + distinctId: userId ?? "server-fn-anonymous", + event: "server_fn_slow", + // No person to attach to: do not mint a profile for the bucket id. + properties: userId + ? properties + : { ...properties, $process_person_profile: false }, + }); +}; + /** A server function that failed with an error not worded for the person. * The properties name the function, never its input. Scrubbed as * `captureApiFailure` is. */ diff --git a/apps/web/src/lib/posthog-client.ts b/apps/web/src/lib/posthog-client.ts index cbcccb9d..c5f75e23 100644 --- a/apps/web/src/lib/posthog-client.ts +++ b/apps/web/src/lib/posthog-client.ts @@ -44,6 +44,15 @@ export function startPostHog({ capture_unhandled_rejections: true, capture_console_errors: false, }, + // A client value wins over the project's remote setting, so vitals are + // on here for every project. Attribution names the element behind a + // slow LCP, INP or CLS. Soft navigations make each router change its + // own measurement (Chrome only; other browsers measure the page load). + capture_performance: { + web_vitals: true, + web_vitals_attribution: true, + __preview_web_vitals_soft_navs: true, + }, before_send: (event) => event && isResizeObserverLoop(event) ? null : event, debug: import.meta.env.DEV, @@ -56,3 +65,24 @@ export function startPostHog({ } return posthog; } + +/** + * Report a server function call that never got an answer. + * + * `fetch` rejects with a `TypeError` when the network fails (Firefox: "NetworkError when + * attempting to fetch resource", Chrome: "Failed to fetch"). The error has + * no URL, so the event names the function. It is a plain event, not an + * exception, because the same rejection can reach the unhandled-rejection + * capture too. The caller rethrows the error. + */ +export function reportServerFnNetworkError( + error: TypeError, + serverFnName: string, +): void { + if (!posthog.__loaded) return; + posthog.capture("server_fn_network_error", { + server_fn_name: serverFnName, + message: error.message, + online: navigator.onLine, + }); +} diff --git a/apps/web/src/start.ts b/apps/web/src/start.ts index 4a5500d9..16efd3bb 100644 --- a/apps/web/src/start.ts +++ b/apps/web/src/start.ts @@ -4,6 +4,8 @@ import { createStart, } from "@tanstack/react-start"; +import { reportServerFnNetworkError } from "./lib/posthog-client"; + /** * Bring the instance's settings up to date before any handler reads one. * @@ -72,8 +74,18 @@ const passThrough = ({ next }: { next: () => Promise }) => next(); // Both server-only imports stay inside this callback: TanStack strips it from // the client bundle, and a top-level import is not stripped. -const captureFailureMiddleware = createMiddleware({ type: "function" }).server( - async (args) => { +const captureFailureMiddleware = createMiddleware({ type: "function" }) + .client(async ({ next, serverFnMeta }) => { + try { + return await next(); + } catch (error) { + if (error instanceof TypeError) { + reportServerFnNetworkError(error, serverFnMeta.id); + } + throw error; + } + }) + .server(async (args) => { // A failed import must not fail the call: the call then runs uncaptured. const modules = await Promise.all([ import("@tanstack/react-start/server"), @@ -85,8 +97,7 @@ const captureFailureMiddleware = createMiddleware({ type: "function" }).server( if (!modules) return passThrough(args); const [{ getRequestHeaders }, { captureFailure }] = modules; return captureFailure(args, getRequestHeaders); - }, -); + }); export const startInstance = createStart(() => ({ requestMiddleware: [csrfMiddleware, instanceSettingsMiddleware], diff --git a/docs/domains/deployment.md b/docs/domains/deployment.md index 1a7a82cf..b79e1abc 100644 --- a/docs/domains/deployment.md +++ b/docs/domains/deployment.md @@ -28,7 +28,9 @@ Each job is env-gated by `_ENABLED` / `_INTERVAL_MINUTES`; the full **Impersonation is not configured here.** The platform admin role — who may become any user in any workspace — is a database value, granted to the instance's first account and passed on from inside the product. There is no environment variable for it, deliberately; see `docs/domains/authentication.md`. -**PostHog's BROWSER half is the part that catches people out.** `POSTHOG_PROJECT_TOKEN` and `POSTHOG_HOST` are instance settings, not `VITE_` variables: `vite build` runs inside the Docker image, so a `VITE_` value could only ever be what CI was given. The server reads them per request (`lib/posthog-server.ts`, one client kept per token and host and rebuilt when either changes, null when either is missing) and `routes/__root.tsx` writes the pair into the inline `` script beside the theme, for the browser to read back off `window`. Not through `getPublicAppConfig`, which is a server FUNCTION: the root route has no loader to call one from, and `RootDocument` is the `shellComponent`, which renders on the error and not-found paths where no loader has run. `POSTHOG_AI_CAPTURE_CONTENT` (default `false`) is the one switch for whether an agent's content — the assistant's prompts and answers, and the MCP server's tool arguments and results — leaves the process at all. The metadata goes either way and is what the dashboards are built on; the content is a customer's timesheet, so on a multi-tenant deployment sending it is a decision an operator makes rather than inherits. Six adapters read that one client and nothing else does: `lib/posthog-ai.ts` (the assistant's turns), `lib/posthog-mcp.ts` (the MCP server's requests), `lib/posthog-api.ts` (the REST API's requests and failures, and the faults of server functions), `lib/posthog-jobs.ts` (a failure a background job caught and went on from, through `jobs/job-failures.ts`; the standalone worker installs no sink), `lib/posthog-impersonation.ts` (the impersonation ledger, see `docs/domains/authentication.md`) and the `capture` calls in `server/*.ts` (what a person did in the browser). +**PostHog's BROWSER half is the part that catches people out.** `POSTHOG_PROJECT_TOKEN` and `POSTHOG_HOST` are instance settings, not `VITE_` variables: `vite build` runs inside the Docker image, so a `VITE_` value could only ever be what CI was given. The server reads them per request (`lib/posthog-server.ts`, one client kept per token and host and rebuilt when either changes, null when either is missing) and `routes/__root.tsx` writes the pair into the inline `` script beside the theme, for the browser to read back off `window`. Not through `getPublicAppConfig`, which is a server FUNCTION: the root route has no loader to call one from, and `RootDocument` is the `shellComponent`, which renders on the error and not-found paths where no loader has run. `POSTHOG_AI_CAPTURE_CONTENT` (default `false`) is the one switch for whether an agent's content — the assistant's prompts and answers, and the MCP server's tool arguments and results — leaves the process at all. The metadata goes either way and is what the dashboards are built on; the content is a customer's timesheet, so on a multi-tenant deployment sending it is a decision an operator makes rather than inherits. Six adapters read that one client and nothing else does: `lib/posthog-ai.ts` (the assistant's turns), `lib/posthog-mcp.ts` (the MCP server's requests), `lib/posthog-api.ts` (the REST API's requests and failures, and the faults of server functions), `lib/posthog-jobs.ts` (a failure a background job caught and went on from, through `jobs/job-failures.ts`; the standalone worker installs no sink), `lib/posthog-impersonation.ts` (the impersonation ledger, see `docs/domains/authentication.md`) and the `capture` calls in `server/*.ts` (what a person did in the browser). `lib/posthog-api.ts` also sends `server_fn_slow` for a server function that takes `SLOW_SERVER_FN_MS` (1 second) or more, whether it threw or not. + +**The browser sends diagnostics too.** `lib/posthog-client.ts` turns on web vitals with attribution and soft navigations (`capture_performance`), and the client value wins over the project's remote setting. The proxy forwards the lazy `/static/web-vitals*.js` script as any other `/static/` path. `src/client.tsx` replaces TanStack Start's default client entry to capture the errors that React recovers from (a hydration mismatch, React error #418) with the component stack, the page language and whether Chrome's page translation was on. The function middleware in `start.ts` also sends a `server_fn_network_error` event when the browser's `fetch` of a server function fails before any answer. **The browser does not talk to PostHog directly.** It sends its events to `/api/k7v2q9` on the app's own origin. The server route `routes/api/k7v2q9/$.ts` forwards them to `POSTHOG_HOST`, and forwards `/static/` and `/array/` paths to the PostHog assets host. An ad blocker that blocks the PostHog domains then does not drop the events. The prefix is a fixed random word on purpose: block lists match words such as "ingest". The proxy is a route, not code in `server.ts`, so it reads fresh instance settings. It forwards only the paths that posthog-js requests, with a 10 second timeout and a 5 MB body limit, because a self-hosted `POSTHOG_HOST` can be on a private network. PostHog takes the GeoIP address from the request, so the route sends the client address as `X-Forwarded-For`. Set `TRUSTED_IP_HEADER`, or every event has the address of the proxy in front of the app. From d92ff903629a382a385a3bba0f08d2bd3ce6ecd3 Mon Sep 17 00:00:00 2001 From: Omar Zunic Date: Fri, 13 Nov 2026 09:59:36 +0100 Subject: [PATCH 2/5] fix(web): limit web vitals attribution to INP and LCP The posthog-js default already attributes INP and LCP only. CLS attribution keeps detached DOM nodes and can leak memory in an SPA, so the explicit value true is removed and a comment says why. --- apps/web/src/lib/posthog-client.ts | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/apps/web/src/lib/posthog-client.ts b/apps/web/src/lib/posthog-client.ts index c5f75e23..acaa8e55 100644 --- a/apps/web/src/lib/posthog-client.ts +++ b/apps/web/src/lib/posthog-client.ts @@ -45,12 +45,13 @@ export function startPostHog({ capture_console_errors: false, }, // A client value wins over the project's remote setting, so vitals are - // on here for every project. Attribution names the element behind a - // slow LCP, INP or CLS. Soft navigations make each router change its - // own measurement (Chrome only; other browsers measure the page load). + // on here for every project. The default attribution (INP and LCP) names + // the element behind a slow metric. CLS stays out, because its + // attribution keeps detached DOM nodes and can leak memory in an SPA. + // Soft navigations make each router change its own measurement + // (Chrome only; other browsers measure the page load). capture_performance: { web_vitals: true, - web_vitals_attribution: true, __preview_web_vitals_soft_navs: true, }, before_send: (event) => @@ -69,9 +70,9 @@ export function startPostHog({ /** * Report a server function call that never got an answer. * - * `fetch` rejects with a `TypeError` when the network fails (Firefox: "NetworkError when - * attempting to fetch resource", Chrome: "Failed to fetch"). The error has - * no URL, so the event names the function. It is a plain event, not an + * `fetch` rejects with a `TypeError` when the network fails (Firefox: + * "NetworkError when attempting to fetch resource", Chrome: "Failed to + * fetch"). The error has no URL, so the event names the function. It is a plain event, not an * exception, because the same rejection can reach the unhandled-rejection * capture too. The caller rethrows the error. */ From 090284e38d14e623702a00df8485c946ba6c3911 Mon Sep 17 00:00:00 2001 From: Omar Zunic Date: Fri, 13 Nov 2026 10:18:02 +0100 Subject: [PATCH 3/5] fix(web): report only fetch failures as network errors The client middleware caught any TypeError from next(). That also matched a TypeError that a handler threw on the server, which TanStack sends back and throws again, and it missed a 502 with an HTML body. - Wrap the fetch of the server function and pass it through next(). Only a rejection of the fetch itself sends the event. The error is rethrown unchanged. - Name the client event property server_fn_id, because the value is the hash. Add the same property to server_fn_slow so that the events join. - Read the session one time for a call, for the error report and the slow report together. One request sends one slow event. - Remove the clock parameter of captureFailure. The test controls performance.now and waits on a condition, not on a fixed time. - Add tests for the client fetch wrapper. --- apps/web/src/lib/capture-failure.test.ts | 100 +++++++++++++------ apps/web/src/lib/capture-failure.ts | 79 ++++++--------- apps/web/src/lib/posthog-api.ts | 118 ++++++++++++++++------- apps/web/src/lib/posthog-client.test.ts | 51 ++++++++++ apps/web/src/lib/posthog-client.ts | 42 +++++--- apps/web/src/start.ts | 15 +-- 6 files changed, 266 insertions(+), 139 deletions(-) create mode 100644 apps/web/src/lib/posthog-client.test.ts diff --git a/apps/web/src/lib/capture-failure.test.ts b/apps/web/src/lib/capture-failure.test.ts index 18464b0d..3350da5b 100644 --- a/apps/web/src/lib/capture-failure.test.ts +++ b/apps/web/src/lib/capture-failure.test.ts @@ -5,11 +5,13 @@ import { PostHog } from "posthog-node"; import { captureFailure, SLOW_SERVER_FN_MS } from "./capture-failure"; import * as posthogServer from "./posthog-server"; +const META = { id: "abc", name: "fn", filename: "file.ts" }; + const run = (error: Error) => captureFailure( { next: () => Promise.reject(error), - serverFnMeta: { name: "fn", filename: "file.ts" }, + serverFnMeta: META, }, // No request here: the capture fails, and the error must still come out. () => { @@ -31,15 +33,13 @@ describe("captureFailure", () => { }); describe("slow server functions", () => { - /** Run a call that takes `ms` on a fake clock. Resolves with the events - * that PostHog got, after the background report had time to run. */ - const eventsFor = async (ms: number, fails = false) => { - const client = new PostHog("test-token", { disabled: true }); - const capture = spyOn(client, "capture").mockImplementation(() => {}); - const getClient = spyOn(posthogServer, "getPostHogClient").mockReturnValue( - client, - ); + const client = new PostHog("test-token", { disabled: true }); + const capture = spyOn(client, "capture").mockImplementation(() => {}); + + /** Run a call that takes `ms` on a fake clock, with the request `headers`. */ + const call = async (ms: number, headers: Headers, fails = false) => { let clock = 0; + const now = spyOn(performance, "now").mockImplementation(() => clock); try { await captureFailure( { @@ -47,35 +47,73 @@ describe("slow server functions", () => { clock += ms; return fails ? Promise.reject(new Error("x")) : Promise.resolve(1); }, - serverFnMeta: { name: "fn", filename: "file.ts" }, + serverFnMeta: META, }, - () => new Headers(), - () => clock, + () => headers, ).catch(() => {}); - // The report is a background task, so give it time to finish. - await Bun.sleep(300); - return capture.mock.calls.map(([message]) => message); + } finally { + now.mockRestore(); + } + }; + + const events = () => capture.mock.calls.map(([message]) => message); + + /** The report is a background task: wait until PostHog got an event of + * this duration. Reports run in call order, so earlier ones are in. */ + const waitForEventOf = async (durationMs: number) => { + const deadline = Date.now() + 5000; + while ( + !events().some((e) => e.properties?.duration_ms === durationMs) && + Date.now() < deadline + ) { + await Bun.sleep(5); + } + return events(); + }; + + const withClient = async (run: () => Promise) => { + capture.mockClear(); + const getClient = spyOn(posthogServer, "getPostHogClient").mockReturnValue( + client, + ); + try { + await run(); } finally { getClient.mockRestore(); } }; - test("a fast call sends nothing", async () => { - expect(await eventsFor(SLOW_SERVER_FN_MS - 1)).toEqual([]); - }); + test("a fast call sends nothing and a slow call sends one event", () => + withClient(async () => { + await call(SLOW_SERVER_FN_MS - 1, new Headers()); + await call(SLOW_SERVER_FN_MS, new Headers()); + const sent = await waitForEventOf(SLOW_SERVER_FN_MS); + expect(sent).toHaveLength(1); + expect(sent[0]).toMatchObject({ + event: "server_fn_slow", + properties: { + server_fn_id: "abc", + server_fn_name: "fn", + duration_ms: SLOW_SERVER_FN_MS, + threw: false, + }, + }); + })); - test("a slow call sends one event", async () => { - const events = await eventsFor(SLOW_SERVER_FN_MS); - expect(events).toHaveLength(1); - expect(events[0]).toMatchObject({ - event: "server_fn_slow", - properties: { server_fn_name: "fn", duration_ms: 1000, threw: false }, - }); - }); + test("a slow call that throws is reported as one that threw", () => + withClient(async () => { + await call(SLOW_SERVER_FN_MS, new Headers(), true); + const sent = await waitForEventOf(SLOW_SERVER_FN_MS); + expect(sent).toMatchObject([{ properties: { threw: true } }]); + })); - test("a slow call that throws is reported as one that threw", async () => { - const events = await eventsFor(SLOW_SERVER_FN_MS, true); - expect(events).toHaveLength(1); - expect(events[0]).toMatchObject({ properties: { threw: true } }); - }); + test("two slow calls of one request send one event", () => + withClient(async () => { + const headers = new Headers(); + await call(SLOW_SERVER_FN_MS, headers); + await call(SLOW_SERVER_FN_MS, headers); + // Another request gets its own event. + await call(2 * SLOW_SERVER_FN_MS, new Headers()); + expect(await waitForEventOf(2 * SLOW_SERVER_FN_MS)).toHaveLength(2); + })); }); diff --git a/apps/web/src/lib/capture-failure.ts b/apps/web/src/lib/capture-failure.ts index 4d98260f..2335278a 100644 --- a/apps/web/src/lib/capture-failure.ts +++ b/apps/web/src/lib/capture-failure.ts @@ -1,3 +1,5 @@ +import type { ServerFnCall } from "./posthog-api"; + /** * Send the unexpected failure of a server function to PostHog error tracking. * @@ -7,7 +9,8 @@ * is logged and dropped. Only a fault is captured: see `isServerFnFault`. The * person is read from the session because the middleware runs before * `orgMiddleware`, so it has no `ctx`. A call that takes `SLOW_SERVER_FN_MS` - * or more is reported the same way, as a `server_fn_slow` event. + * or more is reported in the same way, as a `server_fn_slow` event, also + * when it throws. * * `start.ts` reaches this module with a deferred `import()` inside the * middleware callback, which TanStack strips from the client bundle. A static @@ -19,69 +22,51 @@ export const captureFailure = async ( serverFnMeta, }: { next: () => Promise; - serverFnMeta: { name: string; filename: string }; + serverFnMeta: { id: string; name: string; filename: string }; }, readHeaders: () => Headers, - now: () => number = () => performance.now(), ): Promise => { - const start = now(); + const start = performance.now(); + let error: Error | null = null; + let threw = false; try { - const result = await next(); - reportIfSlow(now() - start, false, serverFnMeta, readHeaders); - return result; - } catch (error) { - reportIfSlow(now() - start, true, serverFnMeta, readHeaders); - if (error instanceof Error) { - reportInBackground(error, serverFnMeta, readHeaders); - } - throw error; + return await next(); + } catch (thrown) { + threw = true; + if (thrown instanceof Error) error = thrown; + throw thrown; + } finally { + const durationMs = performance.now() - start; + reportInBackground( + { + error, + threw, + slowMs: durationMs >= SLOW_SERVER_FN_MS ? durationMs : null, + }, + serverFnMeta, + readHeaders, + ); } }; /** A call at or over this duration is sent as a `server_fn_slow` event. */ export const SLOW_SERVER_FN_MS = 1000; -type FnMeta = { name: string; filename: string }; - -const logCaptureFailure = (captureError: Error) => - console.error("server function capture failed", captureError); - -/** Run a deferred report. It never throws and nothing awaits it. */ -const inBackground = ( +const reportInBackground = ( + call: ServerFnCall, + meta: { id: string; name: string; filename: string }, readHeaders: () => Headers, - report: ( - posthogApi: typeof import("./posthog-api"), - headers: Headers, - ) => Promise, ): void => { + if (!call.error && call.slowMs === null) return; + const fail = (captureError: Error) => + console.error("server function capture failed", captureError); try { // Read at once, while the request context is current. const headers = readHeaders(); void import("./posthog-api") - .then((posthogApi) => report(posthogApi, headers)) - .catch(logCaptureFailure); + .then(({ reportServerFnCall }) => reportServerFnCall(headers, meta, call)) + .catch(fail); } catch (captureError) { console.error("server function capture failed", captureError); } }; - -const reportInBackground = ( - error: Error, - meta: FnMeta, - readHeaders: () => Headers, -): void => - inBackground(readHeaders, ({ reportServerFnError }, headers) => - reportServerFnError(error, headers, meta), - ); - -const reportIfSlow = ( - durationMs: number, - threw: boolean, - meta: FnMeta, - readHeaders: () => Headers, -): void => { - if (durationMs < SLOW_SERVER_FN_MS) return; - inBackground(readHeaders, ({ reportSlowServerFn }, headers) => - reportSlowServerFn(headers, meta, { durationMs, threw }), - ); -}; diff --git a/apps/web/src/lib/posthog-api.ts b/apps/web/src/lib/posthog-api.ts index 4dfb49ae..55155aab 100644 --- a/apps/web/src/lib/posthog-api.ts +++ b/apps/web/src/lib/posthog-api.ts @@ -184,58 +184,104 @@ export const claimServerFnError = (error: Error): boolean => { return true; }; -/** - * Report the error of a server function, if it is a fault. - * - * The caller does not await this: a metric must not delay the answer, and - * the session lookup is one more query on a pool that may be the fault. The - * claim comes first and runs before any `await`, so the inner and the outer - * middleware of a nested call cannot both pass it. `headers` are read by the - * caller, while the request context is still current. - */ -export const reportServerFnError = async ( - error: Error, - headers: Headers, - fn: { name: string; filename: string }, -): Promise => { - if (!claimServerFnError(error)) return; - if (!(await isServerFnFault(error))) return; +export type ServerFnCall = { + /** The error that the call threw, if it is an `Error`. */ + error: Error | null; + /** The duration of a call at or over the slow threshold, else null. */ + slowMs: number | null; + threw: boolean; +}; + +const slowReported = new WeakSet(); + +/** The error, when this call is the first to report it and it is a fault. */ +const claimFault = async (error: Error | null): Promise => { + if (!error || !claimServerFnError(error)) return null; + return (await isServerFnFault(error)) ? error : null; +}; + +/** The duration, when this request has not sent a slow event yet. */ +const claimSlow = (headers: Headers, slowMs: number | null): number | null => { + if (slowMs === null || slowReported.has(headers)) return null; + slowReported.add(headers); + return slowMs; +}; + +const sessionPerson = async (headers: Headers) => { const { auth } = await import("@farmer/core/auth"); const session = await auth.api.getSession({ headers }).catch(() => null); - captureServerFnFailure(error, { + return { userId: session?.user.id ?? null, organizationId: session?.session.activeOrganizationId ?? null, - fn: fn.name, - file: fn.filename, - }); + }; }; /** - * Report a server function that took long, whether it threw or not. + * Report a server function call: its error, if it is a fault, and its + * duration, if it is slow. * - * The caller does not await this and checks the threshold. The person comes - * from the session, as in `reportServerFnError`. + * The caller does not await this: a metric must not delay the answer, and + * the session lookup is one more query on a pool that may be the fault, so + * it runs one time for both reports and only when one of them is due. The + * claims come first and run before any `await`, so the inner and the outer + * middleware of a nested call cannot both pass them. A request sends one + * slow event: its `headers` are the same object in a nested call. `headers` + * are read by the caller, while the request context is still current. */ -export const reportSlowServerFn = async ( +export const reportServerFnCall = async ( headers: Headers, - fn: { name: string; filename: string }, - call: { durationMs: number; threw: boolean }, + fn: { id: string; name: string; filename: string }, + call: ServerFnCall, ): Promise => { - const { auth } = await import("@farmer/core/auth"); - const session = await auth.api.getSession({ headers }).catch(() => null); - const userId = session?.user.id ?? null; + // Both claims start before the first `await`. + const pendingFault = claimFault(call.error); + const slowMs = claimSlow(headers, call.slowMs); + const fault = await pendingFault; + if (!fault && slowMs === null) return; + const person = await sessionPerson(headers); + if (fault) { + captureServerFnFailure(fault, { + ...person, + fn: fn.name, + file: fn.filename, + }); + } + if (slowMs !== null) { + captureSlowServerFn({ + ...person, + id: fn.id, + fn: fn.name, + file: fn.filename, + durationMs: slowMs, + threw: call.threw, + }); + } +}; + +/** A server function that took long. The properties name the function, + * never its input. */ +export const captureSlowServerFn = (ctx: { + userId: string | null; + organizationId: string | null; + id: string; + fn: string; + file: string; + durationMs: number; + threw: boolean; +}): void => { const properties = { - organization_id: session?.session.activeOrganizationId ?? null, - server_fn_name: fn.name, - server_fn_file: fn.filename, - duration_ms: Math.round(call.durationMs), - threw: call.threw, + organization_id: ctx.organizationId, + server_fn_id: ctx.id, + server_fn_name: ctx.fn, + server_fn_file: ctx.file, + duration_ms: Math.round(ctx.durationMs), + threw: ctx.threw, }; getPostHogClient()?.capture({ - distinctId: userId ?? "server-fn-anonymous", + distinctId: ctx.userId ?? "server-fn-anonymous", event: "server_fn_slow", // No person to attach to: do not mint a profile for the bucket id. - properties: userId + properties: ctx.userId ? properties : { ...properties, $process_person_profile: false }, }); diff --git a/apps/web/src/lib/posthog-client.test.ts b/apps/web/src/lib/posthog-client.test.ts new file mode 100644 index 00000000..4ca79709 --- /dev/null +++ b/apps/web/src/lib/posthog-client.test.ts @@ -0,0 +1,51 @@ +import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; + +import posthog from "posthog-js"; + +import { fetchReportingNetworkErrors } from "./posthog-client"; + +describe("fetchReportingNetworkErrors", () => { + const capture = spyOn(posthog, "capture").mockImplementation(() => undefined); + + beforeEach(() => { + capture.mockClear(); + posthog.__loaded = true; + }); + afterEach(() => { + posthog.__loaded = false; + }); + + const callWith = (base: () => Promise) => + fetchReportingNetworkErrors( + "abc", + base, + )("/_serverFn/abc").then( + (response) => response, + (error: Error) => error, + ); + + test("a fetch that rejects sends one event and rethrows the same error", async () => { + const error = new TypeError("NetworkError when attempting to fetch"); + + expect(await callWith(() => Promise.reject(error))).toBe(error); + expect(capture).toHaveBeenCalledTimes(1); + expect(capture.mock.calls[0]?.[0]).toBe("server_fn_network_error"); + expect(capture.mock.calls[0]?.[1]).toMatchObject({ server_fn_id: "abc" }); + }); + + // A TypeError that a handler threw on the server comes back the same way: + // as an answer that TanStack turns into an error after the fetch resolved. + test("an error answer is returned and sends nothing", async () => { + const answer = new Response("Bad gateway", { status: 502 }); + + expect(await callWith(() => Promise.resolve(answer))).toBe(answer); + expect(capture).not.toHaveBeenCalled(); + }); + + test("an aborted fetch sends nothing", async () => { + const abort = new DOMException("aborted", "AbortError"); + + expect(await callWith(() => Promise.reject(abort))).toBe(abort); + expect(capture).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/src/lib/posthog-client.ts b/apps/web/src/lib/posthog-client.ts index acaa8e55..1a37b595 100644 --- a/apps/web/src/lib/posthog-client.ts +++ b/apps/web/src/lib/posthog-client.ts @@ -67,23 +67,37 @@ export function startPostHog({ return posthog; } +/** The call signature of `fetch`, as TanStack's `CustomFetch` has it. */ +type FetchFn = (...args: Parameters) => ReturnType; + /** - * Report a server function call that never got an answer. + * A `fetch` that reports a server function call that got no answer. * * `fetch` rejects with a `TypeError` when the network fails (Firefox: * "NetworkError when attempting to fetch resource", Chrome: "Failed to - * fetch"). The error has no URL, so the event names the function. It is a plain event, not an - * exception, because the same rejection can reach the unhandled-rejection - * capture too. The caller rethrows the error. + * fetch"). The error has no URL, so the event names the function by its id, + * which the server build maps to a name. It wraps the `fetch` itself, not + * the call of the function: a `TypeError` that a handler threw on the server, + * and a non-2xx answer, are not network failures. The event is a plain + * event, not an exception, because the same rejection can reach the + * unhandled-rejection capture too. The error is rethrown unchanged. */ -export function reportServerFnNetworkError( - error: TypeError, - serverFnName: string, -): void { - if (!posthog.__loaded) return; - posthog.capture("server_fn_network_error", { - server_fn_name: serverFnName, - message: error.message, - online: navigator.onLine, - }); +export function fetchReportingNetworkErrors( + serverFnId: string, + baseFetch: FetchFn = globalThis.fetch, +): FetchFn { + return async (input, init) => { + try { + return await baseFetch(input, init); + } catch (error) { + if (error instanceof TypeError && posthog.__loaded) { + posthog.capture("server_fn_network_error", { + server_fn_id: serverFnId, + message: error.message, + online: navigator.onLine, + }); + } + throw error; + } + }; } diff --git a/apps/web/src/start.ts b/apps/web/src/start.ts index 16efd3bb..fe0c095e 100644 --- a/apps/web/src/start.ts +++ b/apps/web/src/start.ts @@ -4,7 +4,7 @@ import { createStart, } from "@tanstack/react-start"; -import { reportServerFnNetworkError } from "./lib/posthog-client"; +import { fetchReportingNetworkErrors } from "./lib/posthog-client"; /** * Bring the instance's settings up to date before any handler reads one. @@ -75,16 +75,9 @@ const passThrough = ({ next }: { next: () => Promise }) => next(); // Both server-only imports stay inside this callback: TanStack strips it from // the client bundle, and a top-level import is not stripped. const captureFailureMiddleware = createMiddleware({ type: "function" }) - .client(async ({ next, serverFnMeta }) => { - try { - return await next(); - } catch (error) { - if (error instanceof TypeError) { - reportServerFnNetworkError(error, serverFnMeta.id); - } - throw error; - } - }) + .client(({ next, serverFnMeta, fetch }) => + next({ fetch: fetchReportingNetworkErrors(serverFnMeta.id, fetch) }), + ) .server(async (args) => { // A failed import must not fail the call: the call then runs uncaptured. const modules = await Promise.all([ From b5fe11843010d91c6d8a807651f4a03b0638a453 Mon Sep 17 00:00:00 2001 From: Omar Zunic Date: Tue, 17 Nov 2026 13:06:17 +0100 Subject: [PATCH 4/5] fix(web): report hung server calls The slow report was sent from a finally block, so a call that never ended sent nothing. This hid the 60 s enterOrganization hang. Send server_fn_slow with pending: true when a call is still pending after 10 s. Clear the timer when the call ends. Do not send a second slow report for the same call at the end. --- apps/web/src/lib/capture-failure.test.ts | 32 ++++++++++++++++++++++++ apps/web/src/lib/capture-failure.ts | 25 ++++++++++++++++-- apps/web/src/lib/posthog-api.ts | 5 ++++ 3 files changed, 60 insertions(+), 2 deletions(-) diff --git a/apps/web/src/lib/capture-failure.test.ts b/apps/web/src/lib/capture-failure.test.ts index 3350da5b..77701311 100644 --- a/apps/web/src/lib/capture-failure.test.ts +++ b/apps/web/src/lib/capture-failure.test.ts @@ -107,6 +107,38 @@ describe("slow server functions", () => { expect(sent).toMatchObject([{ properties: { threw: true } }]); })); + /** A call that ends after `endMs` real time; the pending mark is `markMs`. */ + const lateCall = async (markMs: number, endMs: number, headers: Headers) => { + await captureFailure( + { + next: () => Bun.sleep(endMs).then(() => 1), + serverFnMeta: META, + }, + () => headers, + markMs, + ); + }; + + test("a call still pending at the mark sends one pending event", () => + withClient(async () => { + await lateCall(10, 60, new Headers()); + const sent = await waitForEventOf(10); + // The finish of the same call sends no second event. + await Bun.sleep(50); + expect(events()).toHaveLength(1); + expect(sent[0]).toMatchObject({ + event: "server_fn_slow", + properties: { server_fn_id: "abc", duration_ms: 10, pending: true }, + }); + })); + + test("a call that ends before the mark sends no pending event", () => + withClient(async () => { + await lateCall(50, 1, new Headers()); + await Bun.sleep(100); + expect(events()).toHaveLength(0); + })); + test("two slow calls of one request send one event", () => withClient(async () => { const headers = new Headers(); diff --git a/apps/web/src/lib/capture-failure.ts b/apps/web/src/lib/capture-failure.ts index 2335278a..2eb76e3c 100644 --- a/apps/web/src/lib/capture-failure.ts +++ b/apps/web/src/lib/capture-failure.ts @@ -10,7 +10,8 @@ import type { ServerFnCall } from "./posthog-api"; * person is read from the session because the middleware runs before * `orgMiddleware`, so it has no `ctx`. A call that takes `SLOW_SERVER_FN_MS` * or more is reported in the same way, as a `server_fn_slow` event, also - * when it throws. + * when it throws. A call still pending at `PENDING_SERVER_FN_MS` is reported + * then, with `pending: true`, and not again when it ends. * * `start.ts` reaches this module with a deferred `import()` inside the * middleware callback, which TanStack strips from the client bundle. A static @@ -25,10 +26,22 @@ export const captureFailure = async ( serverFnMeta: { id: string; name: string; filename: string }; }, readHeaders: () => Headers, + pendingMs: number = PENDING_SERVER_FN_MS, ): Promise => { const start = performance.now(); let error: Error | null = null; let threw = false; + let pendingReported = false; + // A call that never ends sends no report from `finally`, so report it here. + const timer = setTimeout(() => { + pendingReported = true; + reportInBackground( + { error: null, threw: false, slowMs: pendingMs, pending: true }, + serverFnMeta, + readHeaders, + ); + }, pendingMs); + timer.unref(); try { return await next(); } catch (thrown) { @@ -36,12 +49,17 @@ export const captureFailure = async ( if (thrown instanceof Error) error = thrown; throw thrown; } finally { + clearTimeout(timer); const durationMs = performance.now() - start; reportInBackground( { error, threw, - slowMs: durationMs >= SLOW_SERVER_FN_MS ? durationMs : null, + slowMs: + !pendingReported && durationMs >= SLOW_SERVER_FN_MS + ? durationMs + : null, + pending: false, }, serverFnMeta, readHeaders, @@ -52,6 +70,9 @@ export const captureFailure = async ( /** A call at or over this duration is sent as a `server_fn_slow` event. */ export const SLOW_SERVER_FN_MS = 1000; +/** A call still pending at this mark is sent as a `server_fn_slow` event. */ +export const PENDING_SERVER_FN_MS = 10_000; + const reportInBackground = ( call: ServerFnCall, meta: { id: string; name: string; filename: string }, diff --git a/apps/web/src/lib/posthog-api.ts b/apps/web/src/lib/posthog-api.ts index 55155aab..9661892c 100644 --- a/apps/web/src/lib/posthog-api.ts +++ b/apps/web/src/lib/posthog-api.ts @@ -190,6 +190,8 @@ export type ServerFnCall = { /** The duration of a call at or over the slow threshold, else null. */ slowMs: number | null; threw: boolean; + /** The call had not ended when it was reported. */ + pending: boolean; }; const slowReported = new WeakSet(); @@ -254,6 +256,7 @@ export const reportServerFnCall = async ( file: fn.filename, durationMs: slowMs, threw: call.threw, + pending: call.pending, }); } }; @@ -268,6 +271,7 @@ export const captureSlowServerFn = (ctx: { file: string; durationMs: number; threw: boolean; + pending: boolean; }): void => { const properties = { organization_id: ctx.organizationId, @@ -276,6 +280,7 @@ export const captureSlowServerFn = (ctx: { server_fn_file: ctx.file, duration_ms: Math.round(ctx.durationMs), threw: ctx.threw, + pending: ctx.pending, }; getPostHogClient()?.capture({ distinctId: ctx.userId ?? "server-fn-anonymous", From 1a9d9b98accfe6abe472e48767176483604ffa04 Mon Sep 17 00:00:00 2001 From: Omar Zunic Date: Tue, 17 Nov 2026 13:06:17 +0100 Subject: [PATCH 5/5] fix(web): skip network reports on unload or abort Firefox and Safari reject an in-flight fetch with a TypeError when the page reloads or the user leaves. These were reported as network errors. Skip the report when the request signal is aborted or when the page is unloading. Set the flag on pagehide and clear it on pageshow. --- apps/web/src/lib/posthog-client.test.ts | 31 ++++++++++++++++++++++++- apps/web/src/lib/posthog-client.ts | 21 ++++++++++++++++- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/apps/web/src/lib/posthog-client.test.ts b/apps/web/src/lib/posthog-client.test.ts index 4ca79709..59fe9b35 100644 --- a/apps/web/src/lib/posthog-client.test.ts +++ b/apps/web/src/lib/posthog-client.test.ts @@ -2,7 +2,7 @@ import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"; import posthog from "posthog-js"; -import { fetchReportingNetworkErrors } from "./posthog-client"; +import { fetchReportingNetworkErrors, watchUnload } from "./posthog-client"; describe("fetchReportingNetworkErrors", () => { const capture = spyOn(posthog, "capture").mockImplementation(() => undefined); @@ -42,6 +42,35 @@ describe("fetchReportingNetworkErrors", () => { expect(capture).not.toHaveBeenCalled(); }); + test("a rejection after the caller aborted sends nothing", async () => { + const error = new TypeError("Load failed"); + const controller = new AbortController(); + controller.abort(); + const base = () => Promise.reject(error); + + const result = await fetchReportingNetworkErrors("abc", base)( + "/_serverFn/abc", + { signal: controller.signal }, + ).catch((e: Error) => e); + + expect(result).toBe(error); + expect(capture).not.toHaveBeenCalled(); + }); + + test("a rejection while the page unloads sends nothing until pageshow", async () => { + const page = new EventTarget(); + watchUnload(page); + const error = new TypeError("NetworkError when attempting to fetch"); + + page.dispatchEvent(new Event("pagehide")); + expect(await callWith(() => Promise.reject(error))).toBe(error); + expect(capture).not.toHaveBeenCalled(); + + page.dispatchEvent(new Event("pageshow")); + expect(await callWith(() => Promise.reject(error))).toBe(error); + expect(capture).toHaveBeenCalledTimes(1); + }); + test("an aborted fetch sends nothing", async () => { const abort = new DOMException("aborted", "AbortError"); diff --git a/apps/web/src/lib/posthog-client.ts b/apps/web/src/lib/posthog-client.ts index 1a37b595..724c611e 100644 --- a/apps/web/src/lib/posthog-client.ts +++ b/apps/web/src/lib/posthog-client.ts @@ -67,6 +67,19 @@ export function startPostHog({ return posthog; } +// Firefox and Safari reject an in-flight fetch with a `TypeError` on unload. +let unloading = false; +export function watchUnload(target: EventTarget): void { + target.addEventListener("pagehide", () => { + unloading = true; + }); + // A page that returns from the back/forward cache is alive again. + target.addEventListener("pageshow", () => { + unloading = false; + }); +} +if (globalThis.window) watchUnload(globalThis.window); + /** The call signature of `fetch`, as TanStack's `CustomFetch` has it. */ type FetchFn = (...args: Parameters) => ReturnType; @@ -90,7 +103,13 @@ export function fetchReportingNetworkErrors( try { return await baseFetch(input, init); } catch (error) { - if (error instanceof TypeError && posthog.__loaded) { + if ( + error instanceof TypeError && + posthog.__loaded && + !unloading && + !(init?.signal ?? (input instanceof Request ? input.signal : null)) + ?.aborted + ) { posthog.capture("server_fn_network_error", { server_fn_id: serverFnId, message: error.message,