Checking if posthog has been initialized

1.1k Views Asked by At

Is there a legit way to check if Posthog has been initialised somewhere in the app?

My NextJS application structure is like that:

  1. _app.tsx -> posthog init inside useEffect

  2. MyComponent-> event capture

My event capture from MyComponent is being initialised before posthog init from _app.tsx and thats why I am not able to record that event. I am just missing those events.

Any hints would be appreciate.

I am also wondering if I place two init functions, one in _app.tsx and one inside MyComponent, would that be a problem?

I would use the same keys and everything. Would I end with two different instances of posthog?

2

There are 2 best solutions below

0
On

You can use posthog.__loaded like this

if(!posthog.__loaded){
  posthog.init(POSTHOG_KEY
  ...
}
0
On

Was just looking into this today myself, and learned that the PostHog lib has a __loaded property which, while undocumented, seems to report on whether the client has been initialized or not.

Checking that this flag was true before using any functions on the exported class did successfully prevent some errors in my own application, and this line in the PostHog source suggests that the library itself does the same whenever the capture method is called.