Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(auth): attach landing lh_cid to login_or_signup_clicked (#16321)

AmAzing-a85ea420498b
diff --git a/src/features/User/UserLoginOrSignup/landingClickId.test.ts b/src/features/User/UserLoginOrSignup/landingClickId.test.ts
new file mode 100644
index 00000000000..9833e6a21b5
--- /dev/null
+++ b/src/features/User/UserLoginOrSignup/landingClickId.test.ts
@@ -0,0 +1,57 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { LANDING_CLICK_ID_KEY, resolveLandingClickId } from './landingClickId';
+
+const resetUrl = () => window.history.replaceState({}, '', '/');
+
+describe('resolveLandingClickId', () => {
+ beforeEach(() => {
+ window.sessionStorage.clear();
+ resetUrl();
+ });
+
+ afterEach(() => {
+ window.sessionStorage.clear();
+ resetUrl();
+ });
+
+ it('returns undefined when nothing is set', () => {
+ expect(resolveLandingClickId()).toBeUndefined();
+ });
+
+ it('reads the id the beacon stashed in sessionStorage', () => {
+ window.sessionStorage.setItem(LANDING_CLICK_ID_KEY, 'cid-from-storage');
+ expect(resolveLandingClickId()).toBe('cid-from-storage');
+ });
+
+ it('falls back to the lh_cid URL param when sessionStorage is empty', () => {
+ window.history.replaceState({}, '', '/signup?lh_cid=cid-from-url');
+ expect(resolveLandingClickId()).toBe('cid-from-url');
+ });
+
+ it('prefers the current URL param over a stale sessionStorage id', () => {
+ window.sessionStorage.setItem(LANDING_CLICK_ID_KEY, 'stale-cid-from-storage');
+ window.history.replaceState({}, '', '/signup?lh_cid=fresh-cid-from-url');
+ expect(resolveLandingClickId()).toBe('fresh-cid-from-url');
+ });
+
+ it('decodes an encoded lh_cid from the URL', () => {
+ window.history.replaceState({}, '', `/signup?lh_cid=${encodeURIComponent('a b+c')}`);
+ expect(resolveLandingClickId()).toBe('a b+c');
+ });
+
+ it('survives sessionStorage throwing (privacy mode) and still reads the URL', () => {
+ vi.spyOn(window.sessionStorage, 'getItem').mockImplementation(() => {
+ throw new Error('SecurityError');
+ });
+ window.history.replaceState({}, '', '/signup?lh_cid=cid-from-url');
+ expect(resolveLandingClickId()).toBe('cid-from-url');
+ });
+
+ it('returns undefined when sessionStorage throws and the URL has no id', () => {
+ vi.spyOn(window.sessionStorage, 'getItem').mockImplementation(() => {
+ throw new Error('SecurityError');
+ });
+ expect(resolveLandingClickId()).toBeUndefined();
+ });
+});
diff --git a/src/features/User/UserLoginOrSignup/landingClickId.ts b/src/features/User/UserLoginOrSignup/landingClickId.ts
new file mode 100644
index 00000000000..e4750dafaad
--- /dev/null
+++ b/src/features/User/UserLoginOrSignup/landingClickId.ts
@@ -0,0 +1,41 @@
+/**
+ * Landing → app correlation id.
+ *
+ * The marketing site (lobehub-landing) generates a fresh `lh_cid` for every
+ * "open app" click, appends it to the destination URL, and the app shell's
+ * load-funnel beacon persists it to `sessionStorage` on arrival. Surfacing it on
+ * auth events lets growth analytics chain a single landing click all the way to a
+ * completed registration by `lh_cid` — instead of relying on coarse first-touch
+ * (`$initial_utm_source`) attribution.
+ */
+export const LANDING_CLICK_ID_KEY = 'lh_cid';
+
+const fromSessionStorage = (): string => {
+ try {
+ return globalThis.sessionStorage?.getItem(LANDING_CLICK_ID_KEY) ?? '';
+ } catch {
+ // sessionStorage can throw (SSR, privacy mode, disabled storage)
+ return '';
+ }
+};
+
+const fromUrl = (): string => {
+ try {
+ return new URLSearchParams(globalThis.location?.search ?? '').get(LANDING_CLICK_ID_KEY) ?? '';
+ } catch {
+ return '';
+ }
+};
+
+/**
+ * Resolve the landing click id, preferring the **current URL** value (the
+ * in-flight click — correct for a fresh `?lh_cid=...` landing/deep link, even
+ * when an older id from an earlier click lingers in `sessionStorage` in the same
+ * tab) and falling back to `sessionStorage` (where the shell beacon stashed it,
+ * for SPA navigations where the URL no longer carries it). Returns `undefined`
+ * when absent so callers can omit the property entirely.
+ */
+export const resolveLandingClickId = (): string | undefined => {
+ const cid = fromUrl() || fromSessionStorage();
+ return cid || undefined;
+};
diff --git a/src/features/User/UserLoginOrSignup/trackLoginOrSignupClicked.test.ts b/src/features/User/UserLoginOrSignup/trackLoginOrSignupClicked.test.ts
new file mode 100644
index 00000000000..9e034da0fb4
--- /dev/null
+++ b/src/features/User/UserLoginOrSignup/trackLoginOrSignupClicked.test.ts
@@ -0,0 +1,114 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { trackLoginOrSignupClicked } from './trackLoginOrSignupClicked';
+
+const getSingletonAnalyticsOptional = vi.hoisted(() => vi.fn());
+vi.mock('@lobehub/analytics', () => ({ getSingletonAnalyticsOptional }));
+
+const makeAnalytics = (initialized = true) => {
+ const track = vi.fn().mockResolvedValue(undefined);
+ const initialize = vi.fn().mockResolvedValue(undefined);
+ const analytics = {
+ getStatus: () => ({ initialized, providersCount: 1 }),
+ initialize,
+ track,
+ };
+ return { analytics, initialize, track };
+};
+
+const resetEnv = () => {
+ window.sessionStorage.clear();
+ window.history.replaceState({}, '', '/');
+};
+
+describe('trackLoginOrSignupClicked', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ resetEnv();
+ });
+
+ afterEach(() => {
+ resetEnv();
+ vi.restoreAllMocks();
+ });
+
+ it('attaches the lh_cid from the current URL', async () => {
+ const { analytics, track } = makeAnalytics();
+ getSingletonAnalyticsOptional.mockReturnValue(analytics);
+ window.history.replaceState({}, '', '/signup?lh_cid=cid-url');
+
+ await trackLoginOrSignupClicked({ spm: 'signup.submit.click' });
+
+ expect(track).toHaveBeenCalledWith({
+ name: 'login_or_signup_clicked',
+ properties: { lh_cid: 'cid-url', spm: 'signup.submit.click' },
+ });
+ });
+
+ it('falls back to the lh_cid the shell beacon stored in sessionStorage', async () => {
+ const { analytics, track } = makeAnalytics();
+ getSingletonAnalyticsOptional.mockReturnValue(analytics);
+ window.sessionStorage.setItem('lh_cid', 'cid-storage');
+
+ await trackLoginOrSignupClicked({ provider: 'google', spm: 'signin.social.click' });
+
+ expect(track).toHaveBeenCalledWith({
+ name: 'login_or_signup_clicked',
+ properties: { lh_cid: 'cid-storage', provider: 'google', spm: 'signin.social.click' },
+ });
+ });
+
+ it('omits lh_cid entirely when no landing click id is present', async () => {
+ const { analytics, track } = makeAnalytics();
+ getSingletonAnalyticsOptional.mockReturnValue(analytics);
+
+ await trackLoginOrSignupClicked({ spm: 'homepage.login_or_signup.click' });
+
+ expect(track).toHaveBeenCalledWith({
+ name: 'login_or_signup_clicked',
+ properties: { spm: 'homepage.login_or_signup.click' },
+ });
+ });
+
+ it('initializes analytics first when it is not yet initialized', async () => {
+ const { analytics, initialize, track } = makeAnalytics(false);
+ getSingletonAnalyticsOptional.mockReturnValue(analytics);
+
+ await trackLoginOrSignupClicked({ spm: 'signin.email_step.submit' });
+
+ expect(initialize).toHaveBeenCalledTimes(1);
+ expect(track).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not initialize again when analytics is already initialized', async () => {
+ const { analytics, initialize, track } = makeAnalytics(true);
+ getSingletonAnalyticsOptional.mockReturnValue(analytics);
+
+ await trackLoginOrSignupClicked({ spm: 'signin.password_step.submit' });
+
+ expect(initialize).not.toHaveBeenCalled();
+ expect(track).toHaveBeenCalledTimes(1);
+ });
+
+ it('no-ops without throwing when analytics is unavailable', async () => {
+ getSingletonAnalyticsOptional.mockReturnValue(undefined);
+
+ await expect(
+ trackLoginOrSignupClicked({ spm: 'homepage.login_or_signup.click' }),
+ ).resolves.toBeUndefined();
+ });
+
+ it('swallows and logs a tracking failure', async () => {
+ const error = new Error('boom');
+ const track = vi.fn().mockRejectedValue(error);
+ getSingletonAnalyticsOptional.mockReturnValue({
+ getStatus: () => ({ initialized: true, providersCount: 1 }),
+ track,
+ });
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await trackLoginOrSignupClicked({ spm: 'signup.submit.click' });
+
+ expect(consoleError).toHaveBeenCalledWith('Failed to track login_or_signup_clicked:', error);
+ });
+});
diff --git a/src/features/User/UserLoginOrSignup/trackLoginOrSignupClicked.ts b/src/features/User/UserLoginOrSignup/trackLoginOrSignupClicked.ts
index 6c24ac23314..9792fc32b35 100644
--- a/src/features/User/UserLoginOrSignup/trackLoginOrSignupClicked.ts
+++ b/src/features/User/UserLoginOrSignup/trackLoginOrSignupClicked.ts
@@ -1,5 +1,7 @@
import { getSingletonAnalyticsOptional } from '@lobehub/analytics';
+import { resolveLandingClickId } from './landingClickId';
+
interface TrackLoginOrSignupClickedParams {
provider?: string;
spm: string;
@@ -16,9 +18,12 @@ export const trackLoginOrSignupClicked = ({ provider, spm }: TrackLoginOrSignupC
await analytics.initialize();
}
+ const lhCid = resolveLandingClickId();
+
await analytics.track({
name: 'login_or_signup_clicked',
properties: {
+ ...(lhCid && { lh_cid: lhCid }),
...(provider && { provider }),
spm,
},