From a39ef483a577ae82ecd62440255ba665f3a8ea8f Mon Sep 17 00:00:00 2001 From: "wizard-ci-bot[bot]" <254716194+wizard-ci-bot[bot]@users.noreply.github.com> Date: Tue, 1 Sep 2026 15:57:35 +0000 Subject: [PATCH] wizard-ci: react-router/rrv7-starter --- .../.posthog-wizard | 0 .../references/identify-users.md | 307 ++++++++++++++ .../references/react-router-v6.md | 394 ++++++++++++++++++ .../react-router/rrv7-starter/.env.example | 2 + .../rrv7-starter/app/components/PostCard.tsx | 6 + .../app/components/posthog-provider.tsx | 56 +++ .../react-router/rrv7-starter/app/root.tsx | 81 ++-- .../rrv7-starter/app/routes/buy-followers.tsx | 21 +- .../rrv7-starter/app/routes/profile.tsx | 13 +- .../react-router/rrv7-starter/env.d.ts | 2 + .../react-router/rrv7-starter/package.json | 2 + .../react-router/rrv7-starter/pnpm-lock.yaml | 128 ++++++ 12 files changed, 968 insertions(+), 44 deletions(-) create mode 100644 apps/basic-integration/react-router/rrv7-starter/.claude/skills/integration-react-react-router-6/.posthog-wizard create mode 100644 apps/basic-integration/react-router/rrv7-starter/.claude/skills/integration-react-react-router-6/references/identify-users.md create mode 100644 apps/basic-integration/react-router/rrv7-starter/.claude/skills/integration-react-react-router-6/references/react-router-v6.md create mode 100644 apps/basic-integration/react-router/rrv7-starter/app/components/posthog-provider.tsx diff --git a/apps/basic-integration/react-router/rrv7-starter/.claude/skills/integration-react-react-router-6/.posthog-wizard b/apps/basic-integration/react-router/rrv7-starter/.claude/skills/integration-react-react-router-6/.posthog-wizard new file mode 100644 index 000000000..e69de29bb diff --git a/apps/basic-integration/react-router/rrv7-starter/.claude/skills/integration-react-react-router-6/references/identify-users.md b/apps/basic-integration/react-router/rrv7-starter/.claude/skills/integration-react-react-router-6/references/identify-users.md new file mode 100644 index 000000000..8647dcb37 --- /dev/null +++ b/apps/basic-integration/react-router/rrv7-starter/.claude/skills/integration-react-react-router-6/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/apps/basic-integration/react-router/rrv7-starter/.claude/skills/integration-react-react-router-6/references/react-router-v6.md b/apps/basic-integration/react-router/rrv7-starter/.claude/skills/integration-react-react-router-6/references/react-router-v6.md new file mode 100644 index 000000000..f96e8fb2c --- /dev/null +++ b/apps/basic-integration/react-router/rrv7-starter/.claude/skills/integration-react-react-router-6/references/react-router-v6.md @@ -0,0 +1,394 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# React Router V6 - Docs + +Copy page + +# React Router V6 - Docs + +This guide walks you through setting up PostHog for React Router V6. If you're using React Router v7, find the guide for that mode in the [React Router page](/docs/libraries/react-router.md). If you're using React with another framework, go to the [React integration guide](/docs/libraries/react.md). + +1. 1 + + ## Install client-side SDKs + + Required + + First, you'll need to install [`posthog-js`](https://github.com/posthog/posthog-js) and `@posthog/react` using your package manager. These packages allow you to capture **client-side** events. + + PostHog AI + + ### npm + + ```bash + npm install --save posthog-js @posthog/react + ``` + + ### Yarn + + ```bash + yarn add posthog-js @posthog/react + ``` + + ### pnpm + + ```bash + pnpm add posthog-js @posthog/react + ``` + + ### Bun + + ```bash + bun add posthog-js @posthog/react + ``` + + > **If your site sets a Content-Security-Policy**, it needs to allow PostHog. This applies to the snippet and to package installs alike: the SDK lazy-loads extra bundles (session replay, surveys) from PostHog's CDN, and sends events to the ingestion host. PostHog serves from subdomains of `posthog.com` that change over time, so allow the wildcard: + > + > PostHog AI + > + > ``` + > script-src 'self' https://*.posthog.com; + > connect-src 'self' https://*.posthog.com; + > worker-src 'self' blob: data:; + > ``` + > + > `script-src` covers the snippet and the lazy-loaded bundles, `connect-src` covers event ingestion and feature flags, and `worker-src` covers session replay. The [toolbar needs a few more](/docs/advanced/content-security-policy.md), or use a [reverse proxy](/docs/advanced/proxy.md) so everything is first-party. Failing to do so causes silent failures where `capture` and `identify` calls never send, so the integration looks complete while zero events arrive. Remember `connect-src` falls back to `default-src`, so `default-src 'self'` blocks event delivery even when the script itself is bundled. + +2. 2 + + ## Add your environment variables + + Required + + Add your environment variables to your `.env.local` file and to your hosting provider (e.g. Vercel, Netlify, AWS). You can find your project token and host in [your project settings](https://us.posthog.com/settings/project). If you're using Vite, prefixing variable names with `VITE_` ensures they are accessible in the frontend. + + .env.local + + PostHog AI + + ```shell + VITE_POSTHOG_PROJECT_TOKEN= + VITE_POSTHOG_HOST=https://us.i.posthog.com + ``` + +3. 3 + + ## Add the PostHogProvider to your app + + Required + + In declarative mode, you'll need to wrap your `BrowserRouter` with the `PostHogProvider` context. This passes an initialized PostHog client to your app. + + src/main.tsx + + PostHog AI + + ```jsx + import { StrictMode } from "react"; + import ReactDOM from "react-dom/client"; + import { BrowserRouter, Routes, Route } from "react-router"; + import posthog from 'posthog-js'; + import { PostHogErrorBoundary, PostHogProvider } from '@posthog/react' + // Initialize PostHog + posthog.init(import.meta.env.VITE_POSTHOG_PROJECT_TOKEN, { + api_host: import.meta.env.VITE_POSTHOG_HOST, + defaults: '2026-05-30', + }); + const root = document.getElementById("root"); + ReactDOM.createRoot(root).render( + + {/* Pass PostHog client through PostHogProvider */} + + + + }> + {/* ... Your routes ... */} + + + + + , + ); + ``` + + This initializes PostHog and passes it to your app through the `PostHogProvider` context. + + TypeError: Cannot read properties of undefined + + If you see the error `TypeError: Cannot read properties of undefined (reading '...')` this is likely because you tried to call a posthog function when posthog was not initialized (such as during the initial render). On purpose, we still render the children even if PostHog is not initialized so that your app still loads even if PostHog can't load. + + To fix this error, add a check that posthog has been initialized such as: + + React + + PostHog AI + + ```jsx + useEffect(() => { + posthog?.capture('test') // using optional chaining (recommended) + if (posthog) { + posthog.capture('test') // using an if statement + } + }, [posthog]) + ``` + + Typescript helps protect against these errors. + +4. ## Verify client-side events are captured + + Checkpoint + + *Confirm that you can capture client-side events and see them in your PostHog project* + + At this point, you should be able to capture client-side events and see them in your PostHog project. This includes basic events like page views and button clicks that are [autocaptured](/docs/product-analytics/autocapture.md). + + You can also try to capture a custom event to verify it's working. You can access PostHog in any component using the `usePostHog` hook. + + TSX + + PostHog AI + + ```jsx + import { usePostHog } from '@posthog/react' + function App() { + const posthog = usePostHog() + return + } + ``` + + You should see these events in a minute or two in the [activity tab](https://app.posthog.com/activity/explore). + +5. 4 + + ## Access PostHog methods + + Required + + On the client-side, you can access the PostHog client using the `usePostHog` hook. This hook returns the initialized PostHog client, which you can use to call PostHog methods. For example: + + TSX + + PostHog AI + + ```jsx + import { usePostHog } from '@posthog/react' + function App() { + const posthog = usePostHog() + return + } + ``` + + For a complete list of available methods, see the [posthog-js documentation](/docs/libraries/js.md). + +6. 5 + + ## Identify your user + + Recommended + + Now that you can capture basic client-side events, you'll want to identify your user so you can associate users with captured events. + + Generally, you identify users when they log in or when they input some identifiable information (e.g. email, name, etc.). You can identify users by calling the `identify` method on the PostHog client: + + TSX + + PostHog AI + + ```jsx + export default function Login() { + const { user, login } = useAuth(); + const posthog = usePostHog(); + const handleLogin = async (e: React.FormEvent) => { + // existing code to handle login... + const user = await login({ email, password }); + posthog?.identify(user.email, + { + email: user.email, + name: user.name, + } + ); + posthog?.capture('user_logged_in'); + }; + return ( +
+ {/* ... existing code ... */} + +
+ ); + } + ``` + + PostHog automatically generates anonymous IDs for users before they're identified. When you call identify, a new identified person is created. All previous events tracked with the anonymous ID link to the new identified distinct ID, and all future captures on the same browser associate with the identified person. + +7. 6 + + ## Create an error boundary + + Recommended + + PostHog can capture exceptions thrown in your app through an error boundary. PostHog provides a `PostHogErrorBoundary` component that you can use to capture exceptions. You can wrap your app with this component to capture exceptions. + + TSX + + PostHog AI + + ```jsx + ReactDOM.createRoot(root).render( + + + + + + }> + {/* ... Your routes ... */} + + + + + + , + ); + ``` + + This automatically captures exceptions thrown in your React Router app using the `posthog.captureException()` method. + +8. 7 + + ## Tracking element visibility + + Recommended + + The `PostHogCaptureOnViewed` component enables you to automatically capture events when elements scroll into view in the browser. This is useful for tracking impressions of important content, monitoring user engagement with specific sections, or understanding which parts of your page users are actually seeing. + + The component wraps your content and sends a `$element_viewed` event to PostHog when the wrapped element becomes visible in the viewport. It only fires once per component instance. + + **Basic usage:** + + React + + PostHog AI + + ```jsx + import { PostHogCaptureOnViewed } from '@posthog/react' + function App() { + return ( + +
Your important content here
+
+ ) + } + ``` + + **With custom properties:** + + You can include additional properties with the event to provide more context: + + React + + PostHog AI + + ```jsx + + + + ``` + + **Tracking multiple children:** + + Use `trackAllChildren` to track each child element separately. This is useful for galleries or lists where you want to know which specific items were viewed: + + React + + PostHog AI + + ```jsx + + + + + + ``` + + When `trackAllChildren` is enabled, each child element sends its own event with a `child_index` property indicating its position. + + **Custom intersection observer options:** + + You can customize when elements are considered "viewed" by passing options to the `IntersectionObserver`: + + React + + PostHog AI + + ```jsx + +