-
Notifications
You must be signed in to change notification settings - Fork 1
Identify authenticated PostHog users #2326
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
55 changes: 55 additions & 0 deletions
55
docs/superpowers/plans/2026-07-29-posthog-user-identification.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| # PostHog User Identification TDD Plan | ||
|
|
||
| > **For agentic workers:** Write and run the failing tests before changing production code. | ||
|
|
||
| **Goal:** Associate web analytics with the authenticated Dofek user and clear that association after logout. | ||
|
|
||
| **Behavior:** After authentication bootstrap returns a user, the web client identifies that user to PostHog with the stable database ID, name, and email. After a successful logout request, it resets PostHog before navigation completes. | ||
|
|
||
| **Scope:** Web only, because PostHog is currently installed and initialized only in `packages/web`; adding a second mobile analytics SDK is out of scope. | ||
|
|
||
| **Docs:** [PostHog user identification](https://posthog.com/docs/product-analytics/identify) | ||
|
|
||
| --- | ||
|
|
||
| ## Current Evidence | ||
|
|
||
| - `packages/web/src/lib/posthog.ts` initializes PostHog and captures page views but exposes no user identity lifecycle. | ||
| - `packages/web/src/lib/auth-context.tsx` is the canonical web authentication lifecycle and already receives the validated `AuthUser`. | ||
| - The current [PostHog identification guidance](https://posthog.com/docs/product-analytics/identify) says to identify as soon as the frontend knows the authenticated user and to reset on logout. | ||
|
|
||
| ## Test Strategy | ||
|
|
||
| - Unit: Verify the PostHog adapter forwards the stable user ID and person properties to `identify()` and delegates logout cleanup to `reset()`. | ||
| - UI/auth lifecycle: Render `AuthProvider` with mocked auth and analytics adapters; verify authenticated bootstrap identifies, unauthenticated bootstrap does not identify, and successful logout resets. | ||
| - Platform parity: No mobile change because the mobile package does not use PostHog; this change completes the lifecycle of the existing web-only integration. | ||
|
|
||
| ## File Structure | ||
|
|
||
| - Modify: `packages/web/src/lib/posthog.test.ts` — adapter regression tests. | ||
| - Modify: `packages/web/src/lib/posthog.ts` — typed identity and reset helpers. | ||
| - Create: `packages/web/src/lib/auth-context.test.tsx` — auth lifecycle regression tests. | ||
| - Modify: `packages/web/src/lib/auth-context.tsx` — connect authenticated bootstrap/logout to PostHog. | ||
|
|
||
| ## Tasks | ||
|
|
||
| ### Task 1: Add Failing Tests | ||
|
|
||
| - [x] Add adapter tests for `identify()` and `reset()`. | ||
| - [x] Add auth-provider tests for authenticated, anonymous, and logout paths. | ||
| - [x] Run `pnpm exec vitest run packages/web/src/lib/posthog.test.ts packages/web/src/lib/auth-context.test.tsx`. | ||
| - [x] Confirm failures are caused by the missing identity lifecycle. | ||
|
|
||
| ### Task 2: Implement Minimal Fix | ||
|
|
||
| - [x] Add typed PostHog identity/reset helpers. | ||
| - [x] Identify after the authenticated user is known. | ||
| - [x] Reset only after the logout request succeeds so a failed logout cannot desynchronize analytics from the still-live server session. | ||
| - [x] Run the focused tests and confirm they pass. | ||
|
|
||
| ### Task 3: Final Verification | ||
|
|
||
| - [x] Run `pnpm lint`. | ||
| - [x] Run root, server, web, and mobile typechecks. | ||
| - [x] Run the full Docker-free test suite. | ||
| - [ ] Commit, push, open the linked PR, and monitor review and CI through merge. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| // @vitest-environment jsdom | ||
|
|
||
| import { act, renderHook, waitFor } from "@testing-library/react"; | ||
| import type { ReactNode } from "react"; | ||
| import { beforeEach, describe, expect, it, vi } from "vitest"; | ||
| import { AuthProvider, useAuth } from "./auth-context.tsx"; | ||
|
|
||
| const mockCaptureException = vi.hoisted(() => vi.fn()); | ||
| const mockIdentifyPostHogUser = vi.hoisted(() => vi.fn()); | ||
| const mockResetPostHogUser = vi.hoisted(() => vi.fn()); | ||
| const mockRedirectToLogin = vi.hoisted(() => vi.fn()); | ||
|
|
||
| vi.mock("./telemetry.ts", () => ({ | ||
| captureException: mockCaptureException, | ||
| })); | ||
|
|
||
| vi.mock("./posthog.ts", () => ({ | ||
| identifyPostHogUser: mockIdentifyPostHogUser, | ||
| resetPostHogUser: mockResetPostHogUser, | ||
| })); | ||
|
|
||
| vi.mock("./auth.ts", async (importOriginal) => { | ||
| const original = await importOriginal<typeof import("./auth.ts")>(); | ||
| return { | ||
| ...original, | ||
| fetchCurrentUser: vi.fn(() => Promise.resolve(null)), | ||
| logout: vi.fn(() => Promise.resolve()), | ||
| redirectToLogin: mockRedirectToLogin, | ||
| }; | ||
| }); | ||
|
|
||
| function wrapper({ children }: { children: ReactNode }) { | ||
| return <AuthProvider>{children}</AuthProvider>; | ||
| } | ||
|
|
||
| describe("AuthProvider analytics identity", () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| it("identifies the authenticated user after bootstrap", async () => { | ||
| const { fetchCurrentUser } = await import("./auth.ts"); | ||
| const user = { | ||
| id: "user-123", | ||
| name: "Alice Example", | ||
| email: "alice@example.com", | ||
| }; | ||
| vi.mocked(fetchCurrentUser).mockResolvedValue(user); | ||
|
|
||
| const { result } = renderHook(() => useAuth(), { wrapper }); | ||
|
|
||
| await waitFor(() => { | ||
| expect(result.current.user).toEqual(user); | ||
| }); | ||
|
|
||
| expect(mockIdentifyPostHogUser).toHaveBeenCalledOnce(); | ||
| expect(mockIdentifyPostHogUser).toHaveBeenCalledWith(user); | ||
| expect(mockResetPostHogUser).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("does not identify or reset an unauthenticated visitor during bootstrap", async () => { | ||
| const { fetchCurrentUser } = await import("./auth.ts"); | ||
| vi.mocked(fetchCurrentUser).mockResolvedValue(null); | ||
|
|
||
| const { result } = renderHook(() => useAuth(), { wrapper }); | ||
|
|
||
| await waitFor(() => { | ||
| expect(result.current.isLoading).toBe(false); | ||
| }); | ||
|
|
||
| expect(mockIdentifyPostHogUser).not.toHaveBeenCalled(); | ||
| expect(mockResetPostHogUser).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("resets the analytics identity after logout succeeds", async () => { | ||
| const { fetchCurrentUser, logout } = await import("./auth.ts"); | ||
| vi.mocked(fetchCurrentUser).mockResolvedValue({ | ||
| id: "user-123", | ||
| name: "Alice Example", | ||
| email: "alice@example.com", | ||
| }); | ||
| vi.mocked(logout).mockResolvedValue(); | ||
|
|
||
| const { result } = renderHook(() => useAuth(), { wrapper }); | ||
| await waitFor(() => { | ||
| expect(result.current.user).not.toBeNull(); | ||
| }); | ||
|
|
||
| await act(async () => { | ||
| await result.current.logout(); | ||
| }); | ||
|
|
||
| expect(mockResetPostHogUser).toHaveBeenCalledOnce(); | ||
| expect(vi.mocked(logout).mock.invocationCallOrder[0]).toBeLessThan( | ||
| mockResetPostHogUser.mock.invocationCallOrder[0] ?? 0, | ||
| ); | ||
| expect(mockResetPostHogUser.mock.invocationCallOrder[0]).toBeLessThan( | ||
| mockRedirectToLogin.mock.invocationCallOrder[0] ?? 0, | ||
| ); | ||
| }); | ||
|
|
||
| it("preserves the analytics identity when logout fails", async () => { | ||
| const { fetchCurrentUser, logout } = await import("./auth.ts"); | ||
| const error = new Error("Network unavailable"); | ||
| vi.mocked(fetchCurrentUser).mockResolvedValue({ | ||
| id: "user-123", | ||
| name: "Alice Example", | ||
| email: "alice@example.com", | ||
| }); | ||
| vi.mocked(logout).mockRejectedValue(error); | ||
|
|
||
| const { result } = renderHook(() => useAuth(), { wrapper }); | ||
| await waitFor(() => { | ||
| expect(result.current.user).not.toBeNull(); | ||
| }); | ||
|
|
||
| await expect( | ||
| act(async () => { | ||
| await result.current.logout(); | ||
| }), | ||
| ).rejects.toThrow("Network unavailable"); | ||
|
|
||
| expect(mockResetPostHogUser).not.toHaveBeenCalled(); | ||
| expect(mockRedirectToLogin).not.toHaveBeenCalled(); | ||
| expect(mockCaptureException).toHaveBeenCalledWith(error, { source: "logout" }); | ||
| expect(result.current.user?.id).toBe("user-123"); | ||
| }); | ||
|
|
||
| it("resets when an identified session becomes unauthenticated", async () => { | ||
| const { fetchCurrentUser } = await import("./auth.ts"); | ||
| vi.mocked(fetchCurrentUser) | ||
| .mockResolvedValueOnce({ | ||
| id: "user-123", | ||
| name: "Alice Example", | ||
| email: "alice@example.com", | ||
| }) | ||
| .mockResolvedValueOnce(null); | ||
|
|
||
| const { result } = renderHook(() => useAuth(), { wrapper }); | ||
| await waitFor(() => { | ||
| expect(result.current.user?.id).toBe("user-123"); | ||
| }); | ||
|
|
||
| await act(async () => { | ||
| await result.current.retryBootstrap(); | ||
| }); | ||
|
|
||
| expect(result.current.user).toBeNull(); | ||
| expect(mockResetPostHogUser).toHaveBeenCalledOnce(); | ||
| }); | ||
|
|
||
| it("resets before identifying a different authenticated user", async () => { | ||
| const { fetchCurrentUser } = await import("./auth.ts"); | ||
| vi.mocked(fetchCurrentUser) | ||
| .mockResolvedValueOnce({ | ||
| id: "user-123", | ||
| name: "Alice Example", | ||
| email: "alice@example.com", | ||
| }) | ||
| .mockResolvedValueOnce({ | ||
| id: "user-456", | ||
| name: "Bob Example", | ||
| email: "bob@example.com", | ||
| }); | ||
|
|
||
| const { result } = renderHook(() => useAuth(), { wrapper }); | ||
| await waitFor(() => { | ||
| expect(result.current.user?.id).toBe("user-123"); | ||
| }); | ||
|
|
||
| await act(async () => { | ||
| await result.current.retryBootstrap(); | ||
| }); | ||
|
|
||
| expect(result.current.user?.id).toBe("user-456"); | ||
| expect(mockResetPostHogUser).toHaveBeenCalledOnce(); | ||
| expect(mockResetPostHogUser.mock.invocationCallOrder[0]).toBeLessThan( | ||
| mockIdentifyPostHogUser.mock.invocationCallOrder[1] ?? 0, | ||
| ); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.