From a96707e9bede49324ce751fdcd37781ccaad8a52 Mon Sep 17 00:00:00 2001 From: Abubakar Khawaja Date: Mon, 7 Sep 2026 12:38:51 +0500 Subject: [PATCH 01/17] feat: Integrate PostHog for analytics tracking and update documentation - Added PostHog integration for user identification and event tracking in the application. - Created new documentation files for identifying users and integrating with TanStack Start. - Updated environment variables for PostHog project token and host. - Removed deprecated analytics event tracking code and replaced it with PostHog's capture methods. - Updated package dependencies to use the latest version of posthog-js. - Refactored components to utilize PostHog for analytics events instead of custom tracking. --- .../.posthog-wizard | 0 .../references/identify-users.md | 307 ++++++++++++++++++ .../references/tanstack-start.md | 221 +++++++++++++ .env.example | 6 +- package.json | 2 +- pnpm-lock.yaml | 10 +- src/analytics/events.ts | 21 -- src/analytics/posthog.ts | 63 ---- src/base/Form.tsx | 6 - src/base/Link.tsx | 5 +- src/routes/__root.tsx | 50 ++- src/sections/Assessment.tsx | 27 +- src/sections/Faq.tsx | 13 +- src/sections/Hero.tsx | 17 +- src/sections/SiteHeader.tsx | 39 +-- 15 files changed, 595 insertions(+), 192 deletions(-) create mode 100644 .claude/skills/integration-tanstack-start/.posthog-wizard create mode 100644 .claude/skills/integration-tanstack-start/references/identify-users.md create mode 100644 .claude/skills/integration-tanstack-start/references/tanstack-start.md delete mode 100644 src/analytics/events.ts delete mode 100644 src/analytics/posthog.ts diff --git a/.claude/skills/integration-tanstack-start/.posthog-wizard b/.claude/skills/integration-tanstack-start/.posthog-wizard new file mode 100644 index 0000000..e69de29 diff --git a/.claude/skills/integration-tanstack-start/references/identify-users.md b/.claude/skills/integration-tanstack-start/references/identify-users.md new file mode 100644 index 0000000..8647dcb --- /dev/null +++ b/.claude/skills/integration-tanstack-start/references/identify-users.md @@ -0,0 +1,307 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Identify users - Docs + +Copy page + +# Identify users - Docs + +Linking events to specific users enables you to build a full picture of how they're using your product across different sessions, devices, and platforms. + +This is straightforward to do when [capturing backend events](/docs/product-analytics/capture-events?tab=Node.js.md), as you associate events to a specific user using a `distinct_id`, which is a required argument. + +However, in the frontend of a [web](/docs/libraries/js/usage.md#capturing-events) or [mobile app](/docs/libraries/ios.md#capturing-events), a `distinct_id` is not a required argument — PostHog's SDKs will generate an anonymous `distinct_id` for you automatically and you can capture events anonymously, provided you use the appropriate [configuration](/docs/libraries/js/usage.md#capturing-anonymous-events). + +To link events to specific users, call `identify`: + +PostHog AI + +### Web + +```javascript +posthog.identify( + 'distinct_id', // Replace 'distinct_id' with your user's unique identifier + { email: 'max@hedgehogmail.com', name: 'Max Hedgehog' } // optional: set additional person properties +); +``` + +### Android + +```kotlin +PostHog.identify( + distinctId = distinctID, // Replace 'distinctID' with your user's unique identifier + // optional: set additional person properties + userProperties = mapOf( + "name" to "Max Hedgehog", + "email" to "max@hedgehogmail.com" + ) +) +``` + +### iOS + +```swift +PostHogSDK.shared.identify("distinct_id", // Replace "distinct_id" with your user's unique identifier + userProperties: ["name": "Max Hedgehog", "email": "max@hedgehogmail.com"]) // optional: set additional person properties +``` + +### React Native + +```jsx +posthog.identify('distinct_id', { // Replace "distinct_id" with your user's unique identifier + email: 'max@hedgehogmail.com', // optional: set additional person properties + name: 'Max Hedgehog' +}) +``` + +### Dart + +```dart +await Posthog().identify( + userId: 'distinct_id', // Replace "distinct_id" with your user's unique identifier + userProperties: { + 'email': 'max@hedgehogmail.com', // optional: set additional person properties + 'name': 'Max Hedgehog', + }, +); +``` + +Events captured after calling `identify` are identified events and this creates a person profile if one doesn't exist already. + +Due to the cost of processing them, anonymous events can be up to 4x cheaper than identified events, so it's recommended you only capture identified events when needed. + +## How identify works + +When a user starts browsing your website or app, PostHog automatically assigns them an **anonymous ID**, which is stored locally. + +Provided you've [configured persistence](/docs/libraries/js/persistence.md) to use cookies or `localStorage`, this enables us to track anonymous users – even across different sessions. + +By calling `identify` with a `distinct_id` of your choice (usually the user's ID in your database, or their email), you link the anonymous ID and distinct ID together. + +Thus, all past and future events made with that anonymous ID are now associated with the distinct ID. + +This enables you to do things like associate events with a user from before they log in for the first time, or associate their events across different devices or platforms. + +Using identify in the backend + +Although you can call `identify` using our backend SDKs, it is used most in frontends. This is because there is no concept of anonymous sessions in the backend SDKs, so calling `identify` only updates person profiles. + +## Best practices when using `identify` + +### 1\. Call `identify` as soon as you're able to + +In your frontend, you should call `identify` as soon as you're able to. + +Typically, this is every time your **app loads** for the first time, and directly after your **users log in**. + +This ensures that events sent during your users' sessions are correctly associated with them. + +You only need to call `identify` once per session, and you should avoid calling it multiple times unnecessarily. + +If you call `identify` multiple times with the same data without reloading the page in between, PostHog will ignore the subsequent calls. + +#### Identify users when the web SDK loads + +If your app already knows the signed-in user when you initialize the JavaScript web SDK, the [`loaded` callback](/docs/libraries/js/config.md) is a convenient place to call `identify`. This identifies the user as soon as the SDK has loaded: + +Web + +PostHog AI + +```javascript +posthog.init('', { + api_host: 'https://us.i.posthog.com', + defaults: '2026-05-30', + loaded: (posthog) => { + if (currentUser?.id) { + posthog.identify(currentUser.id, { + email: currentUser.email, + name: currentUser.name, + }) + } + }, +}) +``` + +In this example, `currentUser` represents user data already available from your authentication system. If your app loads the user asynchronously, call `posthog.identify()` as soon as that data becomes available instead. + +### 2\. Use unique strings for distinct IDs + +If two users have the same distinct ID, their data is merged and they are considered one user in PostHog. Two common ways this can happen are: + +- Your logic for generating IDs does not generate sufficiently strong IDs and you can end up with a clash where 2 users have the same ID. +- There's a bug, typo, or mistake in your code leading to most or all users being identified with generic IDs like `null`, `true`, or `distinctId`. + +PostHog also has built-in protections to stop the most common distinct ID mistakes. + +### 3\. Reset after logout + +If a user logs out on your frontend, you should call `reset()` to unlink any future events made on that device with that user. + +This is important if your users are sharing a computer, as otherwise all of those users are grouped together into a single user due to shared cookies between sessions. + +**We strongly recommend you call `reset` on logout even if you don't expect users to share a computer.** + +You can do that like so: + +PostHog AI + +### Web + +```javascript +posthog.reset() +``` + +### iOS + +```swift +PostHogSDK.shared.reset() +``` + +### Android + +```kotlin +PostHog.reset() +``` + +### React Native + +```jsx +posthog.reset() +``` + +### Dart + +```dart +await Posthog().reset(); +``` + +If you *also* want to reset the `device_id` so that the device will be considered a new device in future events, you can pass `true` as an argument: + +Web + +PostHog AI + +```javascript +posthog.reset(true) +``` + +### 4\. Person profiles and properties + +You'll notice that one of the parameters in the `identify` method is a `properties` object. + +This enables you to set [person properties](/docs/product-analytics/person-properties.md). + +Whenever possible, we recommend passing in all person properties you have available each time you call identify, as this ensures their person profile on PostHog is up to date. + +Person properties can also be set being adding a `$set` property to a event `capture` call. + +**\`$set\` and \`$set\_once\` aren't stored on events** + +These properties only tell PostHog how to update person data during ingestion — they aren't kept on the stored event, so you can't filter, break down, or query events by them. To query the values you set, use [person properties](/docs/product-analytics/person-properties.md) instead. + +See our [person properties docs](/docs/product-analytics/person-properties.md) for more details on how to work with them and best practices. + +### 5\. Use deep links between platforms + +We recommend you call `identify` [as soon as you're able](#1-call-identify-as-soon-as-youre-able), typically when a user signs up or logs in. + +This doesn't work if one or both platforms are unauthenticated. Some examples of such cases are: + +- Onboarding and signup flows before authentication. +- Unauthenticated web pages redirecting to authenticated mobile apps. +- Authenticated web apps prompting an app download. + +In these cases, you can use a [deep link](https://developer.android.com/training/app-links/deep-linking) on Android and [universal links](https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app) on iOS to identify users. + +1. Use `posthog.get_distinct_id()` to get the current distinct ID. Even if you cannot call identify because the user is unauthenticated, this will return an anonymous distinct ID generated by PostHog. +2. Add the distinct ID to the deep link as query parameters, along with other properties like UTM parameters. +3. When the user is redirected to the app, parse the deep link and handle the following cases: + +- The mobile app is already authenticated. In this case, call [`posthog.alias()`](/docs/libraries/js/usage.md#alias) with the distinct ID from the web. This associates the two distinct IDs as a single person. +- The mobile app is unauthenticated. In this case, call [`posthog.identify()`](/docs/libraries/js/usage.md#identifying-users) with the distinct ID from the web so pre-login mobile events stay connected to the web session. When the user later logs in on mobile, call `identify()` again with your canonical user ID. + +As long as you associate the distinct IDs with `posthog.identify()` or `posthog.alias()`, you can track events generated across platforms. + +Here's an example implementation for handling deep links from web to mobile: + +PostHog AI + +### iOS + +```swift +import PostHog +class DeepLinkIdentityManager { + static let shared = DeepLinkIdentityManager() + // MARK: - Deep Link Received + func handleDeepLink(_ url: URL, isAuthenticatedOnMobile: Bool) { + guard let webDistinctId = URLComponents(url: url, resolvingAgainstBaseURL: true)? + .queryItems?.first(where: { $0.name == "ph_distinct_id" })?.value else { + return + } + if isAuthenticatedOnMobile { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHogSDK.shared.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHogSDK.shared.identify(webDistinctId) + } + } + // MARK: - Login/Signup + func handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHogSDK.shared.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + func handleLogout() { + PostHogSDK.shared.reset() + } +} +``` + +### Android + +```kotlin +import android.net.Uri +import com.posthog.PostHog +object DeepLinkIdentityManager { + // Deep Link Received + fun handleDeepLink(uri: Uri, isAuthenticatedOnMobile: Boolean) { + val webDistinctId = uri.getQueryParameter("ph_distinct_id") ?: return + if (isAuthenticatedOnMobile) { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHog.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHog.identify(webDistinctId) + } + } + // Login/Signup + fun handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHog.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + fun handleLogout() { + PostHog.reset() + } +} +``` + +## Further reading + +- [Identifying users docs](/docs/product-analytics/identify.md) +- [How person processing works](/docs/how-posthog-works/ingestion-pipeline.md#2-person-processing) +- [An introductory guide to identifying users in PostHog](/tutorials/identifying-users-guide.md) + +### Still have questions? + +Ask PostHog AI + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/.claude/skills/integration-tanstack-start/references/tanstack-start.md b/.claude/skills/integration-tanstack-start/references/tanstack-start.md new file mode 100644 index 0000000..42329b3 --- /dev/null +++ b/.claude/skills/integration-tanstack-start/references/tanstack-start.md @@ -0,0 +1,221 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# TanStack Start - Docs + +Copy page + +# TanStack Start - Docs + +This tutorial shows how to integrate PostHog with a [TanStack Start](https://tanstack.com/start) app for both client-side and server-side analytics. + +## Installation + +Install the required packages: + +Terminal + +PostHog AI + +```bash +npm install @posthog/react posthog-node +``` + +- `@posthog/react` - React package for our [JS Web SDK](/docs/libraries/js.md) for client-side usage +- `posthog-node` - PostHog [Node.js SDK](/docs/libraries/node.md) for server-side event capture + +## Identifying users + +> **Identifying users is required.** Call `posthog.identify('your-user-id')` after login to link events to a known user. This is what connects frontend event captures, [session replays](/docs/session-replay.md), [LLM traces](/docs/ai-engineering.md), and [error tracking](/docs/error-tracking.md) to the same person — and lets backend events link back too. +> +> Use a stable ID from your auth system when possible, not an email or display name. Send those as person properties instead. If your app has no other stable key, email works as a fallback if they are unique. Never a shared literal like `"anonymous"` or `"user"`, which pools many people onto one person and corrupts their data. When no ID is available at all, skip the identify and retain the anonymous distinct ID that's automatically assigned. +> +> Call `posthog.reset()` on logout, so the next person to use the browser doesn't inherit the last one's identity. +> +> See our guide on [identifying users](/docs/getting-started/identify-users.md) for how to set this up. + +If your app calls your own backend, `tracing_headers` adds `X-POSTHOG-DISTINCT-ID` and `X-POSTHOG-SESSION-ID` to matching `fetch` and `XMLHttpRequest` requests. This lets server-side SDKs link backend events, errors, and LLM traces back to frontend sessions and replays. Use hostnames only, without protocols or paths. + +JavaScript + +PostHog AI + +```javascript +posthog.init('', { + api_host: 'https://us.i.posthog.com', + // Optional: send PostHog session/user context to your backend + tracing_headers: ['api.example.com'], +}) +``` + +This works in local development too, but match on the hostname alone: use `'localhost'`, not `'localhost:3000'`. Ports are never part of a hostname, so a value with one in it never matches anything. `localhost` and `127.0.0.1` are also different hostnames — use whichever your app actually calls. + +Tracing headers help you attribute events across front and backend consistently. When this isn't available, use your server-side stable IDs to deduce the matching `distinctId`, and pass it in when capturing the event. + +## Initialize PostHog on the client + +Wrap your app with `PostHogProvider` in your root route with your project token, host, and other options. + +PostHog AI + +``` +import CspAllowancesCallout from "../_snippets/csp-allowances-callout.mdx" +tsx file=src/routes/__root.tsx +// src/routes/__root.tsx +import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' +import { PostHogProvider } from '@posthog/react' +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + ], + }), + shellComponent: RootDocument, +}) +function RootDocument({ children }: { children: React.ReactNode }) { + return ( + + + + + + + {children} + + + + + ) +} +``` + +Once the provider is in place, PostHog automatically captures pageviews, sessions, and web vitals. + +## Capture events on the client + +Use the `usePostHog` hook from `@posthog/react` in any component to capture custom events: + +src/routes/checkout.tsx + +PostHog AI + +```jsx +import { usePostHog } from '@posthog/react' +function CheckoutButton({ orderId, total }: { orderId: string; total: number }) { + const posthog = usePostHog() + const handleClick = () => { + posthog.capture('checkout_started', { + order_id: orderId, + total: total, + }) + } + return +} +``` + +### Identify users + +Call `posthog.identify()` when a user logs in to link their events to a user ID: + +TSX + +PostHog AI + +```jsx +import { usePostHog } from '@posthog/react' +function LoginForm() { + const posthog = usePostHog() + const handleLogin = async (userId: string, email: string) => { + // ... your login logic + posthog.identify(userId, { + email: email, + }) + posthog.capture('user_logged_in') + } +} +``` + +Call `posthog.reset()` on logout to clear the identified user. + +## Initialize PostHog on the server + +Create a server-side PostHog client using `posthog-node`. Use a singleton pattern so you reuse the same client across requests: + +src/utils/posthog-server.ts + +PostHog AI + +```typescript +// src/utils/posthog-server.ts +import { PostHog } from 'posthog-node' +let posthogClient: PostHog | null = null +export function getPostHogClient() { + if (!posthogClient) { + posthogClient = new PostHog( + '', + { + host: 'https://us.i.posthog.com', + flushAt: 1, + flushInterval: 0, + }, + ) + } + return posthogClient +} +``` + +## Capture events on the server + +Use the server client in TanStack Start API routes to capture events server-side. Server-side capture is useful for tracking events that shouldn't be spoofable from the client, like purchases or authentication: + +src/routes/api/checkout.ts + +PostHog AI + +```typescript +// src/routes/api/checkout.ts +import { createFileRoute } from '@tanstack/react-router' +import { json } from '@tanstack/react-start' +import { getPostHogClient } from '../../utils/posthog-server' +export const Route = createFileRoute('/api/checkout')({ + server: { + handlers: { + POST: async ({ request }) => { + const body = await request.json() + const posthog = getPostHogClient() + posthog.capture({ + distinctId: body.userId, + event: 'item_purchased', + properties: { + item_id: body.itemId, + price: body.price, + source: 'api', + }, + }) + return json({ success: true }) + }, + }, + }, +}) +``` + +The server-side `capture` call requires a `distinctId` (the user identifier), an `event` name, and optional `properties`. + +## Next steps + +Installing the JS Web SDK and Node SDK means all of their functionality is available in your TanStack Start project. To learn more about this, have a look at our [JS Web SDK docs](/docs/libraries/js/usage.md) and [Node SDK docs](/docs/libraries/node.md). + +### Still have questions? + +Ask PostHog AI + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/.env.example b/.env.example index 7738d97..acfed75 100644 --- a/.env.example +++ b/.env.example @@ -11,5 +11,7 @@ VITE_TURNSTILE_SITEKEY=1x00000000000000000000BB # Address behind the form's "Open Email" failure fallback (issue #27) VITE_CONTACT_EMAIL=contact@execil.net -# Empty => initAnalytics() returns early and PostHog never loads (issue #31) -VITE_POSTHOG_PROJECT_TOKEN= +# PostHog browser analytics. Set these to the project's public token and host. +VITE_PUBLIC_POSTHOG_PROJECT_TOKEN= +VITE_PUBLIC_POSTHOG_HOST= + diff --git a/package.json b/package.json index d3ec687..efb34d2 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,7 @@ "@stylexjs/stylex": "^0.19.0", "@tanstack/react-router": "latest", "@tanstack/react-start": "latest", - "posthog-js": "^1.427.1", + "posthog-js": "^1.427.2", "react": "^19.2.0", "react-dom": "^19.2.0" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9287191..994aae0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -18,8 +18,8 @@ importers: specifier: latest version: 1.168.49(esbuild@0.28.1)(react-dom@19.2.8(react@19.2.8))(react@19.2.8)(rolldown@1.2.7)(supports-color@10.2.2)(vite@8.2.2(@types/node@22.20.1)(esbuild@0.28.1)(jiti@2.7.0)) posthog-js: - specifier: ^1.427.1 - version: 1.427.1(@types/react@19.2.18)(react@19.2.8) + specifier: ^1.427.2 + version: 1.427.2(@types/react@19.2.18)(react@19.2.8) react: specifier: ^19.2.0 version: 19.2.8 @@ -1880,8 +1880,8 @@ packages: resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==} engines: {node: ^10 || ^12 || >=14} - posthog-js@1.427.1: - resolution: {integrity: sha512-jPKpF5qQS+SIzg2kJH6mTqkMEVY9YVBEywIccLFdl8A7zn+9aSnXQVv4xbF5gIjPtQe2MdcDugcyyJqfVrImLw==} + posthog-js@1.427.2: + resolution: {integrity: sha512-/jRg3ChHuxcHTTJ/xb+IbpXLYxiBKIWdjrsNNqY1tAwjnFoijmz58i4mIR4A2P5MWx+4R7LlpK9vQfBr8v292g==} peerDependencies: '@types/react': '>=16.8.0' react: '>=16.8.0' @@ -3756,7 +3756,7 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.1 - posthog-js@1.427.1(@types/react@19.2.18)(react@19.2.8): + posthog-js@1.427.2(@types/react@19.2.18)(react@19.2.8): dependencies: '@posthog/browser-common': 0.7.2 '@posthog/core': 1.50.5 diff --git a/src/analytics/events.ts b/src/analytics/events.ts deleted file mode 100644 index 7b14ec9..0000000 --- a/src/analytics/events.ts +++ /dev/null @@ -1,21 +0,0 @@ -/** - * The ten events this page fires. NONE carries a field value, an email, a name, - * a phone number, or any free text a visitor typed. See issue #31. - * - * Two of these exist to audit earlier decisions rather than to measure - * visitors: `email_fallback_used` tests whether #12's manual recovery panel - * actually recovers leads, and `assessment_failed` with reason "delivery" is - * the tripwire for Cloudflare Email Service's Beta status becoming a real - * problem rather than a noted risk. - */ -export type AnalyticsEvent = - | { name: 'cta_clicked'; props: { location: CtaLocation; variant: 'primary' | 'secondary' } } - | { name: 'phone_clicked'; props: { location: CtaLocation } } - | { name: 'nav_clicked'; props: { target: string } } - | { name: 'faq_opened'; props: { question_id: string } } - | { name: 'form_started'; props?: undefined } - | { name: 'assessment_submitted'; props?: undefined } - | { name: 'assessment_failed'; props: { reason: string } } - | { name: 'email_fallback_used'; props: { method: 'open_email' | 'copy_message' } } - -export type CtaLocation = 'header' | 'hero' | 'mobile_menu' | 'assessment' | 'footer' diff --git a/src/analytics/posthog.ts b/src/analytics/posthog.ts deleted file mode 100644 index 1b39692..0000000 --- a/src/analytics/posthog.ts +++ /dev/null @@ -1,63 +0,0 @@ -import type { AnalyticsEvent } from './events' - -const TOKEN = import.meta.env.VITE_POSTHOG_PROJECT_TOKEN ?? '' - -type PostHogClient = { - init: (token: string, options: Record) => void - capture: (name: string, props?: Record) => void -} - -let client: PostHogClient | null = null - -/** - * Client-only, after hydration, on idle. Never runs during prerender. - * - * An empty token makes this a no-op, so the whole application runs with no - * PostHog account — the map's standing constraint. - */ -export function initAnalytics(): void { - if (!TOKEN || client) return - - const start = () => { - void import('posthog-js').then(({ default: posthog }) => { - posthog.init(TOKEN, { - api_host: 'https://us.i.posthog.com', - ui_host: 'https://us.posthog.com', - defaults: '2026-05-30', - - // No cookies, no local/session storage, no persistent identifier. - // This is what removes the need for a consent banner (issue #13). - cookieless_mode: 'always', - person_profiles: 'never', - - // OFF deliberately. Every interactive element on this page is already - // enumerated, so there is nothing to discover; what autocapture would - // add is events keyed on DOM selectors, pushing the page's marketing - // copy into the analytics product as event data. - autocapture: false, - disable_surveys: true, - capture_heatmaps: false, - disable_session_recording: true, - - capture_pageview: 'history_change', - // Carries max scroll depth — the most useful single signal here. - capture_pageleave: true, - capture_dead_clicks: true, - rageclick: true, - }) - client = posthog as unknown as PostHogClient - }) - } - - // Idle, so measurement never competes with LCP. - const idle = (globalThis as { requestIdleCallback?: (cb: () => void) => void }) - .requestIdleCallback - if (idle) idle(start) - else globalThis.setTimeout(start, 1200) -} - -/** NEVER call identify(): in cookieless mode it would defeat the whole - * arrangement by creating a persistent identifier. */ -export function track(event: AnalyticsEvent): void { - client?.capture(event.name, event.props) -} diff --git a/src/base/Form.tsx b/src/base/Form.tsx index e9ec3e8..db6900f 100644 --- a/src/base/Form.tsx +++ b/src/base/Form.tsx @@ -21,7 +21,6 @@ export function Form({ label, onSubmit, onFocusCapture, - noCapture = false, children, style, }: { @@ -30,10 +29,6 @@ export function Form({ onSubmit?: (event: React.FormEvent) => void /** Used to lazy-load third-party form scripts on first interaction. */ onFocusCapture?: () => void - /** Opt this form out of analytics capture entirely. A data attribute rather - * than a className: stylex.props() spreads its own className afterwards and - * would overwrite one passed here. */ - noCapture?: boolean children?: React.ReactNode style?: StyleProp }) { @@ -43,7 +38,6 @@ export function Form({ onSubmit={onSubmit} onFocusCapture={onFocusCapture} noValidate={false} - data-ph-no-capture={noCapture || undefined} {...stylex.props(styles.form, style)} > {children} diff --git a/src/base/Link.tsx b/src/base/Link.tsx index c2d216d..4414011 100644 --- a/src/base/Link.tsx +++ b/src/base/Link.tsx @@ -86,9 +86,8 @@ type LinkProps = { children?: React.ReactNode style?: StyleProp 'aria-label'?: string - /** Fired on activation. Exists so sections can report an event without - * importing the analytics module — base/ must not depend on it, and - * sections must not depend on analytics either (issue #31). */ + /** Fired on activation. A seam for side effects on click, so base/ never + * has to know why a section cares. */ onActivate?: (event: React.MouseEvent) => void current?: boolean } diff --git a/src/routes/__root.tsx b/src/routes/__root.tsx index f214af8..93c44af 100644 --- a/src/routes/__root.tsx +++ b/src/routes/__root.tsx @@ -1,8 +1,7 @@ import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' -import { useEffect } from 'react' import * as stylex from '@stylexjs/stylex' +import { PostHogProvider } from 'posthog-js/react' -import { initAnalytics } from '../analytics/posthog' import { Box } from '../base/Box' import { NotFound } from '../sections/NotFound' import { SiteFooter } from '../sections/SiteFooter' @@ -14,6 +13,23 @@ import { m } from '../messages' import appCss from '../styles/app.css?url' +const POSTHOG_PROJECT_TOKEN = import.meta.env.VITE_PUBLIC_POSTHOG_PROJECT_TOKEN +const POSTHOG_HOST = import.meta.env.VITE_PUBLIC_POSTHOG_HOST + +if (import.meta.env.DEV) { + if (!POSTHOG_PROJECT_TOKEN) { + throw new Error( + 'VITE_PUBLIC_POSTHOG_PROJECT_TOKEN variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once VITE_PUBLIC_POSTHOG_PROJECT_TOKEN is configured', + ) + } + + if (!POSTHOG_HOST) { + throw new Error( + 'VITE_PUBLIC_POSTHOG_HOST variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once VITE_PUBLIC_POSTHOG_HOST is configured', + ) + } +} + export const Route = createRootRoute({ head: () => ({ meta: [ @@ -96,11 +112,12 @@ const styles = stylex.create({ }) function RootDocument({ children }: { children: React.ReactNode }) { - // Client-only, after hydration. Never runs during prerender, where there is - // no browser and no visitor. - useEffect(() => { - initAnalytics() - }, []) + const content = ( + <> + {children} + + + ) return ( @@ -108,9 +125,22 @@ function RootDocument({ children }: { children: React.ReactNode }) { - {children} - - + {POSTHOG_PROJECT_TOKEN && POSTHOG_HOST ? ( + + {content} + + ) : ( + content + )} ) diff --git a/src/sections/Assessment.tsx b/src/sections/Assessment.tsx index 30003ae..113d56f 100644 --- a/src/sections/Assessment.tsx +++ b/src/sections/Assessment.tsx @@ -1,4 +1,5 @@ import { useEffect, useRef, useState } from 'react' +import { usePostHog } from 'posthog-js/react' import * as stylex from '@stylexjs/stylex' import { Badge } from '../base/Badge' @@ -18,7 +19,6 @@ import { Stack } from '../base/Stack' import { Text } from '../base/Text' import { VisuallyHidden } from '../base/VisuallyHidden' import type { AssessmentResult } from '../routes/api/assessment' -import { track } from '../analytics/posthog' import { m } from '../messages' import { color, layout, radius, space, text } from '../styles/tokens.stylex' @@ -91,6 +91,7 @@ function formatSubmission(data: FormData): string { } export function Assessment() { + const posthog = usePostHog() const [state, setState] = useState({ status: 'idle' }) const turnstileLoaded = useRef(false) const widgetRef = useRef(null) @@ -103,15 +104,6 @@ export function Assessment() { * By the time a field is focused it has seconds before a submit is * possible, and the submit path awaits it rather than assuming it is * ready (issue #18). */ - const formStarted = useRef(false) - - const onFirstInteraction = () => { - if (!formStarted.current) { - formStarted.current = true - track({ name: 'form_started' }) - } - loadTurnstile() - } const loadTurnstile = () => { if (turnstileLoaded.current || !TURNSTILE_SITEKEY) return @@ -149,17 +141,15 @@ export function Assessment() { .then(async (response) => { const result = (await response.json()) as AssessmentResult if (result.ok) { - track({ name: 'assessment_submitted' }) + posthog?.capture('assessment_submitted') setState({ status: 'success' }) return } - // The tripwire for Email Service's Beta status becoming a real - // problem rather than a noted risk (issue #13). - track({ name: 'assessment_failed', props: { reason: result.error } }) + posthog?.capture('assessment_submission_failed', { reason: result.error }) setState({ status: 'failure', reason: result.error }) }) .catch(() => { - track({ name: 'assessment_failed', props: { reason: 'delivery' } }) + posthog?.capture('assessment_submission_failed', { reason: 'delivery' }) setState({ status: 'failure', reason: 'delivery' }) }) .finally(() => { @@ -175,9 +165,9 @@ export function Assessment() { * no user gesture. Confirm only on success, so the label never claims * "Copied" when nothing was. The mailto path still works either way. */ const copy = () => { - track({ name: 'email_fallback_used', props: { method: 'copy_message' } }) navigator.clipboard.writeText(submission).then( () => { + posthog?.capture('assessment_details_copied') setCopied(true) }, () => { @@ -235,7 +225,7 @@ export function Assessment() {