CustomPostHogProvider.tsx 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { posthogConfig } from "@shared/services/config/posthog-config"
  2. import posthog from "posthog-js"
  3. import { PostHogProvider } from "posthog-js/react"
  4. import { type ReactNode, useEffect, useState } from "react"
  5. import { useExtensionState } from "./context/ExtensionStateContext"
  6. export function CustomPostHogProvider({ children }: { children: ReactNode }) {
  7. const { distinctId, version, userInfo } = useExtensionState()
  8. // NOTE: This is a hack to stop recording webview click events temporarily.
  9. // Remove this to re-enable.
  10. // const isTelemetryEnabled = telemetrySetting !== "disabled";
  11. const isTelemetryEnabled = false
  12. const [isActive, setIsActive] = useState(false)
  13. useEffect(() => {
  14. if (isActive || !isTelemetryEnabled || !posthogConfig.apiKey) {
  15. return
  16. }
  17. // At this point, we know apiKey is defined due to the check above
  18. const apiKey = posthogConfig.apiKey as string
  19. posthog.init(apiKey, {
  20. api_host: posthogConfig.host,
  21. ui_host: posthogConfig.uiHost,
  22. disable_session_recording: true,
  23. capture_pageview: false,
  24. capture_dead_clicks: true,
  25. // Feature flags should work regardless of telemetry opt-out
  26. advanced_disable_decide: false,
  27. // Autocapture should respect telemetry settings
  28. autocapture: false,
  29. })
  30. setIsActive(true)
  31. }, [])
  32. useEffect(() => {
  33. if (!isTelemetryEnabled || !isActive || !distinctId || !version) {
  34. return
  35. }
  36. posthog.set_config({
  37. before_send: (payload) => {
  38. // Only filter out events if telemetry is disabled, but allow feature flag requests
  39. if (!isTelemetryEnabled && payload?.event !== "$feature_flag_called") {
  40. return null
  41. }
  42. if (payload?.properties) {
  43. payload.properties.extension_version = version
  44. payload.properties.distinct_id = distinctId
  45. }
  46. return payload
  47. },
  48. })
  49. const optedIn = posthog.has_opted_in_capturing()
  50. const optedOut = posthog.has_opted_out_capturing()
  51. const args = {
  52. email: userInfo?.email,
  53. name: userInfo?.displayName,
  54. }
  55. if (isTelemetryEnabled && !optedIn) {
  56. posthog.opt_in_capturing()
  57. posthog.identify(distinctId, args)
  58. } else if (!isTelemetryEnabled && !optedOut) {
  59. // For feature flags to work, we need to identify the user even when telemetry is disabled
  60. posthog.identify(distinctId, args)
  61. // Then opt out of capturing other events
  62. posthog.opt_out_capturing()
  63. }
  64. }, [isActive, isTelemetryEnabled, distinctId, version])
  65. return <PostHogProvider client={posthog}>{children}</PostHogProvider>
  66. }