From 5f112a33faeb40dd6ef59162fc58f2aab8481152 Mon Sep 17 00:00:00 2001 From: Sean Oliver <882952+seanoliver@users.noreply.github.com> Date: Thu, 7 Aug 2025 14:02:51 -0700 Subject: [PATCH] fix: queue user identification calls until PostHog is initialized (#37773) Fixes race condition where user identification was lost when PostHog hadn't finished initializing. Now queues identification calls and applies them once PostHog is ready, similar to how groups are handled. Also ensures groups from pageview properties are properly set. --- packages/common/posthog-client.ts | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/packages/common/posthog-client.ts b/packages/common/posthog-client.ts index de95e29ab73..5e3fc98c46b 100644 --- a/packages/common/posthog-client.ts +++ b/packages/common/posthog-client.ts @@ -9,6 +9,7 @@ interface PostHogClientConfig { class PostHogClient { private initialized = false private pendingGroups: Record = {} + private pendingIdentification: { userId: string; properties?: Record } | null = null private config: PostHogClientConfig constructor(config: PostHogClientConfig = {}) { @@ -38,6 +39,12 @@ class PostHogClient { posthog.group(type, id) }) this.pendingGroups = {} + + // Apply any pending identification + if (this.pendingIdentification) { + posthog.identify(this.pendingIdentification.userId, this.pendingIdentification.properties) + this.pendingIdentification = null + } }, } @@ -47,6 +54,14 @@ class PostHogClient { capturePageView(properties: Record, hasConsent: boolean = true) { if (!hasConsent || !this.initialized) return + + // Store groups from properties if present (for later group() calls) + if (properties.$groups) { + Object.entries(properties.$groups).forEach(([type, id]) => { + if (id) posthog.group(type, id as string) + }) + } + posthog.capture('$pageview', properties) } @@ -56,7 +71,13 @@ class PostHogClient { } identify(userId: string, properties?: Record, hasConsent: boolean = true) { - if (!hasConsent || !this.initialized) return + if (!hasConsent) return + + if (!this.initialized) { + // Queue the identification for when PostHog initializes + this.pendingIdentification = { userId, properties } + return + } posthog.identify(userId, properties) }