: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(frontend): load feature flags once with complete inputs (#118002)
Paul D'Ambra7a1d2e03c4f7
diff --git a/frontend/src/lib/logic/preflightLogic.tsx b/frontend/src/lib/logic/preflightLogic.tsxindex e501703abf4b..d27b6baf5b54 100644--- a/frontend/src/lib/logic/preflightLogic.tsx+++ b/frontend/src/lib/logic/preflightLogic.tsx@@ -5,6 +5,7 @@ import posthog from 'posthog-js'import api from 'lib/api'import { getAppContext } from 'lib/utils/getAppContext'+import { identifyInstanceInPostHog } from 'lib/utils/posthogIdentity'import { urls } from 'scenes/urls'import { PreflightStatus, Realm } from '~/types'@@ -402,10 +403,8 @@ export const preflightLogic = kea<preflightLogicType>([commit_sha: appContext?.commit_sha,})- if (values.preflight.site_url) {- posthog.group('instance', values.preflight.site_url, {- site_url: values.preflight.site_url,- })+ if (values.preflight.site_url && identifyInstanceInPostHog(posthog, values.preflight.site_url)) {+ posthog.reloadFeatureFlags()}}},diff --git a/frontend/src/lib/utils/posthogIdentity.ts b/frontend/src/lib/utils/posthogIdentity.tsnew file mode 100644index 000000000000..466b1a13f1a1--- /dev/null+++ b/frontend/src/lib/utils/posthogIdentity.ts@@ -0,0 +1,103 @@+import type { PostHog, Properties } from 'posthog-js'++import type { UserType } from '~/types'++interface PostHogGroup {+ type: string+ key: string+ properties?: Properties+}++interface UserIdentity {+ distinctId: string+ personProperties: Properties+ superProperties: Properties+ groups: PostHogGroup[]+}++/** Feature flags target these person and group properties, so this list also decides what a user's flags can use. */+function userIdentity(user: UserType): UserIdentity {+ const groups: PostHogGroup[] = []+ if (user.team) {+ groups.push({+ type: 'project',+ key: user.team.uuid,+ properties: {+ id: user.team.id,+ uuid: user.team.uuid,+ name: user.team.name,+ ingested_event: user.team.ingested_event,+ is_demo: user.team.is_demo,+ timezone: user.team.timezone,+ instance_tag: user.organization?.metadata?.instance_tag,+ },+ })+ }+ if (user.organization) {+ groups.push({+ type: 'organization',+ key: user.organization.id,+ properties: {+ id: user.organization.id,+ name: user.organization.name,+ slug: user.organization.slug,+ created_at: user.organization.created_at,+ available_product_features: user.organization.available_product_features,+ member_count: user.organization.member_count,+ project_count: user.organization.teams.length,+ ...user.organization.metadata,+ },+ })+ if (user.organization.customer_id) {+ groups.push({ type: 'customer', key: user.organization.customer_id })+ }+ }+ return {+ distinctId: user.distinct_id,+ personProperties: { email: user.anonymize_data ? null : user.email, realm: user.realm },+ superProperties: { is_demo_project: user.team?.is_demo },+ groups,+ }+}++const sentIdentities = new Map<'user' | 'instance', string>()++/**+ * Sends an identity only when it differs from the last one this page sent. posthog-js stores the person+ * and group properties from these calls as the inputs of the next /flags request. The calls schedule+ * flag reloads, and posthog-js debounces all reloads made in one task into one /flags request, so the+ * caller can reload flags after this returns true without a second request.+ */+function sendIdentityIfChanged<T extends UserIdentity | PostHogGroup>(+ kind: 'user' | 'instance',+ identity: T,+ send: (identity: T) => void+): boolean {+ const fingerprint = JSON.stringify(identity)+ if (sentIdentities.get(kind) === fingerprint) {+ return false+ }+ send(identity)+ sentIdentities.set(kind, fingerprint)+ return true+}++/** Returns true when the user's identity changed, which means the flags need a reload. */+export function identifyUserInPostHog(posthog: PostHog, user: UserType): boolean {+ return sendIdentityIfChanged('user', userIdentity(user), (identity) => {+ posthog.identify(identity.distinctId)+ posthog.setPersonProperties(identity.personProperties)+ posthog.register(identity.superProperties)+ for (const group of identity.groups) {+ posthog.group(group.type, group.key, group.properties)+ }+ })+}++/** Returns true when the instance changed, which means the flags need a reload. */+export function identifyInstanceInPostHog(posthog: PostHog, siteUrl: string): boolean {+ const instance: PostHogGroup = { type: 'instance', key: siteUrl, properties: { site_url: siteUrl } }+ return sendIdentityIfChanged('instance', instance, (group) => {+ posthog.group(group.type, group.key, group.properties)+ })+}diff --git a/frontend/src/loadPostHogJS.flagRequests.test.ts b/frontend/src/loadPostHogJS.flagRequests.test.tsnew file mode 100644index 000000000000..aec7752a4250--- /dev/null+++ b/frontend/src/loadPostHogJS.flagRequests.test.ts@@ -0,0 +1,192 @@+/**+ * @jest-environment-options {"url": "https://app.example.com/project/1"}+ */+import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_TEAM, MOCK_DEFAULT_USER } from 'lib/api.mock'++import { createMemoryHistory } from 'history'++import type { userLogic as UserLogic } from 'scenes/userLogic'++import { AppContext, PreflightStatus, Realm, UserType } from '~/types'++// The real SDK decides when /flags is requested, so these tests count the requests it sends.+jest.unmock('posthog-js')+// The toolbar starts a second posthog-js instance with its own flags requests, which are out of scope here.+jest.mock('~/toolbar/toolbarPosthogJS', () => ({+ toolbarPosthogJS: {},+ captureToolbarException: jest.fn(),+ useToolbarFeatureFlag: () => false,+}))++interface FlagsRequestBody {+ distinct_id: string+ $anon_distinct_id?: string+ groups: Record<string, string>+ group_properties?: Record<string, Record<string, unknown>>+ person_properties: Record<string, unknown>+}++const PROJECT_TOKEN = 'phc_example'+const SITE_URL = 'https://posthog.example.com'++const userInProject = (projectUuid: string): UserType => ({+ ...MOCK_DEFAULT_USER,+ realm: Realm.Cloud,+ team: { ...MOCK_DEFAULT_TEAM, uuid: projectUuid, name: `Project ${projectUuid}` },+ organization: { ...MOCK_DEFAULT_ORGANIZATION, customer_id: 'cus_example' },+})+const USER = userInProject('project-a')++interface Page {+ userLogic: typeof UserLogic+ flagsRequests: FlagsRequestBody[]+ groupIdentifyTypes: string[]+}++const LOGGED_OUT_FLAGS_REQUEST = expect.objectContaining({ groups: {} })++function loggedInFlagsRequest(user: UserType, anonymousId: string | undefined): FlagsRequestBody {+ return expect.objectContaining({+ distinct_id: user.distinct_id,+ ...(anonymousId ? { $anon_distinct_id: anonymousId } : {}),+ groups: {+ project: user.team!.uuid,+ organization: user.organization!.id,+ customer: user.organization!.customer_id,+ instance: SITE_URL,+ },+ person_properties: expect.objectContaining({ email: user.email, realm: user.realm }),+ group_properties: expect.objectContaining({+ instance: { site_url: SITE_URL },+ project: expect.objectContaining({ uuid: user.team!.uuid, name: user.team!.name }),+ organization: expect.objectContaining({ id: user.organization!.id, name: user.organization!.name }),+ }),+ })+}++function decodeFlagsRequest(body: ArrayBuffer): FlagsRequestBody {+ const data = new URLSearchParams(Buffer.from(body).toString()).get('data') ?? ''+ return JSON.parse(Buffer.from(data, 'base64').toString())+}++describe('loadPostHogJS feature flag requests', () => {+ beforeEach(() => {+ jest.useFakeTimers()+ localStorage.clear()+ sessionStorage.clear()+ for (const cookie of document.cookie.split(';')) {+ const name = cookie.split('=')[0].trim()+ for (const domain of ['', '; domain=.example.com']) {+ document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/${domain}`+ }+ }+ window.JS_POSTHOG_API_KEY = PROJECT_TOKEN+ window.JS_POSTHOG_HOST = 'https://us.example.com'+ })++ afterEach(() => {+ jest.useRealTimers()+ })++ /** Boots a fresh copy of posthog-js and the app logics that identify the user, like a full page load. */+ async function loadPage(user: UserType | null): Promise<Page> {+ jest.resetModules()+ // posthog-js keeps the fetch it finds at import, so the instance of an earlier page, which acts+ // like another open tab, records its requests elsewhere.+ const flagsRequests: FlagsRequestBody[] = []+ global.fetch = jest.fn(async (url: RequestInfo | URL, init?: RequestInit) => {+ if (String(url).includes('/flags/')) {+ flagsRequests.push(decodeFlagsRequest(init?.body as ArrayBuffer))+ return new Response(JSON.stringify({ flags: {} }), { status: 200 })+ }+ return new Response('{}', { status: 200 })+ }) as typeof fetch+ window.POSTHOG_APP_CONTEXT = {+ current_user: user,+ // The server leaves site_url out of the preflight for a logged-out visitor.+ preflight: (user ? { site_url: SITE_URL } : {}) as PreflightStatus,+ } as AppContext+ window.POSTHOG_USER_IDENTITY_WITH_FLAGS = user ? { featureFlags: { 'bootstrapped-flag': true } } : {}++ const posthog = (await import('posthog-js')).default+ const groupIdentifyTypes: string[] = []+ posthog.on('eventCaptured', ({ event, properties }) => {+ if (event === '$groupidentify') {+ groupIdentifyTypes.push(properties.$group_type)+ }+ })+ const { loadPostHogJS } = await import('./loadPostHogJS')+ const { initKea } = await import('./initKea')+ const { userLogic } = await import('scenes/userLogic')+ const { preflightLogic } = await import('lib/logic/preflightLogic')++ loadPostHogJS()+ const history = createMemoryHistory()+ initKea({ routerLocation: history.location, routerHistory: history })+ userLogic.mount()+ preflightLogic.mount()++ // posthog-js loads its remote config with a script tag, which jsdom never runs, so deliver it by hand.+ ;(window as any)._POSTHOG_REMOTE_CONFIG = { [PROJECT_TOKEN]: { config: {} } }+ document.querySelector<HTMLScriptElement>('script[src*="/config.js"]')?.onload?.(new Event('load'))++ await jest.advanceTimersByTimeAsync(1000)+ return { userLogic, flagsRequests, groupIdentifyTypes }+ }++ it.each<{+ case: string+ previousPage: UserType | null | undefined+ user: UserType | null+ groupIdentifyTypes: string[]+ }>([+ { case: 'a logged-out page', previousPage: undefined, user: null, groupIdentifyTypes: [] },+ {+ case: 'the first page after login',+ previousPage: null,+ user: USER,+ groupIdentifyTypes: ['project', 'organization', 'customer', 'instance'],+ },+ {+ case: 'a reload while logged in',+ previousPage: USER,+ user: USER,+ groupIdentifyTypes: ['project', 'organization', 'instance'],+ },+ {+ case: 'the page after a project switch',+ previousPage: userInProject('project-b'),+ user: USER,+ groupIdentifyTypes: ['project', 'organization', 'instance'],+ },+ ])('sends one flags request with every input on $case', async ({ previousPage, user, groupIdentifyTypes }) => {+ const previous = previousPage === undefined ? undefined : await loadPage(previousPage)+ // A login keeps the flag values the anonymous visitor had, for flags with experience continuity.+ const anonymousId = previousPage === null ? previous?.flagsRequests[0].distinct_id : undefined++ const page = await loadPage(user)++ expect(page.groupIdentifyTypes).toEqual(groupIdentifyTypes)+ expect(page.flagsRequests).toEqual([user ? loggedInFlagsRequest(user, anonymousId) : LOGGED_OUT_FLAGS_REQUEST])+ })++ it.each<{ case: string; loadedUser: UserType; requestedProjects: string[] }>([+ { case: 'the same user loads again', loadedUser: USER, requestedProjects: [] },+ {+ case: 'the user moves to another project',+ loadedUser: userInProject('project-b'),+ requestedProjects: ['project-b'],+ },+ ])(+ 'loads flags only for a changed user when $case without a page load',+ async ({ loadedUser, requestedProjects }) => {+ const { userLogic, flagsRequests } = await loadPage(USER)+ flagsRequests.length = 0++ userLogic.actions.loadUserSuccess(loadedUser)+ await jest.advanceTimersByTimeAsync(1000)++ expect(flagsRequests.map((request) => request.groups.project)).toEqual(requestedProjects)+ }+ )+})diff --git a/frontend/src/loadPostHogJS.tsx b/frontend/src/loadPostHogJS.tsxindex a8eaca1bf1a7..bba64887e7f6 100644--- a/frontend/src/loadPostHogJS.tsx+++ b/frontend/src/loadPostHogJS.tsx@@ -5,6 +5,7 @@ import { isOAuthMode } from 'lib/oauth/oauthClient'import { inStorybook, inStorybookTestRunner } from 'lib/utils/dom'import { isEmbeddedPageFrame } from 'lib/utils/embeddedPageFrame'import { getAppContext, isHobbyDeployment } from 'lib/utils/getAppContext'+import { identifyInstanceInPostHog, identifyUserInPostHog } from 'lib/utils/posthogIdentity'import { startDetachedElementTracking } from './detachedElementTracker'@@ -65,6 +66,22 @@ function writeLastSeenFeatureFlags(lastSeen: LastSeenFeatureFlags): void {}}+/**+ * The server bootstrap evaluates flags locally with only a few properties, so it can be wrong for a flag+ * that uses a cohort or a group. This sends every flag input the page knows, then loads flags once.+ * userLogic and preflightLogic send the same identities again, and they reload flags only when one changed.+ */+function loadFeatureFlagsForPage(): void {+ const appContext = getAppContext()+ if (appContext?.current_user) {+ identifyUserInPostHog(posthog, appContext.current_user)+ }+ if (appContext?.preflight?.site_url) {+ identifyInstanceInPostHog(posthog, appContext.preflight.site_url)+ }+ posthog.reloadFeatureFlags()+}+export function loadPostHogJS(): void {if (window.JS_POSTHOG_API_KEY) {posthog.init(window.JS_POSTHOG_API_KEY, {@@ -87,6 +104,8 @@ export function loadPostHogJS(): void {getAppContext()?.current_user?.distinct_id): {},+ // The first flags request must wait until the user and groups from the page are set.+ advanced_disable_feature_flags_on_first_load: true,opt_in_site_apps: true,disable_surveys: window.IMPERSONATED_SESSION,disable_product_tours: true,@@ -229,6 +248,8 @@ export function loadPostHogJS(): void {window.POSTHOG_GLOBAL_ERRORS ||= {}window.POSTHOG_GLOBAL_ERRORS['onFeatureFlagsLoadError'] = true})++ loadFeatureFlagsForPage()} else {posthog.init('fake_token', {autocapture: false,diff --git a/frontend/src/scenes/userLogic.ts b/frontend/src/scenes/userLogic.tsindex 7a3cc627005b..ab9fe3684f8c 100644--- a/frontend/src/scenes/userLogic.ts+++ b/frontend/src/scenes/userLogic.ts@@ -11,6 +11,7 @@ import { DashboardCompatibleScenes } from 'lib/components/SceneDashboardChoice/simport { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'import { clearSession, isOAuthMode, setOAuthContextIds } from 'lib/oauth/oauthClient'import { getAppContext } from 'lib/utils/getAppContext'+import { identifyUserInPostHog } from 'lib/utils/posthogIdentity'import { clearPendingVerificationEmail } from 'scenes/authentication/shared/verificationCode'import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'@@ -739,45 +740,10 @@ export const userLogic = kea<userLogicType>([})}- if (posthog) {- posthog.identify(user.distinct_id)- posthog.people.set({- email: user.anonymize_data ? null : user.email,- realm: user.realm,- })-- posthog.register({- is_demo_project: user.team?.is_demo,- })-- if (user.team) {- posthog.group('project', user.team.uuid, {- id: user.team.id,- uuid: user.team.uuid,- name: user.team.name,- ingested_event: user.team.ingested_event,- is_demo: user.team.is_demo,- timezone: user.team.timezone,- instance_tag: user.organization?.metadata?.instance_tag,- })- }-- if (user.organization) {- posthog.group('organization', user.organization.id, {- id: user.organization.id,- name: user.organization.name,- slug: user.organization.slug,- created_at: user.organization.created_at,- available_product_features: user.organization.available_product_features,- member_count: user.organization.member_count,- project_count: user.organization.teams.length,- ...user.organization.metadata,- })-- if (user.organization.customer_id) {- posthog.group('customer', user.organization.customer_id)- }- }+ // loadPostHogJS already identified the user in the page and loaded flags for them, so+ // flags reload here only for a user that changed without a page load.+ if (posthog && identifyUserInPostHog(posthog, user)) {+ posthog.reloadFeatureFlags()}// First-login interstitial: route users with unreviewed pre-existing API keys