Rallly is an open-source scheduling and collaboration tool designed to make organizing events and meetings easier.
TypeScript i18nextnext-authnextjspostgresqlprismareact-emailt3-stacktailwindcsstrpcturborepotypescriptzod
π Stop PostHog minting empty person profiles: memory-only client, no cookie banner (#3156)
Luke Vellabe8b75dc5a79
diff --git a/apps/landing/src/app/[locale]/(main)/cookie-policy/page.tsx b/apps/landing/src/app/[locale]/(main)/cookie-policy/page.tsxindex b43907581..fd564a252 100644--- a/apps/landing/src/app/[locale]/(main)/cookie-policy/page.tsx+++ b/apps/landing/src/app/[locale]/(main)/cookie-policy/page.tsx@@ -8,7 +8,7 @@ export default async function CookiePolicy() {cacheLife("max");return (<Section>- <LegalPageLayout title="Cookie policy" lastUpdated="2026-04-04">+ <LegalPageLayout title="Cookie policy" lastUpdated="2026-09-03"><p>This Policy explains how we use cookies and other similar technologieson our website, and your options to control them.@@ -30,26 +30,33 @@ export default async function CookiePolicy() {enable you to access secure areas of the website. They cannot bedisabled.</p>- <h3>Analytics cookies</h3>+ <h3>Attribution cookies</h3><p>- We use PostHog to collect anonymous analytics data that helps us- understand how visitors use our website and identify areas for- improvement. PostHog sets cookies to distinguish between users and- sessions. The data collected includes pages visited, events triggered,- device type, and IP address (used for approximate geolocation only).- This information is stored on PostHog's EU-based servers and is- not used for advertising or shared with third parties.+ When you open the app from a link on this website, we set a cookie+ named <code>rallly_ref</code> (and, where applicable,{" "}+ <code>rallly_cta</code>) that records which page and button you came+ from. It exists only so we can tell which pages lead people to sign+ up. It is set by us, not by a third party, expires after 30 days, is+ read once if you create an account, and is not shared with anyone.+ </p>++ <h2>Analytics</h2>+ <p>+ We use PostHog for product analytics. PostHog does not set cookies and+ does not store anything on your device. Users who are signed in are+ recognised through their account. Visitors who are not signed in are+ counted using a hash derived from IP address and browser that changes+ every day and cannot be used to identify anyone. The data collected+ includes pages visited, events triggered, and device type. It is+ stored on PostHog's servers in the EU and is not used for+ advertising or shared with third parties.</p><h2>Your options</h2><p>Most web browsers allow you to control cookies through their settings- preferences. You can also opt out of analytics cookies by enabling the{" "}- <a href="https://globalprivacycontrol.org/" rel="noopener noreferrer">- Global Privacy Control- </a>{" "}- signal in your browser. Please be aware that disabling essential- cookies may prevent you from accessing certain parts of our website.+ preferences. Please be aware that disabling essential cookies may+ prevent you from accessing certain parts of our website.</p><h2>Changes to this policy</h2>diff --git a/apps/landing/src/app/[locale]/layout.tsx b/apps/landing/src/app/[locale]/layout.tsxindex f18a17b7f..1defb0246 100644--- a/apps/landing/src/app/[locale]/layout.tsx+++ b/apps/landing/src/app/[locale]/layout.tsx@@ -1,11 +1,11 @@import "./globals.css";import languages from "@rallly/languages";+import { PostHogInit } from "@rallly/posthog/client";import { Analytics } from "@vercel/analytics/react";import { domAnimation, LazyMotion } from "motion/react";import type { Metadata, Viewport } from "next";import { cacheLife } from "next/cache";-import { CookieConsent } from "@/components/cookie-consent";import { sans } from "@/fonts/sans";import { I18nProvider } from "@/i18n/client/i18n-provider";import { getTranslation } from "@/i18n/server";@@ -36,11 +36,9 @@ export default async function Root(props: {<body><LazyMotion features={domAnimation}><I18nProvider locale={i18n.resolvedLanguage} resources={translations}>- {children}- <CookieConsent />- {/* Cookieless (daily-rotating server-side hash, nothing stored- on the device), so it runs outside the consent gate β same- posture as PostHog's pre-consent cookieless capture. */}+ {/* Both cookieless (daily-rotating server-side hash, nothing+ stored on the device), so neither needs consent. */}+ <PostHogInit>{children}</PostHogInit><Analytics /></I18nProvider></LazyMotion>diff --git a/apps/landing/src/components/cookie-consent.tsx b/apps/landing/src/components/cookie-consent.tsxdeleted file mode 100644index f3aae0163..000000000--- a/apps/landing/src/components/cookie-consent.tsx+++ /dev/null@@ -1,48 +0,0 @@-"use client";-import { useCookieConsent } from "@rallly/posthog/client";-import { Button } from "@rallly/ui/button";-import { LinkBase } from "@/i18n/client/link";-import { Trans } from "@/i18n/client/trans";-import { useTranslation } from "@/i18n/client/use-translation";--export function CookieConsent() {- const { t } = useTranslation();- const { status, accept, reject } = useCookieConsent();-- if (status !== "pending") {- return null;- }-- return (- <section- aria-label={t("cookieConsentLabel", {- defaultValue: "Cookie consent",- })}- className="fixed bottom-4 left-4 z-50 flex max-w-[min(32rem,calc(100vw-2rem))] flex-wrap items-center gap-x-6 gap-y-3 rounded-xl border bg-white p-4 shadow-lg"- >- <p className="min-w-0 flex-1 basis-56 text-pretty text-sm">- <Trans- i18nKey="cookieConsentIntro"- defaults="We use cookies to improve your experience."- />{" "}- <Trans- i18nKey="cookieConsentPolicy"- defaults="Learn more in our <policyLink>cookie policy</policyLink>."- components={{- policyLink: (- <LinkBase className="underline" href="/cookie-policy" />- ),- }}- />- </p>- <div className="flex gap-2">- <Button onClick={reject}>- <Trans i18nKey="cookieConsentOptOut" defaults="Opt out" />- </Button>- <Button variant="primary" onClick={accept}>- <Trans i18nKey="cookieConsentAccept" defaults="Accept" />- </Button>- </div>- </section>- );-}diff --git a/apps/web/src/app/[locale]/components/posthog-init.tsx b/apps/web/src/app/[locale]/components/posthog-init.tsxnew file mode 100644index 000000000..fba3a867d--- /dev/null+++ b/apps/web/src/app/[locale]/components/posthog-init.tsx@@ -0,0 +1,25 @@+import { PostHogInit } from "@rallly/posthog/client";+import { getSession } from "@/lib/auth";++// Lives in the root layout so every route captures, including the login,+// setup and quick-create pages that mount no UserProvider. Wraps the page+// content rather than sitting beside it: the session read streams under a+// Suspense boundary, and a sibling boundary can resolve after the page's+// own gates have hydrated and run their effects, which posthog-js silently+// drops when it has not been initialised yet. As an ancestor it always+// renders first. getSession is request-cached, so the inner gates share+// this read.+export async function PostHogSessionInit({+ children,+}: {+ children: React.ReactNode;+}) {+ const session = await getSession();+ const user = session?.user;++ return (+ <PostHogInit distinctId={user && !user.isGuest ? user.id : undefined}>+ {children}+ </PostHogInit>+ );+}diff --git a/apps/web/src/app/[locale]/e/[id]/components/rsvp-verify-email.tsx b/apps/web/src/app/[locale]/e/[id]/components/rsvp-verify-email.tsxindex e03338a82..782e5881d 100644--- a/apps/web/src/app/[locale]/e/[id]/components/rsvp-verify-email.tsx+++ b/apps/web/src/app/[locale]/e/[id]/components/rsvp-verify-email.tsx@@ -18,7 +18,6 @@ import {FormItem,FormMessage,} from "@rallly/ui/form";-import { useRouter } from "next/navigation";import React from "react";import { useForm } from "react-hook-form";import * as z from "zod";@@ -42,7 +41,6 @@ export function RsvpVerifyEmail({const isCaptchaEnabled = useFeatureFlag("captcha");const isTurnstileEnabled = isCaptchaEnabled && !!turnstileSiteKey;const { t, i18n } = useTranslation();- const router = useRouter();const dialog = useDialog();const turnstileRef = React.useRef<TurnstileInstance>(null);const [otpSent, setOtpSent] = React.useState(false);@@ -131,7 +129,10 @@ export function RsvpVerifyEmail({}dialog.dismiss();- router.refresh();+ // A full reload, not router.refresh(): the PostHog client fixes its+ // identity at page load (cookieless for the guest who opened this page),+ // and only a new document can start it as the signed-in user.+ window.location.reload();});return (diff --git a/apps/web/src/app/[locale]/layout.tsx b/apps/web/src/app/[locale]/layout.tsxindex 63d653c45..15d073872 100644--- a/apps/web/src/app/[locale]/layout.tsx+++ b/apps/web/src/app/[locale]/layout.tsx@@ -8,8 +8,9 @@ import type { Metadata, Viewport } from "next";import { Inter } from "next/font/google";import { notFound } from "next/navigation";import type React from "react";+import { Suspense } from "react";+import { PostHogSessionInit } from "@/app/[locale]/components/posthog-init";import type { Params } from "@/app/[locale]/types";-import { CookieConsentBanner } from "@/components/cookie-consent-banner";import { SkipNavLink } from "@/components/skip-nav-link";import { BrandingProvider } from "@/features/branding/client";import { getInstanceBrandingConfig } from "@/features/branding/data";@@ -87,9 +88,12 @@ export default async function Root({<LazyMotion features={domAnimation}><SkipNavLink /><TimeZoneSync>- <TooltipProvider>{children}</TooltipProvider>+ <TooltipProvider>+ <Suspense>+ <PostHogSessionInit>{children}</PostHogSessionInit>+ </Suspense>+ </TooltipProvider></TimeZoneSync>- <CookieConsentBanner /></LazyMotion></TRPCProvider></I18nProvider>diff --git a/apps/web/src/app/api/trpc/[trpc]/route.ts b/apps/web/src/app/api/trpc/[trpc]/route.tsindex e5bd048ee..847e104ca 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 { getClientAnonymousDistinctId, withPostHog } from "@/lib/posthog";+import { withPostHog } from "@/lib/posthog";import type { TRPCContext } from "@/trpc/context";import { appRouter } from "@/trpc/routers";@@ -49,7 +49,6 @@ const handler = async (req: NextRequest) => {locale,identifier,event,- anonymousDistinctId: getClientAnonymousDistinctId(req),} satisfies TRPCContext;},onError: ({ error }) => {diff --git a/apps/web/src/components/cookie-consent-banner.tsx b/apps/web/src/components/cookie-consent-banner.tsxdeleted file mode 100644index 7777b7b5a..000000000--- a/apps/web/src/components/cookie-consent-banner.tsx+++ /dev/null@@ -1,55 +0,0 @@-"use client";-import { useCookieConsent } from "@rallly/posthog/client";-import { Button } from "@rallly/ui/button";-import { isSelfHosted } from "@/components/environment";-import { Trans, useTranslation } from "@/i18n/client";--export function CookieConsentBanner() {- const { t } = useTranslation();- const { status, accept, reject } = useCookieConsent();-- if (status !== "pending") {- return null;- }-- return (- <section- aria-label={t("cookieConsentLabel", { defaultValue: "Cookie consent" })}- className="fixed bottom-4 left-4 z-50 flex max-w-[min(32rem,calc(100vw-2rem))] flex-wrap items-center gap-x-6 gap-y-3 rounded-xl border bg-background p-4 shadow-lg"- >- <p className="min-w-0 flex-1 basis-56 text-pretty text-sm">- <Trans- i18nKey="cookieConsentIntro"- defaults="We use cookies to improve your experience."- />- {isSelfHosted ? null : (- <>- {" "}- <Trans- i18nKey="cookieConsentPolicy"- defaults="Learn more in our <policyLink>cookie policy</policyLink>."- components={{- policyLink: (- <a- className="underline"- href="https://rallly.co/cookie-policy"- target="_blank"- rel="noreferrer"- />- ),- }}- />- </>- )}- </p>- <div className="flex gap-2">- <Button onClick={reject}>- <Trans i18nKey="cookieConsentOptOut" defaults="Opt out" />- </Button>- <Button variant="primary" onClick={accept}>- <Trans i18nKey="cookieConsentAccept" defaults="Accept" />- </Button>- </div>- </section>- );-}diff --git a/apps/web/src/features/space/client.tsx b/apps/web/src/features/space/client.tsxindex d7c60b743..39db83f11 100644--- a/apps/web/src/features/space/client.tsx+++ b/apps/web/src/features/space/client.tsx@@ -1,6 +1,5 @@"use client";-import { posthog } from "@rallly/posthog/client";import React from "react";import { getPrimaryColorVars } from "@/features/branding/utils";import { useInstancePolicy } from "@/features/instance-policy/client";@@ -44,15 +43,6 @@ export function SpaceProvider({space: SpaceDTO;children: React.ReactNode;}) {- React.useEffect(() => {- // No properties here β posthog-js captures $groupidentify on EVERY- // group() call that passes properties (no diffing), which fired one- // event per page load. Without properties it only fires when the- // group key changes. Group properties are maintained by the- // server-side identifyGroup calls on the mutations that change them.- posthog?.group("space", space.id);- }, [space.id]);-const { spaceBrandingAllowed } = useInstancePolicy();const primaryColorVars =diff --git a/apps/web/src/features/user/client.tsx b/apps/web/src/features/user/client.tsxindex 4a187392b..618a45065 100644--- a/apps/web/src/features/user/client.tsx+++ b/apps/web/src/features/user/client.tsx@@ -22,14 +22,20 @@ export function UserProvider({const isGuest = user?.isGuest;const { locale } = useLocale();- // Changing the language refreshes the router with a new [locale] param, so- // this re-runs; posthog-js turns a repeat identify into a $set and drops it- // when the properties are unchanged.+ const name = user?.name;+ const email = user?.email;++ // The client is already identified as this user from init (bootstrap in+ // packages/posthog/src/client-config.ts), so no identify() here. Name and+ // email ride along so a profile PostHog has to recreate for an existing+ // account is never empty. Changing the language refreshes the router with+ // a new [locale] param, so this re-runs; posthog-js drops a repeat $set+ // with unchanged properties.React.useEffect(() => {if (userId && !isGuest) {- posthog.identify(userId, { locale });+ posthog.setPersonProperties({ name, email, locale });}- }, [userId, isGuest, locale]);+ }, [userId, isGuest, name, email, locale]);return <UserContext.Provider value={user}>{children}</UserContext.Provider>;}diff --git a/apps/web/src/lib/posthog.ts b/apps/web/src/lib/posthog.tsindex c4f377918..da15071ab 100644--- a/apps/web/src/lib/posthog.ts+++ b/apps/web/src/lib/posthog.ts@@ -1,9 +1,5 @@import { createLogger } from "@rallly/logger";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";@@ -31,35 +27,27 @@ export function posthog() {* server β importing the raw `posthog` client is lint-restricted (see* noRestrictedImports in apps/web/biome.json) so the guest decision cannot* be forgotten at individual capture sites. Guests are captured as anonymous- * events (no person profile β they are transient and rarely convert);- * identified users get person processing as usual. Note: PostHog drops- * group associations on personless events, so `groups` passed here only- * take effect for identified users β put poll/space/tier on plain- * properties when guest events need them.+ * events under their guest user id (no person profile β they are transient+ * and rarely convert); registered users get person processing as usual.+ * Note: PostHog drops group associations on personless events, so `groups`+ * passed here only take effect for identified users β put poll/space/tier on+ * plain properties when guest events need them.*- * 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.+ * The browser client stores nothing on the device (see+ * packages/posthog/src/client-config.ts), so there is no anonymous id to+ * stitch guest server events to; they stand alone.*/export function track(- user: { id: string; isGuest: boolean; anonymousDistinctId?: string },+ user: { id: string; isGuest: boolean },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,+ distinctId: user.id,properties: {...event.properties,$process_person_profile: !user.isGuest,@@ -67,22 +55,6 @@ 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;-}-// Without an explicit distinctId, groupIdentify defaults to// $<groupType>_<groupKey>, creating a dummy person profile per group// (PostHog/posthog#7921). A single shared id caps the junk at one person.diff --git a/apps/web/src/trpc/context.ts b/apps/web/src/trpc/context.tsindex 75659c9b2..d5b560924 100644--- a/apps/web/src/trpc/context.ts+++ b/apps/web/src/trpc/context.ts@@ -6,10 +6,4 @@ 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.tsindex 3b772ef62..3a5469abb 100644--- a/apps/web/src/trpc/routers/polls.ts+++ b/apps/web/src/trpc/routers/polls.ts@@ -139,17 +139,14 @@ export const polls = router({});if (moderation.verdict !== "safe") {- track(- { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },- {- event: "flagged_content",- properties: {- action: "create_poll",- verdict: moderation.verdict,- reason: moderation.reason,- },+ track(ctx.user, {+ event: "flagged_content",+ properties: {+ action: "create_poll",+ verdict: moderation.verdict,+ reason: moderation.reason,},- );+ });}if (moderation.verdict === "flagged") {@@ -272,30 +269,27 @@ export const polls = router({},});- track(- { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },- {- event: "poll_create",- properties: {- title: poll.title,- kind,- source: "web",- 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, {+ event: "poll_create",+ properties: {+ title: poll.title,+ kind,+ source: "web",+ 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,17 +343,14 @@ export const polls = router({});if (moderation.verdict !== "safe") {- track(- { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },- {- event: "flagged_content",- properties: {- action: "update_poll",- verdict: moderation.verdict,- reason: moderation.reason,- },+ track(ctx.user, {+ event: "flagged_content",+ properties: {+ action: "update_poll",+ verdict: moderation.verdict,+ reason: moderation.reason,},- );+ });}if (moderation.verdict === "flagged") {@@ -631,54 +622,45 @@ export const polls = router({input.requireParticipantEmail !== undefined;if (hasDetailsUpdate) {- 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,- },+ 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,+ },+ });}if (hasOptionsUpdate) {- track(- { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },- {- event: "poll_update_options",- properties: {- option_count: updatedPoll._count.options,- },- groups: {- poll: pollId,- },+ track(ctx.user, {+ event: "poll_update_options",+ properties: {+ option_count: updatedPoll._count.options,},- );+ groups: {+ poll: pollId,+ },+ });}if (hasSettingsUpdate) {- 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,- },+ 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,+ },+ });}return { ok: true as const };@@ -706,15 +688,12 @@ export const polls = router({});// Track poll deletion analytics- track(- { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },- {- event: "poll_delete",- groups: {- poll: pollId,- },+ track(ctx.user, {+ event: "poll_delete",+ groups: {+ poll: pollId,},- );+ });}),// END LEGACY ROUTESget: publicProcedure@@ -1221,20 +1200,17 @@ export const polls = router({);}- 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,- },+ 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,+ },+ });}}),reopen: privateProcedure@@ -1297,15 +1273,12 @@ export const polls = router({]);});- track(- { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },- {- event: "poll_reopen",- groups: {- poll: input.pollId,- },+ track(ctx.user, {+ event: "poll_reopen",+ groups: {+ poll: input.pollId,},- );+ });}),close: possiblyPublicProcedure.input(@@ -1355,15 +1328,12 @@ export const polls = router({]);});- track(- { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },- {- event: "poll_close",- groups: {- poll: input.pollId,- },+ track(ctx.user, {+ 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.tsindex 095fa7f65..1043d4de2 100644--- a/apps/web/src/trpc/routers/polls/comments.ts+++ b/apps/web/src/trpc/routers/polls/comments.ts@@ -187,18 +187,15 @@ export const comments = router({}// Track comment addition analytics- track(- { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },- {- event: "poll_comment_add",- properties: {- is_guest: ctx.user.isGuest,- },- groups: {- poll: pollId,- },+ track(ctx.user, {+ event: "poll_comment_add",+ properties: {+ is_guest: ctx.user.isGuest,+ },+ groups: {+ poll: pollId,},- );+ });return newComment;}),@@ -240,14 +237,11 @@ export const comments = router({});// Track comment deletion analytics- track(- { ...actor, anonymousDistinctId: ctx.anonymousDistinctId },- {- event: "poll_comment_delete",- groups: {- poll: comment.pollId,- },+ track(actor, {+ 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.tsindex cf8a92191..bb41a7d7a 100644--- a/apps/web/src/trpc/routers/polls/participants.ts+++ b/apps/web/src/trpc/routers/polls/participants.ts@@ -280,18 +280,15 @@ export const participants = router({]);});- track(- { ...actor, anonymousDistinctId: ctx.anonymousDistinctId },- {- event: "poll_response_delete",- properties: {- participant_id: participant.id,- },- groups: {- poll: participant.pollId,- },+ track(actor, {+ event: "poll_response_delete",+ properties: {+ participant_id: participant.id,},- );+ groups: {+ poll: participant.pollId,+ },+ });}),add: publicProcedure.use(createRateLimitMiddleware("add_participant", 10, "1 h"))@@ -448,27 +445,24 @@ export const participants = router({}),);- track(- { ...ctx.user, anonymousDistinctId: ctx.anonymousDistinctId },- {- event: "poll_response_submit",- properties: {- participant_id: participant.id,- // plain properties, not groups: guest events are personless and- // PostHog drops group associations without person processing- poll_id: pollId,- space_id: participant.poll.space?.id,- tier: participant.poll.space?.tier,- has_email: !!email,- has_note: !!participant.note,- note_length: participant.note?.length,- total_responses: totalResponses,- },- groups: {- poll: pollId,- },+ track(ctx.user, {+ event: "poll_response_submit",+ properties: {+ participant_id: participant.id,+ // plain properties, not groups: guest events are personless and+ // PostHog drops group associations without person processing+ poll_id: pollId,+ space_id: participant.poll.space?.id,+ tier: participant.poll.space?.tier,+ has_email: !!email,+ has_note: !!participant.note,+ note_length: participant.note?.length,+ total_responses: totalResponses,},- );+ groups: {+ poll: pollId,+ },+ });return createParticipantFullDTO(participant);},@@ -601,15 +595,12 @@ export const participants = router({return updatedParticipant;});- track(- { ...actor, anonymousDistinctId: ctx.anonymousDistinctId },- {- event: "poll_response_update",- groups: {- poll: pollId,- },+ track(actor, {+ event: "poll_response_update",+ groups: {+ poll: pollId,},- );+ });return createParticipantFullDTO(participant);}),diff --git a/packages/posthog/src/client-config.test.ts b/packages/posthog/src/client-config.test.tsnew file mode 100644index 000000000..a2e9a10f5--- /dev/null+++ b/packages/posthog/src/client-config.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from "vitest";+import { getPostHogInitOptions } from "./client-config";++describe("getPostHogInitOptions", () => {+ it("runs cookieless when there is no identified user", () => {+ const options = getPostHogInitOptions({});++ expect(options.cookieless_mode).toBe("always");+ expect(options.bootstrap).toBeUndefined();+ });++ it("bootstraps an identified user in memory without a cookie", () => {+ const options = getPostHogInitOptions({ distinctId: "user_123" });++ expect(options.persistence).toBe("memory");+ expect(options.bootstrap).toEqual({+ distinctID: "user_123",+ isIdentifiedID: true,+ });+ expect(options.cookieless_mode).toBeUndefined();+ });++ it("never creates person profiles for anonymous ids", () => {+ expect(getPostHogInitOptions({}).person_profiles).toBe("identified_only");+ expect(+ getPostHogInitOptions({ distinctId: "user_123" }).person_profiles,+ ).toBe("identified_only");+ });+});diff --git a/packages/posthog/src/client-config.ts b/packages/posthog/src/client-config.tsnew file mode 100644index 000000000..2b8f785bd--- /dev/null+++ b/packages/posthog/src/client-config.ts@@ -0,0 +1,39 @@+import type { PostHogConfig } from "posthog-js";++/**+ * Persistence and identity options for the browser client. Nothing is ever+ * stored on the device, so no consent banner is needed under ePrivacy:+ *+ * - A logged-in user is bootstrapped as already identified. The first event+ * carries their user id, so no anonymous id is minted and no merge runs β+ * every anonymous id that gets merged would otherwise be appended to the+ * person's distinct ids forever, one per page load.+ * - Anyone else captures cookielessly: the client sends a sentinel id and the+ * server substitutes a daily-rotating hash of IP+UA. Requires "Cookieless+ * server hash mode" in PostHog project settings. identify() is unavailable+ * in this mode, which is why the identified branch bootstraps at init+ * instead of identifying after the fact.+ *+ * Person profiles stay identified-only in both branches. Never call+ * posthog.group() from the browser: registering a group turns person+ * processing on for whatever distinct id is current, identified or not,+ * which is how cookieless visitors ended up with a fresh empty person per+ * day. Group membership is attached server-side by track() and identifyGroup.+ */+export function getPostHogInitOptions({+ distinctId,+}: {+ distinctId?: string;+}): Partial<PostHogConfig> {+ const identity: Partial<PostHogConfig> = distinctId+ ? {+ persistence: "memory",+ bootstrap: { distinctID: distinctId, isIdentifiedID: true },+ }+ : { cookieless_mode: "always" };++ return {+ person_profiles: "identified_only",+ ...identity,+ };+}diff --git a/packages/posthog/src/client.ts b/packages/posthog/src/client.tsindex e0e2c136d..1d7561315 100644--- a/packages/posthog/src/client.ts+++ b/packages/posthog/src/client.ts@@ -1,41 +1,40 @@"use client";import posthog from "posthog-js";-import React from "react";+import type React from "react";export { useFeatureFlagEnabled } from "posthog-js/react";+import { getPostHogInitOptions } from "./client-config";import {isAbortError,- isGlobalPrivacyControlEnabled,isInjectedExtensionException,isResizeObserverLoopError,isUnsymbolicatedMinifiedException,} from "./utils";-if (typeof window !== "undefined" && process.env.NEXT_PUBLIC_POSTHOG_API_KEY) {- posthog.init(process.env.NEXT_PUBLIC_POSTHOG_API_KEY, {+let initialized = false;++/**+ * Initialise the browser client once per page load. Idempotent and safe to+ * call during render, which is deliberate: it has to run before any child+ * effect captures an event or registers a group, and effects run child-first.+ * No-op on the server and when no key is configured.+ */+export function initPostHog({ distinctId }: { distinctId?: string } = {}) {+ const apiKey = process.env.NEXT_PUBLIC_POSTHOG_API_KEY;+ if (initialized || typeof window === "undefined" || !apiKey) {+ return;+ }+ initialized = true;++ posthog.init(apiKey, {debug: false,api_host: process.env.NEXT_PUBLIC_POSTHOG_API_HOST,ui_host: process.env.NEXT_PUBLIC_POSTHOG_UI_HOST,capture_pageview: "history_change",capture_pageleave: true,enable_heatmaps: false,- persistence: "cookie",autocapture: false,- // ePrivacy consent model: until the user accepts the cookie banner β- // and permanently if they reject it β nothing is stored on the device- // (no ph_* cookie) and events are captured cookielessly: the client- // sends a sentinel distinct_id and the server substitutes a- // daily-rotating hash of IP+UA. Requires "Cookieless server hash mode"- // in PostHog project settings; without it these events are dropped at- // ingestion. opt_in_capturing() switches to full cookie persistence.- cookieless_mode: "on_reject",- opt_out_capturing_by_default: true,- opt_out_persistence_by_default: true,- // The consent decision rides the apex-domain cookie like the identity- // cookie, so a choice made on the landing site carries to the app.- opt_out_capturing_persistence_type: "cookie",- cross_subdomain_cookie: true,capture_performance: {web_vitals: false,},@@ -51,43 +50,32 @@ if (typeof window !== "undefined" && process.env.NEXT_PUBLIC_POSTHOG_API_KEY) {}return event;},+ ...getPostHogInitOptions({ distinctId }),});}-export { posthog };-/**- * Consent state for the cookie banner, backed by PostHog's own consent- * store (a cross-subdomain first-party cookie β strictly necessary, so- * exempt from consent itself).+ * Wrap the page content in this so the client is initialised before any+ * descendant renders or runs an effect β a sibling placed earlier in the+ * tree is not enough once Suspense boundaries stream in out of order. Pass+ * the logged-in user's id so the session is identified from its first+ * event; omit it for anonymous visitors and guests.*- * `status` is null until mounted (the decision is client-side state, so- * banners must render nothing on the server), and stays null when there is- * no PostHog key or the browser sends Global Privacy Control β GPC is an- * opt-out signal, so showing the banner would ask the user to override a- * choice they already expressed; capture stays cookieless instead.+ * Identity is fixed for the life of the document: a cookieless instance+ * cannot identify later, and a bootstrapped one must not be re-pointed at+ * another user. Sign-in flows therefore end in a full navigation, never a+ * router.refresh(), and sign-out calls posthog.reset() so events after it+ * are anonymous until the next document load.*/-export function useCookieConsent() {- const [status, setStatus] = React.useState<- "pending" | "granted" | "denied" | null- >(null);-- React.useEffect(() => {- if (!posthog.__loaded || isGlobalPrivacyControlEnabled()) {- return;- }- setStatus(posthog.get_explicit_consent_status());- }, []);-- const accept = React.useCallback(() => {- posthog.opt_in_capturing();- setStatus("granted");- }, []);-- const reject = React.useCallback(() => {- posthog.opt_out_capturing();- setStatus("denied");- }, []);-- return { status, accept, reject };+export function PostHogInit({+ distinctId,+ children,+}: {+ distinctId?: string;+ children: React.ReactNode;+}) {+ initPostHog({ distinctId });+ return children;}++export { posthog };diff --git a/packages/posthog/src/scripts/purge-guest-profiles.ts b/packages/posthog/src/scripts/purge-guest-profiles.tsindex 443661bfe..db542cea1 100644--- a/packages/posthog/src/scripts/purge-guest-profiles.ts+++ b/packages/posthog/src/scripts/purge-guest-profiles.ts@@ -1,5 +1,11 @@/**- * Deletes guest person profiles (no email property) from PostHog.+ * Deletes disposable person profiles from PostHog: profiles with no email+ * that were never identified and whose every distinct id is one nothing can+ * reattach to β a cookieless daily hash, a legacy `user-` guest id, or an+ * anonymous browser uuid. Profiles carrying a real user id, an email used as+ * a distinct id (license buyers) or an old cuid are left alone even when+ * they lack an email: deleting those would detach the account's event+ * history from the profile PostHog recreates on its next event.** Two-phase design so the delete loop never paginates a table it is mutating:*@@ -48,17 +54,21 @@ const DELETE_BATCH_SIZE = 1000;const DELETE_INTERVAL_MS = 800;const MAX_RATE_LIMIT_RETRIES = 5;-// Guests are persons with no usable email. `email = ''` matched 0 rows in-// production, but keep it in the predicate for correctness.-const GUEST_PREDICATE = "isNull(properties.email) OR properties.email = ''";+// A distinct id nothing can reattach to: the cookieless server hash rotates+// daily, `user-` ids are legacy guest ids from before guests captured+// personless, and 36-char uuids are anonymous browser ids from the old+// cookie persistence (ignored since the client went memory-only).+const DISPOSABLE_DISTINCT_ID =+ "startsWith(distinct_id, 'cookieless_') OR startsWith(distinct_id, 'user-') OR length(distinct_id) = 36";++// No email, never identified, and every distinct id disposable. `email = ''`+// matched 0 rows in production, but keep it in the predicate for correctness.+const GUEST_PREDICATE = `(isNull(properties.email) OR properties.email = '')+ AND NOT is_identified+ AND id IN (SELECT person_id FROM person_distinct_ids WHERE ${DISPOSABLE_DISTINCT_ID})+ AND id NOT IN (SELECT person_id FROM person_distinct_ids WHERE NOT (${DISPOSABLE_DISTINCT_ID}))`;const GUEST_COUNT_QUERY = `SELECT count() FROM persons WHERE ${GUEST_PREDICATE}`;-// Persons REST filter for the sample/canary reads (that endpoint uses property-// filters, not HogQL). Matches the "email not set" pass of the predicate.-const GUEST_REST_PROPERTIES = [- { key: "email", operator: "is_not_set", value: "is_not_set", type: "person" },-];-function sleep(ms: number) {return new Promise((resolve) => setTimeout(resolve, ms));}@@ -158,65 +168,66 @@ async function snapshotGuestIds(): Promise<string[]> {return ids;}-async function fetchGuestPage({- properties,- limit,-}: {- properties: unknown[];- limit: number;-}): Promise<- {- id: string | number;- uuid?: string;- distinct_ids?: string[];- properties?: Record<string, unknown>;- created_at?: string;- }[]+async function fetchGuestSample(+ limit: number,+): Promise<+ { id: string; created_at: string; distinctId: string | undefined }[]> {- const params = new URLSearchParams({- properties: JSON.stringify(properties),- limit: String(limit),- });- const data = await apiRequest({- path: `/api/projects/${PROJECT_ID}/persons/?${params}`,- });- return data.results ?? [];+ const rows = await hogqlQuery(+ `SELECT id, created_at FROM persons WHERE ${GUEST_PREDICATE} ORDER BY created_at DESC LIMIT ${limit}`,+ );+ if (rows.length === 0) return [];++ const ids = rows.map((row) => `toUUID('${quoteUuid(String(row[0]))}')`);+ const distinctRows = await hogqlQuery(+ `SELECT person_id, any(distinct_id) FROM person_distinct_ids WHERE person_id IN (${ids.join(", ")}) GROUP BY person_id`,+ );+ const distinctIdByPerson = new Map(+ distinctRows.map((row) => [String(row[0]), String(row[1])]),+ );++ return rows.map((row) => ({+ id: String(row[0]),+ created_at: String(row[1]),+ distinctId: distinctIdByPerson.get(String(row[0])),+ }));}async function preflight() {console.info("π Pre-flight counts (HogQL):\n");- const guests = await hogqlCount(+ const noEmail = await hogqlCount("SELECT count() FROM persons WHERE isNull(properties.email) OR properties.email = ''",);- const identifiedGuests = await hogqlCount(- "SELECT count() FROM persons WHERE (isNull(properties.email) OR properties.email = '') AND is_identified",- );+ const disposable = await hogqlCount(GUEST_COUNT_QUERY);const withEmail = await hogqlCount("SELECT count() FROM persons WHERE isNotNull(properties.email) AND properties.email != ''",);- console.info(`β’ Guest profiles (no email): ${guests}`);- console.info(`β’ β¦of which is_identified: ${identifiedGuests}`);- console.info(`β’ Profiles with an email: ${withEmail}`);+ console.info(`β’ Profiles with no email: ${fmt(noEmail)}`);+ console.info(+ `β’ β¦of which disposable (will be deleted): ${fmt(disposable)}`,+ );+ console.info(+ `β’ β¦kept (real user id, email id, or cuid): ${fmt(noEmail - disposable)}`,+ );+ console.info(+ `β’ Profiles with an email: ${fmt(withEmail)}`,+ );console.info("\nβ οΈ Sanity check: the with-email count should roughly match the registered user count in Postgres before you run --apply.",);- return guests;+ return disposable;}async function printSample() {- const sample = await fetchGuestPage({- properties: GUEST_REST_PROPERTIES,- limit: SAMPLE_SIZE,- });+ const sample = await fetchGuestSample(SAMPLE_SIZE);console.info(`\nπ Sample of ${sample.length} matched profiles:\n`);for (const person of sample) {- const email = person.properties?.email;console.info(- `β’ ${person.id} created=${person.created_at ?? "?"} email=${JSON.stringify(email ?? null)} distinct_id=${person.distinct_ids?.[0] ?? "?"}`,+ `β’ ${person.id} created=${person.created_at} distinct_id=${person.distinctId ?? "?"}`,);}}@@ -256,27 +267,24 @@ async function verifyCanary() {"π§ͺ Canary check β deletes ONE real guest profile and asserts its events are preserved.\n",);- const sample = await fetchGuestPage({- properties: GUEST_REST_PROPERTIES,- limit: SAMPLE_SIZE,- });+ const sample = await fetchGuestSample(SAMPLE_SIZE);let canary:| {- id: string | number;+ id: string;uuid: string;distinctId: string;eventCount: number;}| undefined;for (const person of sample) {- const distinctId = person.distinct_ids?.[0];+ const distinctId = person.distinctId;if (!distinctId) continue;const eventCount = await countEvents(distinctId);if (eventCount > 0) {canary = {id: person.id,- uuid: person.uuid ?? String(person.id),+ uuid: person.id,distinctId,eventCount,};diff --git a/packages/posthog/src/utils.test.ts b/packages/posthog/src/utils.test.tsindex 3535d4f1c..0035c95b4 100644--- a/packages/posthog/src/utils.test.ts+++ b/packages/posthog/src/utils.test.ts@@ -1,19 +1,11 @@import type { CaptureResult } from "posthog-js";import { describe, expect, it } from "vitest";import {- getPostHogCookieName,isAbortError,isResizeObserverLoopError,isUnsymbolicatedMinifiedException,- parsePostHogCookieDistinctId,} from "./utils";-describe("getPostHogCookieName", () => {- it("builds the posthog-js persistence cookie name", () => {- expect(getPostHogCookieName("phc_abc123")).toBe("ph_phc_abc123_posthog");- });-});-describe("isAbortError", () => {const event = (exceptionList: unknown) =>({@@ -184,61 +176,3 @@ describe("isUnsymbolicatedMinifiedException", () => {).toBe(false);});});--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.tsindex d1d6ffbeb..c7598de28 100644--- a/packages/posthog/src/utils.ts+++ b/packages/posthog/src/utils.ts@@ -1,59 +1,5 @@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;-};--export function isGlobalPrivacyControlEnabled() {- return (- typeof navigator !== "undefined" &&- (navigator as NavigatorWithGlobalPrivacyControl).globalPrivacyControl ===- true- );-}-/*** Stack-frame function names that only ever appear in password-manager browser* extension content scripts (1Password/Dashlane-style form scanners), never in