Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
48 changes: 48 additions & 0 deletions front_end/src/utils/posthog.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import "server-only";

import { cookies } from "next/headers";
import { PostHog } from "posthog-node";

import { getPublicSettings } from "./public_settings.server";

let posthogClient: PostHog | null = null;

function getPostHogClient(): PostHog | null {
const { PUBLIC_POSTHOG_KEY, PUBLIC_POSTHOG_BASE_URL } = getPublicSettings();
const apiKey = PUBLIC_POSTHOG_KEY;
if (!apiKey) return null;

if (!posthogClient) {
posthogClient = new PostHog(apiKey, {
host: PUBLIC_POSTHOG_BASE_URL || "https://us.i.posthog.com",
flushAt: 1,
flushInterval: 0,
});
}
return posthogClient;
}

export async function getFeatureFlag(
flagName: string,
defaultValue: boolean | string = false
): Promise<boolean | string> {
const client = getPostHogClient();
if (!client) return defaultValue;

const { PUBLIC_POSTHOG_KEY } = getPublicSettings();

const cookieStore = await cookies();
const cookieName = "ph_" + PUBLIC_POSTHOG_KEY + "_posthog";
const cookieValue = cookieStore.get(cookieName)?.value;
const distinctId = cookieValue
? JSON.parse(cookieValue).distinct_id
: "anonymous";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe that anonymous is not the best fallback here, as then If there’s no cookie, every user becomes "anonymous" and will all share the same flag evaluation. Maybe it's better to go with a user's id or sth similar


Comment on lines +37 to +40
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe this can crash a function in JSON.parse if the cookie value is malformed and it won't be caught then

try {
const flag = await client.getFeatureFlag(flagName, distinctId);

return flag !== undefined ? flag : defaultValue;
} catch {
return defaultValue;
}
}