Repository navigation
feat(analytics): tell logged-in users apart from anonymous visitors in GA4 #1396
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
Open
f
wants to merge
2
commits into
main
Choose a base branch
from
cursor/ga-logged-in-user-property-2c4b
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
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
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,164 @@ | ||
| import { describe, it, expect, vi, beforeEach } from "vitest"; | ||
| import { render } from "@testing-library/react"; | ||
| import { Analytics, buildGtagInitScript } from "@/components/layout/analytics"; | ||
| import { applyAnalyticsAuthState } from "@/lib/analytics"; | ||
|
|
||
| type SessionStatus = "loading" | "authenticated" | "unauthenticated"; | ||
|
|
||
| const sessionState = vi.hoisted(() => ({ | ||
| status: "loading" as SessionStatus, | ||
| user: null as null | { id: string; analyticsId?: string }, | ||
| })); | ||
|
|
||
| vi.mock("next-auth/react", () => ({ | ||
| useSession: () => ({ | ||
| status: sessionState.status, | ||
| data: sessionState.user ? { user: sessionState.user } : null, | ||
| }), | ||
| })); | ||
|
|
||
| vi.mock("next/script", () => ({ | ||
| default: () => null, | ||
| })); | ||
|
|
||
| function gtagCalls(dataLayer: unknown[]) { | ||
| return dataLayer.map((entry) => Array.from(entry as ArrayLike<unknown>)); | ||
| } | ||
|
|
||
| function runInitScript(script: string, consent: string | null) { | ||
| const fakeWindow = { dataLayer: [] as unknown[] }; | ||
| const fakeStorage = { getItem: (key: string) => (key === "cookie-consent" ? consent : null) }; | ||
| new Function("window", "dataLayer", "localStorage", script)(fakeWindow, fakeWindow.dataLayer, fakeStorage); | ||
| return gtagCalls(fakeWindow.dataLayer); | ||
| } | ||
|
|
||
| describe("buildGtagInitScript", () => { | ||
| it("sets logged_in and user_id before config so the first page_view carries them", () => { | ||
| const script = buildGtagInitScript({ gaId: "G-MSNHFWTE77", loggedIn: true, analyticsId: "abc123" }); | ||
| const calls = runInitScript(script, "accepted"); | ||
|
|
||
| expect(calls.map((c) => c[0])).toEqual(["js", "set", "set", "config"]); | ||
| expect(calls[1]).toEqual(["set", "user_properties", { logged_in: "true" }]); | ||
| expect(calls[2]).toEqual(["set", { user_id: "abc123" }]); | ||
| expect(calls[3]).toEqual(["config", "G-MSNHFWTE77"]); | ||
| }); | ||
|
|
||
| it("does not send user_id without analytics cookie consent", () => { | ||
| const script = buildGtagInitScript({ gaId: "G-TEST", loggedIn: true, analyticsId: "abc123" }); | ||
| for (const consent of [null, "rejected"]) { | ||
| const calls = runInitScript(script, consent); | ||
| expect(calls).toContainEqual(["set", "user_properties", { logged_in: "true" }]); | ||
| expect(calls.some((c) => (c[1] as { user_id?: unknown })?.user_id !== undefined)).toBe(false); | ||
| } | ||
| }); | ||
|
|
||
| it("marks anonymous visitors as logged_in=false and sends no user_id", () => { | ||
| const calls = runInitScript(buildGtagInitScript({ gaId: "G-TEST", loggedIn: false, analyticsId: null }), "accepted"); | ||
| expect(calls).toEqual([ | ||
| ["js", expect.any(Date)], | ||
| ["set", "user_properties", { logged_in: "false" }], | ||
| ["config", "G-TEST"], | ||
| ]); | ||
| }); | ||
|
|
||
| it("omits the user property when the server could not resolve the session", () => { | ||
| const calls = runInitScript(buildGtagInitScript({ gaId: "G-TEST" }), "accepted"); | ||
| expect(calls.map((c) => c[0])).toEqual(["js", "config"]); | ||
| }); | ||
|
|
||
| it("escapes values so they cannot break out of the script tag", () => { | ||
| const script = buildGtagInitScript({ gaId: "G-</script><script>alert(1)//", loggedIn: false }); | ||
| expect(script).not.toContain("</script>"); | ||
| }); | ||
| }); | ||
|
|
||
| describe("applyAnalyticsAuthState", () => { | ||
| beforeEach(() => { | ||
| delete window.gtag; | ||
| window.dataLayer = []; | ||
| }); | ||
|
|
||
| it("queues commands on dataLayer when gtag is not defined yet", () => { | ||
| applyAnalyticsAuthState({ loggedIn: true, userId: "abc" }); | ||
| expect(gtagCalls(window.dataLayer!)).toEqual([ | ||
| ["set", "user_properties", { logged_in: "true" }], | ||
| ["set", { user_id: "abc" }], | ||
| ]); | ||
| }); | ||
|
|
||
| it("clears user_id with null only when one was previously set", () => { | ||
| const gtag = vi.fn(); | ||
| window.gtag = gtag; | ||
|
|
||
| applyAnalyticsAuthState({ loggedIn: false, userId: null }, { loggedIn: true, userId: "abc" }); | ||
| expect(gtag.mock.calls).toEqual([ | ||
| ["set", "user_properties", { logged_in: "false" }], | ||
| ["set", { user_id: null }], | ||
| ]); | ||
|
|
||
| gtag.mockClear(); | ||
| applyAnalyticsAuthState({ loggedIn: false, userId: null }, null); | ||
| expect(gtag.mock.calls).toEqual([["set", "user_properties", { logged_in: "false" }]]); | ||
| }); | ||
| }); | ||
|
|
||
| describe("Analytics session sync", () => { | ||
| let gtag: ReturnType<typeof vi.fn>; | ||
|
|
||
| beforeEach(() => { | ||
| gtag = vi.fn(); | ||
| window.gtag = gtag; | ||
| localStorage.clear(); | ||
| sessionState.status = "loading"; | ||
| sessionState.user = null; | ||
| }); | ||
|
|
||
| it("does nothing while the client session matches the server state", () => { | ||
| sessionState.status = "authenticated"; | ||
| sessionState.user = { id: "u1", analyticsId: "abc" }; | ||
| localStorage.setItem("cookie-consent", "accepted"); | ||
|
|
||
| render(<Analytics gaId="G-TEST" loggedIn analyticsId="abc" />); | ||
| expect(gtag).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it("updates GA when the user signs in without a full page load", () => { | ||
| localStorage.setItem("cookie-consent", "accepted"); | ||
| sessionState.status = "unauthenticated"; | ||
| const { rerender } = render(<Analytics gaId="G-TEST" loggedIn={false} analyticsId={null} />); | ||
| expect(gtag).not.toHaveBeenCalled(); | ||
|
|
||
| sessionState.status = "authenticated"; | ||
| sessionState.user = { id: "u1", analyticsId: "abc" }; | ||
| rerender(<Analytics gaId="G-TEST" loggedIn={false} analyticsId={null} />); | ||
|
|
||
| expect(gtag.mock.calls).toEqual([ | ||
| ["set", "user_properties", { logged_in: "true" }], | ||
| ["set", { user_id: "abc" }], | ||
| ]); | ||
| }); | ||
|
|
||
| it("clears user_id when the session ends", () => { | ||
| localStorage.setItem("cookie-consent", "accepted"); | ||
| sessionState.status = "authenticated"; | ||
| sessionState.user = { id: "u1", analyticsId: "abc" }; | ||
| const { rerender } = render(<Analytics gaId="G-TEST" loggedIn analyticsId="abc" />); | ||
|
|
||
| sessionState.status = "unauthenticated"; | ||
| sessionState.user = null; | ||
| rerender(<Analytics gaId="G-TEST" loggedIn analyticsId="abc" />); | ||
|
|
||
| expect(gtag.mock.calls).toEqual([ | ||
| ["set", "user_properties", { logged_in: "false" }], | ||
| ["set", { user_id: null }], | ||
| ]); | ||
| }); | ||
|
|
||
| it("sets logged_in but not user_id without consent", () => { | ||
| sessionState.status = "authenticated"; | ||
| sessionState.user = { id: "u1", analyticsId: "abc" }; | ||
|
|
||
| render(<Analytics gaId="G-TEST" />); | ||
| expect(gtag.mock.calls).toEqual([["set", "user_properties", { logged_in: "true" }]]); | ||
| }); | ||
| }); |
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,48 @@ | ||
| import { describe, it, expect, beforeEach, afterEach } from "vitest"; | ||
| import { getAnalyticsUserId } from "@/lib/analytics-user"; | ||
|
|
||
| describe("getAnalyticsUserId", () => { | ||
| const originalEnv = { ...process.env }; | ||
|
|
||
| beforeEach(() => { | ||
| process.env.GOOGLE_ANALYTICS_ID = "G-TEST123"; | ||
| process.env.AUTH_SECRET = "secret-a"; | ||
| }); | ||
|
|
||
| afterEach(() => { | ||
| process.env = { ...originalEnv }; | ||
| }); | ||
|
|
||
| it("returns a stable 32-char hex id that does not contain the raw id", () => { | ||
| const id = getAnalyticsUserId("cluser123"); | ||
| expect(id).toMatch(/^[0-9a-f]{32}$/); | ||
| expect(id).not.toContain("cluser123"); | ||
| expect(getAnalyticsUserId("cluser123")).toBe(id); | ||
| }); | ||
|
|
||
| it("differs per user and per secret", () => { | ||
| const a = getAnalyticsUserId("user-a"); | ||
| expect(getAnalyticsUserId("user-b")).not.toBe(a); | ||
| process.env.AUTH_SECRET = "secret-b"; | ||
| expect(getAnalyticsUserId("user-a")).not.toBe(a); | ||
| }); | ||
|
|
||
| it("falls back to NEXTAUTH_SECRET", () => { | ||
| delete process.env.AUTH_SECRET; | ||
| process.env.NEXTAUTH_SECRET = "legacy-secret"; | ||
| expect(getAnalyticsUserId("user-a")).toMatch(/^[0-9a-f]{32}$/); | ||
| }); | ||
|
|
||
| it("returns null without a user id, GA id, or secret", () => { | ||
| expect(getAnalyticsUserId(undefined)).toBeNull(); | ||
| expect(getAnalyticsUserId("")).toBeNull(); | ||
|
|
||
| delete process.env.GOOGLE_ANALYTICS_ID; | ||
| expect(getAnalyticsUserId("user-a")).toBeNull(); | ||
|
|
||
| process.env.GOOGLE_ANALYTICS_ID = "G-TEST123"; | ||
| delete process.env.AUTH_SECRET; | ||
| delete process.env.NEXTAUTH_SECRET; | ||
| expect(getAnalyticsUserId("user-a")).toBeNull(); | ||
| }); | ||
| }); |
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
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.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Clear
user_idwhen another tab rejects consent.The sync effect reads consent only when a dependency changes. Consent is not a dependency, and no
storagelistener updates the applied state. After another tab rejects consent, this tab keeps theuser_idit applied at mount until it reloads or its session values change. Hits from this tab can therefore stay linked to the account after the user rejected consent.Impact is limited. It affects only tabs that were loaded before the rejection, and a reload removes the stale value.
Subscribe to the
storageevent inAnalytics, and handle only changes toCOOKIE_CONSENT_KEY. When the new value is notaccepted, or the event reports a cleared store (event.key === null), apply a state withuserId: nullthrough the sameapplyAnalyticsAuthStatepath, then updateapplied.current. Remove the listener on unmount. Thestorageevent fires only in other same-origin documents, so this does not interfere with the tab that wrote the value. Do not add a second write path for unchanged consent.