React Error Tracking installation
Install with the wizard
Run this command in your project directory to add PostHog to your React 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
posthog-jsand@posthog/reactusing your package manager: - 2
Add environment variables
RequiredAdd your PostHog project token and host to your environment variables. For Vite-based React apps, use the
VITE_prefix to expose them to the client:.env - 3
Initialize PostHog
RequiredWrap your app with the
PostHogProvidercomponent at the root of your application (such asmain.tsxif you're using Vite):main.tsxdefaults optionThe
defaultsoption automatically configures PostHog with recommended settings for new projects. See SDK defaults for details. - 4
Accessing PostHog in your code
RecommendedUse the
usePostHoghook to access the PostHog instance in any component wrapped byPostHogProvider:MyComponent.tsxYou can also import
posthogdirectly for non-React code or utility functions:utils/analytics.ts - 5
Send events
RecommendedClick around and view a couple pages to generate some events. PostHog automatically captures pageviews, clicks, and other interactions for you.
If you'd like, you can also manually capture custom events:
JavaScript - 6
Set up exception autocapture
RecommendedYou can enable exception autocapture for the JavaScript Web SDK in the Error tracking section of your project settings.
When enabled, this automatically captures
$exceptionevents when errors are thrown by wrapping thewindow.onerrorandwindow.onunhandledrejectionlisteners. - 7
Set up error boundaries
OptionalYou can use the
PostHogErrorBoundarycomponent to capture rendering errors thrown by components:JavaScript - 8
Manually capture exceptions
OptionalIt is also possible to manually capture exceptions using the
captureExceptionmethod:JavaScript - 9







