diff --git a/packages/backend-core/src/environment.ts b/packages/backend-core/src/environment.ts index e064398153..6377d682d0 100644 --- a/packages/backend-core/src/environment.ts +++ b/packages/backend-core/src/environment.ts @@ -145,6 +145,7 @@ const environment = { COOKIE_DOMAIN: process.env.COOKIE_DOMAIN, PLATFORM_URL: process.env.PLATFORM_URL || "", POSTHOG_TOKEN: process.env.POSTHOG_TOKEN, + POSTHOG_PERSONAL_TOKEN: process.env.POSTHOG_PERSONAL_TOKEN, POSTHOG_API_HOST: process.env.POSTHOG_API_HOST || "https://us.i.posthog.com", ENABLE_ANALYTICS: process.env.ENABLE_ANALYTICS, TENANT_FEATURE_FLAGS: process.env.TENANT_FEATURE_FLAGS, diff --git a/packages/backend-core/src/features/index.ts b/packages/backend-core/src/features/index.ts index d3f00af87d..5305da4764 100644 --- a/packages/backend-core/src/features/index.ts +++ b/packages/backend-core/src/features/index.ts @@ -10,6 +10,7 @@ export function init(opts?: PostHogOptions) { console.log("initializing posthog client...") posthog = new PostHog(env.POSTHOG_TOKEN, { host: env.POSTHOG_API_HOST, + personalApiKey: env.POSTHOG_PERSONAL_TOKEN, ...opts, }) } else { @@ -186,10 +187,23 @@ export class FlagSet, T extends { [key: string]: V }> { tags[`identity.tenantId`] = identity?.tenantId tags[`identity._id`] = identity?._id - if (posthog && identity?.type === IdentityType.USER) { + // Until we're confident this performs well, we're only enabling it in QA + // and test environments. + const usePosthog = env.isTest() || env.isQA() + if (usePosthog && posthog && identity?.type === IdentityType.USER) { tags[`readFromPostHog`] = true - const posthogFlags = await posthog.getAllFlagsAndPayloads(identity._id) + const personProperties: Record = {} + if (identity.tenantId) { + personProperties.tenantId = identity.tenantId + } + + const posthogFlags = await posthog.getAllFlagsAndPayloads( + identity._id, + { + personProperties, + } + ) console.log("posthog flags", JSON.stringify(posthogFlags)) for (const [name, value] of Object.entries(posthogFlags.featureFlags)) { diff --git a/packages/backend-core/src/features/tests/features.spec.ts b/packages/backend-core/src/features/tests/features.spec.ts index 9c928f5545..1b6a6e041b 100644 --- a/packages/backend-core/src/features/tests/features.spec.ts +++ b/packages/backend-core/src/features/tests/features.spec.ts @@ -153,6 +153,7 @@ describe("feature flags", () => { mockPosthogFlags(posthogFlags) env.POSTHOG_TOKEN = "test" env.POSTHOG_API_HOST = "https://us.i.posthog.com" + env.POSTHOG_PERSONAL_TOKEN = "test" } const ctx = { user: { license: { features: licenseFlags || [] } } } @@ -160,7 +161,11 @@ describe("feature flags", () => { await withEnv(env, async () => { // We need to pass in node-fetch here otherwise nock won't get used // because posthog-node uses axios under the hood. - init({ fetch: nodeFetch }) + init({ + fetch: (url, opts) => { + return nodeFetch(url, opts) + }, + }) const fullIdentity: IdentityContext = { _id: "us_1234",