NestJS Error Tracking installation
Contents
- 1
Install the PostHog Node SDK
RequiredInstall the PostHog Node SDK:
Terminal - 2
Initialize the client and interceptor
RequiredCreate a PostHog client and register the
PostHogInterceptorglobally withcaptureExceptionsenabled:main.tsThis automatically captures unhandled exceptions (5xx) and sends them to PostHog as
$exceptionevents, including stack traces and request context.Configuration options
Option Type Default Description captureExceptionsboolean \| objectfalseEnable exception capture. Pass truefor defaults or an object to configure.captureExceptions.minStatusToCapturenumber500Minimum HTTP status code to capture. Exceptions with a lower status (e.g. 4xx) are skipped. To also capture 4xx errors:
TypeScriptHow it worksThe interceptor observes exceptions transparently using an RxJS
catchErrorwithout interfering with NestJS's exception filter pipeline. It skips already-captured errors andHttpExceptions below the configured threshold, then re-throws so your exception filters still work. - 3
Connect frontend context
RecommendedTo link server-side errors with client sessions and users, configure
__add_tracing_headersin your frontend PostHog JS setup:JavaScriptThis automatically adds
X-POSTHOG-SESSION-IDandX-POSTHOG-DISTINCT-IDheaders to allfetchandXMLHttpRequestcalls to the specified hostnames. ThePostHogInterceptorreads these headers automatically to attach session and user context to captured exceptions. - 4
Manual exception capture (optional)
OptionalYou can also manually capture exceptions anywhere in your NestJS application using
captureException:app.controller.ts - 5
Verify error tracking
RecommendedTrigger a test exception to confirm events are being sent to PostHog. Add a test route to your controller:
TypeScriptVisit
/debug-errorin your browser and check the activity feed for the$exceptionevent.