diff --git a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/.posthog-wizard b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/.posthog-wizard new file mode 100644 index 00000000..e69de29b diff --git a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/SKILL.md b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/SKILL.md new file mode 100644 index 00000000..3217a8af --- /dev/null +++ b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/SKILL.md @@ -0,0 +1,62 @@ +--- +name: integration-react-tanstack-router-code-based +description: >- + PostHog integration for React applications using TanStack Router with + code-based routing +metadata: + author: PostHog + version: dev +--- + +# PostHog integration for React with TanStack Router (code-based) + +This skill helps you add PostHog analytics to React with TanStack Router (code-based) applications. + +## Workflow + +Follow these steps in order to complete the integration: + +1. `references/1-begin.md` - PostHog Setup - Begin ← **Start here** +2. `references/2-edit.md` - PostHog Setup - Edit +3. `references/3-revise.md` - PostHog Setup - Revise +4. `references/4-conclude.md` - PostHog Setup - Conclusion + +## Reference files + +- `references/EXAMPLE.md` - React with TanStack Router (code-based) example project code +- `references/1-begin.md` - Start the event tracking setup process by analyzing the project and creating an event tracking plan +- `references/2-edit.md` - Implement PostHog event tracking in the identified files, following best practices and the example project +- `references/3-revise.md` - Review and fix any errors in the PostHog integration implementation +- `references/4-conclude.md` - Review and fix any errors in the PostHog integration implementation +- `references/tanstack-start.md` - Tanstack start - docs +- `references/identify-users.md` - Identify users - docs + +The example project shows the target implementation pattern. Consult the documentation for API details. + +## Key principles + +- **Environment variables**: Always use environment variables for PostHog keys. Never hardcode them. +- **Minimal changes**: Add PostHog code alongside existing integrations. Don't replace or restructure existing code. +- **Match the example**: Your implementation should follow the example project's patterns as closely as possible. + +## Framework guidelines + +- For feature flags, use useFeatureFlagEnabled() or useFeatureFlagPayload() hooks - they handle loading states and external sync automatically +- Add analytics capture in event handlers where user actions occur, NOT in useEffect reacting to state changes +- Do NOT use useEffect for data transformation - calculate derived values during render instead +- Do NOT use useEffect to respond to user events - put that logic in the event handler itself +- Do NOT use useEffect to chain state updates - calculate all related updates together in the event handler +- Do NOT use useEffect to notify parent components - call the parent callback alongside setState in the event handler +- To reset component state when a prop changes, pass the prop as the component's key instead of using useEffect +- useEffect is ONLY for synchronizing with external systems (non-React widgets, browser APIs, network subscriptions) +- Use TanStack Router's built-in navigation events for pageview tracking instead of useEffect +- Use PostHogProvider in the root component defined in either the file-based convention (__root.tsx) or code-based convention (wherever createRootRoute() is called) so all child routes have access to the PostHog client +- When a reverse proxy is configured, both /static/* AND /array/* must route to the assets origin (us-assets.i.posthog.com or eu-assets.i.posthog.com). + +## Identifying users + +Identify users during login and signup events. Refer to the example code and documentation for the correct identify pattern for this framework. If both frontend and backend code exist, pass the client-side session and distinct ID using `X-POSTHOG-DISTINCT-ID` and `X-POSTHOG-SESSION-ID` headers to maintain correlation. + +## Error tracking + +Add PostHog error tracking to relevant files, particularly around critical user flows and API boundaries. diff --git a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/1-begin.md b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/1-begin.md new file mode 100644 index 00000000..55f0a832 --- /dev/null +++ b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/1-begin.md @@ -0,0 +1,56 @@ +--- +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. + +This is the first of several phases — plan the events, implement them, revise and validate changes, then conclude by creating a dashboard and writing a setup report. + +## Task list + +As soon as you've read this description and have a rough sense of the work, make a single **call `TaskCreate` immediately** before reading any reference file or beginning analysis. The user is watching the task pane and shouldn't see it sit empty. + +It's fine if your first list is incomplete or imprecise. Seed it with whatever high-level items you can infer from the overview above, then call `TaskCreate` again (or `TaskUpdate` to refine existing items) every time your understanding sharpens: after a phase reveals work you didn't anticipate, after planning surfaces concrete sub-items, after you hit something new. Use `TaskUpdate` to mark items `in_progress` when you start them and `completed` when you finish. Keeping the list current matters more than getting it right on the first call. + +Keep task titles broad and job-oriented. Describe the purpose or area of work with wording like "Planning event tracking", "Identifying users", "Installing PostHog", "Capturing events", or "Creating dashboards", not the specific files, paths, or symbols involved. Adjust the task names according to the user's project and context. + +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. Do not spawn subagents. + +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 with these exact field names: `event_name` (the event name), `event_description` (one sentence), and `file` (the file path the event goes in). The wizard reads this file to surface the plan in the UI. 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 + +## Abort statuses + +If and only if the instructions have `[ABORT]` states specified, and you clearly match the conditions for an abort, emit the abort message. Do NOT attempt to exit or halt yourself — the wizard's middleware catches `[ABORT]` and terminates the run for you. + +--- + +**Upon completion, continue with:** [2-edit.md](2-edit.md) \ No newline at end of file diff --git a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/2-edit.md b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/2-edit.md new file mode 100644 index 00000000..e5f7ffd1 --- /dev/null +++ b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/2-edit.md @@ -0,0 +1,36 @@ +--- +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. Do not spawn subagents. + +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:** [3-revise.md](3-revise.md) \ No newline at end of file diff --git a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/3-revise.md b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/3-revise.md new file mode 100644 index 00000000..3b07f506 --- /dev/null +++ b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/3-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. Do not spawn subagents. + +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, but ONLY on the files you have edited or created during this session. Do not run formatting or linting across the entire project's codebase. + +## 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:** [4-conclude.md](4-conclude.md) \ No newline at end of file diff --git a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/4-conclude.md b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/4-conclude.md new file mode 100644 index 00000000..d876d435 --- /dev/null +++ b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/4-conclude.md @@ -0,0 +1,57 @@ +--- +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 (wizard)" based on the events created here. Keep the `(wizard)` tag with that exact casing so anyone browsing PostHog can see the wizard created this dashboard, and so a quick search for `(wizard)` surfaces every wizard-created artifact in one go. 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. + +Once the dashboard exists, emit its URL on its own line in your assistant message using this exact marker: `[DASHBOARD_URL] `. The wizard parses this marker from your visible message and surfaces the link in the success summary. Mentioning the URL only in thinking or in prose without the marker means the link is dropped. + +Search for a file called `.posthog-events.json` and read it for available events. + +Do not spawn subagents. + +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, a list of links for the dashboard and insights created, and a "Verify before merging" checklist (see below). 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] + +## Verify before merging + +[checklist] + +### 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. + + + +For the "Verify before merging" checklist, write GitHub-style checkboxes (`- [ ] ...`) covering what the developer (or their coding agent) still needs to do to take this from "wizard finished" to "merged". Include ONLY the items that actually apply to the integration you just performed — judge each against the code you changed in this run, and drop any that don't fit. Phrase each item as a concrete, checkable action. Candidate items, with the condition for including each: + +- Always: "Run a full production build (the wizard only verified the files it touched) and fix any lint or type errors introduced by the generated code." +- Always: "Run the test suite — call sites that were rewritten or instrumented may need updated mocks or fixtures." +- If you added environment variables: "Add the exact PostHog env var names you added to `.env.example` and any monorepo/bootstrap scripts so collaborators know what to set." +- If this integration ships a minified production browser bundle (most SPA/SSR web frameworks — e.g. Next.js, Nuxt, SvelteKit, Astro, Vite-based apps): "Wire source-map upload (`posthog-cli sourcemap` or your bundler's upload step) into CI so production stack traces de-minify." +- If LLM analytics was set up in this run: "Trigger the LLM call path(s) you instrumented and confirm `$ai_generation` events appear in PostHog AI Observability." +- If the app has user auth and an `identify` call was added: "Confirm the returning-visitor path also calls `identify` — a handler that only identifies on fresh login can leave returning sessions on anonymous distinct IDs." + +Do not invent items beyond what applies. If only the two "Always" items apply, the checklist is just those two. + +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/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/EXAMPLE.md b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/EXAMPLE.md new file mode 100644 index 00000000..1999cc15 --- /dev/null +++ b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/EXAMPLE.md @@ -0,0 +1,793 @@ +# PostHog React with TanStack Router (code-based) Example Project + +Repository: https://github.com/PostHog/context-mill +Path: example-apps/react-tanstack-router-code-based + +--- + +## README.md + +# PostHog TanStack Router Example (Code-Based Routing) + +This is a React and [TanStack Router](https://tanstack.com/router) example demonstrating PostHog integration with product analytics, session replay, and error tracking. This example uses **code-based routing** where routes are defined programmatically. + +## Features + +- **Product analytics**: Track user events and behaviors +- **Session replay**: Record and replay user sessions +- **Error tracking**: Capture and track errors +- **User authentication**: Demo login system with PostHog user identification +- **Client-side tracking**: Pure client-side React implementation +- **Reverse proxy**: PostHog ingestion through Vite proxy + +## Getting started + +### 1. Install dependencies + +```bash +npm install +``` + +### 2. Configure environment variables + +Create a `.env` file in the root directory: + +```bash +VITE_PUBLIC_POSTHOG_PROJECT_TOKEN=your_posthog_project_token +VITE_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com +``` + +Get your PostHog project token from your [PostHog project settings](https://app.posthog.com/project/settings). + +### 3. Run the development server + +```bash +npm run dev +``` + +Open [http://localhost:3000](http://localhost:3000) with your browser to see the app. + +## Project structure + +``` +src/ +├── contexts/ +│ └── AuthContext.tsx # Authentication context with PostHog integration +├── main.tsx # App entry point with all routes defined in code +├── reportWebVitals.ts # Performance monitoring +└── styles.css # Global styles +``` + +## Key integration points + +### PostHog provider setup (main.tsx) + +PostHog is initialized using `PostHogProvider` from `@posthog/react`. The provider wraps the entire app in the root route component: + +```typescript +import { PostHogProvider } from '@posthog/react' +import { createRootRoute } from '@tanstack/react-router' + +const rootRoute = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + {/* your app */} + + ) +} +``` + +### User identification (contexts/AuthContext.tsx) + +```typescript +import { usePostHog } from '@posthog/react' + +const posthog = usePostHog() + +posthog.identify(username, { + username: username, +}) +``` + +### Event tracking (main.tsx - BurritoPage) + +```typescript +import { usePostHog } from '@posthog/react' + +const posthog = usePostHog() + +posthog.capture('burrito_considered', { + total_considerations: count, + username: username, +}) +``` + +### Error tracking (main.tsx - ProfilePage) + +```typescript +posthog.captureException(error) +``` + +## TanStack Router details + +This example uses TanStack Router with **code-based routing**. Key details: + +1. **Client-side only**: No server-side logic, no API routes, no posthog-node +2. **Code-based routing**: All routes defined in `main.tsx` using `createRoute()` and `createRootRoute()` +3. **Manual route tree**: Routes connected with `addChildren()` method +4. **Standard hooks**: Uses `useNavigate()` from @tanstack/react-router +5. **Vite proxy**: Uses Vite's proxy config for PostHog calls +6. **Environment variables**: Uses `import.meta.env.VITE_*` +7. **PostHog provider**: Uses `PostHogProvider` from `@posthog/react` in root route + +### Code-based vs File-based routing + +This example demonstrates **code-based routing**, where routes are defined programmatically: + +```typescript +import { createRoute, createRootRoute, createRouter } from '@tanstack/react-router' + +const rootRoute = createRootRoute({ component: RootComponent }) + +const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: Home, +}) + +const burritoRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/burrito', + component: BurritoPage, +}) + +const routeTree = rootRoute.addChildren([indexRoute, burritoRoute]) + +const router = createRouter({ routeTree }) +``` + +For file-based routing (auto-generated from file structure), see the `react-tanstack-router-file-based` example. + +## Learn more + +- [PostHog Documentation](https://posthog.com/docs) +- [TanStack Router Documentation](https://tanstack.com/router) +- [TanStack Router Code-Based Routing](https://tanstack.com/router/latest/docs/framework/react/guide/code-based-routing) +- [PostHog React Integration Guide](https://posthog.com/docs/libraries/react) + +--- + +## .env.example + +```example +VITE_PUBLIC_POSTHOG_PROJECT_TOKEN= +VITE_PUBLIC_POSTHOG_HOST= + +``` + +--- + +## .prettierignore + +``` +package-lock.json +pnpm-lock.yaml +yarn.lock + +``` + +--- + +## index.html + +```html + + + + + + + + + + + React TanStack Router - Code-Based + + +
+ + + + +``` + +--- + +## prettier.config.js + +```js +// @ts-check + +/** @type {import('prettier').Config} */ +const config = { + semi: false, + singleQuote: true, + trailingComma: "all", +}; + +export default config; + +``` + +--- + +## public/robots.txt + +```txt +# https://www.robotstxt.org/robotstxt.html +User-agent: * +Disallow: + +``` + +--- + +## src/contexts/AuthContext.tsx + +```tsx +import { createContext, useContext, useState, type ReactNode } from 'react'; +import { usePostHog } from '@posthog/react'; + +interface User { + username: string; + burritoConsiderations: number; +} + +interface AuthContextType { + user: User | null; + login: (username: string, password: string) => Promise; + logout: () => void; + incrementBurritoConsiderations: () => void; +} + +const AuthContext = createContext(undefined); + +const users: Map = new Map(); + +export function AuthProvider({ children }: { children: ReactNode }) { + // Use lazy initializer to read from localStorage only once on mount + const [user, setUser] = useState(() => { + if (typeof window === 'undefined') return null; + + const storedUsername = localStorage.getItem('currentUser'); + if (storedUsername) { + const existingUser = users.get(storedUsername); + if (existingUser) { + return existingUser; + } + } + return null; + }); + const posthog = usePostHog(); + + const login = async (username: string, password: string): Promise => { + if (!username || !password) { + return false; + } + + // Get or create user in local map + let user = users.get(username); + const isNewUser = !user; + + if (!user) { + user = { username, burritoConsiderations: 0 }; + users.set(username, user); + } + + setUser(user); + localStorage.setItem('currentUser', username); + + // Identify user in PostHog using username as distinct ID + posthog.identify(username, { + username: username, + isNewUser: isNewUser, + }); + + // Capture login event + posthog.capture('user_logged_in', { + username: username, + isNewUser: isNewUser, + }); + + return true; + }; + + const logout = () => { + // Capture logout event before resetting + posthog.capture('user_logged_out'); + posthog.reset(); + + setUser(null); + localStorage.removeItem('currentUser'); + }; + + const incrementBurritoConsiderations = () => { + if (user) { + user.burritoConsiderations++; + users.set(user.username, user); + setUser({ ...user }); + } + }; + + return ( + + {children} + + ); +} + +export function useAuth() { + const context = useContext(AuthContext); + if (context === undefined) { + throw new Error('useAuth must be used within an AuthProvider'); + } + return context; +} + +``` + +--- + +## src/main.tsx + +```tsx +import { StrictMode, useState } from 'react' +import ReactDOM from 'react-dom/client' +import { + Link, + Outlet, + RouterProvider, + createRootRoute, + createRoute, + createRouter, + useNavigate, +} from '@tanstack/react-router' +import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools' +import { TanStackDevtools } from '@tanstack/react-devtools' +import { PostHogProvider, usePostHog } from '@posthog/react' + +import { AuthProvider, useAuth } from './contexts/AuthContext' +import './styles.css' +import reportWebVitals from './reportWebVitals' + +// ============================================================================ +// Root Route +// ============================================================================ + +const rootRoute = createRootRoute({ + component: RootComponent, +}) + +function RootComponent() { + return ( + + +
+
+ +
+ , + }, + ]} + /> + + + ) +} + +// ============================================================================ +// Header Component +// ============================================================================ + +function Header() { + const { user, logout } = useAuth() + + return ( +
+
+ +
+ {user ? ( + <> + Welcome, {user.username}! + + + ) : ( + Not logged in + )} +
+
+
+ ) +} + +// ============================================================================ +// Index Route (Home Page) +// ============================================================================ + +const indexRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/', + component: Home, +}) + +function Home() { + const { user, login } = useAuth() + const [username, setUsername] = useState('') + const [password, setPassword] = useState('') + const [error, setError] = useState('') + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault() + setError('') + + try { + const success = await login(username, password) + if (success) { + setUsername('') + setPassword('') + } else { + setError('Please provide both username and password') + } + } catch (err) { + console.error('Login failed:', err) + setError('An error occurred during login') + } + } + + if (user) { + return ( +
+

Welcome back, {user.username}!

+

You are now logged in. Feel free to explore:

+
    +
  • Consider the potential of burritos
  • +
  • View your profile and statistics
  • +
+
+ ) + } + + return ( +
+

Welcome to Burrito Consideration App

+

Please sign in to begin your burrito journey

+ +
+
+ + setUsername(e.target.value)} + placeholder="Enter any username" + /> +
+ +
+ + setPassword(e.target.value)} + placeholder="Enter any password" + /> +
+ + {error &&

{error}

} + + +
+ +

+ Note: This is a demo app. Use any username and password to sign in. +

+
+ ) +} + +// ============================================================================ +// Burrito Route +// ============================================================================ + +const burritoRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/burrito', + component: BurritoPage, +}) + +function BurritoPage() { + const { user, incrementBurritoConsiderations } = useAuth() + const navigate = useNavigate() + const posthog = usePostHog() + const [hasConsidered, setHasConsidered] = useState(false) + + // Redirect to home if not logged in + if (!user) { + navigate({ to: '/' }) + return null + } + + const handleConsideration = () => { + incrementBurritoConsiderations() + setHasConsidered(true) + setTimeout(() => setHasConsidered(false), 2000) + + // Capture burrito consideration event + console.log('posthog', posthog) + posthog.capture('burrito_considered', { + total_considerations: user.burritoConsiderations + 1, + username: user.username, + }) + } + + return ( +
+

Burrito consideration zone

+

Take a moment to truly consider the potential of burritos.

+ +
+ + + {hasConsidered && ( +

+ Thank you for your consideration! Count: {user.burritoConsiderations} +

+ )} +
+ +
+

Consideration stats

+

Total considerations: {user.burritoConsiderations}

+
+
+ ) +} + +// ============================================================================ +// Profile Route +// ============================================================================ + +const profileRoute = createRoute({ + getParentRoute: () => rootRoute, + path: '/profile', + component: ProfilePage, +}) + +function ProfilePage() { + const { user } = useAuth() + const navigate = useNavigate() + const posthog = usePostHog() + + // Redirect to home if not logged in + if (!user) { + navigate({ to: '/' }) + return null + } + + const triggerTestError = () => { + try { + throw new Error('Test error for PostHog error tracking') + } catch (err) { + posthog.captureException(err) + console.error('Captured error:', err) + alert('Error captured and sent to PostHog!') + } + } + + return ( +
+

User Profile

+ +
+

Your Information

+

+ Username: {user.username} +

+

+ Burrito Considerations: {user.burritoConsiderations} +

+
+ +
+ +
+ +
+

Your Burrito Journey

+ {user.burritoConsiderations === 0 ? ( +

+ You haven't considered any burritos yet. Visit the Burrito + Consideration page to start! +

+ ) : user.burritoConsiderations === 1 ? ( +

You've considered the burrito potential once. Keep going!

+ ) : user.burritoConsiderations < 5 ? ( +

You're getting the hang of burrito consideration!

+ ) : user.burritoConsiderations < 10 ? ( +

You're becoming a burrito consideration expert!

+ ) : ( +

You are a true burrito consideration master!

+ )} +
+
+ ) +} + +// ============================================================================ +// Route Tree & Router Setup +// ============================================================================ + +const routeTree = rootRoute.addChildren([indexRoute, burritoRoute, profileRoute]) + +const router = createRouter({ + routeTree, + context: {}, + defaultPreload: 'intent', + scrollRestoration: true, + defaultStructuralSharing: true, + defaultPreloadStaleTime: 0, +}) + +// Register the router instance for type safety +declare module '@tanstack/react-router' { + interface Register { + router: typeof router + } +} + +// ============================================================================ +// Render the App +// ============================================================================ + +const rootElement = document.getElementById('app') +if (rootElement && !rootElement.innerHTML) { + const root = ReactDOM.createRoot(rootElement) + root.render( + + + , + ) +} + +// If you want to start measuring performance in your app, pass a function +// to log results (for example: reportWebVitals(console.log)) +// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals +reportWebVitals() + +``` + +--- + +## src/reportWebVitals.ts + +```ts +const reportWebVitals = (onPerfEntry?: () => void) => { + if (onPerfEntry && onPerfEntry instanceof Function) { + import('web-vitals').then(({ onCLS, onINP, onFCP, onLCP, onTTFB }) => { + onCLS(onPerfEntry) + onINP(onPerfEntry) + onFCP(onPerfEntry) + onLCP(onPerfEntry) + onTTFB(onPerfEntry) + }) + } +} + +export default reportWebVitals + +``` + +--- + +## vite.config.ts + +```ts +import { defineConfig, loadEnv } from 'vite' +import viteReact from '@vitejs/plugin-react' +import tailwindcss from '@tailwindcss/vite' + +import { fileURLToPath, URL } from 'node:url' + +// https://vitejs.dev/config/ +export default defineConfig(({ mode }) => { + const env = loadEnv(mode, process.cwd(), '') + + return { + plugins: [viteReact(), tailwindcss()], + resolve: { + alias: { + '@': fileURLToPath(new URL('./src', import.meta.url)), + }, + }, + server: { + proxy: { + '/ingest/static': { + target: 'https://us-assets.i.posthog.com', + changeOrigin: true, + rewrite: (path) => path.replace(/^\/ingest/, ''), + }, + '/ingest/array': { + target: 'https://us-assets.i.posthog.com', + changeOrigin: true, + rewrite: (path) => path.replace(/^\/ingest/, ''), + }, + '/ingest': { + target: env.VITE_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com', + changeOrigin: true, + rewrite: (path) => path.replace(/^\/ingest/, ''), + }, + }, + }, + } +}) + +``` + +--- + diff --git a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/identify-users.md b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/identify-users.md new file mode 100644 index 00000000..1417e03a --- /dev/null +++ b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/identify-users.md @@ -0,0 +1,272 @@ +# 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.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/features.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. + +### 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. + +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/features.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/features.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) + +### Community questions + +Ask a question + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/tanstack-start.md b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/tanstack-start.md new file mode 100644 index 00000000..0504850f --- /dev/null +++ b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.claude/skills/integration-react-tanstack-router-code-based/references/tanstack-start.md @@ -0,0 +1,193 @@ +# 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. +> +> See our guide on [identifying users](/docs/getting-started/identify-users.md) for how to set this up. + +## Initialize PostHog on the client + +Wrap your app with `PostHogProvider` in your root route with your project token, host, and other options. + +src/routes/\_\_root.tsx + +PostHog AI + +```jsx +// 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). + +### Community questions + +Ask a question + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.gitignore b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.gitignore index d451ff16..30df6062 100644 --- a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.gitignore +++ b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.gitignore @@ -3,3 +3,4 @@ node_modules dist dist-ssr *.local +.env diff --git a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/package.json b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/package.json index 00908a18..206e8649 100644 --- a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/package.json +++ b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/package.json @@ -9,10 +9,12 @@ "start": "vite" }, "dependencies": { + "@posthog/react": "^1.10.3", "@tailwindcss/vite": "^4.1.18", "@tanstack/react-router": "^1.158.1", "@tanstack/react-router-devtools": "^1.158.1", "immer": "^10.1.1", + "posthog-js": "^1.392.0", "react": "^19.0.0", "react-dom": "^19.0.0", "redaxios": "^0.5.1", diff --git a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/pnpm-lock.yaml b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/pnpm-lock.yaml index 74ce37d8..392f09a6 100644 --- a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/pnpm-lock.yaml +++ b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/pnpm-lock.yaml @@ -8,6 +8,9 @@ importers: .: dependencies: + '@posthog/react': + specifier: ^1.10.3 + version: 1.10.3(@types/react@19.2.13)(posthog-js@1.392.0)(react@19.2.4) '@tailwindcss/vite': specifier: ^4.1.18 version: 4.1.18(vite@7.3.1(jiti@2.6.1)(lightningcss@1.30.2)) @@ -20,6 +23,9 @@ importers: immer: specifier: ^10.1.1 version: 10.2.0 + posthog-js: + specifier: ^1.392.0 + version: 1.392.0 react: specifier: ^19.0.0 version: 19.2.4 @@ -309,6 +315,22 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@posthog/core@1.35.4': + resolution: {integrity: sha512-DowOjN83tGtg4NPv0tmExjXiIWapHDDTv0ZZHg70XBjH5o/AB3DkMVMvj5ODIi1Y5bw7eMETidGvRwWH0/g3wA==} + + '@posthog/react@1.10.3': + resolution: {integrity: sha512-Qu//fGQmVlX0B9kTA3LLg67e7AYLEmeuA0Bf1qSyUM0uUILcRQGjQezhNQPLYSTakOqvXEnl6fM2iQBF6Toxrw==} + peerDependencies: + '@types/react': '>=16.8.0' + posthog-js: '>=1.257.2' + react: '>=16.8.0' + peerDependenciesMeta: + '@types/react': + optional: true + + '@posthog/types@1.390.2': + resolution: {integrity: sha512-WcfKz2GNn2vfDX8vXmJYbKxegPxVWHuDQ/pHdAn0HoZDXDFnEp/+x3qBQA+fEvtbPjjtjgAt2wIgJMlM7asx7g==} + '@rolldown/pluginutils@1.0.0-beta.27': resolution: {integrity: sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==} @@ -596,6 +618,9 @@ packages: '@types/react@19.2.13': resolution: {integrity: sha512-KkiJeU6VbYbUOp5ITMIc7kBfqlYkKA5KhEHVrGMmUUMt7NeaZg65ojdPk+FtNrBAOXNVM5QM72jnADjM+XVRAQ==} + '@types/trusted-types@2.0.7': + resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==} + '@vitejs/plugin-react@4.7.0': resolution: {integrity: sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==} engines: {node: ^14.18.0 || >=16.0.0} @@ -624,6 +649,9 @@ packages: cookie-es@2.0.0: resolution: {integrity: sha512-RAj4E421UYRgqokKUmotqAwuplYw15qtdXfY+hGzgCJ/MBjCVZcSoHK/kH9kocfjRjcDME7IiDWR/1WX1TM2Pg==} + core-js@3.49.0: + resolution: {integrity: sha512-es1U2+YTtzpwkxVLwAFdSpaIMyQaq0PBgm3YD1W3Qpsn1NAmO3KSgZfu+oGSWVu6NvLHoHCV/aYcsE5wiB7ALg==} + csstype@3.2.3: resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} @@ -640,6 +668,9 @@ packages: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} + dompurify@3.4.11: + resolution: {integrity: sha512-zhlUV12GsaRzMsf9q5M254YhA4+VuF0fG+QFqu6aYpoGlKtz+w8//jBcGVYBgQkR5GHjUomejY84AV+/uPbWdw==} + electron-to-chromium@1.5.286: resolution: {integrity: sha512-9tfDXhJ4RKFNerfjdCcZfufu49vg620741MNs26a9+bhLThdB+plgMeou98CAaHu/WATj2iHOOHTp1hWtABj2A==} @@ -665,6 +696,9 @@ packages: picomatch: optional: true + fflate@0.4.8: + resolution: {integrity: sha512-FJqqoDBR00Mdj9ppamLa/Y7vxm+PRmNWA67N846RvsoYVMKB4q3y/de5PA7gUmRMYK/8CMz2GDZQmCRN1wBcWA==} + fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -804,6 +838,15 @@ packages: resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==} engines: {node: ^10 || ^12 || >=14} + posthog-js@1.392.0: + resolution: {integrity: sha512-dOZMzav59dRzI4SNmF+ZoRWj6evUVNxTMuHgbQWt+vTJzVl9UvdsUPFBBa13Skcw8eTwXpB54089yaCrEv11Ew==} + + preact@10.29.2: + resolution: {integrity: sha512-7tNmwg/7mzzAoB/8kSg6Hl37JraAZw3Z3A0JSY7VXlZwo82Xn0G7wKbNNs2qoF4ZEEsQGTwDAroNdqKs1ofJxQ==} + + query-selector-shadow-dom@1.0.1: + resolution: {integrity: sha512-lT5yCqEBgfoMYpf3F2xQRK7zEr1rhIIZuceDK6+xRkJQ4NMbHTwXqk4NkwDwQMNqXgG9r9fyHnzwNVs6zV5KRw==} + react-dom@19.2.4: resolution: {integrity: sha512-AXJdLo8kgMbimY95O2aKQqsz2iWi9jMgKJhRBAxECE4IFxfcazB2LmzloIoibJI3C12IlY20+KFaLv+71bUJeQ==} peerDependencies: @@ -919,6 +962,9 @@ packages: yaml: optional: true + web-vitals@5.3.0: + resolution: {integrity: sha512-q6LWsLatGYZp5VGBIOvbTj6JBV2nOmC8KvWztXBmwJcfFAzhwKwbOxhUH306XY3CcaZDUlSmSuNPBsCn0bFu+g==} + yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} @@ -1136,6 +1182,19 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 + '@posthog/core@1.35.4': + dependencies: + '@posthog/types': 1.390.2 + + '@posthog/react@1.10.3(@types/react@19.2.13)(posthog-js@1.392.0)(react@19.2.4)': + dependencies: + posthog-js: 1.392.0 + react: 19.2.4 + optionalDependencies: + '@types/react': 19.2.13 + + '@posthog/types@1.390.2': {} + '@rolldown/pluginutils@1.0.0-beta.27': {} '@rollup/rollup-android-arm-eabi@4.57.1': @@ -1364,6 +1423,9 @@ snapshots: dependencies: csstype: 3.2.3 + '@types/trusted-types@2.0.7': + optional: true + '@vitejs/plugin-react@4.7.0(vite@7.3.1(jiti@2.6.1)(lightningcss@1.30.2))': dependencies: '@babel/core': 7.29.0 @@ -1394,6 +1456,8 @@ snapshots: cookie-es@2.0.0: {} + core-js@3.49.0: {} + csstype@3.2.3: {} debug@4.4.3: @@ -1402,6 +1466,10 @@ snapshots: detect-libc@2.1.2: {} + dompurify@3.4.11: + optionalDependencies: + '@types/trusted-types': 2.0.7 + electron-to-chromium@1.5.286: {} enhanced-resolve@5.19.0: @@ -1444,6 +1512,8 @@ snapshots: optionalDependencies: picomatch: 4.0.3 + fflate@0.4.8: {} + fsevents@2.3.3: optional: true @@ -1540,6 +1610,21 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.1 + posthog-js@1.392.0: + dependencies: + '@posthog/core': 1.35.4 + '@posthog/types': 1.390.2 + core-js: 3.49.0 + dompurify: 3.4.11 + fflate: 0.4.8 + preact: 10.29.2 + query-selector-shadow-dom: 1.0.1 + web-vitals: 5.3.0 + + preact@10.29.2: {} + + query-selector-shadow-dom@1.0.1: {} + react-dom@19.2.4(react@19.2.4): dependencies: react: 19.2.4 @@ -1632,6 +1717,8 @@ snapshots: jiti: 2.6.1 lightningcss: 1.30.2 + web-vitals@5.3.0: {} + yallist@3.1.1: {} zod@3.25.76: {} diff --git a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/posthog-setup-report.md b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/posthog-setup-report.md new file mode 100644 index 00000000..1f1adc63 --- /dev/null +++ b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/posthog-setup-report.md @@ -0,0 +1,49 @@ + +# PostHog post-wizard report + +The wizard has completed a deep integration of PostHog analytics into CloudFlow, a React + TanStack Router (code-based) SaaS application. The following changes were made: + +- **`vite.config.js`** — Converted to a factory function and added a reverse-proxy configuration that routes `/ingest/*` to the PostHog ingest host and `/ingest/static`, `/ingest/array` to the PostHog asset CDN, both sourced from environment variables. +- **`tsconfig.json`** — Added `"types": ["vite/client"]` so `import.meta.env` references type-check correctly. +- **`.env`** — Created with `VITE_PUBLIC_POSTHOG_PROJECT_TOKEN`, `VITE_PUBLIC_POSTHOG_HOST`, and `VITE_PUBLIC_POSTHOG_ASSET_HOST`. +- **`src/main.tsx`** — Added `PostHogProvider` wrapping the root route component with session replay, exception capture, and debug mode wired to the dev environment. Added `posthog.identify()` on login and `posthog.reset()` on logout. Added 12 `posthog.capture()` call sites across all key user flows. + +| Event name | Description | File | +|---|---|---| +| `user_signed_in` | User submits the login form and authenticates. | `src/main.tsx` | +| `user_signed_out` | User logs out from the profile page or the login page. | `src/main.tsx` | +| `invoice_created` | User successfully creates a new invoice. | `src/main.tsx` | +| `invoice_creation_failed` | An error occurred while attempting to create a new invoice. | `src/main.tsx` | +| `invoice_updated` | User successfully saves changes to an existing invoice. | `src/main.tsx` | +| `invoice_update_failed` | An error occurred while attempting to save invoice changes. | `src/main.tsx` | +| `invoice_viewed` | User opens a specific invoice detail page (top of invoice conversion funnel). | `src/main.tsx` | +| `invoice_notes_toggled` | User opens or closes the internal notes section on an invoice. | `src/main.tsx` | +| `plan_upgrade_clicked` | User clicks the Upgrade button on the profile/account page. | `src/main.tsx` | +| `team_member_viewed` | User opens a team member's profile details. | `src/main.tsx` | +| `team_members_filtered` | User applies a text filter to search through team members. | `src/main.tsx` | +| `team_members_sorted` | User changes the sort order of the team members list. | `src/main.tsx` | + +## 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: + +- [Analytics basics (wizard) — Dashboard](https://us.i.posthog.com/project/2/dashboard/4284026) +- [Invoice creation funnel (wizard)](https://us.i.posthog.com/project/2/insights/lyzhnj) — `invoice_viewed → invoice_created` conversion funnel +- [Invoice creation vs failure trend (wizard)](https://us.i.posthog.com/project/2/insights/q41dj3) — `invoice_created` vs `invoice_creation_failed` over time +- [User authentication trend (wizard)](https://us.i.posthog.com/project/2/insights/6ondyx) — `user_signed_in` and `user_signed_out` over 30 days +- [Plan upgrade clicks (wizard)](https://us.i.posthog.com/project/2/insights/o307jh) — `plan_upgrade_clicked` trend (revenue signal) +- [Invoice update success vs failure (wizard)](https://us.i.posthog.com/project/2/insights/1p2qq1) — `invoice_updated` vs `invoice_update_failed` over time + +## Verify before merging + +- [ ] Run a full production build (the wizard only verified the files it touched) and fix any lint or type errors introduced by the generated code. +- [ ] Run the test suite — call sites that were rewritten or instrumented may need updated mocks or fixtures. +- [ ] Add `VITE_PUBLIC_POSTHOG_PROJECT_TOKEN`, `VITE_PUBLIC_POSTHOG_HOST`, and `VITE_PUBLIC_POSTHOG_ASSET_HOST` to `.env.example` and any monorepo/bootstrap scripts so collaborators know what to set. +- [ ] Wire source-map upload (`posthog-cli sourcemap` or your bundler's upload step) into CI so production stack traces de-minify. +- [ ] Confirm the returning-visitor path also calls `identify` — the current implementation only identifies on login form submit, so users who return with an active session (if persistence is added) may be on anonymous distinct IDs. + +### 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. + + diff --git a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/src/main.tsx b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/src/main.tsx index 05a68721..7d51e41b 100644 --- a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/src/main.tsx +++ b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/src/main.tsx @@ -20,6 +20,7 @@ import { useSearch, } from '@tanstack/react-router' import { TanStackRouterDevtools } from '@tanstack/react-router-devtools' +import { PostHogProvider, usePostHog } from '@posthog/react' import { z } from 'zod' import { fetchInvoiceById, @@ -86,7 +87,16 @@ function RouterSpinner() { function RootComponent() { return ( - <> +
@@ -132,7 +142,7 @@ function RootComponent() {
- + ) } @@ -433,9 +443,13 @@ const invoicesIndexRoute = createRoute({ }) function InvoicesIndexComponent() { + const posthog = usePostHog() const createInvoiceMutation = useMutation({ fn: postInvoice, - onSuccess: () => router.invalidate(), + onSuccess: ({ data }) => { + posthog.capture('invoice_created', { invoice_id: data.id, invoice_title: data.title }) + router.invalidate() + }, }) return ( @@ -449,14 +463,17 @@ function InvoicesIndexComponent() {
{ + onSubmit={async (event) => { event.preventDefault() event.stopPropagation() const formData = new FormData(event.target as HTMLFormElement) - createInvoiceMutation.mutate({ + const result = await createInvoiceMutation.mutate({ title: formData.get('title') as string, body: formData.get('body') as string, }) + if (!result) { + posthog.capture('invoice_creation_failed') + } }} className="bg-gray-50 dark:bg-gray-800 rounded-xl p-6 space-y-4" > @@ -517,11 +534,19 @@ function InvoiceComponent() { const search = invoiceRoute.useSearch() const navigate = useNavigate({ from: invoiceRoute.fullPath }) const invoice = invoiceRoute.useLoaderData() + const posthog = usePostHog() const updateInvoiceMutation = useMutation({ fn: patchInvoice, - onSuccess: () => router.invalidate(), + onSuccess: ({ data }) => { + posthog.capture('invoice_updated', { invoice_id: data?.id, invoice_title: data?.title }) + router.invalidate() + }, }) const [notes, setNotes] = React.useState(search.notes ?? '') + + React.useEffect(() => { + posthog.capture('invoice_viewed', { invoice_id: invoice.id, invoice_title: invoice.title }) + }, [invoice.id]) React.useEffect(() => { navigate({ search: (old) => ({ @@ -574,15 +599,18 @@ function InvoiceComponent() { { + onSubmit={async (event) => { event.preventDefault() event.stopPropagation() const formData = new FormData(event.target as HTMLFormElement) - updateInvoiceMutation.mutate({ + const result = await updateInvoiceMutation.mutate({ id: invoice.id, title: formData.get('title') as string, body: formData.get('body') as string, }) + if (!result) { + posthog.capture('invoice_update_failed', { invoice_id: invoice.id }) + } }} className="space-y-4" > @@ -602,6 +630,10 @@ function InvoiceComponent() { ...old, showNotes: old.showNotes ? undefined : true, })} + onClick={() => posthog.capture('invoice_notes_toggled', { + invoice_id: invoice.id, + action: search.showNotes ? 'hidden' : 'shown', + })} className="text-sm text-blue-600 hover:text-blue-700 dark:text-blue-400" from={invoiceRoute.fullPath} params={true} @@ -688,6 +720,7 @@ function UsersLayoutComponent() { const navigate = useNavigate({ from: usersLayoutRoute.fullPath }) const { usersView } = usersLayoutRoute.useSearch() const users = usersLayoutRoute.useLoaderData() + const posthog = usePostHog() const sortBy = usersView?.sortBy ?? 'name' const filterBy = usersView?.filterBy @@ -715,7 +748,8 @@ function UsersLayoutComponent() { ) }, [sortedUsers, filterBy]) - const setSortBy = (sortBy: UsersViewSortBy) => + const setSortBy = (sortBy: UsersViewSortBy) => { + posthog.capture('team_members_sorted', { sort_by: sortBy }) navigate({ search: (old) => { return { @@ -728,6 +762,7 @@ function UsersLayoutComponent() { }, replace: true, }) + } React.useEffect(() => { navigate({ @@ -759,6 +794,11 @@ function UsersLayoutComponent() { setFilterDraft(e.target.value)} + onBlur={(e) => { + if (e.target.value) { + posthog.capture('team_members_filtered', { filter_by: e.target.value }) + } + }} placeholder="Search team members..." className="w-full px-3 py-2 text-sm border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-900 focus:ring-2 focus:ring-blue-500 focus:border-transparent outline-none transition-all" /> @@ -861,6 +901,13 @@ const userRoute = createRoute({ function UserComponent() { const user = userRoute.useLoaderData() + const posthog = usePostHog() + + React.useEffect(() => { + if (user) { + posthog.capture('team_member_viewed', { user_id: user.id, user_name: user.name }) + } + }, [user?.id]) if (!user) { return
User not found
@@ -1003,6 +1050,7 @@ const profileRoute = createRoute({ function ProfileComponent() { const { username } = profileRoute.useRouteContext() + const posthog = usePostHog() const initials = username?.slice(0, 2).toUpperCase() ?? 'U' @@ -1049,7 +1097,10 @@ function ProfileComponent() {
Free Plan
Basic features included
- @@ -1067,6 +1118,8 @@ function ProfileComponent() {