+
+ );
+}
+
+const resources = [
+ {
+ href: "https://reactrouter.com/docs",
+ text: "React Router Docs",
+ icon: (
+
+ ),
+ },
+ {
+ href: "https://rmx.as/discord",
+ text: "Join Discord",
+ icon: (
+
+ ),
+ },
+];
+
+```
+
+---
+
+## react-router.config.ts
+
+```ts
+import type { Config } from "@react-router/dev/config";
+
+export default {
+ // Config options...
+ // Server-side render by default, to enable SPA mode set this to `false`
+ ssr: true,
+ future: {
+ v8_middleware: true,
+ },
+} satisfies Config;
+
+```
+
+---
+
+## vite.config.ts
+
+```ts
+import { reactRouter } from "@react-router/dev/vite";
+import tailwindcss from "@tailwindcss/vite";
+import { defineConfig, loadEnv } from "vite";
+import tsconfigPaths from "vite-tsconfig-paths";
+
+export default defineConfig(({ mode }) => {
+ const env = loadEnv(mode, process.cwd(), '');
+
+ return {
+ plugins: [tailwindcss(), reactRouter(), tsconfigPaths()],
+ ssr: {
+ noExternal: ['posthog-js', '@posthog/react'],
+ },
+ server: {
+ proxy: {
+ '/ingest': {
+ target: env.VITE_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com',
+ changeOrigin: true,
+ rewrite: (path) => path.replace(/^\/ingest/, ''),
+ },
+ },
+ },
+ };
+});
+
+```
+
+---
+
diff --git a/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/basic-integration-1.0-begin.md b/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/basic-integration-1.0-begin.md
new file mode 100644
index 0000000..953ead2
--- /dev/null
+++ b/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/basic-integration-1.0-begin.md
@@ -0,0 +1,43 @@
+---
+title: PostHog Setup - Begin
+description: Start the event tracking setup process by analyzing the project and creating an event tracking plan
+---
+
+We're making an event tracking plan for this project.
+
+Before proceeding, find any existing `posthog.capture()` code. Make note of event name formatting.
+
+From the project's file list, select between 10 and 15 files that might have interesting business value for event tracking, especially conversion and churn events. Also look for additional files related to login that could be used for identifying users, along with error handling. Read the files. If a file is already well-covered by PostHog events, replace it with another option.
+
+Look for opportunities to track client-side events.
+
+**IMPORTANT: Server-side events are REQUIRED** if the project includes any instrumentable server-side code. If the project has API routes (e.g., `app/api/**/route.ts`) or Server Actions, you MUST include server-side events for critical business operations like:
+
+ - Payment/checkout completion
+ - Webhook handlers
+ - Authentication endpoints
+
+Do not skip server-side events - they capture actions that cannot be tracked client-side.
+
+Create a new file with a JSON array at the root of the project: .posthog-events.json. It should include one object for each event we want to add: event name, event description, and the file path we want to place the event in. If events already exist, don't duplicate them; supplement them.
+
+Track actions only, not pageviews. These can be captured automatically. Exceptions can be made for "viewed"-type events that correspond to the top of a conversion funnel.
+
+As you review files, make an internal note of opportunities to identify users and catch errors. We'll need them for the next step.
+
+## Status
+
+Before beginning a phase of the setup, you will send a status message with the exact prefix '[STATUS]', as in:
+
+[STATUS] Checking project structure.
+
+Status to report in this phase:
+
+- Checking project structure
+- Verifying PostHog dependencies
+- Generating events based on project
+
+
+---
+
+**Upon completion, continue with:** [basic-integration-1.1-edit.md](basic-integration-1.1-edit.md)
\ No newline at end of file
diff --git a/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/basic-integration-1.1-edit.md b/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/basic-integration-1.1-edit.md
new file mode 100644
index 0000000..44c1a4e
--- /dev/null
+++ b/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/basic-integration-1.1-edit.md
@@ -0,0 +1,37 @@
+---
+title: PostHog Setup - Edit
+description: Implement PostHog event tracking in the identified files, following best practices and the example project
+---
+
+For each of the files and events noted in .posthog-events.json, make edits to capture events using PostHog. Make sure to set up any helper files needed. Carefully examine the included example project code: your implementation should match it as closely as possible.
+
+Use environment variables for PostHog keys. Do not hardcode PostHog keys.
+
+If a file already has existing integration code for other tools or services, don't overwrite or remove that code. Place PostHog code below it.
+
+For each event, add useful properties, and use your access to the PostHog source code to ensure correctness. You also have access to documentation about creating new events with PostHog. Consider this documentation carefully and follow it closely before adding events. Your integration should be based on documented best practices. Carefully consider how the user project's framework version may impact the correct PostHog integration approach.
+
+Remember that you can find the source code for any dependency in the node_modules directory. This may be necessary to properly populate property names. There are also example project code files available via the PostHog MCP; use these for reference.
+
+Where possible, add calls for PostHog's identify() function on the client side upon events like logins and signups. Use the contents of login and signup forms to identify users on submit. If there is server-side code, pass the client-side session and distinct ID to the server-side code to identify the user. On the server side, make sure events have a matching distinct ID where relevant.
+
+It's essential to do this in both client code and server code, so that user behavior from both domains is easy to correlate.
+
+You should also add PostHog exception capture error tracking to these files where relevant.
+
+Remember: Do not alter the fundamental architecture of existing files. Make your additions minimal and targeted.
+
+Remember the documentation and example project resources you were provided at the beginning. Read them now.
+
+## Status
+
+Status to report in this phase:
+
+- Inserting PostHog capture code
+- A status message for each file whose edits you are planning, including a high level summary of changes
+- A status message for each file you have edited
+
+
+---
+
+**Upon completion, continue with:** [basic-integration-1.2-revise.md](basic-integration-1.2-revise.md)
\ No newline at end of file
diff --git a/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/basic-integration-1.2-revise.md b/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/basic-integration-1.2-revise.md
new file mode 100644
index 0000000..26f3a60
--- /dev/null
+++ b/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/basic-integration-1.2-revise.md
@@ -0,0 +1,22 @@
+---
+title: PostHog Setup - Revise
+description: Review and fix any errors in the PostHog integration implementation
+---
+
+Check the project for errors. Read the package.json file for any type checking or build scripts that may provide input about what to fix. Remember that you can find the source code for any dependency in the node_modules directory.
+
+Ensure that any components created were actually used.
+
+Once all other tasks are complete, run any linter or prettier-like scripts found in the package.json.
+
+## Status
+
+Status to report in this phase:
+
+- Finding and correcting errors
+- Report details of any errors you fix
+- Linting, building and prettying
+
+---
+
+**Upon completion, continue with:** [basic-integration-1.3-conclude.md](basic-integration-1.3-conclude.md)
\ No newline at end of file
diff --git a/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/basic-integration-1.3-conclude.md b/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/basic-integration-1.3-conclude.md
new file mode 100644
index 0000000..552118f
--- /dev/null
+++ b/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/basic-integration-1.3-conclude.md
@@ -0,0 +1,36 @@
+---
+title: PostHog Setup - Conclusion
+description: Review and fix any errors in the PostHog integration implementation
+---
+
+Use the PostHog MCP to create a new dashboard named "Analytics basics" based on the events created here. Make sure to use the exact same event names as implemented in the code. Populate it with up to five insights, with special emphasis on things like conversion funnels, churn events, and other business critical insights.
+
+Create the file posthog-setup-report.md. It should include a summary of the integration edits, a table with the event names, event descriptions, and files where events were added, along with a list of links for the dashboard and insights created. Follow this format:
+
+
+# PostHog post-wizard report
+
+The wizard has completed a deep integration of your project. [Detailed summary of changes]
+
+[table of events/descriptions/files]
+
+## Next steps
+
+We've built some insights and a dashboard for you to keep an eye on user behavior, based on the events we just instrumented:
+
+[links]
+
+### Agent skill
+
+We've left an agent skill folder in your project. You can use this context for further agent development when using Claude Code. This will help ensure the model provides the most up-to-date approaches for integrating PostHog.
+
+
+
+Upon completion, remove .posthog-events.json.
+
+## Status
+
+Status to report in this phase:
+
+- Configured dashboard: [insert PostHog dashboard URL]
+- Created setup report: [insert full local file path]
\ No newline at end of file
diff --git a/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/identify-users.md b/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/identify-users.md
new file mode 100644
index 0000000..ce16545
--- /dev/null
+++ b/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/identify-users.md
@@ -0,0 +1,202 @@
+# 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/features#capturing-events.md) or [mobile app](/docs/libraries/ios#capturing-events.md), 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/features#capturing-anonymous-events.md).
+
+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.
+
+### 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
+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.
+
+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 user is already authenticated on the mobile app. In this case, call [`posthog.alias()`](/docs/libraries/js/features#alias.md) with the distinct ID from the web. This associates the two distinct IDs as a single person.
+- The user is unauthenticated. In this case, call [`posthog.identify()`](/docs/libraries/js/features#identifying-users.md) with the distinct ID from the web. Events will be associated with this distinct ID.
+
+As long as you associate the distinct IDs with `posthog.identify()` or `posthog.alias()`, you can track events generated across platforms.
+
+## Further reading
+
+- [Identifying users docs](/docs/product-analytics/identify.md)
+- [How person processing works](/docs/how-posthog-works/ingestion-pipeline#2-person-processing.md)
+- [An introductory guide to identifying users in PostHog](/tutorials/identifying-users-guide.md)
+
+### Community questions
+
+Ask a question
+
+### Was this page useful?
+
+HelpfulCould be better
\ No newline at end of file
diff --git a/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/react-router-v7-framework-mode.md b/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/react-router-v7-framework-mode.md
new file mode 100644
index 0000000..9071e8b
--- /dev/null
+++ b/apps/react-router/shopper/.claude/skills/react-react-router-7-framework/references/react-router-v7-framework-mode.md
@@ -0,0 +1,479 @@
+# React Router V7 framework mode (Remix V3) - Docs
+
+This guide walks you through setting up PostHog for React Router V7 in framework mode. If you're using React Router in another mode, 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
+ ```
+
+ In framework mode, you'll also need to set `posthog-js` and `@posthog/react` as external packages in your `vite.config.ts` file to avoid SSR errors.
+
+ vite.config.ts
+
+ PostHog AI
+
+ ```typescript
+ // ... imports
+ export default defineConfig({
+ plugins: [tailwindcss(), reactRouter(), tsconfigPaths()],
+ ssr: {
+ noExternal: ['posthog-js', '@posthog/react']
+ }
+ });
+ ```
+
+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 API key and host in [your project settings](https://us.posthog.com/settings/project). If you're using Vite, including `VITE_PUBLIC_` in their names ensures they are accessible in the frontend.
+
+ .env.local
+
+ PostHog AI
+
+ ```shell
+ VITE_PUBLIC_POSTHOG_KEY=
+ VITE_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
+ ```
+
+3. 3
+
+ ## Add the PostHogProvider to your app
+
+ Required
+
+ In framework mode, your app enters from the `app/entry.client.tsx` file. In this file, you'll need to initialize the PostHog SDK and pass it to your app through the `PostHogProvider` context.
+
+ app/entry.client.tsx
+
+ PostHog AI
+
+ ```jsx
+ import { startTransition, StrictMode } from "react";
+ import { hydrateRoot } from "react-dom/client";
+ import { HydratedRouter } from "react-router/dom";
+ import posthog from 'posthog-js';
+ import { PostHogProvider } from '@posthog/react'
+ posthog.init(import.meta.env.VITE_PUBLIC_POSTHOG_KEY, {
+ api_host: import.meta.env.VITE_PUBLIC_POSTHOG_HOST,
+ defaults: '2025-11-30',
+ __add_tracing_headers: [ window.location.host, 'localhost' ],
+ });
+ startTransition(() => {
+ hydrateRoot(
+ document,
+ {/* Pass PostHog client through PostHogProvider */}
+
+
+
+
+ ,
+ );
+ });
+ ```
+
+ To help PostHog track your user sessions across the client and server, you'll need to add the `__add_tracing_headers: ['your-backend-domain1.com', 'your-backend-domain2.com', ...]` option to your PostHog initialization. This adds the `X-POSTHOG-DISTINCT-ID` and `X-POSTHOG-SESSION-ID` headers to your requests, which we'll later use on the server-side.
+
+ 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. React Router in framework mode has a built-in error boundary that you can use to capture exceptions. You can create an error boundary by exporting `ErrorBoundary` from your `app/root.tsx` file.
+
+ app/root.tsx
+
+ PostHog AI
+
+ ```jsx
+ import { usePostHog } from '@posthog/react'
+ export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
+ const posthog = usePostHog();
+ posthog?.captureException(error);
+ // other error handling code...
+ return (
+
+
Something went wrong
+
{error.message}
+
+ );
+ }
+ ```
+
+ 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
+
+
+
+ ```
+
+ The component passes all other props to the wrapper `div`, so you can add styling, classes, or other HTML attributes as needed.
+
+9. 8
+
+ ## Install server-side SDKs
+
+ Recommended
+
+ Install the [PostHog Node SDK](/docs/libraries/node.md) using your package manager. This is the SDK you'll use to capture server-side events.
+
+ PostHog AI
+
+ ### npm
+
+ ```bash
+ npm install posthog-node --save
+ ```
+
+ ### Yarn
+
+ ```bash
+ yarn add posthog-node
+ ```
+
+ ### pnpm
+
+ ```bash
+ pnpm add posthog-node
+ ```
+
+ ### Bun
+
+ ```bash
+ bun add posthog-node
+ ```
+
+10. 9
+
+ ## Create a server-side middleware
+
+ Recommended
+
+ Next, create a server-side middleware to help you capture server-side events. This middleware helps you achieve the following:
+
+ - Initialize a PostHog client
+ - Fetch the session and distinct ID from the `X-POSTHOG-SESSION-ID` and `X-POSTHOG-DISTINCT-ID` headers and pass them to your request as a [context](/docs/libraries/node#contexts.md). This automatically identifies the user and session for you in all subsequent event captures.
+ - Calls `shutdown()` on the PostHog client to ensure all events are sent before the request is completed.
+
+ app/lib/posthog-middleware.ts
+
+ PostHog AI
+
+ ```typescript
+ import { PostHog } from "posthog-node";
+ import type { RouterContextProvider } from "react-router";
+ import type { Route } from "../+types/root";
+ export interface PostHogContext extends RouterContextProvider {
+ posthog?: PostHog;
+ }
+ export const posthogMiddleware: Route.MiddlewareFunction = async ({ request, context }, next) => {
+ const posthog = new PostHog(process.env.VITE_PUBLIC_POSTHOG_KEY!, {
+ host: process.env.VITE_PUBLIC_POSTHOG_HOST!,
+ flushAt: 1,
+ flushInterval: 0,
+ });
+ const sessionId = request.headers.get('X-POSTHOG-SESSION-ID');
+ const distinctId = request.headers.get('X-POSTHOG-DISTINCT-ID');
+ (context as PostHogContext).posthog = posthog;
+ const response = await posthog.withContext(
+ { sessionId: sessionId ?? undefined, distinctId: distinctId ?? undefined },
+ next
+ );
+ await posthog.shutdown().catch(() => {});
+ return response;
+ };
+ ```
+
+ Then, you'll need to register the middleware in your app in the `app/root.tsx` file by exporting it in the `Route.MiddlewareFunction[]` array.
+
+ app/root.tsx
+
+ PostHog AI
+
+ ```jsx
+ import { posthogMiddleware } from './lib/posthog-middleware';
+ export const middleware: Route.MiddlewareFunction[] = [
+ posthogMiddleware,
+ // other middlewares...
+ ];
+ ```
+
+11. ## Verify server-side events are captured
+
+ Checkpoint
+
+ *Confirm that you can capture server-side events and see them in your PostHog project*
+
+ At this point, you should be able to capture server-side events and see them in your PostHog project.
+
+ In a route, you can access the PostHog client from the context and capture an event. The middleware assigns the session ID and the distinct ID. This ensures that the system associates events with the correct user and session.
+
+ app/routes/api.checkout.ts
+
+ PostHog AI
+
+ ```jsx
+ import type { PostHogContext } from "../lib/posthog-middleware";
+ export async function action({ request, context }: Route.ActionArgs) {
+ const body = await request.json();
+ // ... existing code ...
+ // Access the PostHog client from the context and capture an event
+ const posthog = (context as PostHogContext).posthog;
+ posthog?.capture({ event: 'checkout_completed' });
+ return Response.json({
+ success: true,
+ // ... existing code ...
+ });
+ }
+ ```
+
+12. 10
+
+ ## Next steps
+
+ Recommended
+
+ Now that you've set up PostHog for React Router, you can start capturing events and exceptions in your app.
+
+ To get the most out of PostHog, you should familiarize yourself with the following:
+
+ - [PostHog Web SDK docs](/docs/libraries/js.md): Learn more about the PostHog Web SDK and how to use it on the client-side.
+ - [PostHog Node SDK docs](/docs/libraries/node.md): Learn more about the PostHog Node SDK and how to use it on the server-side.
+ - [Identify users](/docs/product-analytics/identify.md): Learn more about how to identify users in your app.
+ - [Group analytics](/docs/product-analytics/group-analytics.md): Learn more about how to use group analytics in your app.
+ - [PostHog AI](/docs/posthog-ai.md): After capturing events, use PostHog AI to help you understand your data and build insights.
+ - [Feature flags and experiments](/docs/libraries/react#feature-flags.md): Feature flag and experiment setup is the same as React. You can find more details in the React integration guide.
+
+### Community questions
+
+Ask a question
+
+### Was this page useful?
+
+HelpfulCould be better
\ No newline at end of file
diff --git a/apps/react-router/shopper/app/entry.client.tsx b/apps/react-router/shopper/app/entry.client.tsx
new file mode 100644
index 0000000..e793f5e
--- /dev/null
+++ b/apps/react-router/shopper/app/entry.client.tsx
@@ -0,0 +1,23 @@
+import { startTransition, StrictMode } from "react";
+import { hydrateRoot } from "react-dom/client";
+import { HydratedRouter } from "react-router/dom";
+
+import posthog from 'posthog-js';
+import { PostHogProvider } from '@posthog/react'
+
+posthog.init(import.meta.env.VITE_PUBLIC_POSTHOG_KEY, {
+ api_host: import.meta.env.VITE_PUBLIC_POSTHOG_HOST,
+ defaults: '2025-11-30',
+ __add_tracing_headers: [window.location.host, 'localhost'],
+});
+
+startTransition(() => {
+ hydrateRoot(
+ document,
+
+
+
+
+ ,
+ );
+});
diff --git a/apps/react-router/shopper/app/lib/posthog-middleware.ts b/apps/react-router/shopper/app/lib/posthog-middleware.ts
new file mode 100644
index 0000000..8348dc4
--- /dev/null
+++ b/apps/react-router/shopper/app/lib/posthog-middleware.ts
@@ -0,0 +1,29 @@
+import { PostHog } from "posthog-node";
+import type { RouterContextProvider } from "react-router";
+import type { Route } from "../+types/root";
+
+export interface PostHogContext extends RouterContextProvider {
+ posthog?: PostHog;
+}
+
+export const posthogMiddleware: Route.MiddlewareFunction = async ({ request, context }, next) => {
+ const posthog = new PostHog(process.env.VITE_PUBLIC_POSTHOG_KEY!, {
+ host: process.env.VITE_PUBLIC_POSTHOG_HOST!,
+ flushAt: 1,
+ flushInterval: 0,
+ });
+
+ const sessionId = request.headers.get('X-POSTHOG-SESSION-ID');
+ const distinctId = request.headers.get('X-POSTHOG-DISTINCT-ID');
+
+ (context as PostHogContext).posthog = posthog;
+
+ const response = await posthog.withContext(
+ { sessionId: sessionId ?? undefined, distinctId: distinctId ?? undefined },
+ next
+ );
+
+ await posthog.shutdown().catch(() => {});
+
+ return response;
+};
diff --git a/apps/react-router/shopper/app/root.tsx b/apps/react-router/shopper/app/root.tsx
index 95d59ac..be87bff 100644
--- a/apps/react-router/shopper/app/root.tsx
+++ b/apps/react-router/shopper/app/root.tsx
@@ -1,3 +1,4 @@
+import { usePostHog } from '@posthog/react';
import {
isRouteErrorResponse,
Links,
@@ -11,6 +12,11 @@ import type { Route } from "./+types/root";
import "./app.css";
import { CartProvider } from "./context/CartContext";
import Navbar from "./components/Navbar";
+import { posthogMiddleware } from "./lib/posthog-middleware";
+
+export const middleware: Route.MiddlewareFunction[] = [
+ posthogMiddleware,
+];
export const links: Route.LinksFunction = () => [
{ rel: "preconnect", href: "https://fonts.googleapis.com" },
@@ -59,6 +65,9 @@ export function ErrorBoundary({ error }: Route.ErrorBoundaryProps) {
let details = "An unexpected error occurred.";
let stack: string | undefined;
+ const posthog = usePostHog();
+ posthog?.captureException(error);
+
if (isRouteErrorResponse(error)) {
message = error.status === 404 ? "404" : "Error";
details =
diff --git a/apps/react-router/shopper/app/routes/cart.tsx b/apps/react-router/shopper/app/routes/cart.tsx
index 987dc7b..fc044c3 100644
--- a/apps/react-router/shopper/app/routes/cart.tsx
+++ b/apps/react-router/shopper/app/routes/cart.tsx
@@ -1,15 +1,52 @@
import { Link } from "react-router";
import { useCart, type CartItem } from "../context/CartContext";
+import { usePostHog } from "@posthog/react";
export default function Cart() {
const { cart, removeFromCart, updateQuantity, getCartTotal } = useCart();
+ const posthog = usePostHog();
const handleRemoveFromCart = (item: CartItem) => {
removeFromCart(item.id);
+ posthog?.capture("product_removed_from_cart", {
+ product_id: item.id,
+ product_name: item.name,
+ product_price: item.price,
+ product_category: item.category,
+ quantity_removed: item.quantity,
+ });
};
const handleUpdateQuantity = (item: CartItem, newQuantity: number) => {
+ const oldQuantity = item.quantity;
updateQuantity(item.id, newQuantity);
+ posthog?.capture("cart_quantity_updated", {
+ product_id: item.id,
+ product_name: item.name,
+ old_quantity: oldQuantity,
+ new_quantity: newQuantity,
+ change: newQuantity - oldQuantity,
+ });
+ };
+
+ const handleCheckoutClick = () => {
+ posthog?.capture("checkout_started", {
+ cart_total: getCartTotal(),
+ cart_items_count: cart.length,
+ cart_items: cart.map((item) => ({
+ product_id: item.id,
+ product_name: item.name,
+ quantity: item.quantity,
+ price: item.price,
+ })),
+ });
+ };
+
+ const handleContinueShoppingClick = () => {
+ posthog?.capture("continue_shopping_clicked", {
+ cart_total: getCartTotal(),
+ cart_items_count: cart.length,
+ });
};
if (cart.length === 0) {
@@ -154,6 +191,7 @@ export default function Cart() {
Proceed to Checkout
@@ -161,6 +199,7 @@ export default function Cart() {
Continue Shopping
diff --git a/apps/react-router/shopper/app/routes/checkout.tsx b/apps/react-router/shopper/app/routes/checkout.tsx
index c27d52c..ccff7df 100644
--- a/apps/react-router/shopper/app/routes/checkout.tsx
+++ b/apps/react-router/shopper/app/routes/checkout.tsx
@@ -1,10 +1,12 @@
import { useState } from "react";
import { useNavigate } from "react-router";
import { useCart } from "../context/CartContext";
+import { usePostHog } from "@posthog/react";
export default function Checkout() {
const { cart, getCartTotal, clearCart } = useCart();
const navigate = useNavigate();
+ const posthog = usePostHog();
const [isProcessing, setIsProcessing] = useState(false);
const [formData, setFormData] = useState({
fullName: "",
@@ -42,7 +44,35 @@ export default function Checkout() {
e.preventDefault();
setIsProcessing(true);
+ // Identify the user by email on checkout
+ posthog?.identify(formData.email, {
+ email: formData.email,
+ name: formData.fullName,
+ city: formData.city,
+ });
+
+ const orderTotal = getCartTotal() * 1.1; // Including tax
+ const orderItems = cart.map((item) => ({
+ product_id: item.id,
+ product_name: item.name,
+ quantity: item.quantity,
+ price: item.price,
+ category: item.category,
+ }));
+
setTimeout(() => {
+ // Capture order_completed event
+ posthog?.capture("order_completed", {
+ order_total: orderTotal,
+ subtotal: getCartTotal(),
+ tax: getCartTotal() * 0.1,
+ shipping: 0,
+ items_count: cart.length,
+ items: orderItems,
+ customer_email: formData.email,
+ shipping_city: formData.city,
+ });
+
clearCart();
setIsProcessing(false);
alert("Order placed successfully! Thank you for your purchase.");
diff --git a/apps/react-router/shopper/app/routes/home.tsx b/apps/react-router/shopper/app/routes/home.tsx
index 82de5ac..a048f04 100644
--- a/apps/react-router/shopper/app/routes/home.tsx
+++ b/apps/react-router/shopper/app/routes/home.tsx
@@ -1,5 +1,6 @@
import { Link } from "react-router";
import type { Route } from "./+types/home";
+import { usePostHog } from "@posthog/react";
export function meta({}: Route.MetaArgs) {
return [
@@ -9,6 +10,14 @@ export function meta({}: Route.MetaArgs) {
}
export default function Home() {
+ const posthog = usePostHog();
+
+ const handleStartShoppingClick = () => {
+ posthog?.capture("start_shopping_clicked", {
+ source: "home_hero",
+ });
+ };
+
return (