diff --git a/__tests__/components/providers/analytics-tracking.test.tsx b/__tests__/components/providers/analytics-tracking.test.tsx index f1ea02243..d6546bc7d 100644 --- a/__tests__/components/providers/analytics-tracking.test.tsx +++ b/__tests__/components/providers/analytics-tracking.test.tsx @@ -1,4 +1,4 @@ -import { useSegments } from 'expo-router'; +import { useGlobalSearchParams, useSegments } from 'expo-router'; import { AnalyticsProvider } from '@/components/providers/analytics'; import { @@ -11,6 +11,7 @@ import { clearUserIdentified, hasIdentifiedUser, markUserIdentified } from '@/li import { renderHook, waitFor } from '@/lib/test-utils'; jest.mock('expo-router', () => ({ + useGlobalSearchParams: jest.fn(), useSegments: jest.fn(), })); @@ -19,6 +20,9 @@ jest.mock('@/components/providers/auth', () => ({ })); const mockUseSegments = useSegments as jest.MockedFunction<() => string[]>; +const mockUseGlobalSearchParams = useGlobalSearchParams as jest.MockedFunction< + () => Record | undefined> +>; const mockUseAuth = useAuth as jest.MockedFunction; function mockAuthenticated(isAuthenticated: boolean) { @@ -50,6 +54,7 @@ function renderWithAnalytics(hook: () => void, providers: ReadonlyArray { beforeEach(() => { jest.clearAllMocks(); + mockUseGlobalSearchParams.mockReturnValue({}); }); it('tracks the current screen on mount', async () => { @@ -75,6 +80,186 @@ describe('useAnalyticsScreenTracking', () => { }); }); + it('sends the route params along with the route pattern', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); + mockUseGlobalSearchParams.mockReturnValue({ id: '42', tab: 'comments' }); + + renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledWith('/feed/[id]', { id: '42', tab: 'comments' }); + }); + }); + + it('joins repeated params with commas and drops undefined values', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed']); + mockUseGlobalSearchParams.mockReturnValue({ tag: ['news', 'sports'], page: undefined }); + + renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledWith('/feed', { tag: 'news,sports' }); + }); + }); + + it('does not send the URL fragment', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed']); + mockUseGlobalSearchParams.mockReturnValue({ '#': 'access_token=secret', 'tab': 'comments' }); + + renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledWith('/feed', { tab: 'comments' }); + }); + }); + + it('converts primitive values to strings and drops nested objects', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed']); + (mockUseGlobalSearchParams as jest.Mock).mockReturnValue({ + page: 2, + draft: false, + filter: { status: 'open' }, + empty: null, + none: [], + }); + + renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledWith('/feed', { draft: 'false', page: '2' }); + }); + }); + + it('tracks again when only the params change', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); + mockUseGlobalSearchParams.mockReturnValue({ id: '1' }); + + const { rerender } = renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledTimes(1); + }); + + mockUseGlobalSearchParams.mockReturnValue({ id: '2' }); + rerender({}); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledTimes(2); + }); + expect(provider.trackScreen).toHaveBeenLastCalledWith('/feed/[id]', { id: '2' }); + }); + + it('does not track again when the same params come back in a new object or order', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); + mockUseGlobalSearchParams.mockReturnValue({ id: '1', tab: 'comments' }); + + const { rerender } = renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledTimes(1); + }); + + mockUseGlobalSearchParams.mockReturnValue({ tab: 'comments', id: '1' }); + rerender({}); + // Wait past the tracker's setTimeout so a wrongly scheduled report would land. + await new Promise(resolve => setTimeout(resolve, 20)); + + expect(provider.trackScreen).toHaveBeenCalledTimes(1); + }); + + it('does not track again when the params change and come back within the same tick', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); + mockUseGlobalSearchParams.mockReturnValue({ id: '1' }); + + const { rerender } = renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledTimes(1); + }); + + mockUseGlobalSearchParams.mockReturnValue({ id: '2' }); + rerender({}); + mockUseGlobalSearchParams.mockReturnValue({ id: '1' }); + rerender({}); + // Wait past the tracker's setTimeout so a wrongly scheduled report would land. + await new Promise(resolve => setTimeout(resolve, 20)); + + expect(provider.trackScreen).toHaveBeenCalledTimes(1); + }); + + it('sorts params by name in code unit order', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed']); + mockUseGlobalSearchParams.mockReturnValue({ b: '2', a: '1', B: '3' }); + + renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledTimes(1); + }); + expect(Object.keys(provider.trackScreen.mock.calls[0][1])).toEqual(['B', 'a', 'b']); + }); + + // Route params only carry ids, modes and similar values by design, so the + // default sends all of them without filtering by name or value. + it('sends every route param by default', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); + mockUseGlobalSearchParams.mockReturnValue({ id: '42', mode: 'edit', tab: 'comments', ref: 'home' }); + + renderWithAnalytics(useAnalyticsScreenTracking, [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledWith('/feed/[id]', { id: '42', mode: 'edit', ref: 'home', tab: 'comments' }); + }); + }); + + it('sends no params when param tracking is turned off', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); + mockUseGlobalSearchParams.mockReturnValue({ id: '42', tab: 'comments' }); + + renderWithAnalytics(() => useAnalyticsScreenTracking({ trackParams: false }), [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledWith('/feed/[id]', undefined); + }); + }); + + it('sends only the params accepted by a trackParams function', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); + mockUseGlobalSearchParams.mockReturnValue({ id: '42', tab: 'comments' }); + + renderWithAnalytics(() => useAnalyticsScreenTracking({ trackParams: name => name === 'tab' }), [provider]); + + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledWith('/feed/[id]', { tab: 'comments' }); + }); + }); + + it('does not track again when only a param rejected by trackParams changes', async () => { + const provider = createMockProvider(); + mockUseSegments.mockReturnValue(['(app)', 'feed', '[id]']); + mockUseGlobalSearchParams.mockReturnValue({ id: '42', tab: 'comments' }); + + const { rerender } = renderWithAnalytics(() => useAnalyticsScreenTracking({ trackParams: name => name === 'tab' }), [provider]); + await waitFor(() => { + expect(provider.trackScreen).toHaveBeenCalledTimes(1); + }); + + mockUseGlobalSearchParams.mockReturnValue({ id: '43', tab: 'comments' }); + rerender({}); + // Wait past the tracker's setTimeout so a wrongly scheduled report would land. + await new Promise(resolve => setTimeout(resolve, 20)); + + expect(provider.trackScreen).toHaveBeenCalledTimes(1); + }); + it('reports the index route of a group as the root screen', async () => { const provider = createMockProvider(); mockUseSegments.mockReturnValue(['(app)']); diff --git a/docs/src/content/docs/guides/analytics.mdx b/docs/src/content/docs/guides/analytics.mdx index 2d22150db..967b96f3b 100644 --- a/docs/src/content/docs/guides/analytics.mdx +++ b/docs/src/content/docs/guides/analytics.mdx @@ -78,9 +78,26 @@ Keep params flat and primitive (`string`, `number`, `boolean`, `null`) so they c ## Automatic screen tracking -`useAnalyticsScreenTracking` is called once in `AnalyticsTrackers`, a component that renders nothing and sits next to the root `Stack` in `GuardedStack` (`src/app/_layout.tsx`). `GuardedStack` only renders after auth has been hydrated, so the placeholder stack shown while auth loads is not reported, and keeping the hook in its own component means route changes re-render only that component, not the root `Stack`. It reads the current route with `useSegments()` from expo-router and calls `trackScreen` every time it changes, without any code in the screens themselves. The report waits one tick so that when a route guard redirects on launch (for example to `/sign-in`) only the screen the user lands on is reported, and the same screen is never reported twice in a row. +`useAnalyticsScreenTracking` is called once in `AnalyticsTrackers`, a component that renders nothing and sits next to the root `Stack` in `GuardedStack` (`src/app/_layout.tsx`). `GuardedStack` only renders after auth has been hydrated, so the placeholder stack shown while auth loads is not reported, and keeping the hook in its own component means route changes re-render only that component, not the root `Stack`. It reads the current route with `useSegments()` and its params with `useGlobalSearchParams()` from expo-router, and calls `trackScreen` every time either changes, without any code in the screens themselves. The report waits one tick so that when a route guard redirects on launch (for example to `/sign-in`) only the screen the user lands on is reported, and the same screen with the same params is never reported twice in a row. -Screen names are route patterns, not resolved paths: route groups are dropped and dynamic segments are kept as written, so `/feed/42` is reported as `/feed/[id]` and `/(app)/settings` as `/settings`. This keeps the number of distinct screens small and keeps ids and other path values out of your vendors. If you need the concrete value, track it as an event param. +Screen names are route patterns, not resolved paths: route groups are dropped and dynamic segments are kept as written, so `/feed/42` is reported as `/feed/[id]` and `/(app)/settings` as `/settings`. This keeps the number of distinct screens small. + +The concrete values are sent as the `params` argument of `trackScreen`: dynamic segment values and search params of the focused route, so `/feed/42?tab=comments` is reported as `trackScreen('/feed/[id]', { id: '42', tab: 'comments' })`. Values are strings; a param that appears more than once (`?tag=news&tag=sports`) or a catch-all segment is joined with commas (`{ tag: 'news,sports' }`). Non-string navigation params (numbers, booleans) are converted to strings and object values (or arrays with no primitive values) are dropped, so params stay flat. The URL fragment (`#...`) is never sent, as it is not a route or search param. Routes without params are reported with `params` set to `undefined`. Navigating to the same route with different params (for example from `/feed/1` to `/feed/2`) counts as a new screen view. + +:::caution[Route params are sent by default] +This is a deliberate default chosen by the template maintainers: every route param except the URL fragment is sent with the screen view and forwarded to every registered provider. Route params are treated as non-sensitive by design, since they only carry ids, modes and similar values, so never put tokens or personal data in route params. This also applies to incoming deep links and universal links (password reset, magic links, OAuth callbacks): their query params become route params, so design those links to carry ids only, or turn param tracking off or narrow it with `trackParams` for apps whose links carry credentials. The default lives in `DEFAULT_TRACK_PARAMS` in `src/components/providers/analytics-tracking.ts`. +::: + +To change what is sent, pass the `trackParams` option where `useAnalyticsScreenTracking` is called in `AnalyticsTrackers` (`src/app/_layout.tsx`): + +```tsx +// Send no params at all: trackScreen always receives `undefined`. +useAnalyticsScreenTracking({ trackParams: false }); + +// Send only the params you list (an allowlist). +const TRACKED_PARAMS = new Set(['id', 'tab']); +useAnalyticsScreenTracking({ trackParams: name => TRACKED_PARAMS.has(name) }); +``` diff --git a/src/components/providers/analytics-tracking.ts b/src/components/providers/analytics-tracking.ts index 74362abd0..a10fbd1a3 100644 --- a/src/components/providers/analytics-tracking.ts +++ b/src/components/providers/analytics-tracking.ts @@ -1,10 +1,51 @@ -import { useSegments } from 'expo-router'; +import type { AnalyticsParams } from '@/lib/analytics'; +import { useGlobalSearchParams, useSegments } from 'expo-router'; import { useEffect, useRef } from 'react'; import { useAnalytics } from '@/components/providers/analytics'; import { useAuth } from '@/components/providers/auth'; import { hasIdentifiedUser } from '@/lib/analytics'; +/** + * expo-router exposes the URL fragment as a `#` param. It is not a route or + * search param, so it is never sent. + */ +const HASH_PARAM = '#'; + +/** + * Which route params are sent with each screen view: + * - `true` (the default): every param except the URL fragment. + * - `false`: no params; `trackScreen` always receives `undefined`. + * - a function: only the params whose name it accepts. + */ +export type TrackScreenParamsOption = boolean | ((name: string) => boolean); + +export type AnalyticsScreenTrackingOptions = { + trackParams?: TrackScreenParamsOption; +}; + +/** + * Default decided by the template maintainers: every route param is sent with + * screen views, with no filtering by name or value. Route params are treated + * as non-sensitive by design: they only carry ids, modes and similar values. + * Tokens, codes and personal data must never be passed as route params (keep + * them in secure storage or request bodies instead). This includes incoming + * deep links: the app defines its own link routes, so they must carry ids + * only. A name or value denylist was used before and intentionally removed, + * since it could never be complete and gave a false sense of safety; the + * trade-off (no redaction when an app breaks this rule) is accepted. Apps + * whose links carry credentials pass `trackParams: false` or an allowlist + * function. + */ +const DEFAULT_TRACK_PARAMS: TrackScreenParamsOption = true; + +function acceptsParam(trackParams: TrackScreenParamsOption, key: string) { + if (trackParams === false || key === HASH_PARAM) { + return false; + } + return trackParams === true || trackParams(key); +} + function isRouteGroup(segment: string) { return segment.startsWith('(') && segment.endsWith(')'); } @@ -13,25 +54,76 @@ function toScreenName(segments: ReadonlyArray) { return `/${segments.filter(segment => !isRouteGroup(segment)).join('/')}`; } +function isPrimitiveParam(value: unknown): value is string | number | boolean { + return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean'; +} + /** - * Reports a screen view to every analytics provider whenever the route - * changes. Call it once, inside `AnalyticsProvider`, after auth is ready. + * Navigation params can hold non-string values at runtime (numbers, nested + * objects), so values are converted to strings and anything that is not a + * primitive (or an array of primitives) is dropped, keeping params flat. + */ +function toParamValue(value: unknown) { + const values = (Array.isArray(value) ? value : [value]) + .filter(isPrimitiveParam) + .map(String); + return values.length > 0 ? values.join(',') : undefined; +} + +/** + * Serialises the route params into a stable key (sorted by name), so the same + * params in a different order are not reported as a new screen view. + * Repeated params are joined with commas. Returns an empty string when the + * route has no params. + */ +function toParamsKey(routeParams: Readonly>, trackParams: TrackScreenParamsOption) { + const entries = Object.keys(routeParams) + .filter(key => acceptsParam(trackParams, key)) + // Same UTF-16 code unit order as the default sort, stated explicitly + // rather than with `localeCompare`, which would depend on the device locale. + .sort((a, b) => Number(a > b) - Number(a < b)) + .flatMap((key) => { + const value = toParamValue(routeParams[key]); + return value === undefined ? [] : [[key, value] as const]; + }); + return entries.length > 0 ? JSON.stringify(Object.fromEntries(entries)) : ''; +} + +/** + * The serialised key is the only value the tracking effect depends on, so a + * new params object on every render never re-triggers it; the params are read + * back from that key when a screen view is reported. `toParamsKey` only ever + * serialises a flat object of strings, which is what the cast states. + */ +function fromParamsKey(paramsKey: string): AnalyticsParams | undefined { + return paramsKey ? (JSON.parse(paramsKey) as Record) : undefined; +} + +/** + * Reports a screen view to every analytics provider whenever the route or its + * params change, sending the route params (dynamic segments and search params) + * along with the route pattern. By default every param is sent (see + * `DEFAULT_TRACK_PARAMS` and `TrackScreenParamsOption`); pass + * `{ trackParams: false }` to send none, or a function to narrow them. + * Call it once, inside `AnalyticsProvider`, after auth is ready. */ -export function useAnalyticsScreenTracking() { +export function useAnalyticsScreenTracking({ trackParams = DEFAULT_TRACK_PARAMS }: AnalyticsScreenTrackingOptions = {}) { const screenName = toScreenName(useSegments()); + const paramsKey = toParamsKey(useGlobalSearchParams(), trackParams); const { trackScreen } = useAnalytics(); - const lastTrackedRef = useRef(null); + const lastTrackedRef = useRef<{ screenName: string; paramsKey: string } | null>(null); useEffect(() => { const timeout = setTimeout(() => { - if (lastTrackedRef.current === screenName) { + const last = lastTrackedRef.current; + if (last?.screenName === screenName && last.paramsKey === paramsKey) { return; } - lastTrackedRef.current = screenName; - trackScreen(screenName); + lastTrackedRef.current = { screenName, paramsKey }; + trackScreen(screenName, fromParamsKey(paramsKey)); }, 0); return () => clearTimeout(timeout); - }, [screenName, trackScreen]); + }, [screenName, paramsKey, trackScreen]); } /**