Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(signup): ask which influencer referred when source is social media (#123312)

Joe Martin69b6d81655f3
diff --git a/frontend/src/lib/components/SignupReferralSource.test.ts b/frontend/src/lib/components/SignupReferralSource.test.ts
new file mode 100644
index 000000000000..85e7d9341bd5
--- /dev/null
+++ b/frontend/src/lib/components/SignupReferralSource.test.ts
@@ -0,0 +1,27 @@
+import { getReferralFollowUp } from 'lib/components/SignupReferralSource'
+
+describe('signup referral source follow-up triggers', () => {
+ test.each([
+ ['ChatGPT recommended it', 'ai'],
+ ['claude', 'ai'],
+ ['a web search', null],
+ ['a colleague', null],
+ ['found it on TikTok', 'influencer'],
+ ['instagram', 'influencer'],
+ ['a YouTuber I follow', 'influencer'],
+ ['saw a tweet', 'influencer'],
+ ['an influencer', 'influencer'],
+ // When both patterns match, the AI prompt wins
+ ['an AI influencer on YouTube', 'ai'],
+ // Except when 'chat' is the only AI trigger: it also names social features
+ ['Discord chat', 'influencer'],
+ ['Twitch chat', 'influencer'],
+ // Prefix triggers keep matching while the word is typed out, and plurals match
+ ['Instag', 'influencer'],
+ ['influencers', 'influencer'],
+ // "max" must not match the bare "x" pattern inside a word
+ ['my friend max', null],
+ ] as const)('"%s" → %s', (input, followUp) => {
+ expect(getReferralFollowUp(input)).toBe(followUp)
+ })
+})
diff --git a/frontend/src/lib/components/SignupReferralSource.tsx b/frontend/src/lib/components/SignupReferralSource.tsx
index 5767219865a1..de355d8a5372 100644
--- a/frontend/src/lib/components/SignupReferralSource.tsx
+++ b/frontend/src/lib/components/SignupReferralSource.tsx
@@ -74,6 +74,74 @@ const AI_REFERRAL_PATTERNS = [
]
const AI_REFERRAL_PATTERN = new RegExp(`\\b(${AI_REFERRAL_PATTERNS.join('|')})\\b`, 'i')
+// Used to trigger the influencer prompt when the user mentions a social network or creator channel. This is a simple heuristic and can be adjusted as needed.
+// Longer triggers allow the word to continue (\w*) so the field does not close mid-word
+// ("Insta" → "Instag" → "Instagram") and plurals match. One-or-two-letter abbreviations
+// stay exact words so "max" or "ignore" do not match.
+const SOCIAL_REFERRAL_PATTERNS = [
+ // Social networks
+ 'insta\\w*',
+ 'ig',
+ 'tik ?tok\\w*',
+ 'you ?tub\\w*',
+ 'yt',
+ 'twitter',
+ 'tweet\\w*',
+ 'x',
+ 'x.com',
+ 'linked ?in',
+ 'facebook',
+ 'fb',
+ 'threads',
+ 'blue ?sky',
+ 'mastodon',
+ 'reddit\\w*',
+ 'twitch',
+ 'snap ?chat\\w*',
+ 'discord',
+ 'telegram',
+ 'whats ?app',
+ 'we ?chat',
+ 'weibo',
+ 'pinterest',
+ 'social ?media',
+ 'social ?network\\w*',
+ // Creator channels
+ 'influencer\\w*',
+ 'creator\\w*',
+ 'content ?creator\\w*',
+ 'streamer\\w*',
+ 'blogger\\w*',
+ 'vlogger\\w*',
+ 'podcast\\w*',
+ 'news ?letter\\w*',
+ 'substack',
+]
+const SOCIAL_REFERRAL_PATTERN = new RegExp(`\\b(${SOCIAL_REFERRAL_PATTERNS.join('|')})\\b`, 'i')
+
+// 'chat' also names social features ("Twitch chat", "Discord chat"), so it does not count
+// toward the AI tie-break when a social trigger is present. Any other AI trigger still wins.
+const AI_TIEBREAK_PATTERN = new RegExp(
+ `\\b(${AI_REFERRAL_PATTERNS.filter((pattern) => pattern !== 'chat').join('|')})\\b`,
+ 'i'
+)
+
+// At most one follow-up shows at a time
+export function getReferralFollowUp(referralSource: string): 'ai' | 'influencer' | null {
+ const matchesAi = AI_REFERRAL_PATTERN.test(referralSource)
+ const matchesSocial = SOCIAL_REFERRAL_PATTERN.test(referralSource)
+ if (matchesAi && matchesSocial) {
+ return AI_TIEBREAK_PATTERN.test(referralSource) ? 'ai' : 'influencer'
+ }
+ if (matchesAi) {
+ return 'ai'
+ }
+ if (matchesSocial) {
+ return 'influencer'
+ }
+ return null
+}
+
export default function SignupReferralSource({ disabled }: { disabled: boolean }): JSX.Element {
return (
<>
@@ -92,23 +160,45 @@ export default function SignupReferralSource({ disabled }: { disabled: boolean }
{/* Subscribing here rather than in the parent keeps a keystroke from re-rendering the
whole signup panel. */}
<KeaField name="referral_source" noStyle>
- {({ value }) => (
- <AnimatedCollapsible collapsed={!AI_REFERRAL_PATTERN.test(value ?? '')}>
- <LemonField
- name="referral_source_ai_prompt"
- label="What prompt or search led you to PostHog?"
- help="Paste the prompt or search queries if you remember, even roughly"
- showOptional
- >
- <LemonInput
- className="ph-ignore-input"
- data-attr="signup-referral-source-ai-prompt"
- placeholder="e.g. Product analytics tool with error tracking"
- disabled={disabled}
- />
- </LemonField>
- </AnimatedCollapsible>
- )}
+ {({ value }) => {
+ const followUp = getReferralFollowUp(value ?? '')
+ return (
+ <>
+ <AnimatedCollapsible collapsed={followUp !== 'ai'}>
+ <LemonField
+ name="referral_source_ai_prompt"
+ label="What prompt or search led you to PostHog?"
+ help="Paste the prompt or search queries if you remember, even roughly"
+ showOptional
+ >
+ <LemonInput
+ className="ph-ignore-input"
+ data-attr="signup-referral-source-ai-prompt"
+ placeholder="e.g. Product analytics tool with error tracking"
+ // Also disabled while collapsed, to keep the hidden input out of the tab order
+ disabled={disabled || followUp !== 'ai'}
+ />
+ </LemonField>
+ </AnimatedCollapsible>
+ <AnimatedCollapsible collapsed={followUp !== 'influencer'}>
+ <LemonField
+ name="referral_source_influencer"
+ label="Which account or person led you to PostHog?"
+ help="Name the account, channel, or person if you remember"
+ showOptional
+ >
+ <LemonInput
+ className="ph-ignore-input"
+ data-attr="signup-referral-source-influencer"
+ placeholder="e.g. a YouTube channel, or an X account"
+ // Also disabled while collapsed, to keep the hidden input out of the tab order
+ disabled={disabled || followUp !== 'influencer'}
+ />
+ </LemonField>
+ </AnimatedCollapsible>
+ </>
+ )
+ }}
</KeaField>
</>
)
diff --git a/frontend/src/scenes/authentication/auth/signupLogic.test.ts b/frontend/src/scenes/authentication/auth/signupLogic.test.ts
index 5a78d476da66..e69fc117b734 100644
--- a/frontend/src/scenes/authentication/auth/signupLogic.test.ts
+++ b/frontend/src/scenes/authentication/auth/signupLogic.test.ts
@@ -291,6 +291,25 @@ describe('signupLogic — name handling', () => {
expect(signupRequestBody?.last_name).toBe('van Der Berg')
})
+ it('sends only the follow-up answer whose question is shown for the referral source', async () => {
+ await advanceToOnboardingPanel()
+ logic.actions.setSignupPanelOnboardingValues({
+ name: 'John Smith',
+ organization_name: 'Hogflix',
+ role_at_organization: 'engineer',
+ referral_source: 'A YouTube video',
+ // A stale answer from before the referral source was edited away from an AI mention
+ referral_source_ai_prompt: 'best analytics tool',
+ referral_source_influencer: 'The Hedgehog Dev channel',
+ })
+ logic.actions.submitSignupPanelOnboarding()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(signupRequestBody?.referral_source).toBe('A YouTube video')
+ expect(signupRequestBody?.referral_source_ai_prompt).toBe('')
+ expect(signupRequestBody?.referral_source_influencer).toBe('The Hedgehog Dev channel')
+ })
+
it('omits a whitespace-only organization name so the backend applies its default', async () => {
await advanceToOnboardingPanel()
logic.actions.setSignupPanelOnboardingValues({
diff --git a/frontend/src/scenes/authentication/auth/signupLogic.ts b/frontend/src/scenes/authentication/auth/signupLogic.ts
index bc325f5b5838..c7922fec54a5 100644
--- a/frontend/src/scenes/authentication/auth/signupLogic.ts
+++ b/frontend/src/scenes/authentication/auth/signupLogic.ts
@@ -9,6 +9,7 @@ import { lemonToast } from '@posthog/lemon-ui'
import api from 'lib/api'
import { ValidatedPasswordResult, validatePassword } from 'lib/components/PasswordStrength'
+import { getReferralFollowUp } from 'lib/components/SignupReferralSource'
import { CLOUD_HOSTNAMES, FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { splitFullName } from 'lib/utils/strings'
@@ -44,6 +45,7 @@ export interface SignupPanelOnboardingForm {
role_at_organization: string
referral_source: string
referral_source_ai_prompt: string
+ referral_source_influencer: string
}
export interface PendingInvite {
@@ -468,6 +470,7 @@ export const signupLogic = kea<signupLogicType>([
// The partner that started the OAuth connection is where this person heard about PostHog
referral_source: readPendingOAuthConnection()?.clientName ?? '',
referral_source_ai_prompt: '',
+ referral_source_influencer: '',
} as SignupPanelOnboardingForm,
errors: ({ name, role_at_organization }) => ({
name: !name?.trim() ? 'Please enter your name' : undefined,
@@ -485,13 +488,16 @@ export const signupLogic = kea<signupLogicType>([
try {
const nextUrl = getRelativeNextPath(new URLSearchParams(location.search).get('next'), location)
+ // An answer typed into a follow-up that a later referral source edit hid again must not be sent
+ const followUp = getReferralFollowUp(payload.referral_source ?? '')
const signupData: Record<string, any> = {
email: values.signupEmail,
...splitFullName(payload.name),
organization_name: payload.organization_name?.trim() || undefined,
role_at_organization: payload.role_at_organization,
referral_source: payload.referral_source,
- referral_source_ai_prompt: payload.referral_source_ai_prompt,
+ referral_source_ai_prompt: followUp === 'ai' ? payload.referral_source_ai_prompt : '',
+ referral_source_influencer: followUp === 'influencer' ? payload.referral_source_influencer : '',
next_url: nextUrl ?? undefined,
}
diff --git a/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.ts b/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.ts
index 6141866648a2..8e6d857d4a9a 100644
--- a/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.ts
+++ b/frontend/src/scenes/organization/ConfirmOrganization/confirmOrganizationLogic.ts
@@ -4,6 +4,7 @@ import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from
import { urlToAction } from 'kea-router'
import api from 'lib/api'
+import { getReferralFollowUp } from 'lib/components/SignupReferralSource'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { getRelativeNextPath } from 'lib/utils/url'
import { readPendingOAuthConnection } from 'scenes/authentication/shared/pendingOAuthConnectionLogic'
@@ -14,6 +15,7 @@ export interface ConfirmOrganizationFormValues {
role_at_organization?: string
referral_source?: string
referral_source_ai_prompt?: string
+ referral_source_influencer?: string
}
const LOGIC_PATH = ['scenes', 'organization', 'confirmOrganizationLogic']
@@ -26,6 +28,7 @@ const FIELDS_IN_RENDER_ORDER: (keyof ConfirmOrganizationFormValues)[] = [
'role_at_organization',
'referral_source',
'referral_source_ai_prompt',
+ 'referral_source_influencer',
]
// kea-forms ids each field input `<logic path>.<form key>.<field>`
@@ -146,6 +149,7 @@ export const confirmOrganizationLogic = kea<confirmOrganizationLogicType>([
// The partner that started the OAuth connection is where this person heard about PostHog
referral_source: readPendingOAuthConnection()?.clientName ?? '',
referral_source_ai_prompt: '',
+ referral_source_influencer: '',
} as ConfirmOrganizationFormValues,
errors: ({ organization_name, first_name, role_at_organization }) => ({
first_name: !first_name?.trim() ? 'Please enter your name' : undefined,
@@ -162,6 +166,8 @@ export const confirmOrganizationLogic = kea<confirmOrganizationLogicType>([
},
submit: async (formValues) => {
+ // An answer typed into a follow-up that a later referral source edit hid again must not be sent
+ const followUp = getReferralFollowUp(formValues.referral_source ?? '')
try {
// nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. No generated function covers this endpoint yet. Find out why the generated client skips it (no schema, no product tag, or excluded from the spec) and fix that first.
await api.create('api/social_signup/', {
@@ -169,6 +175,9 @@ export const confirmOrganizationLogic = kea<confirmOrganizationLogicType>([
// Trim rather than reject: surrounding whitespace is still a good signup
first_name: formValues.first_name?.trim(),
organization_name: formValues.organization_name?.trim(),
+ referral_source_ai_prompt: followUp === 'ai' ? formValues.referral_source_ai_prompt : '',
+ referral_source_influencer:
+ followUp === 'influencer' ? formValues.referral_source_influencer : '',
})
} catch (error: any) {
const attr = error.attr as keyof ConfirmOrganizationFormValues | undefined
diff --git a/posthog/api/signup.py b/posthog/api/signup.py
index dfd38182b88a..eb53ed0b5782 100644
--- a/posthog/api/signup.py
+++ b/posthog/api/signup.py
@@ -144,6 +144,12 @@ class SignupSerializer(serializers.Serializer):
referral_source_ai_prompt: serializers.Field = serializers.CharField(
max_length=1000, required=False, allow_blank=True
)
+ referral_source_influencer: serializers.Field = serializers.CharField(
+ max_length=1000,
+ required=False,
+ allow_blank=True,
+ help_text="The social media account or person that referred the user, asked when the referral source mentions a social network or creator channel.",
+ )
turnstile_token: serializers.Field = serializers.CharField(required=False, allow_blank=True, default="")
challenge_nonce: serializers.Field = serializers.CharField(required=False, allow_blank=True, default="")
@@ -292,6 +298,7 @@ class SignupSerializer(serializers.Serializer):
role_at_organization = validated_data.pop("role_at_organization", "")
referral_source = validated_data.pop("referral_source", "")
referral_source_ai_prompt = validated_data.pop("referral_source_ai_prompt", "")
+ referral_source_influencer = validated_data.pop("referral_source_influencer", "")
# For passkey signup, set password to None and use the pre-generated UUID
if passkey_credential:
@@ -368,6 +375,7 @@ class SignupSerializer(serializers.Serializer):
role_at_organization=role_at_organization,
referral_source=referral_source,
referral_source_ai_prompt=referral_source_ai_prompt,
+ referral_source_influencer=referral_source_influencer,
oauth_connection=oauth_connection,
)
@@ -831,6 +839,13 @@ class SocialSignupSerializer(serializers.Serializer):
referral_source_ai_prompt: serializers.Field = serializers.CharField(
max_length=1000, required=False, allow_blank=True, default=""
)
+ referral_source_influencer: serializers.Field = serializers.CharField(
+ max_length=1000,
+ required=False,
+ allow_blank=True,
+ default="",
+ help_text="The social media account or person that referred the user, asked when the referral source mentions a social network or creator channel.",
+ )
def validate_first_name(self, value: str) -> str:
return validate_display_name(value)
@@ -851,6 +866,7 @@ class SocialSignupSerializer(serializers.Serializer):
role_at_organization = validated_data["role_at_organization"]
referral_source = validated_data.get("referral_source", "")
referral_source_ai_prompt = validated_data.get("referral_source_ai_prompt", "")
+ referral_source_influencer = validated_data.get("referral_source_influencer", "")
first_name = validated_data["first_name"]
serializer = SignupSerializer(
@@ -862,6 +878,7 @@ class SocialSignupSerializer(serializers.Serializer):
"role_at_organization": role_at_organization,
"referral_source": referral_source,
"referral_source_ai_prompt": referral_source_ai_prompt,
+ "referral_source_influencer": referral_source_influencer,
},
context={"request": request},
)
diff --git a/posthog/api/test/test_signup.py b/posthog/api/test/test_signup.py
index 65f1cbc80b92..9acc1be766e0 100644
--- a/posthog/api/test/test_signup.py
+++ b/posthog/api/test/test_signup.py
@@ -128,7 +128,7 @@ class TestSignupAPI(APIBaseTest):
@pytest.mark.skip_on_multitenancy
@patch("posthoganalytics.capture")
- def test_api_sign_up_with_ai_referral_source(self, mock_capture):
+ def test_api_sign_up_with_referral_source_follow_up_answers(self, mock_capture):
response = self.client.post(
"/api/signup/",
{
@@ -139,6 +139,7 @@ class TestSignupAPI(APIBaseTest):
"role_at_organization": "product",
"referral_source": "ChatGPT recommended it",
"referral_source_ai_prompt": "What is the best product analytics tool?",
+ "referral_source_influencer": "The Hedgehog Dev channel",
},
)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
@@ -148,8 +149,10 @@ class TestSignupAPI(APIBaseTest):
event_props = signup_calls[0].kwargs["properties"]
self.assertEqual(event_props["referral_source"], "ChatGPT recommended it")
self.assertEqual(event_props["referral_source_ai_prompt"], "What is the best product analytics tool?")
+ self.assertEqual(event_props["referral_source_influencer"], "The Hedgehog Dev channel")
self.assertEqual(event_props["$set"]["referral_source"], "ChatGPT recommended it")
self.assertEqual(event_props["$set"]["referral_source_ai_prompt"], "What is the best product analytics tool?")
+ self.assertEqual(event_props["$set"]["referral_source_influencer"], "The Hedgehog Dev channel")
@patch("posthog.api.signup.is_email_available", return_value=True)
@patch("posthog.api.signup.email_verification_code_verifier.send_code")
@@ -395,6 +398,32 @@ class TestSignupAPI(APIBaseTest):
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertTrue(User.objects.filter(email="[email protected]").exists())
+ @pytest.mark.skip_on_multitenancy
+ @patch("posthoganalytics.capture")
+ def test_social_signup_passes_referral_fields_through(self, mock_capture):
+ session = self.client.session
+ session["backend"] = "google-oauth2"
+ session["email"] = "[email protected]"
+ session["user_name"] = "Social User"
+ session.save()
+
+ response = self.client.post(
+ "/api/social_signup/",
+ {
+ "first_name": "Social",
+ "organization_name": "Social Org",
+ "referral_source": "a TikTok influencer",
+ "referral_source_influencer": "The Hedgehog Dev channel",
+ },
+ )
+ self.assertEqual(response.status_code, status.HTTP_201_CREATED)
+
+ signup_calls = [c for c in mock_capture.call_args_list if c.kwargs.get("event") == "user signed up"]
+ self.assertEqual(len(signup_calls), 1)
+ event_props = signup_calls[0].kwargs["properties"]
+ self.assertEqual(event_props["referral_source"], "a TikTok influencer")
+ self.assertEqual(event_props["referral_source_influencer"], "The Hedgehog Dev channel")
+
@pytest.mark.skip_on_multitenancy
def test_signup_normalizes_email_to_lowercase(self):
"""Test that new signups normalize email addresses to lowercase."""
diff --git a/posthog/event_usage.py b/posthog/event_usage.py
index b563458baae9..988b81315ac6 100644
--- a/posthog/event_usage.py
+++ b/posthog/event_usage.py
@@ -44,6 +44,7 @@ def report_user_signed_up(
role_at_organization: str = "", # select input to ask what the user role is at the org
referral_source: str = "", # free text input to ask users where did they hear about us
referral_source_ai_prompt: str = "", # prompt they used when discovering PostHog via AI
+ referral_source_influencer: str = "", # account or person that referred them via a social or creator channel
oauth_connection: Optional[PendingOAuthConnection] = None, # the app whose OAuth request sent them to sign up
) -> None:
"""
@@ -66,6 +67,7 @@ def report_user_signed_up(
"role_at_organization": role_at_organization,
"referral_source": referral_source,
"referral_source_ai_prompt": referral_source_ai_prompt,
+ "referral_source_influencer": referral_source_influencer,
"is_email_verified": user.is_email_verified,
}
if oauth_connection is not None: