Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix(frontend): Sync client PostHog opt-in status with server setting (#11728)

sp.wackd5b2d2ebc53b
diff --git a/frontend/src/hooks/use-sync-posthog-consent.ts b/frontend/src/hooks/use-sync-posthog-consent.ts
new file mode 100644
index 0000000000..615aa9a1bf
--- /dev/null
+++ b/frontend/src/hooks/use-sync-posthog-consent.ts
@@ -0,0 +1,41 @@
+import React from "react";
+import { usePostHog } from "posthog-js/react";
+import { handleCaptureConsent } from "#/utils/handle-capture-consent";
+import { useSettings } from "./query/use-settings";
+
+/**
+ * Hook to sync PostHog opt-in/out state with backend setting on mount.
+ * This ensures that if the backend setting changes (e.g., via API or different client),
+ * the PostHog instance reflects the current user preference.
+ */
+export const useSyncPostHogConsent = () => {
+ const posthog = usePostHog();
+ const { data: settings } = useSettings();
+ const hasSyncedRef = React.useRef(false);
+
+ React.useEffect(() => {
+ // Only run once when both PostHog and settings are available
+ if (!posthog || settings === undefined || hasSyncedRef.current) {
+ return;
+ }
+
+ const backendConsent = settings.USER_CONSENTS_TO_ANALYTICS;
+
+ // Only sync if there's a backend preference set
+ if (backendConsent !== null) {
+ const posthogHasOptedIn = posthog.has_opted_in_capturing();
+ const posthogHasOptedOut = posthog.has_opted_out_capturing();
+
+ // Check if PostHog state is out of sync with backend
+ const needsSync =
+ (backendConsent === true && !posthogHasOptedIn) ||
+ (backendConsent === false && !posthogHasOptedOut);
+
+ if (needsSync) {
+ handleCaptureConsent(posthog, backendConsent);
+ }
+
+ hasSyncedRef.current = true;
+ }
+ }, [posthog, settings]);
+};
diff --git a/frontend/src/routes/root-layout.tsx b/frontend/src/routes/root-layout.tsx
index 930451dae9..264ae541c8 100644
--- a/frontend/src/routes/root-layout.tsx
+++ b/frontend/src/routes/root-layout.tsx
@@ -25,6 +25,7 @@ import { useIsOnTosPage } from "#/hooks/use-is-on-tos-page";
import { useAutoLogin } from "#/hooks/use-auto-login";
import { useAuthCallback } from "#/hooks/use-auth-callback";
import { useReoTracking } from "#/hooks/use-reo-tracking";
+import { useSyncPostHogConsent } from "#/hooks/use-sync-posthog-consent";
import { LOCAL_STORAGE_KEYS } from "#/utils/local-storage";
import { EmailVerificationGuard } from "#/components/features/guards/email-verification-guard";
import { MaintenanceBanner } from "#/components/features/maintenance/maintenance-banner";
@@ -100,6 +101,9 @@ export default function MainApp() {
// Initialize Reo.dev tracking in SaaS mode
useReoTracking();
+ // Sync PostHog opt-in/out state with backend setting on mount
+ useSyncPostHogConsent();
+
React.useEffect(() => {
// Don't change language when on TOS page
if (!isOnTosPage && settings?.LANGUAGE) {