1- import { posthog , type Properties } from "posthog-js " ;
1+ import { PostHog } from "posthog-node " ;
22
3- let initialized = false ;
3+ let posthog : PostHog | undefined ;
44
5- const doInitPostHog = ( ) : void => {
6- if ( initialized ) return ;
7- if (
8- ! process . env . NEXT_PUBLIC_POSTHOG_KEY ||
9- ! process . env . NEXT_PUBLIC_POSTHOG_HOST
10- ) {
11- throw new Error ( "PostHog environment variables are not set" ) ;
5+ const getPostHog = ( ) : PostHog => {
6+ if ( posthog === undefined ) {
7+ if (
8+ ! process . env . NEXT_PUBLIC_POSTHOG_KEY ||
9+ ! process . env . NEXT_PUBLIC_POSTHOG_HOST
10+ ) {
11+ throw new Error ( "PostHog environment variables are not set" ) ;
12+ }
13+ posthog = new PostHog ( process . env . NEXT_PUBLIC_POSTHOG_KEY , {
14+ host : process . env . NEXT_PUBLIC_POSTHOG_HOST ,
15+ flushAt : 1 ,
16+ flushInterval : 0 ,
17+ } ) ;
1218 }
13- posthog . init ( process . env . NEXT_PUBLIC_POSTHOG_KEY , {
14- /* eslint-disable @typescript-eslint/naming-convention */
15- api_host : process . env . NEXT_PUBLIC_POSTHOG_HOST ,
16- capture_pageview : false ,
17- /* eslint-enable @typescript-eslint/naming-convention */
18- } ) ;
19- initialized = true ;
19+ return posthog ;
2020} ;
2121
2222const NON_WORD = / \W + / g;
@@ -28,13 +28,12 @@ export const internalError = ({
2828} : {
2929 error : unknown ;
3030 type ?: string ;
31- context ?: Properties ;
31+ context ?: object ;
3232 forceSendInDev ?: boolean ;
3333} ) : void => {
3434 if ( process . env . NODE_ENV === "development" && forceSendInDev !== true ) {
3535 console . error ( error ) ;
3636 } else {
37- doInitPostHog ( ) ;
3837 type = type || "Internal Error" ;
3938 const slugType = type . replaceAll ( NON_WORD , "-" ) . toLowerCase ( ) ;
4039 context = {
@@ -52,7 +51,12 @@ export const internalError = ({
5251 error = new Error ( typeof error ) ;
5352 }
5453 }
55- posthog . captureException ( error , { ...context , type : slugType } ) ;
54+ const posthog = getPostHog ( ) ;
55+ const result = posthog . captureException ( error , undefined , {
56+ ...context ,
57+ type : slugType ,
58+ } ) ;
59+ console . error ( result ) ;
5660 if ( process . env . NODE_ENV === "development" ) console . error ( error ) ;
5761 }
5862} ;
0 commit comments