: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
perf(toolbar): load the toolbar's flags when it mounts, not on every app page (#117828)
Paul D'Ambraeda7b29d0562
diff --git a/frontend/jest.setup.ts b/frontend/jest.setup.tsindex bcf563e0fe00..50b317116edf 100644--- a/frontend/jest.setup.ts+++ b/frontend/jest.setup.ts@@ -199,6 +199,8 @@ jest.mock('posthog-js', () => {unregister: jest.fn(),reset: jest.fn(),group: jest.fn(),+ reloadFeatureFlags: jest.fn(),+ set_config: jest.fn(),setPersonProperties: jest.fn(),updateEarlyAccessFeatureEnrollment: jest.fn(),people: { set: jest.fn() },diff --git a/frontend/src/toolbar/index.test.ts b/frontend/src/toolbar/index.test.tsindex 0f93c5db5c89..8b3acc9dc77d 100644--- a/frontend/src/toolbar/index.test.ts+++ b/frontend/src/toolbar/index.test.ts@@ -204,6 +204,31 @@ describe('Toolbar flag loading', () => {expect(mockPostHog.featureFlags.overrideFeatureFlags).not.toHaveBeenCalled()})+ it.each([+ { launch: 'without a user to identify', params: {}, expectedReloads: 1 },+ { launch: 'with instrumentation but no distinct id', params: { instrument: true }, expectedReloads: 1 },+ // identify() changes the distinct id, and posthog-js then loads the flags for that user+ { launch: 'with a user to identify', params: { instrument: true, distinctId: 'user-1' }, expectedReloads: 0 },+ ])('loads the toolbar instance flags only when the toolbar mounts $launch', async ({ params, expectedReloads }) => {+ await import('./index')+ const { default: posthog } = await import('posthog-js')++ expect(posthog.init).toHaveBeenCalledWith(+ expect.any(String),+ expect.objectContaining({+ advanced_disable_feature_flags_on_first_load: true,+ remote_config_refresh_interval_ms: 0,+ }),+ 'ph_toolbar_internal'+ )+ expect(posthog.reloadFeatureFlags).not.toHaveBeenCalled()++ await (window as any).ph_load_toolbar({ apiURL: 'http://localhost:8010', token: 'test-token', ...params })++ expect(posthog.reloadFeatureFlags).toHaveBeenCalledTimes(expectedReloads)+ expect(posthog.set_config).toHaveBeenCalledWith({ remote_config_refresh_interval_ms: 300000 })+ })+it('is idempotent — a repeat ph_load_toolbar keeps the live toolbar instead of remounting it', async () => {// On an SPA, posthog-js calls ph_load_toolbar again on client-side route changes.// Remounting resets the Kea context out from under the mounted React tree, so the toolbardiff --git a/frontend/src/toolbar/index.tsx b/frontend/src/toolbar/index.tsxindex f4e17a4365cd..f657e8b4e9b0 100644--- a/frontend/src/toolbar/index.tsx+++ b/frontend/src/toolbar/index.tsx@@ -14,10 +14,10 @@ import type { PostHog } from 'posthog-js'import { createRoot } from 'react-dom/client'import { ToolbarApp } from '~/toolbar/ToolbarApp'-import { canonicalizeApiHost } from '~/toolbar/toolbarConfigLogic'+import { canonicalizeApiHost, identifiesToolbarUser } from '~/toolbar/toolbarConfigLogic'import { isToolbarMounted, posthogToolbarController, setToolbarRefs } from '~/toolbar/toolbarController'import { toolbarLogger } from '~/toolbar/toolbarLogger'-import { captureToolbarException } from '~/toolbar/toolbarPosthogJS'+import { captureToolbarException, toolbarPosthogJS } from '~/toolbar/toolbarPosthogJS'import { isToolbarRequestError } from '~/toolbar/toolbarRequestError'import { safeFetch, toError } from '~/toolbar/utils'import { ToolbarParams } from '~/types'@@ -95,6 +95,17 @@ win['posthogToolbarController'] = posthogToolbarController// Re-exported for the loader script (loader.ts), which forwards its controller stub here.export { posthogToolbarController }+// posthog-js's default refresh interval. The toolbar instance starts with refresh off, see toolbarPosthogJS.ts.+const TOOLBAR_FLAGS_REFRESH_INTERVAL_MS = 5 * 60 * 1000++function startToolbarFlags(toolbarParams: ToolbarParams): void {+ toolbarPosthogJS.set_config({ remote_config_refresh_interval_ms: TOOLBAR_FLAGS_REFRESH_INTERVAL_MS })+ // Otherwise identify() gives the instance a new distinct id, and posthog-js loads the flags for that user+ if (!identifiesToolbarUser(toolbarParams)) {+ toolbarPosthogJS.reloadFeatureFlags()+ }+}+// Tracks an in-flight mount. The mounted-state flag isn't set until the very end of the async// mount, so without this two overlapping ph_load_toolbar calls would both pass the guard below// and mount twice. Concurrent calls dedupe onto this promise instead.@@ -132,6 +143,8 @@ async function mountToolbar(toolbarParams: ToolbarParams, posthog?: PostHog): Pr// duration includes the chunk fetch — keep the earliest timestamp.;(window as any).__posthog_toolbar_load_start ??= performance.now()+ startToolbarFlags(toolbarParams)+// If posthog and toolbarFlagsKey is present, fetch the feature flags from the backendif (posthog && toolbarParams.toolbarFlagsKey) {// Validate with canonicalizeApiHost so an attacker-controlled apiURL indiff --git a/frontend/src/toolbar/toolbarConfigLogic.ts b/frontend/src/toolbar/toolbarConfigLogic.tsindex 123589490860..84b0845128d5 100644--- a/frontend/src/toolbar/toolbarConfigLogic.ts+++ b/frontend/src/toolbar/toolbarConfigLogic.ts@@ -691,6 +691,12 @@ function maybeMigrateTemporaryToken(}}+export function identifiesToolbarUser<P extends Pick<ToolbarProps, 'instrument' | 'distinctId'>>(+ props: P+): props is P & { distinctId: string } {+ return !!props.instrument && !!props.distinctId+}+/** Set up PostHog instrumentation and capture the "toolbar loaded" event. */function initInstrumentation(props: ToolbarProps,@@ -703,9 +709,9 @@ function initInstrumentation(): void {if (props.instrument) {toolbarPosthogJS.opt_in_capturing()- if (props.distinctId) {- toolbarPosthogJS.identify(props.distinctId, props.userEmail ? { email: props.userEmail } : {})- }+ }+ if (identifiesToolbarUser(props)) {+ toolbarPosthogJS.identify(props.distinctId, props.userEmail ? { email: props.userEmail } : {})}const loadStart = (window as any).__posthog_toolbar_load_start as number | undefineddiff --git a/frontend/src/toolbar/toolbarPosthogJS.ts b/frontend/src/toolbar/toolbarPosthogJS.tsindex 98a813e221a5..af2d41306b8d 100644--- a/frontend/src/toolbar/toolbarPosthogJS.ts+++ b/frontend/src/toolbar/toolbarPosthogJS.ts@@ -19,6 +19,10 @@ const initResult = posthog.init(bootstrap: {featureFlags: {},},+ // The web app imports toolbar modules, which creates this instance on every app page load.+ // Only a mounted toolbar reads these flags, so the toolbar loads them and starts the refresh when it mounts.+ advanced_disable_feature_flags_on_first_load: true,+ remote_config_refresh_interval_ms: 0,autocapture: false,// The toolbar runs on customer pages and must not install global exception handlers.capture_exceptions: false,