refactor(telemetry): remove server-side anonymous ID in favor of PostHog native tracking

Let PostHog generate its own distinct ID client-side instead of deriving one from hostname/username.
This commit is contained in:
kumarabhirup 2026-03-05 16:09:06 -08:00
parent a0aef2c2f8
commit 00c04f89d3
No known key found for this signature in database
GPG Key ID: DB7CA2289CAB0167
3 changed files with 11 additions and 24 deletions

View File

@ -10,15 +10,11 @@ const POSTHOG_HOST = "https://us.i.posthog.com";
let initialized = false;
function initPostHog(anonymousId: string) {
function initPostHog() {
if (initialized || !POSTHOG_KEY || typeof window === "undefined") return;
posthog.init(POSTHOG_KEY, {
api_host: POSTHOG_HOST,
bootstrap: {
distinctID: anonymousId,
isIdentifiedID: false,
},
capture_pageview: false,
capture_pageleave: true,
persistence: "memory",
@ -43,15 +39,13 @@ function PageviewTracker() {
}
export function PostHogProvider({
anonymousId,
children,
}: {
anonymousId: string;
children: React.ReactNode;
}) {
useEffect(() => {
initPostHog(anonymousId);
}, [anonymousId]);
initPostHog();
}, []);
if (!POSTHOG_KEY) return <>{children}</>;

View File

@ -1,6 +1,5 @@
import type { Metadata, Viewport } from "next";
import { Suspense } from "react";
import { getAnonymousId } from "@/lib/telemetry";
import { PostHogProvider } from "./components/posthog-provider";
import "./globals.css";
@ -43,7 +42,7 @@ export default function RootLayout({
</head>
<body className="antialiased">
<Suspense fallback={null}>
<PostHogProvider anonymousId={getAnonymousId()}>
<PostHogProvider>
{children}
</PostHogProvider>
</Suspense>

View File

@ -1,5 +1,4 @@
import { createHash } from "node:crypto";
import os from "node:os";
import { randomUUID } from "node:crypto";
import { PostHog } from "posthog-node";
const POSTHOG_KEY = process.env.NEXT_PUBLIC_POSTHOG_KEY || "";
@ -7,15 +6,6 @@ const POSTHOG_HOST = "https://us.i.posthog.com";
let client: PostHog | null = null;
export function getAnonymousId(): string {
try {
const raw = `${os.hostname()}:${os.userInfo().username}`;
return createHash("sha256").update(raw).digest("hex").slice(0, 16);
} catch {
return "unknown";
}
}
function ensureClient(): PostHog | null {
if (!POSTHOG_KEY) return null;
if (!client) {
@ -28,12 +18,16 @@ function ensureClient(): PostHog | null {
return client;
}
export function trackServer(event: string, properties?: Record<string, unknown>): void {
export function trackServer(
event: string,
properties?: Record<string, unknown>,
distinctId?: string,
): void {
const ph = ensureClient();
if (!ph) return;
ph.capture({
distinctId: getAnonymousId(),
distinctId: distinctId || randomUUID(),
event,
properties: {
...properties,