@rivi-software/posthog-tanstack-start
v1.0.1
Published
PostHog error tracking for TanStack Start apps on Cloudflare Workers: the Worker's capture, the Start middlewares, the browser SDK loaded after hydration, secret-path redaction and the source map upload
Maintainers
Readme
@rivi-software/posthog-tanstack-start
PostHog error tracking for TanStack Start apps on Cloudflare Workers:
- the Worker's exceptions and events, through
posthog-node - Start middlewares that report what server functions and server routes throw
- the browser SDK, loaded after hydration
- redaction of routes whose address is a credential
- the source map upload
Your app keeps control of what it tracks: its own posthog-js options, such as consent, analytics and session replay.
Install
npm install @rivi-software/posthog-tanstack-start posthog-node posthog-js
# for the source map upload
npm install --save-dev @posthog/rollup-pluginThe PostHog libraries are peer dependencies, so the app and this package share one SDK:
posthog-node:./serverand./startneed it.posthog-js: only./browserneeds it.@posthog/rollup-plugin: only./viteneeds it.
The rollup plugin depends on @posthog/cli, whose build script pnpm 12 asks you to approve or deny. Deny it, because the CLI downloads its binary when it first runs: put allowBuilds: { "@posthog/cli": false } in pnpm-workspace.yaml.
It needs TanStack Start 1.169 or later (with TanStack Router 1.170 or later), Vite 6, 7 or 8, posthog-node 5.57.1 or later and posthog-js 1.438.21 or later. The package is ESM only.
Entry points
| Entry point | Contents | Runs in |
| --- | --- | --- |
| …/server | captureServerException, captureServerEvent, setSecretPaths, installPostHogForTests | The Worker (cloudflare:workers) |
| …/start | posthogFunctionErrors, posthogRequestErrors (the Start middlewares), getPostHogBrowserConfig (the browser's settings, for the router's dehydrate) | TanStack Start, both sides |
| …/browser | initPostHog(config, options), withPostHog, captureClientException, redactSecretPaths, PostHogBrowserConfig | The browser |
| …/vite | posthogSourcemaps({ releaseName, releaseVersion }), PostHogSourcemapOptions | Vite config |
TanStack Start compiles this package as it compiles the app's own code, because the package peer-depends on @tanstack/react-start. So the middlewares' server code and getPostHogBrowserConfig stay out of the browser's bundle.
Configuration
| Variable | Where | What |
| --- | --- | --- |
| POSTHOG_PROJECT_TOKEN | Worker var | The project API key (phc_…). Empty turns PostHog off on both sides, with a console error in development. |
| POSTHOG_HOST | Worker var | The ingestion host: https://us.i.posthog.com (the default) or https://eu.i.posthog.com |
| POSTHOG_PERSONAL_API_KEY | Build env | Turns on the source map upload. Set it only on the build that deploys. |
| POSTHOG_PROJECT_ID | Build env | The project the maps go to |
| POSTHOG_API_HOST | Build env | The app host for the upload: https://us.posthog.com (the default) or https://eu.posthog.com |
One pair of Worker vars configures the browser and the Worker alike: getPostHogBrowserConfig reads them during SSR, and the router hands them to the client. Declare them in the Worker's Env (wrangler types).
Usage
// vite.config.ts
import { posthogSourcemaps } from "@rivi-software/posthog-tanstack-start/vite";
export default defineConfig({
plugins: [/* tanstackStart(), cloudflare(), … */ ...posthogSourcemaps({ releaseName: "web" })],
});// src/start.ts
import { posthogFunctionErrors, posthogRequestErrors } from "@rivi-software/posthog-tanstack-start/start";
export const startInstance = createStart(() => ({
requestMiddleware: [posthogRequestErrors],
functionMiddleware: [posthogFunctionErrors],
}));// src/router.tsx
import { captureClientException, initPostHog } from "@rivi-software/posthog-tanstack-start/browser";
import { getPostHogBrowserConfig } from "@rivi-software/posthog-tanstack-start/start";
const router = createRouter({
routeTree,
dehydrate: () => ({ posthog: getPostHogBrowserConfig() }),
hydrate: ({ posthog }) => initPostHog(posthog, { person_profiles: "identified_only" }),
defaultOnCatch: (error) => captureClientException(error),
});// Anywhere on the server: a failure the code answers or logs instead of throwing.
import { captureServerException } from "@rivi-software/posthog-tanstack-start/server";
captureServerException(error, { request, properties: { handler: "file-upload" } });With @rivi-software/deploy-watch, report a router error only once it is not a missing chunk that reloads the page: recoverFromChunkError(error).then((reloading) => reloading || captureClientException(error)).
How it works
The Worker.
posthog-node(its workerd build) sends every exception and event on its own (captureExceptionImmediate,captureImmediate) and keeps the send alive past the response withwaitUntil. Nothing waits in a batch the isolate could drop.captureServerException(error, { request, distinctId, properties })sends the request's method, origin and path, never its query (which can hold a token or a search term). It also sends the browser's person and session, read from posthog-js' tracing headers on same-origin fetches, or from the SDK's cookie on a page load. That links the exception to the session replay.A handler that knows the person passes
distinctId.captureServerEvent(event, distinctId, properties, anonymousId)sends any other event. Without adistinctIdit sends the event anonymously (no person profile), underanonymousIdwhen you pass one, so related events (one conversation's calls) share an id.Neither waits for PostHog or throws: a send that fails logs a
console.warnline, and the handler's response goes out either way.Secret paths. A route whose address is a credential, such as a shared ticket's page
/t/$token, reaches PostHog as its pattern, never as the link. List the patterns, as TanStack Router writes them, once for each side:- In the Worker's entry module,
setSecretPaths(patterns)covers what the Worker sends: an exception's$current_urland$pathname, the error's message and stack, and the properties of every exception and event. - In the posthog-js options,
before_send: redactSecretPaths(patterns)covers every address an event or a person carries: an exception's message and stack, an autocaptured link and the heatmap's keys included.
A pattern is read part by part, between slashes, as the router reads it, and matches in any case:
| Part | Matches | | --- | --- | |
t,files| That text | |$token| One segment | |{$token}, with fixed text around it:ticket-{$id},{$token}.pdf| One segment that starts and ends with that text | |{-$token}, with or without text around it | One segment, or none | |$, or{$}with fixed text around it | The rest of the path, slashes included |A trailing slash (
/t/$token/, an index route) is optional.setSecretPathsandredactSecretPathsthrow for a pattern the router would read differently: a part it reads as fixed text, such asprefix$id(writeprefix{$id}),{token}or two parameters in one part; anything after$; and anything but fixed text after{$}.Three things get past that:
- Session replay's
$snapshotis compressed and goes as it is. Keep replay off, or block those paths in the project settings. - posthog-js' flags request sends the person's first address past
before_send. Setadvanced_disable_flagswhen you use no feature flags. - The redaction walks plain objects and arrays only. An
Erroror a class instance in the properties goes as the SDK writes it (posthog-node writes anError's message and stack), so send itsmessageor its fields instead.
- In the Worker's entry module,
The middlewares. Server functions turn a thrown error into an error response, and server routes answer one with a 500, before the Worker's
fetchsees it; the middlewares report them there. Redirects,notFoundand a thrownResponseare control flow, and go unreported.The browser.
initPostHogloads posthog-js as its own chunk after hydration (about 100 kB gzipped), so no page waits for it. It applies the SDK defaults of 2026-05-30 and tracing headers to the page's own host, then the app's options over them.withPostHogruns a callback once the SDK has loaded (identify, reset, a custom event), and does nothing while PostHog is off.captureClientExceptionreports what the router's error boundaries catch, which never reacheswindow.onerror.When posthog-js does not load, such as on a dropped connection or in a tab that outlived the deploy that removed its chunk,
initPostHoglogs one warning and PostHog stays off:withPostHogandcaptureClientExceptiondo nothing, and no rejection reaches the app'sunhandledrejectionhandlers. The next call toinitPostHogimports posthog-js again. When posthog-js throws as it starts,initPostHoglogs one warning too, and PostHog stays off for the page: posthog-js counts itself started before it throws, so a secondinitwould do nothing.Source maps.
posthogSourcemapsuploads the browser's maps and the server environments' maps as releasereleaseNameatreleaseVersion. The version defaults toGITHUB_SHA, elseWORKERS_CI_COMMIT_SHA. The browser's maps are deleted after the upload, so they are never served. The server's stay on disk for Wrangler's own upload (upload_source_maps). WithoutPOSTHOG_PERSONAL_API_KEYit returns no plugins, so a local build uploads nothing and needs no PostHog credentials.The plugin writes a snippet into every browser chunk that holds the chunk's id and, in event mode (the default), the release's id. Every release then renames every browser chunk, a server-only commit too. With
@rivi-software/deploy-watch, every deploy that uploads source maps is a new browser build: each open tab loads the whole page at its next navigation, and a notice withoutmoduleshows after each deploy. A notice per module still shows only once a deploy changed that module's code.
In your app's tests
vi.mock does not reach a module your test worker already imported, so a test swaps the client instead:
installPostHogForTests({ captureImmediate, captureExceptionImmediate })puts a stand-in in its place. It gets the error and your properties as you passed them: the real client replaces the secret paths in them as it builds the event.installPostHogForTests(null)turns PostHog off again.
Pin POSTHOG_PROJECT_TOKEN empty in your test config, so no test reports to your production project.
Development
The package's tests run in Node: vitest.config.ts points cloudflare:workers at tests/cloudflare-workers.ts, a stand-in with the Worker vars and no request context. tests/browser.test.ts runs in happy-dom instead, a dev dependency, with a stand-in posthog-js that fails to load or to start. In this directory, run pnpm run test, pnpm run check and pnpm run build.
License
Licensed under the MIT License. Copyright © 2026 RIVI Software.
