React Router Error Tracking installation
Install with the wizard
Run this command in your project directory to add PostHog to your React Router project. The wizard detects your framework, installs the SDK, and sets up your first events.
Or set it up manually by following the rest of this guide.
- 1
Install the package
RequiredInstall the PostHog JavaScript library and React SDK using your package manager:
- 2
Configure Vite
RequiredAdd
posthog-jsand@posthog/reacttossr.noExternalin yourvite.config.tsto avoid SSR errors:vite.config.ts - 3
Capture browser exceptions
RequiredReact Router catches every error thrown while rendering a route or running a loader, action or fetcher, and shows the route's
ErrorBoundary, so these errors never reach the browser's global error handlers. Turn on exception autocapture withcapture_exceptions: truefor everything else, and pass anonErrorhandler to the router for the errors it catches.onErroralso receives responses you throw on purpose (throw data(..., { status: 404 }), unknown URLs) and, in production builds, the browser's copy of a server error, which React Router renames to "Unexpected Server Error". The server captures the original with its full stack. Skip both.In framework mode, the router is
<HydratedRouter>inapp/entry.client.tsx(runnpx react-router reveal entry.clientif your app does not have this file yet):app/entry.client.tsxWhich prop to use depends on your React Router version:
- 7.11 or later:
onError, as above. - 7.8.2 to 7.10: pass the same handler as
unstable_onErrorand type it withunstable_ClientOnErrorFunction. - Earlier versions: capture inside a
useEffectin everyErrorBoundaryyour routes export, with the same two checks.
In data mode, pass the handler to
<RouterProvider router={router} onError={onError} />and skip the server steps below. In declarative mode (<BrowserRouter>), React Router has no error boundaries of its own: follow the React guide instead.Do not also capture in an
ErrorBoundary: each error would arrive twice. In framework and data mode, aPostHogErrorBoundaryaround the router never sees these errors, because React Router's own boundaries catch them first. - 7.11 or later:
- 4
Create the server client
RequiredIn framework mode, loaders, actions, middleware and server rendering run on your server, and their errors never reach the browser: React Router sends the browser "Unexpected Server Error" instead. Install
posthog-node6.1.0 or later, create one client for the server process, and create the React Router error handler from it.enableExceptionAutocapturecaptures errors no request handles, such as a rejected promise nobody awaits, from the moment the client exists: create it when the module loads, not on first use.readPostHogCookielinks page loads, which carry only the PostHog cookie, to the visitor's person and session replay.app/lib/posthog.server.tsThe handler links each server error to the visitor's person, session and page. It reads IDs you set with
posthog.withContextfirst, then theX-POSTHOG-*headers posthog-js adds withtracing_headers, then the cookie. An anonymous visitor's errors carry their anonymous distinct ID and create no person profile.If visitors can opt out of tracking, set
opt_out_capturing_persistence_type: 'cookie'inposthog.init, so the server can see the choice: posthog-js stores it in localStorage by default. If you useopt_out_capturing_by_default, passreadPostHogCookie: { optOutCapturingByDefault: true }.On Vercel, Netlify or another serverless host, the function can stop as soon as the response is sent. Pass the platform's
waitUntilso queued events are still sent, for examplewaitUntilfrom@vercel/functions:new PostHog('<ph_project_token>', { host: '<ph_client_api_host>', readPostHogCookie: true, waitUntil }). On Cloudflare Workers, create the client and the handler for each request, with the request'sctx.waitUntil, as the Cloudflare Workers guide shows. - 5
Capture server errors
RequiredExport the handler as
handleErrorfromapp/entry.server.tsx(runnpx react-router reveal entry.serverif your app does not have this file yet). React Router calls it for errors in loaders, actions, middleware, resource routes and server rendering, on both page loads and data requests. It skips requests the browser cancelled and the 404 and 405 responses React Router creates, and logs each error the way React Router does.Errors thrown while streaming, after the first part of the page was sent, skip
handleErrorand reach React'sonErrorin the same file instead. Call the handler there too, in therenderToPipeableStreamoptions (renderToReadableStreamon edge runtimes):app/entry.server.tsxThe handler captures each error once per request, however many hooks pass it on. To keep your own error logging, pass it as an option:
createReactRouterErrorHandler(posthog, { handleError: yourHandleError }). To skip errors you do not want to track, passshouldCapture, a function that returnsfalsefor them.React Router does not call
handleErrorfor a promise that a loader returns and the page renders with<Await>, and the browser receives it as "Unexpected Server Error", which the browser step skips. Pass those rejections to the handler in the loader, and give the<Await>anerrorElement:app/routes/product.tsx - 6
Test a server error
RecommendedThrow an error from a loader, then run
npm run buildandnpm start. Load another page first, so posthog-js sets its cookie, then open the failing page, and also navigate to it from another page. Each should send one exception fromposthog-nodewith the page's URL and your browser's session, and none from the browser for the same error.Test with a production build: in
react-router dev, React Router sends the browser the original server error, so each error arrives twice. - 7







