1+ import { usePathname } from 'next/navigation'
12import posthog , { type Survey } from 'posthog-js'
23import { PostHogProvider as PHProvider } from 'posthog-js/react'
34import { createContext , useContext , useEffect , useState } from 'react'
@@ -31,12 +32,20 @@ export function PostHogProvider({
3132 children : React . ReactNode
3233 enabled : boolean
3334} ) {
35+ const pathname = usePathname ( )
3436 const [ dashboardFeedbackSurvey , setDashboardFeedbackSurvey ] =
3537 useState < Survey | null > ( null )
3638 const [ isInitialized , setIsInitialized ] = useState ( false )
3739
40+ // Only track the dashboard app — not auth, marketing, or proxied (docs/blog)
41+ // paths. PostHog initializes lazily once the user reaches a /dashboard route.
42+ const shouldInit = enabled && ! ! pathname ?. startsWith ( '/dashboard' )
43+
3844 useEffect ( ( ) => {
39- if ( ! enabled || ! process . env . NEXT_PUBLIC_POSTHOG_KEY ) {
45+ if ( ! shouldInit || ! process . env . NEXT_PUBLIC_POSTHOG_KEY ) {
46+ return
47+ }
48+ if ( posthog . __loaded ) {
4049 return
4150 }
4251
@@ -48,6 +57,11 @@ export function PostHogProvider({
4857 // https://posthog.com/docs/libraries/next-js#configuring-a-reverse-proxy-to-posthog
4958 api_host : '/ph-proxy' ,
5059 ui_host : 'https://us.posthog.com' ,
60+ capture_exceptions : {
61+ capture_unhandled_errors : true ,
62+ capture_unhandled_rejections : true ,
63+ capture_console_errors : false ,
64+ } ,
5165 advanced_enable_surveys : true ,
5266 disable_session_recording : process . env . NODE_ENV !== 'production' ,
5367 advanced_disable_toolbar_metrics : true ,
@@ -57,6 +71,10 @@ export function PostHogProvider({
5771 } ,
5872 } )
5973
74+ posthog . register ( {
75+ environment : process . env . NEXT_PUBLIC_VERCEL_ENV ?? 'development' ,
76+ } )
77+
6078 posthog . getSurveys ( ( surveys ) => {
6179 for ( const survey of surveys ) {
6280 switch ( survey . id ) {
@@ -67,7 +85,7 @@ export function PostHogProvider({
6785 }
6886 setIsInitialized ( true )
6987 } )
70- } , [ enabled ] )
88+ } , [ shouldInit ] )
7189
7290 return (
7391 < AppPostHogContext . Provider
0 commit comments