Skip to content

Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.

✨ Stitch guest server-side PostHog events to the client's anonymous id (#2680)

Luke Vella10b36b1c0176
diff --git a/apps/web/src/app/api/trpc/[trpc]/route.ts b/apps/web/src/app/api/trpc/[trpc]/route.ts
index 847e104ca..e5bd048ee 100644
--- a/apps/web/src/app/api/trpc/[trpc]/route.ts
+++ b/apps/web/src/app/api/trpc/[trpc]/route.ts
@@ -6,7 +6,7 @@ import { ipAddress } from "@vercel/functions";
import type { NextRequest } from "next/server";
import { getSession } from "@/lib/auth";
import { getLocaleFromRequest } from "@/lib/locale/server";
-import { withPostHog } from "@/lib/posthog";
+import { getClientAnonymousDistinctId, withPostHog } from "@/lib/posthog";
import type { TRPCContext } from "@/trpc/context";
import { appRouter } from "@/trpc/routers";
@@ -49,6 +49,7 @@ const handler = async (req: NextRequest) => {
locale,
identifier,
event,
+ anonymousDistinctId: getClientAnonymousDistinctId(req),
} satisfies TRPCContext;
},
onError: ({ error }) => {
diff --git a/apps/web/src/lib/posthog.ts b/apps/web/src/lib/posthog.ts
index 6bed1f7f6..de8412656 100644
--- a/apps/web/src/lib/posthog.ts
+++ b/apps/web/src/lib/posthog.ts
@@ -1,4 +1,8 @@
import { PostHog } from "@rallly/posthog/server";
+import {
+ getPostHogCookieName,
+ parsePostHogCookieDistinctId,
+} from "@rallly/posthog/utils";
import type { NextRequest } from "next/server";
import { after } from "next/server";
import { env } from "@/env";
@@ -27,18 +31,30 @@ export function posthog() {
* events (no person profile — they are transient and rarely convert);
* identified users get person processing as usual. Group analytics is
* unaffected either way.
+ *
+ * When a guest's client-side anonymous distinct_id is known (read from the
+ * posthog-js persistence cookie via getClientAnonymousDistinctId), guest
+ * events adopt it so server events stitch to the same journey as the guest's
+ * pageviews. Without it (ad blocker, GPC opt-out, cookie not yet written) we
+ * fall back to the guest user id — the event is still captured, just
+ * unstitched. Registered users always capture under their user id.
*/
export function track(
- user: { id: string; isGuest: boolean },
+ user: { id: string; isGuest: boolean; anonymousDistinctId?: string },
event: {
event: string;
properties?: Record<string, unknown>;
groups?: Record<string, string>;
},
) {
+ const distinctId =
+ user.isGuest && user.anonymousDistinctId
+ ? user.anonymousDistinctId
+ : user.id;
+
posthog()?.capture({
...event,
- distinctId: user.id,
+ distinctId,
properties: {
...event.properties,
$process_person_profile: !user.isGuest,
@@ -46,6 +62,22 @@ export function track(
});
}
+/**
+ * Read the client's anonymous distinct_id from the posthog-js persistence
+ * cookie (persistence: "cookie"). Absent or malformed cookies yield undefined.
+ */
+export function getClientAnonymousDistinctId(req: NextRequest) {
+ if (!env.NEXT_PUBLIC_POSTHOG_API_KEY) {
+ return undefined;
+ }
+
+ const cookie = req.cookies.get(
+ getPostHogCookieName(env.NEXT_PUBLIC_POSTHOG_API_KEY),
+ );
+
+ return parsePostHogCookieDistinctId(cookie?.value) ?? undefined;
+}
+
/**
* Update properties on a group (e.g. poll, space). Groups are independent
* of person profiles, so no guest handling is involved.
diff --git a/apps/web/src/trpc/context.ts b/apps/web/src/trpc/context.ts
index d5b560924..75659c9b2 100644
--- a/apps/web/src/trpc/context.ts
+++ b/apps/web/src/trpc/context.ts
@@ -6,4 +6,10 @@ export type TRPCContext = {
locale?: string;
identifier?: string;
event?: WideEvent;
+ /**
+ * The client's PostHog anonymous distinct_id, read from the posthog-js
+ * persistence cookie. Used to stitch guest server-side captures to the
+ * client's event stream. Absent when the cookie is missing or malformed.
+ */
+ anonymousDistinctId?: string;
};
diff --git a/apps/web/src/trpc/routers/polls.ts b/apps/web/src/trpc/routers/polls.ts
index 9477f25af..9ac501f3c 100644
--- a/apps/web/src/trpc/routers/polls.ts
+++ b/apps/web/src/trpc/routers/polls.ts
@@ -158,14 +158,17 @@ export const polls = router({
});
if (moderation.verdict !== "safe") {
- track(ctx.user, {
- event: "flagged_content",
- properties: {
- action: "create_poll",
- verdict: moderation.verdict,
- reason: moderation.reason,
+ track(
+ { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },
+ {
+ event: "flagged_content",
+ properties: {
+ action: "create_poll",
+ verdict: moderation.verdict,
+ reason: moderation.reason,
+ },
},
- });
+ );
}
if (moderation.verdict === "flagged") {
@@ -278,25 +281,28 @@ export const polls = router({
},
});
- track(ctx.user, {
- event: "poll_create",
- properties: {
- title: poll.title,
- optionCount: poll.options.length,
- hasLocation: !!location,
- hasDescription: !!description,
- timezone: input.timeZone,
- disableComments: poll.disableComments,
- hideParticipants: poll.hideParticipants,
- hideScores: poll.hideScores,
- requireParticipantEmail: poll.requireParticipantEmail,
- isGuest: ctx.user.isGuest,
- },
- groups: {
- poll: poll.id,
- ...(poll.spaceId ? { space: poll.spaceId } : {}),
+ track(
+ { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },
+ {
+ event: "poll_create",
+ properties: {
+ title: poll.title,
+ optionCount: poll.options.length,
+ hasLocation: !!location,
+ hasDescription: !!description,
+ timezone: input.timeZone,
+ disableComments: poll.disableComments,
+ hideParticipants: poll.hideParticipants,
+ hideScores: poll.hideScores,
+ requireParticipantEmail: poll.requireParticipantEmail,
+ isGuest: ctx.user.isGuest,
+ },
+ groups: {
+ poll: poll.id,
+ ...(poll.spaceId ? { space: poll.spaceId } : {}),
+ },
},
- });
+ );
return { ok: true as const, data: { id: poll.id } };
}),
@@ -349,14 +355,17 @@ export const polls = router({
});
if (moderation.verdict !== "safe") {
- track(ctx.user, {
- event: "flagged_content",
- properties: {
- action: "update_poll",
- verdict: moderation.verdict,
- reason: moderation.reason,
+ track(
+ { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },
+ {
+ event: "flagged_content",
+ properties: {
+ action: "update_poll",
+ verdict: moderation.verdict,
+ reason: moderation.reason,
+ },
},
- });
+ );
}
if (moderation.verdict === "flagged") {
@@ -500,45 +509,54 @@ export const polls = router({
input.requireParticipantEmail !== undefined;
if (hasDetailsUpdate) {
- track(ctx.user, {
- event: "poll_update_details",
- properties: {
- title: updatedPoll.title,
- has_location: !!updatedPoll.location,
- has_description: !!updatedPoll.description,
- is_guest: ctx.user.isGuest,
- },
- groups: {
- poll: pollId,
+ track(
+ { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },
+ {
+ event: "poll_update_details",
+ properties: {
+ title: updatedPoll.title,
+ has_location: !!updatedPoll.location,
+ has_description: !!updatedPoll.description,
+ is_guest: ctx.user.isGuest,
+ },
+ groups: {
+ poll: pollId,
+ },
},
- });
+ );
}
if (hasOptionsUpdate) {
- track(ctx.user, {
- event: "poll_update_options",
- properties: {
- option_count: updatedPoll._count.options,
- },
- groups: {
- poll: pollId,
+ track(
+ { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },
+ {
+ event: "poll_update_options",
+ properties: {
+ option_count: updatedPoll._count.options,
+ },
+ groups: {
+ poll: pollId,
+ },
},
- });
+ );
}
if (hasSettingsUpdate) {
- track(ctx.user, {
- event: "poll_update_settings",
- properties: {
- disable_comments: !!updatedPoll.disableComments,
- hide_participants: !!updatedPoll.hideParticipants,
- hide_scores: !!updatedPoll.hideScores,
- require_participant_email: !!updatedPoll.requireParticipantEmail,
- },
- groups: {
- poll: pollId,
+ track(
+ { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },
+ {
+ event: "poll_update_settings",
+ properties: {
+ disable_comments: !!updatedPoll.disableComments,
+ hide_participants: !!updatedPoll.hideParticipants,
+ hide_scores: !!updatedPoll.hideScores,
+ require_participant_email: !!updatedPoll.requireParticipantEmail,
+ },
+ groups: {
+ poll: pollId,
+ },
},
- });
+ );
}
return { ok: true as const };
@@ -566,12 +584,15 @@ export const polls = router({
});
// Track poll deletion analytics
- track(ctx.user, {
- event: "poll_delete",
- groups: {
- poll: pollId,
+ track(
+ { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },
+ {
+ event: "poll_delete",
+ groups: {
+ poll: pollId,
+ },
},
- });
+ );
}),
// END LEGACY ROUTES
toggleMuted: privateProcedure
@@ -1073,17 +1094,20 @@ export const polls = router({
);
}
- track(ctx.user, {
- event: "poll_schedule",
- properties: {
- attendee_count: attendees.length,
- days_since_created: dayjs().diff(poll.createdAt, "day"),
- participant_count: poll.participants.length,
- },
- groups: {
- poll: poll.id,
+ track(
+ { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },
+ {
+ event: "poll_schedule",
+ properties: {
+ attendee_count: attendees.length,
+ days_since_created: dayjs().diff(poll.createdAt, "day"),
+ participant_count: poll.participants.length,
+ },
+ groups: {
+ poll: poll.id,
+ },
},
- });
+ );
}
}),
reopen: privateProcedure
@@ -1122,12 +1146,15 @@ export const polls = router({
}
});
- track(ctx.user, {
- event: "poll_reopen",
- groups: {
- poll: input.pollId,
+ track(
+ { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },
+ {
+ event: "poll_reopen",
+ groups: {
+ poll: input.pollId,
+ },
},
- });
+ );
}),
close: possiblyPublicProcedure
.input(
@@ -1156,12 +1183,15 @@ export const polls = router({
},
});
- track(ctx.user, {
- event: "poll_close",
- groups: {
- poll: input.pollId,
+ track(
+ { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },
+ {
+ event: "poll_close",
+ groups: {
+ poll: input.pollId,
+ },
},
- });
+ );
}),
duplicate: proProcedure
.input(
diff --git a/apps/web/src/trpc/routers/polls/comments.ts b/apps/web/src/trpc/routers/polls/comments.ts
index a9bf112e7..805c2b651 100644
--- a/apps/web/src/trpc/routers/polls/comments.ts
+++ b/apps/web/src/trpc/routers/polls/comments.ts
@@ -166,15 +166,18 @@ export const comments = router({
}
// Track comment addition analytics
- track(ctx.user, {
- event: "poll_comment_add",
- properties: {
- is_guest: ctx.user.isGuest,
- },
- groups: {
- poll: pollId,
+ track(
+ { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },
+ {
+ event: "poll_comment_add",
+ properties: {
+ is_guest: ctx.user.isGuest,
+ },
+ groups: {
+ poll: pollId,
+ },
},
- });
+ );
return newComment;
}),
@@ -216,11 +219,14 @@ export const comments = router({
});
// Track comment deletion analytics
- track(actor, {
- event: "poll_comment_delete",
- groups: {
- poll: comment.pollId,
+ track(
+ { ...actor, anonymousDistinctId: ctx.anonymousDistinctId },
+ {
+ event: "poll_comment_delete",
+ groups: {
+ poll: comment.pollId,
+ },
},
- });
+ );
}),
});
diff --git a/apps/web/src/trpc/routers/polls/participants.ts b/apps/web/src/trpc/routers/polls/participants.ts
index 7d4695bc7..dbb6c7352 100644
--- a/apps/web/src/trpc/routers/polls/participants.ts
+++ b/apps/web/src/trpc/routers/polls/participants.ts
@@ -210,15 +210,18 @@ export const participants = router({
},
});
- track(actor, {
- event: "poll_response_delete",
- properties: {
- participant_id: participant.id,
- },
- groups: {
- poll: participant.pollId,
+ track(
+ { ...actor, anonymousDistinctId: ctx.anonymousDistinctId },
+ {
+ event: "poll_response_delete",
+ properties: {
+ participant_id: participant.id,
+ },
+ groups: {
+ poll: participant.pollId,
+ },
},
- });
+ );
}),
add: publicProcedure
.use(createRateLimitMiddleware("add_participant", 10, "1 h"))
@@ -347,17 +350,20 @@ export const participants = router({
}),
);
- track(ctx.user, {
- event: "poll_response_submit",
- properties: {
- participant_id: participant.id,
- has_email: !!email,
- total_responses: totalResponses,
- },
- groups: {
- poll: pollId,
+ track(
+ { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },
+ {
+ event: "poll_response_submit",
+ properties: {
+ participant_id: participant.id,
+ has_email: !!email,
+ total_responses: totalResponses,
+ },
+ groups: {
+ poll: pollId,
+ },
},
- });
+ );
return createParticipantFullDTO(participant);
},
@@ -466,12 +472,15 @@ export const participants = router({
});
});
- track(actor, {
- event: "poll_response_update",
- groups: {
- poll: pollId,
+ track(
+ { ...actor, anonymousDistinctId: ctx.anonymousDistinctId },
+ {
+ event: "poll_response_update",
+ groups: {
+ poll: pollId,
+ },
},
- });
+ );
return createParticipantFullDTO(participant);
}),
diff --git a/packages/posthog/package.json b/packages/posthog/package.json
index 30a49695e..be7c71ac8 100644
--- a/packages/posthog/package.json
+++ b/packages/posthog/package.json
@@ -10,6 +10,7 @@
"scripts": {
"backfill-space-group-properties": "dotenv -e .env -- pnpx tsx ./src/scripts/backfill-space-group-properties.ts",
"purge-guest-profiles": "dotenv -e .env -- pnpx tsx ./src/scripts/purge-guest-profiles.ts",
+ "test:unit": "vitest run",
"type-check": "tsc --noEmit"
},
"dependencies": {
@@ -23,6 +24,7 @@
"@rallly/tsconfig": "workspace:*",
"@types/js-cookie": "^3.0.1",
"@types/node": "^24.1.0",
- "@types/react": "19.2.13"
+ "@types/react": "19.2.13",
+ "vitest": "^4.0.16"
}
}
diff --git a/packages/posthog/src/utils.test.ts b/packages/posthog/src/utils.test.ts
new file mode 100644
index 000000000..7113f036e
--- /dev/null
+++ b/packages/posthog/src/utils.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from "vitest";
+import { getPostHogCookieName, parsePostHogCookieDistinctId } from "./utils";
+
+describe("getPostHogCookieName", () => {
+ it("builds the posthog-js persistence cookie name", () => {
+ expect(getPostHogCookieName("phc_abc123")).toBe("ph_phc_abc123_posthog");
+ });
+});
+
+describe("parsePostHogCookieDistinctId", () => {
+ it("parses a URL-encoded JSON cookie value", () => {
+ const value = encodeURIComponent(
+ JSON.stringify({ distinct_id: "0198c0de-anon", $sesid: [123, "abc"] }),
+ );
+ expect(parsePostHogCookieDistinctId(value)).toBe("0198c0de-anon");
+ });
+
+ it("parses an already-decoded JSON cookie value", () => {
+ const value = JSON.stringify({ distinct_id: "anon-id" });
+ expect(parsePostHogCookieDistinctId(value)).toBe("anon-id");
+ });
+
+ it("parses a decoded value containing a literal percent sign", () => {
+ const value = JSON.stringify({
+ distinct_id: "anon-id",
+ $initial_referrer: "https://example.com/?q=100%",
+ });
+ expect(parsePostHogCookieDistinctId(value)).toBe("anon-id");
+ });
+
+ it("returns null for undefined", () => {
+ expect(parsePostHogCookieDistinctId(undefined)).toBeNull();
+ });
+
+ it("returns null for an empty string", () => {
+ expect(parsePostHogCookieDistinctId("")).toBeNull();
+ });
+
+ it("returns null for malformed JSON", () => {
+ expect(parsePostHogCookieDistinctId("not-json")).toBeNull();
+ expect(parsePostHogCookieDistinctId("%7Bbroken")).toBeNull();
+ });
+
+ it("returns null for JSON without a distinct_id", () => {
+ expect(
+ parsePostHogCookieDistinctId(JSON.stringify({ $sesid: [1, "a"] })),
+ ).toBeNull();
+ });
+
+ it("returns null for a non-string distinct_id", () => {
+ expect(
+ parsePostHogCookieDistinctId(JSON.stringify({ distinct_id: 42 })),
+ ).toBeNull();
+ });
+
+ it("returns null for an empty distinct_id", () => {
+ expect(
+ parsePostHogCookieDistinctId(JSON.stringify({ distinct_id: "" })),
+ ).toBeNull();
+ });
+
+ it("returns null for non-object JSON", () => {
+ expect(parsePostHogCookieDistinctId('"a string"')).toBeNull();
+ expect(parsePostHogCookieDistinctId("null")).toBeNull();
+ });
+});
diff --git a/packages/posthog/src/utils.ts b/packages/posthog/src/utils.ts
index 1f68c7bfb..fee9ca296 100644
--- a/packages/posthog/src/utils.ts
+++ b/packages/posthog/src/utils.ts
@@ -1,5 +1,47 @@
import type { CaptureResult } from "posthog-js";
+export function getPostHogCookieName(apiKey: string) {
+ return `ph_${apiKey}_posthog`;
+}
+
+/**
+ * Extract the client's distinct_id from the posthog-js persistence cookie
+ * (`persistence: "cookie"` in client.ts). The raw cookie value is URL-encoded
+ * JSON, but some runtimes hand it over already decoded — handle both. Returns
+ * null for a missing or malformed value.
+ */
+export function parsePostHogCookieDistinctId(
+ cookieValue: string | undefined,
+): string | null {
+ if (!cookieValue) {
+ return null;
+ }
+
+ let json = cookieValue;
+ try {
+ json = decodeURIComponent(cookieValue);
+ } catch {
+ // Not URL-encoded — parse as-is
+ }
+
+ try {
+ const parsed: unknown = JSON.parse(json);
+ if (
+ typeof parsed === "object" &&
+ parsed !== null &&
+ "distinct_id" in parsed
+ ) {
+ const distinctId = (parsed as { distinct_id: unknown }).distinct_id;
+ if (typeof distinctId === "string" && distinctId.length > 0) {
+ return distinctId;
+ }
+ }
+ return null;
+ } catch {
+ return null;
+ }
+}
+
type NavigatorWithGlobalPrivacyControl = Navigator & {
globalPrivacyControl?: boolean;
};
diff --git a/packages/posthog/vitest.config.mts b/packages/posthog/vitest.config.mts
new file mode 100644
index 000000000..0e094b1ee
--- /dev/null
+++ b/packages/posthog/vitest.config.mts
@@ -0,0 +1,9 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ globals: true,
+ include: ["**/*.test.ts"],
+ exclude: ["**/node_modules/**", "**/*.spec.ts"],
+ },
+});
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 04391da85..48f5e06d9 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -693,6 +693,9 @@ importers:
'@types/react':
specifier: 19.2.13
version: 19.2.13
+ vitest:
+ specifier: ^4.0.16
packages/screenshots:
dependencies: