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 000000000..e69de29bb 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 000000000..8647dcb37 --- /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,307 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Identify users - Docs + +Copy page + +# Identify users - Docs + +Linking events to specific users enables you to build a full picture of how they're using your product across different sessions, devices, and platforms. + +This is straightforward to do when [capturing backend events](/docs/product-analytics/capture-events?tab=Node.js.md), as you associate events to a specific user using a `distinct_id`, which is a required argument. + +However, in the frontend of a [web](/docs/libraries/js/usage.md#capturing-events) or [mobile app](/docs/libraries/ios.md#capturing-events), a `distinct_id` is not a required argument — PostHog's SDKs will generate an anonymous `distinct_id` for you automatically and you can capture events anonymously, provided you use the appropriate [configuration](/docs/libraries/js/usage.md#capturing-anonymous-events). + +To link events to specific users, call `identify`: + +PostHog AI + +### Web + +```javascript +posthog.identify( + 'distinct_id', // Replace 'distinct_id' with your user's unique identifier + { email: 'max@hedgehogmail.com', name: 'Max Hedgehog' } // optional: set additional person properties +); +``` + +### Android + +```kotlin +PostHog.identify( + distinctId = distinctID, // Replace 'distinctID' with your user's unique identifier + // optional: set additional person properties + userProperties = mapOf( + "name" to "Max Hedgehog", + "email" to "max@hedgehogmail.com" + ) +) +``` + +### iOS + +```swift +PostHogSDK.shared.identify("distinct_id", // Replace "distinct_id" with your user's unique identifier + userProperties: ["name": "Max Hedgehog", "email": "max@hedgehogmail.com"]) // optional: set additional person properties +``` + +### React Native + +```jsx +posthog.identify('distinct_id', { // Replace "distinct_id" with your user's unique identifier + email: 'max@hedgehogmail.com', // optional: set additional person properties + name: 'Max Hedgehog' +}) +``` + +### Dart + +```dart +await Posthog().identify( + userId: 'distinct_id', // Replace "distinct_id" with your user's unique identifier + userProperties: { + 'email': 'max@hedgehogmail.com', // optional: set additional person properties + 'name': 'Max Hedgehog', + }, +); +``` + +Events captured after calling `identify` are identified events and this creates a person profile if one doesn't exist already. + +Due to the cost of processing them, anonymous events can be up to 4x cheaper than identified events, so it's recommended you only capture identified events when needed. + +## How identify works + +When a user starts browsing your website or app, PostHog automatically assigns them an **anonymous ID**, which is stored locally. + +Provided you've [configured persistence](/docs/libraries/js/persistence.md) to use cookies or `localStorage`, this enables us to track anonymous users – even across different sessions. + +By calling `identify` with a `distinct_id` of your choice (usually the user's ID in your database, or their email), you link the anonymous ID and distinct ID together. + +Thus, all past and future events made with that anonymous ID are now associated with the distinct ID. + +This enables you to do things like associate events with a user from before they log in for the first time, or associate their events across different devices or platforms. + +Using identify in the backend + +Although you can call `identify` using our backend SDKs, it is used most in frontends. This is because there is no concept of anonymous sessions in the backend SDKs, so calling `identify` only updates person profiles. + +## Best practices when using `identify` + +### 1\. Call `identify` as soon as you're able to + +In your frontend, you should call `identify` as soon as you're able to. + +Typically, this is every time your **app loads** for the first time, and directly after your **users log in**. + +This ensures that events sent during your users' sessions are correctly associated with them. + +You only need to call `identify` once per session, and you should avoid calling it multiple times unnecessarily. + +If you call `identify` multiple times with the same data without reloading the page in between, PostHog will ignore the subsequent calls. + +#### Identify users when the web SDK loads + +If your app already knows the signed-in user when you initialize the JavaScript web SDK, the [`loaded` callback](/docs/libraries/js/config.md) is a convenient place to call `identify`. This identifies the user as soon as the SDK has loaded: + +Web + +PostHog AI + +```javascript +posthog.init('', { + api_host: 'https://us.i.posthog.com', + defaults: '2026-05-30', + loaded: (posthog) => { + if (currentUser?.id) { + posthog.identify(currentUser.id, { + email: currentUser.email, + name: currentUser.name, + }) + } + }, +}) +``` + +In this example, `currentUser` represents user data already available from your authentication system. If your app loads the user asynchronously, call `posthog.identify()` as soon as that data becomes available instead. + +### 2\. Use unique strings for distinct IDs + +If two users have the same distinct ID, their data is merged and they are considered one user in PostHog. Two common ways this can happen are: + +- Your logic for generating IDs does not generate sufficiently strong IDs and you can end up with a clash where 2 users have the same ID. +- There's a bug, typo, or mistake in your code leading to most or all users being identified with generic IDs like `null`, `true`, or `distinctId`. + +PostHog also has built-in protections to stop the most common distinct ID mistakes. + +### 3\. Reset after logout + +If a user logs out on your frontend, you should call `reset()` to unlink any future events made on that device with that user. + +This is important if your users are sharing a computer, as otherwise all of those users are grouped together into a single user due to shared cookies between sessions. + +**We strongly recommend you call `reset` on logout even if you don't expect users to share a computer.** + +You can do that like so: + +PostHog AI + +### Web + +```javascript +posthog.reset() +``` + +### iOS + +```swift +PostHogSDK.shared.reset() +``` + +### Android + +```kotlin +PostHog.reset() +``` + +### React Native + +```jsx +posthog.reset() +``` + +### Dart + +```dart +await Posthog().reset(); +``` + +If you *also* want to reset the `device_id` so that the device will be considered a new device in future events, you can pass `true` as an argument: + +Web + +PostHog AI + +```javascript +posthog.reset(true) +``` + +### 4\. Person profiles and properties + +You'll notice that one of the parameters in the `identify` method is a `properties` object. + +This enables you to set [person properties](/docs/product-analytics/person-properties.md). + +Whenever possible, we recommend passing in all person properties you have available each time you call identify, as this ensures their person profile on PostHog is up to date. + +Person properties can also be set being adding a `$set` property to a event `capture` call. + +**\`$set\` and \`$set\_once\` aren't stored on events** + +These properties only tell PostHog how to update person data during ingestion — they aren't kept on the stored event, so you can't filter, break down, or query events by them. To query the values you set, use [person properties](/docs/product-analytics/person-properties.md) instead. + +See our [person properties docs](/docs/product-analytics/person-properties.md) for more details on how to work with them and best practices. + +### 5\. Use deep links between platforms + +We recommend you call `identify` [as soon as you're able](#1-call-identify-as-soon-as-youre-able), typically when a user signs up or logs in. + +This doesn't work if one or both platforms are unauthenticated. Some examples of such cases are: + +- Onboarding and signup flows before authentication. +- Unauthenticated web pages redirecting to authenticated mobile apps. +- Authenticated web apps prompting an app download. + +In these cases, you can use a [deep link](https://developer.android.com/training/app-links/deep-linking) on Android and [universal links](https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app) on iOS to identify users. + +1. Use `posthog.get_distinct_id()` to get the current distinct ID. Even if you cannot call identify because the user is unauthenticated, this will return an anonymous distinct ID generated by PostHog. +2. Add the distinct ID to the deep link as query parameters, along with other properties like UTM parameters. +3. When the user is redirected to the app, parse the deep link and handle the following cases: + +- The mobile app is already authenticated. In this case, call [`posthog.alias()`](/docs/libraries/js/usage.md#alias) with the distinct ID from the web. This associates the two distinct IDs as a single person. +- The mobile app is unauthenticated. In this case, call [`posthog.identify()`](/docs/libraries/js/usage.md#identifying-users) with the distinct ID from the web so pre-login mobile events stay connected to the web session. When the user later logs in on mobile, call `identify()` again with your canonical user ID. + +As long as you associate the distinct IDs with `posthog.identify()` or `posthog.alias()`, you can track events generated across platforms. + +Here's an example implementation for handling deep links from web to mobile: + +PostHog AI + +### iOS + +```swift +import PostHog +class DeepLinkIdentityManager { + static let shared = DeepLinkIdentityManager() + // MARK: - Deep Link Received + func handleDeepLink(_ url: URL, isAuthenticatedOnMobile: Bool) { + guard let webDistinctId = URLComponents(url: url, resolvingAgainstBaseURL: true)? + .queryItems?.first(where: { $0.name == "ph_distinct_id" })?.value else { + return + } + if isAuthenticatedOnMobile { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHogSDK.shared.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHogSDK.shared.identify(webDistinctId) + } + } + // MARK: - Login/Signup + func handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHogSDK.shared.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + func handleLogout() { + PostHogSDK.shared.reset() + } +} +``` + +### Android + +```kotlin +import android.net.Uri +import com.posthog.PostHog +object DeepLinkIdentityManager { + // Deep Link Received + fun handleDeepLink(uri: Uri, isAuthenticatedOnMobile: Boolean) { + val webDistinctId = uri.getQueryParameter("ph_distinct_id") ?: return + if (isAuthenticatedOnMobile) { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHog.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHog.identify(webDistinctId) + } + } + // Login/Signup + fun handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHog.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + fun handleLogout() { + PostHog.reset() + } +} +``` + +## Further reading + +- [Identifying users docs](/docs/product-analytics/identify.md) +- [How person processing works](/docs/how-posthog-works/ingestion-pipeline.md#2-person-processing) +- [An introductory guide to identifying users in PostHog](/tutorials/identifying-users-guide.md) + +### Still have questions? + +Ask PostHog AI + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/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 000000000..42329b3bb --- /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,221 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# TanStack Start - Docs + +Copy page + +# TanStack Start - Docs + +This tutorial shows how to integrate PostHog with a [TanStack Start](https://tanstack.com/start) app for both client-side and server-side analytics. + +## Installation + +Install the required packages: + +Terminal + +PostHog AI + +```bash +npm install @posthog/react posthog-node +``` + +- `@posthog/react` - React package for our [JS Web SDK](/docs/libraries/js.md) for client-side usage +- `posthog-node` - PostHog [Node.js SDK](/docs/libraries/node.md) for server-side event capture + +## Identifying users + +> **Identifying users is required.** Call `posthog.identify('your-user-id')` after login to link events to a known user. This is what connects frontend event captures, [session replays](/docs/session-replay.md), [LLM traces](/docs/ai-engineering.md), and [error tracking](/docs/error-tracking.md) to the same person — and lets backend events link back too. +> +> Use a stable ID from your auth system when possible, not an email or display name. Send those as person properties instead. If your app has no other stable key, email works as a fallback if they are unique. Never a shared literal like `"anonymous"` or `"user"`, which pools many people onto one person and corrupts their data. When no ID is available at all, skip the identify and retain the anonymous distinct ID that's automatically assigned. +> +> Call `posthog.reset()` on logout, so the next person to use the browser doesn't inherit the last one's identity. +> +> See our guide on [identifying users](/docs/getting-started/identify-users.md) for how to set this up. + +If your app calls your own backend, `tracing_headers` adds `X-POSTHOG-DISTINCT-ID` and `X-POSTHOG-SESSION-ID` to matching `fetch` and `XMLHttpRequest` requests. This lets server-side SDKs link backend events, errors, and LLM traces back to frontend sessions and replays. Use hostnames only, without protocols or paths. + +JavaScript + +PostHog AI + +```javascript +posthog.init('', { + api_host: 'https://us.i.posthog.com', + // Optional: send PostHog session/user context to your backend + tracing_headers: ['api.example.com'], +}) +``` + +This works in local development too, but match on the hostname alone: use `'localhost'`, not `'localhost:3000'`. Ports are never part of a hostname, so a value with one in it never matches anything. `localhost` and `127.0.0.1` are also different hostnames — use whichever your app actually calls. + +Tracing headers help you attribute events across front and backend consistently. When this isn't available, use your server-side stable IDs to deduce the matching `distinctId`, and pass it in when capturing the event. + +## Initialize PostHog on the client + +Wrap your app with `PostHogProvider` in your root route with your project token, host, and other options. + +PostHog AI + +``` +import CspAllowancesCallout from "../_snippets/csp-allowances-callout.mdx" +tsx file=src/routes/__root.tsx +// src/routes/__root.tsx +import { HeadContent, Scripts, createRootRoute } from '@tanstack/react-router' +import { PostHogProvider } from '@posthog/react' +export const Route = createRootRoute({ + head: () => ({ + meta: [ + { charSet: 'utf-8' }, + { name: 'viewport', content: 'width=device-width, initial-scale=1' }, + ], + }), + shellComponent: RootDocument, +}) +function RootDocument({ children }: { children: React.ReactNode }) { + return ( + + + + + + + {children} + + + + + ) +} +``` + +Once the provider is in place, PostHog automatically captures pageviews, sessions, and web vitals. + +## Capture events on the client + +Use the `usePostHog` hook from `@posthog/react` in any component to capture custom events: + +src/routes/checkout.tsx + +PostHog AI + +```jsx +import { usePostHog } from '@posthog/react' +function CheckoutButton({ orderId, total }: { orderId: string; total: number }) { + const posthog = usePostHog() + const handleClick = () => { + posthog.capture('checkout_started', { + order_id: orderId, + total: total, + }) + } + return +} +``` + +### Identify users + +Call `posthog.identify()` when a user logs in to link their events to a user ID: + +TSX + +PostHog AI + +```jsx +import { usePostHog } from '@posthog/react' +function LoginForm() { + const posthog = usePostHog() + const handleLogin = async (userId: string, email: string) => { + // ... your login logic + posthog.identify(userId, { + email: email, + }) + posthog.capture('user_logged_in') + } +} +``` + +Call `posthog.reset()` on logout to clear the identified user. + +## Initialize PostHog on the server + +Create a server-side PostHog client using `posthog-node`. Use a singleton pattern so you reuse the same client across requests: + +src/utils/posthog-server.ts + +PostHog AI + +```typescript +// src/utils/posthog-server.ts +import { PostHog } from 'posthog-node' +let posthogClient: PostHog | null = null +export function getPostHogClient() { + if (!posthogClient) { + posthogClient = new PostHog( + '', + { + host: 'https://us.i.posthog.com', + flushAt: 1, + flushInterval: 0, + }, + ) + } + return posthogClient +} +``` + +## Capture events on the server + +Use the server client in TanStack Start API routes to capture events server-side. Server-side capture is useful for tracking events that shouldn't be spoofable from the client, like purchases or authentication: + +src/routes/api/checkout.ts + +PostHog AI + +```typescript +// src/routes/api/checkout.ts +import { createFileRoute } from '@tanstack/react-router' +import { json } from '@tanstack/react-start' +import { getPostHogClient } from '../../utils/posthog-server' +export const Route = createFileRoute('/api/checkout')({ + server: { + handlers: { + POST: async ({ request }) => { + const body = await request.json() + const posthog = getPostHogClient() + posthog.capture({ + distinctId: body.userId, + event: 'item_purchased', + properties: { + item_id: body.itemId, + price: body.price, + source: 'api', + }, + }) + return json({ success: true }) + }, + }, + }, +}) +``` + +The server-side `capture` call requires a `distinctId` (the user identifier), an `event` name, and optional `properties`. + +## Next steps + +Installing the JS Web SDK and Node SDK means all of their functionality is available in your TanStack Start project. To learn more about this, have a look at our [JS Web SDK docs](/docs/libraries/js/usage.md) and [Node SDK docs](/docs/libraries/node.md). + +### Still have questions? + +Ask PostHog AI + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.env.example b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.env.example new file mode 100644 index 000000000..b2c042ddf --- /dev/null +++ b/apps/basic-integration/tanstack-router/tanstack-router-code-based-saas/.env.example @@ -0,0 +1,2 @@ +VITE_PUBLIC_POSTHOG_PROJECT_TOKEN= +VITE_PUBLIC_POSTHOG_HOST= 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 00908a187..7ed61ed92 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.5", "@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.424.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 74ce37d87..954145d3a 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.5 + version: 1.10.5(@types/react@19.2.13)(posthog-js@1.424.0(@types/react@19.2.13)(react@19.2.4))(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.424.0 + version: 1.424.0(@types/react@19.2.13)(react@19.2.4) react: specifier: ^19.0.0 version: 19.2.4 @@ -309,6 +315,25 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@posthog/browser-common@0.7.1': + resolution: {integrity: sha512-JO/5dIVx3NTrbg0W2VciDDmmizsvwaYYHE5cnJE1Gra+UqBnEuVGH9DTE/kBFgVMp+08z5uj/aAprsYD2WG/QQ==} + + '@posthog/core@1.50.1': + resolution: {integrity: sha512-REG9hSmWdQhPvXJfZuH0cwvveq5lS3wAluNSav7mqiaZszALRL4+4qS5FFO2gpgvV5D7OIhkJFB4ZKFbzqbviA==} + + '@posthog/react@1.10.5': + resolution: {integrity: sha512-lehh9+mJwb6iEjRBkIvh8olnJ6RV+YgQgdgJ6fdTr+T7EMoml/G1k+q92Oil8vZPcA9Dzg+2n0xaLY5yZrY3YA==} + peerDependencies: + '@types/react': '>=16.8.0' + posthog-js: '>=1.257.2' + react: '>=16.8.0' + peerDependenciesMeta: + '@types/react': + optional: true + + '@posthog/types@1.407.1': + resolution: {integrity: sha512-WhbkXPC2rgylXqmxHqv70ffI3k+KxyR6s7DBIfr5NvIqHkxp6v0pk31D/jbz0DNVbzwkLjyll2pxr4FNbJiYzg==} + '@rolldown/pluginutils@1.0.0-beta.27': resolution: {integrity: sha512-+d0F4MKMCbeVUJwG96uQ4SgAznZNSq93I3V+9NHA4OpvqG8mRCpGdKmK8l/dl02h2CCDHwW2FqilnTyDcAnqjA==} @@ -346,66 +371,79 @@ packages: resolution: {integrity: sha512-F8sWbhZ7tyuEfsmOxwc2giKDQzN3+kuBLPwwZGyVkLlKGdV1nvnNwYD0fKQ8+XS6hp9nY7B+ZeK01EBUE7aHaw==} cpu: [arm] os: [linux] + libc: [glibc] '@rollup/rollup-linux-arm-musleabihf@4.57.1': resolution: {integrity: sha512-rGfNUfn0GIeXtBP1wL5MnzSj98+PZe/AXaGBCRmT0ts80lU5CATYGxXukeTX39XBKsxzFpEeK+Mrp9faXOlmrw==} cpu: [arm] os: [linux] + libc: [musl] '@rollup/rollup-linux-arm64-gnu@4.57.1': resolution: {integrity: sha512-MMtej3YHWeg/0klK2Qodf3yrNzz6CGjo2UntLvk2RSPlhzgLvYEB3frRvbEF2wRKh1Z2fDIg9KRPe1fawv7C+g==} cpu: [arm64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-arm64-musl@4.57.1': resolution: {integrity: sha512-1a/qhaaOXhqXGpMFMET9VqwZakkljWHLmZOX48R0I/YLbhdxr1m4gtG1Hq7++VhVUmf+L3sTAf9op4JlhQ5u1Q==} cpu: [arm64] os: [linux] + libc: [musl] '@rollup/rollup-linux-loong64-gnu@4.57.1': resolution: {integrity: sha512-QWO6RQTZ/cqYtJMtxhkRkidoNGXc7ERPbZN7dVW5SdURuLeVU7lwKMpo18XdcmpWYd0qsP1bwKPf7DNSUinhvA==} cpu: [loong64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-loong64-musl@4.57.1': resolution: {integrity: sha512-xpObYIf+8gprgWaPP32xiN5RVTi/s5FCR+XMXSKmhfoJjrpRAjCuuqQXyxUa/eJTdAE6eJ+KDKaoEqjZQxh3Gw==} cpu: [loong64] os: [linux] + libc: [musl] '@rollup/rollup-linux-ppc64-gnu@4.57.1': resolution: {integrity: sha512-4BrCgrpZo4hvzMDKRqEaW1zeecScDCR+2nZ86ATLhAoJ5FQ+lbHVD3ttKe74/c7tNT9c6F2viwB3ufwp01Oh2w==} cpu: [ppc64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-ppc64-musl@4.57.1': resolution: {integrity: sha512-NOlUuzesGauESAyEYFSe3QTUguL+lvrN1HtwEEsU2rOwdUDeTMJdO5dUYl/2hKf9jWydJrO9OL/XSSf65R5+Xw==} cpu: [ppc64] os: [linux] + libc: [musl] '@rollup/rollup-linux-riscv64-gnu@4.57.1': resolution: {integrity: sha512-ptA88htVp0AwUUqhVghwDIKlvJMD/fmL/wrQj99PRHFRAG6Z5nbWoWG4o81Nt9FT+IuqUQi+L31ZKAFeJ5Is+A==} cpu: [riscv64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-riscv64-musl@4.57.1': resolution: {integrity: sha512-S51t7aMMTNdmAMPpBg7OOsTdn4tySRQvklmL3RpDRyknk87+Sp3xaumlatU+ppQ+5raY7sSTcC2beGgvhENfuw==} cpu: [riscv64] os: [linux] + libc: [musl] '@rollup/rollup-linux-s390x-gnu@4.57.1': resolution: {integrity: sha512-Bl00OFnVFkL82FHbEqy3k5CUCKH6OEJL54KCyx2oqsmZnFTR8IoNqBF+mjQVcRCT5sB6yOvK8A37LNm/kPJiZg==} cpu: [s390x] os: [linux] + libc: [glibc] '@rollup/rollup-linux-x64-gnu@4.57.1': resolution: {integrity: sha512-ABca4ceT4N+Tv/GtotnWAeXZUZuM/9AQyCyKYyKnpk4yoA7QIAuBt6Hkgpw8kActYlew2mvckXkvx0FfoInnLg==} cpu: [x64] os: [linux] + libc: [glibc] '@rollup/rollup-linux-x64-musl@4.57.1': resolution: {integrity: sha512-HFps0JeGtuOR2convgRRkHCekD7j+gdAuXM+/i6kGzQtFhlCtQkpwtNzkNj6QhCDp7DRJ7+qC/1Vg2jt5iSOFw==} cpu: [x64] os: [linux] + libc: [musl] '@rollup/rollup-openbsd-x64@4.57.1': resolution: {integrity: sha512-H+hXEv9gdVQuDTgnqD+SQffoWoc0Of59AStSzTEj/feWTBAnSfSD3+Dql1ZruJQxmykT/JVY0dE8Ka7z0DH1hw==} @@ -475,24 +513,28 @@ packages: engines: {node: '>= 10'} cpu: [arm64] os: [linux] + libc: [glibc] '@tailwindcss/oxide-linux-arm64-musl@4.1.18': resolution: {integrity: sha512-1px92582HkPQlaaCkdRcio71p8bc8i/ap5807tPRDK/uw953cauQBT8c5tVGkOwrHMfc2Yh6UuxaH4vtTjGvHg==} engines: {node: '>= 10'} cpu: [arm64] os: [linux] + libc: [musl] '@tailwindcss/oxide-linux-x64-gnu@4.1.18': resolution: {integrity: sha512-v3gyT0ivkfBLoZGF9LyHmts0Isc8jHZyVcbzio6Wpzifg/+5ZJpDiRiUhDLkcr7f/r38SWNe7ucxmGW3j3Kb/g==} engines: {node: '>= 10'} cpu: [x64] os: [linux] + libc: [glibc] '@tailwindcss/oxide-linux-x64-musl@4.1.18': resolution: {integrity: sha512-bhJ2y2OQNlcRwwgOAGMY0xTFStt4/wyU6pvI6LSuZpRgKQwxTec0/3Scu91O8ir7qCR3AuepQKLU/kX99FouqQ==} engines: {node: '>= 10'} cpu: [x64] os: [linux] + libc: [musl] '@tailwindcss/oxide-wasm32-wasi@4.1.18': resolution: {integrity: sha512-LffYTvPjODiP6PT16oNeUQJzNVyJl1cjIebq/rWWBF+3eDst5JGEFSc5cWxyRCJ0Mxl+KyIkqRxk1XPEs9x8TA==} @@ -596,6 +638,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 +669,9 @@ packages: cookie-es@2.0.0: resolution: {integrity: sha512-RAj4E421UYRgqokKUmotqAwuplYw15qtdXfY+hGzgCJ/MBjCVZcSoHK/kH9kocfjRjcDME7IiDWR/1WX1TM2Pg==} + core-js@3.50.0: + resolution: {integrity: sha512-BRWgOLKkFeCgRudR6zrs8p9XJZcE14grzKMMssoYrk6krtuEZ7MTKPIY5RzOnqsEKIR9kst7wNzphttraT+Yqw==} + csstype@3.2.3: resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} @@ -640,6 +688,9 @@ packages: resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} engines: {node: '>=8'} + dompurify@3.4.14: + resolution: {integrity: sha512-dVoH9z+MY+C9IilgGCk3YfFqjLi3fChm2OiKJMzh6axrJ5qwxqWaZamgmHrpv22CN/KdbZJuGEGgfQoL00LTdg==} + electron-to-chromium@1.5.286: resolution: {integrity: sha512-9tfDXhJ4RKFNerfjdCcZfufu49vg620741MNs26a9+bhLThdB+plgMeou98CAaHu/WATj2iHOOHTp1hWtABj2A==} @@ -665,6 +716,9 @@ packages: picomatch: optional: true + fflate@0.4.9: + resolution: {integrity: sha512-zdxgIEddhfsyCaWpJ2SdXEP8ZMrKJ6+5jl4OupODcywU0IhRk6gdXuVGcPICyfx2H97hVK7xmJtRLPjkxAX8Vw==} + fsevents@2.3.3: resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} @@ -741,24 +795,28 @@ packages: engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] + libc: [glibc] lightningcss-linux-arm64-musl@1.30.2: resolution: {integrity: sha512-5Vh9dGeblpTxWHpOx8iauV02popZDsCYMPIgiuw97OJ5uaDsL86cnqSFs5LZkG3ghHoX5isLgWzMs+eD1YzrnA==} engines: {node: '>= 12.0.0'} cpu: [arm64] os: [linux] + libc: [musl] lightningcss-linux-x64-gnu@1.30.2: resolution: {integrity: sha512-Cfd46gdmj1vQ+lR6VRTTadNHu6ALuw2pKR9lYq4FnhvgBc4zWY1EtZcAc6EffShbb1MFrIPfLDXD6Xprbnni4w==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] + libc: [glibc] lightningcss-linux-x64-musl@1.30.2: resolution: {integrity: sha512-XJaLUUFXb6/QG2lGIW6aIk6jKdtjtcffUT0NKvIqhSBY3hh9Ch+1LCeH80dR9q9LBjG3ewbDjnumefsLsP6aiA==} engines: {node: '>= 12.0.0'} cpu: [x64] os: [linux] + libc: [musl] lightningcss-win32-arm64-msvc@1.30.2: resolution: {integrity: sha512-FZn+vaj7zLv//D/192WFFVA0RgHawIcHqLX9xuWiQt7P0PtdFEVaxgF9rjM/IRYHQXNnk61/H/gb2Ei+kUQ4xQ==} @@ -804,6 +862,28 @@ packages: resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==} engines: {node: ^10 || ^12 || >=14} + posthog-js@1.424.0: + resolution: {integrity: sha512-owEiZm26dJe7THtRvgMuKRJ0RS7GhZieL42PVcDN8IWzHdDL2VMEIX6bcIN8+HmK9Jleih7cyhPjw8o3GxRC3w==} + peerDependencies: + '@types/react': '>=16.8.0' + react: '>=16.8.0' + peerDependenciesMeta: + '@types/react': + optional: true + react: + optional: true + + preact@10.29.8: + resolution: {integrity: sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q==} + peerDependencies: + preact-render-to-string: '>=5' + peerDependenciesMeta: + preact-render-to-string: + optional: true + + 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 +999,9 @@ packages: yaml: optional: true + web-vitals@6.2.1: + resolution: {integrity: sha512-rLcLXA2sx6+9dE88NHFubwTtGxpK4yYBLj6qHPdFoCaLr0cXGb4efOqtKLlm4loGA4OEKHIQKMKzZkKyOh5ctw==} + yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} @@ -1136,6 +1219,24 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 + '@posthog/browser-common@0.7.1': + dependencies: + '@posthog/core': 1.50.1 + '@posthog/types': 1.407.1 + + '@posthog/core@1.50.1': + dependencies: + '@posthog/types': 1.407.1 + + '@posthog/react@1.10.5(@types/react@19.2.13)(posthog-js@1.424.0(@types/react@19.2.13)(react@19.2.4))(react@19.2.4)': + dependencies: + posthog-js: 1.424.0(@types/react@19.2.13)(react@19.2.4) + react: 19.2.4 + optionalDependencies: + '@types/react': 19.2.13 + + '@posthog/types@1.407.1': {} + '@rolldown/pluginutils@1.0.0-beta.27': {} '@rollup/rollup-android-arm-eabi@4.57.1': @@ -1364,6 +1465,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 +1498,8 @@ snapshots: cookie-es@2.0.0: {} + core-js@3.50.0: {} + csstype@3.2.3: {} debug@4.4.3: @@ -1402,6 +1508,10 @@ snapshots: detect-libc@2.1.2: {} + dompurify@3.4.14: + optionalDependencies: + '@types/trusted-types': 2.0.7 + electron-to-chromium@1.5.286: {} enhanced-resolve@5.19.0: @@ -1444,6 +1554,8 @@ snapshots: optionalDependencies: picomatch: 4.0.3 + fflate@0.4.9: {} + fsevents@2.3.3: optional: true @@ -1540,6 +1652,28 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.1 + posthog-js@1.424.0(@types/react@19.2.13)(react@19.2.4): + dependencies: + '@posthog/browser-common': 0.7.1 + '@posthog/core': 1.50.1 + '@posthog/types': 1.407.1 + core-js: 3.50.0 + dompurify: 3.4.14 + fflate: 0.4.9 + preact: 10.29.8 + query-selector-shadow-dom: 1.0.1 + web-vitals: 6.2.1 + web-vitals-soft-navs: web-vitals@6.2.1 + optionalDependencies: + '@types/react': 19.2.13 + react: 19.2.4 + transitivePeerDependencies: + - preact-render-to-string + + preact@10.29.8: {} + + query-selector-shadow-dom@1.0.1: {} + react-dom@19.2.4(react@19.2.4): dependencies: react: 19.2.4 @@ -1632,6 +1766,8 @@ snapshots: jiti: 2.6.1 lightningcss: 1.30.2 + web-vitals@6.2.1: {} + yallist@3.1.1: {} zod@3.25.76: {} 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 05a68721a..5f21b2110 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 { PostHogErrorBoundary, PostHogProvider, usePostHog } from '@posthog/react' import { z } from 'zod' import { fetchInvoiceById, @@ -84,11 +85,51 @@ function RouterSpinner() { return } +const posthogProjectToken = import.meta.env.VITE_PUBLIC_POSTHOG_PROJECT_TOKEN +const posthogHost = import.meta.env.VITE_PUBLIC_POSTHOG_HOST + +if (import.meta.env.DEV && !posthogProjectToken) { + throw new Error( + 'VITE_PUBLIC_POSTHOG_PROJECT_TOKEN variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once VITE_PUBLIC_POSTHOG_PROJECT_TOKEN is configured', + ) +} + +if (import.meta.env.DEV && !posthogHost) { + throw new Error( + 'VITE_PUBLIC_POSTHOG_HOST variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once VITE_PUBLIC_POSTHOG_HOST is configured', + ) +} + +function PostHogRoot({ children }: { children: React.ReactNode }) { + if (!posthogProjectToken || !posthogHost) { + return children + } + + return ( + + {children} + + ) +} + function RootComponent() { return ( - <> -
-
+ + }> +
+
CF @@ -131,8 +172,9 @@ function RootComponent() {
- - + + + ) } @@ -433,6 +475,7 @@ const invoicesIndexRoute = createRoute({ }) function InvoicesIndexComponent() { + const posthog = usePostHog() const createInvoiceMutation = useMutation({ fn: postInvoice, onSuccess: () => router.invalidate(), @@ -449,14 +492,20 @@ function InvoicesIndexComponent() {
{ + onSubmit={async (event) => { event.preventDefault() event.stopPropagation() const formData = new FormData(event.target as HTMLFormElement) - createInvoiceMutation.mutate({ + const invoice = await createInvoiceMutation.mutate({ title: formData.get('title') as string, body: formData.get('body') as string, }) + + if (invoice) { + posthog.capture('invoice_created', { + invoice_id: invoice.id, + }) + } }} className="bg-gray-50 dark:bg-gray-800 rounded-xl p-6 space-y-4" > @@ -514,6 +563,7 @@ const invoiceRoute = createRoute({ }) function InvoiceComponent() { + const posthog = usePostHog() const search = invoiceRoute.useSearch() const navigate = useNavigate({ from: invoiceRoute.fullPath }) const invoice = invoiceRoute.useLoaderData() @@ -574,15 +624,21 @@ function InvoiceComponent() { { + onSubmit={async (event) => { event.preventDefault() event.stopPropagation() const formData = new FormData(event.target as HTMLFormElement) - updateInvoiceMutation.mutate({ + const updatedInvoice = await updateInvoiceMutation.mutate({ id: invoice.id, title: formData.get('title') as string, body: formData.get('body') as string, }) + + if (updatedInvoice) { + posthog.capture('invoice_updated', { + invoice_id: invoice.id, + }) + } }} className="space-y-4" > @@ -1002,6 +1058,7 @@ const profileRoute = createRoute({ }) function ProfileComponent() { + const posthog = usePostHog() const { username } = profileRoute.useRouteContext() const initials = username?.slice(0, 2).toUpperCase() ?? 'U' @@ -1049,7 +1106,10 @@ function ProfileComponent() {
Free Plan
Basic features included
-
@@ -1067,6 +1127,7 @@ function ProfileComponent() {