This commit is contained in:
echo 2026-03-01 01:36:11 +01:00
parent e218ad57e8
commit 01a3c1a776
18 changed files with 1562 additions and 53 deletions

View File

@ -0,0 +1,61 @@
---
name: integration-react-tanstack-router-code-based
description: >-
PostHog integration for React applications using TanStack Router with
code-based routing
metadata:
author: PostHog
version: 1.8.1
---
# 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. `basic-integration-1.0-begin.md` - PostHog Setup - Begin ← **Start here**
2. `basic-integration-1.1-edit.md` - PostHog Setup - Edit
3. `basic-integration-1.2-revise.md` - PostHog Setup - Revise
4. `basic-integration-1.3-conclude.md` - PostHog Setup - Conclusion
## Reference files
- `EXAMPLE.md` - React with TanStack Router (code-based) example project code
- `tanstack-start.md` - Tanstack start - docs
- `identify-users.md` - Identify users - docs
- `basic-integration-1.0-begin.md` - PostHog setup - begin
- `basic-integration-1.1-edit.md` - PostHog setup - edit
- `basic-integration-1.2-revise.md` - PostHog setup - revise
- `basic-integration-1.3-conclude.md` - PostHog setup - conclusion
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
## 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.

View File

@ -0,0 +1,783 @@
# PostHog React with TanStack Router (code-based) Example Project
Repository: https://github.com/PostHog/context-mill
Path: basics/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_KEY=your_posthog_project_api_key
VITE_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
```
Get your PostHog API key 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 (
<PostHogProvider
apiKey={import.meta.env.VITE_PUBLIC_POSTHOG_KEY!}
options={{
api_host: '/ingest',
ui_host: import.meta.env.VITE_PUBLIC_POSTHOG_HOST || 'https://us.posthog.com',
defaults: '2026-01-30',
capture_exceptions: true,
debug: import.meta.env.DEV,
}}
>
{/* your app */}
</PostHogProvider>
)
}
```
### 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_KEY=<ph_project_api_key>
VITE_PUBLIC_POSTHOG_HOST=<ph_client_api_host>
```
---
## .prettierignore
```
package-lock.json
pnpm-lock.yaml
yarn.lock
```
---
## index.html
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="/favicon.ico" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="React TanStack Router code-based routing example"
/>
<link rel="apple-touch-icon" href="/logo192.png" />
<link rel="manifest" href="/manifest.json" />
<title>React TanStack Router - Code-Based</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
```
---
## 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<boolean>;
logout: () => void;
incrementBurritoConsiderations: () => void;
}
const AuthContext = createContext<AuthContextType | undefined>(undefined);
const users: Map<string, User> = new Map();
export function AuthProvider({ children }: { children: ReactNode }) {
// Use lazy initializer to read from localStorage only once on mount
const [user, setUser] = useState<User | null>(() => {
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<boolean> => {
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 (
<AuthContext.Provider value={{ user, login, logout, incrementBurritoConsiderations }}>
{children}
</AuthContext.Provider>
);
}
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 (
<PostHogProvider
apiKey={import.meta.env.VITE_PUBLIC_POSTHOG_KEY!}
options={{
api_host: '/ingest',
ui_host:
import.meta.env.VITE_PUBLIC_POSTHOG_HOST || 'https://us.posthog.com',
defaults: '2026-01-30',
capture_exceptions: true,
debug: import.meta.env.DEV,
}}
>
<AuthProvider>
<Header />
<main>
<Outlet />
</main>
<TanStackDevtools
config={{
position: 'bottom-right',
}}
plugins={[
{
name: 'Tanstack Router',
render: <TanStackRouterDevtoolsPanel />,
},
]}
/>
</AuthProvider>
</PostHogProvider>
)
}
// ============================================================================
// Header Component
// ============================================================================
function Header() {
const { user, logout } = useAuth()
return (
<header className="header">
<div className="header-container">
<nav>
<Link to="/">Home</Link>
{user && (
<>
<Link to="/burrito">Burrito Consideration</Link>
<Link to="/profile">Profile</Link>
</>
)}
</nav>
<div className="user-section">
{user ? (
<>
<span>Welcome, {user.username}!</span>
<button onClick={logout} className="btn-logout">
Logout
</button>
</>
) : (
<span>Not logged in</span>
)}
</div>
</div>
</header>
)
}
// ============================================================================
// 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 (
<div className="container">
<h1>Welcome back, {user.username}!</h1>
<p>You are now logged in. Feel free to explore:</p>
<ul>
<li>Consider the potential of burritos</li>
<li>View your profile and statistics</li>
</ul>
</div>
)
}
return (
<div className="container">
<h1>Welcome to Burrito Consideration App</h1>
<p>Please sign in to begin your burrito journey</p>
<form onSubmit={handleSubmit} className="form">
<div className="form-group">
<label htmlFor="username">Username:</label>
<input
type="text"
id="username"
value={username}
onChange={(e) => setUsername(e.target.value)}
placeholder="Enter any username"
/>
</div>
<div className="form-group">
<label htmlFor="password">Password:</label>
<input
type="password"
id="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
placeholder="Enter any password"
/>
</div>
{error && <p className="error">{error}</p>}
<button type="submit" className="btn-primary">
Sign In
</button>
</form>
<p className="note">
Note: This is a demo app. Use any username and password to sign in.
</p>
</div>
)
}
// ============================================================================
// 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 (
<div className="container">
<h1>Burrito consideration zone</h1>
<p>Take a moment to truly consider the potential of burritos.</p>
<div style={{ textAlign: 'center' }}>
<button onClick={handleConsideration} className="btn-burrito">
I have considered the burrito potential
</button>
{hasConsidered && (
<p className="success">
Thank you for your consideration! Count: {user.burritoConsiderations}
</p>
)}
</div>
<div className="stats">
<h3>Consideration stats</h3>
<p>Total considerations: {user.burritoConsiderations}</p>
</div>
</div>
)
}
// ============================================================================
// 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 (
<div className="container">
<h1>User Profile</h1>
<div className="stats">
<h2>Your Information</h2>
<p>
<strong>Username:</strong> {user.username}
</p>
<p>
<strong>Burrito Considerations:</strong> {user.burritoConsiderations}
</p>
</div>
<div style={{ marginTop: '2rem' }}>
<button
onClick={triggerTestError}
className="btn-primary"
style={{ backgroundColor: '#dc3545' }}
>
Trigger Test Error (for PostHog)
</button>
</div>
<div style={{ marginTop: '2rem' }}>
<h3>Your Burrito Journey</h3>
{user.burritoConsiderations === 0 ? (
<p>
You haven't considered any burritos yet. Visit the Burrito
Consideration page to start!
</p>
) : user.burritoConsiderations === 1 ? (
<p>You've considered the burrito potential once. Keep going!</p>
) : user.burritoConsiderations < 5 ? (
<p>You're getting the hang of burrito consideration!</p>
) : user.burritoConsiderations < 10 ? (
<p>You're becoming a burrito consideration expert!</p>
) : (
<p>You are a true burrito consideration master!</p>
)}
</div>
</div>
)
}
// ============================================================================
// 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(
<StrictMode>
<RouterProvider router={router} />
</StrictMode>,
)
}
// 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': {
target: env.VITE_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/ingest/, ''),
},
},
},
}
})
```
---

View File

@ -0,0 +1,43 @@
---
title: PostHog Setup - Begin
description: Start the event tracking setup process by analyzing the project and creating an event tracking plan
---
We're making an event tracking plan for this project.
Before proceeding, find any existing `posthog.capture()` code. Make note of event name formatting.
From the project's file list, select between 10 and 15 files that might have interesting business value for event tracking, especially conversion and churn events. Also look for additional files related to login that could be used for identifying users, along with error handling. Read the files. If a file is already well-covered by PostHog events, replace it with another option. 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: event name, event description, and the file path we want to place the event in. If events already exist, don't duplicate them; supplement them.
Track actions only, not pageviews. These can be captured automatically. Exceptions can be made for "viewed"-type events that correspond to the top of a conversion funnel.
As you review files, make an internal note of opportunities to identify users and catch errors. We'll need them for the next step.
## Status
Before beginning a phase of the setup, you will send a status message with the exact prefix '[STATUS]', as in:
[STATUS] Checking project structure.
Status to report in this phase:
- Checking project structure
- Verifying PostHog dependencies
- Generating events based on project
---
**Upon completion, continue with:** [basic-integration-1.1-edit.md](basic-integration-1.1-edit.md)

View File

@ -0,0 +1,37 @@
---
title: PostHog Setup - Edit
description: Implement PostHog event tracking in the identified files, following best practices and the example project
---
For each of the files and events noted in .posthog-events.json, make edits to capture events using PostHog. Make sure to set up any helper files needed. Carefully examine the included example project code: your implementation should match it as closely as possible. 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:** [basic-integration-1.2-revise.md](basic-integration-1.2-revise.md)

View File

@ -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:** [basic-integration-1.3-conclude.md](basic-integration-1.3-conclude.md)

View File

@ -0,0 +1,38 @@
---
title: PostHog Setup - Conclusion
description: Review and fix any errors in the PostHog integration implementation
---
Use the PostHog MCP to create a new dashboard named "Analytics basics" based on the events created here. Make sure to use the exact same event names as implemented in the code. Populate it with up to five insights, with special emphasis on things like conversion funnels, churn events, and other business critical insights.
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, along with a list of links for the dashboard and insights created. Follow this format:
<wizard-report>
# PostHog post-wizard report
The wizard has completed a deep integration of your project. [Detailed summary of changes]
[table of events/descriptions/files]
## Next steps
We've built some insights and a dashboard for you to keep an eye on user behavior, based on the events we just instrumented:
[links]
### Agent skill
We've left an agent skill folder in your project. You can use this context for further agent development when using Claude Code. This will help ensure the model provides the most up-to-date approaches for integrating PostHog.
</wizard-report>
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]

View File

@ -0,0 +1,202 @@
# Identify users - Docs
Linking events to specific users enables you to build a full picture of how they're using your product across different sessions, devices, and platforms.
This is straightforward to do when [capturing backend events](/docs/product-analytics/capture-events?tab=Node.js.md), as you associate events to a specific user using a `distinct_id`, which is a required argument.
However, in the frontend of a [web](/docs/libraries/js/features#capturing-events.md) or [mobile app](/docs/libraries/ios#capturing-events.md), a `distinct_id` is not a required argument — PostHog's SDKs will generate an anonymous `distinct_id` for you automatically and you can capture events anonymously, provided you use the appropriate [configuration](/docs/libraries/js/features#capturing-anonymous-events.md).
To link events to specific users, call `identify`:
PostHog AI
### Web
```javascript
posthog.identify(
'distinct_id', // Replace 'distinct_id' with your user's unique identifier
{ email: 'max@hedgehogmail.com', name: 'Max Hedgehog' } // optional: set additional person properties
);
```
### Android
```kotlin
PostHog.identify(
distinctId = distinctID, // Replace 'distinctID' with your user's unique identifier
// optional: set additional person properties
userProperties = mapOf(
"name" to "Max Hedgehog",
"email" to "max@hedgehogmail.com"
)
)
```
### iOS
```swift
PostHogSDK.shared.identify("distinct_id", // Replace "distinct_id" with your user's unique identifier
userProperties: ["name": "Max Hedgehog", "email": "max@hedgehogmail.com"]) // optional: set additional person properties
```
### React Native
```jsx
posthog.identify('distinct_id', { // Replace "distinct_id" with your user's unique identifier
email: 'max@hedgehogmail.com', // optional: set additional person properties
name: 'Max Hedgehog'
})
```
### Dart
```dart
await Posthog().identify(
userId: 'distinct_id', // Replace "distinct_id" with your user's unique identifier
userProperties: {
email: "max@hedgehogmail.com", // optional: set additional person properties
name: "Max Hedgehog"
});
```
Events captured after calling `identify` are identified events and this creates a person profile if one doesn't exist already.
Due to the cost of processing them, anonymous events can be up to 4x cheaper than identified events, so it's recommended you only capture identified events when needed.
## How identify works
When a user starts browsing your website or app, PostHog automatically assigns them an **anonymous ID**, which is stored locally.
Provided you've [configured persistence](/docs/libraries/js/persistence.md) to use cookies or `localStorage`, this enables us to track anonymous users even across different sessions.
By calling `identify` with a `distinct_id` of your choice (usually the user's ID in your database, or their email), you link the anonymous ID and distinct ID together.
Thus, all past and future events made with that anonymous ID are now associated with the distinct ID.
This enables you to do things like associate events with a user from before they log in for the first time, or associate their events across different devices or platforms.
Using identify in the backend
Although you can call `identify` using our backend SDKs, it is used most in frontends. This is because there is no concept of anonymous sessions in the backend SDKs, so calling `identify` only updates person profiles.
## Best practices when using `identify`
### 1\. Call `identify` as soon as you're able to
In your frontend, you should call `identify` as soon as you're able to.
Typically, this is every time your **app loads** for the first time, and directly after your **users log in**.
This ensures that events sent during your users' sessions are correctly associated with them.
You only need to call `identify` once per session, and you should avoid calling it multiple times unnecessarily.
If you call `identify` multiple times with the same data without reloading the page in between, PostHog will ignore the subsequent calls.
### 2\. Use unique strings for distinct IDs
If two users have the same distinct ID, their data is merged and they are considered one user in PostHog. Two common ways this can happen are:
- Your logic for generating IDs does not generate sufficiently strong IDs and you can end up with a clash where 2 users have the same ID.
- There's a bug, typo, or mistake in your code leading to most or all users being identified with generic IDs like `null`, `true`, or `distinctId`.
PostHog also has built-in protections to stop the most common distinct ID mistakes.
### 3\. Reset after logout
If a user logs out on your frontend, you should call `reset()` to unlink any future events made on that device with that user.
This is important if your users are sharing a computer, as otherwise all of those users are grouped together into a single user due to shared cookies between sessions.
**We strongly recommend you call `reset` on logout even if you don't expect users to share a computer.**
You can do that like so:
PostHog AI
### Web
```javascript
posthog.reset()
```
### iOS
```swift
PostHogSDK.shared.reset()
```
### Android
```kotlin
PostHog.reset()
```
### React Native
```jsx
posthog.reset()
```
### Dart
```dart
Posthog().reset()
```
If you *also* want to reset the `device_id` so that the device will be considered a new device in future events, you can pass `true` as an argument:
Web
PostHog AI
```javascript
posthog.reset(true)
```
### 4\. Person profiles and properties
You'll notice that one of the parameters in the `identify` method is a `properties` object.
This enables you to set [person properties](/docs/product-analytics/person-properties.md).
Whenever possible, we recommend passing in all person properties you have available each time you call identify, as this ensures their person profile on PostHog is up to date.
Person properties can also be set being adding a `$set` property to a event `capture` call.
See our [person properties docs](/docs/product-analytics/person-properties.md) for more details on how to work with them and best practices.
### 5\. Use deep links between platforms
We recommend you call `identify` [as soon as you're able](#1-call-identify-as-soon-as-youre-able), typically when a user signs up or logs in.
This doesn't work if one or both platforms are unauthenticated. Some examples of such cases are:
- Onboarding and signup flows before authentication.
- Unauthenticated web pages redirecting to authenticated mobile apps.
- Authenticated web apps prompting an app download.
In these cases, you can use a [deep link](https://developer.android.com/training/app-links/deep-linking) on Android and [universal links](https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app) on iOS to identify users.
1. Use `posthog.get_distinct_id()` to get the current distinct ID. Even if you cannot call identify because the user is unauthenticated, this will return an anonymous distinct ID generated by PostHog.
2. Add the distinct ID to the deep link as query parameters, along with other properties like UTM parameters.
3. When the user is redirected to the app, parse the deep link and handle the following cases:
- The user is already authenticated on the mobile app. In this case, call [`posthog.alias()`](/docs/libraries/js/features#alias.md) with the distinct ID from the web. This associates the two distinct IDs as a single person.
- The user is unauthenticated. In this case, call [`posthog.identify()`](/docs/libraries/js/features#identifying-users.md) with the distinct ID from the web. Events will be associated with this distinct ID.
As long as you associate the distinct IDs with `posthog.identify()` or `posthog.alias()`, you can track events generated across platforms.
## Further reading
- [Identifying users docs](/docs/product-analytics/identify.md)
- [How person processing works](/docs/how-posthog-works/ingestion-pipeline#2-person-processing.md)
- [An introductory guide to identifying users in PostHog](/tutorials/identifying-users-guide.md)
### Community questions
Ask a question
### Was this page useful?
HelpfulCould be better

View File

@ -0,0 +1,187 @@
# 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
## 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 (
<html lang="en">
<head>
<HeadContent />
</head>
<body>
<PostHogProvider
apiKey="<ph_project_token>"
options={{
api_host: 'https://us.i.posthog.com',
defaults: '2026-01-30',
capture_exceptions: true
}}
>
{children}
</PostHogProvider>
<Scripts />
</body>
</html>
)
}
```
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 <button onClick={handleClick}>Checkout</button>
}
```
### 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(
'<ph_project_token>',
{
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

2
frontend/.gitignore vendored
View File

@ -22,3 +22,5 @@ dist-ssr
*.njsproj
*.sln
*.sw?
.env.local
.env

View File

@ -0,0 +1,47 @@
<wizard-report>
# PostHog post-wizard report
The wizard has completed a deep integration of PostHog analytics into the Placebo.mk React (TanStack Router, code-based routing) application. Here is a summary of all changes made:
## Integration summary
- **`src/main.tsx`** — Updated `PostHogProvider` options to use a `/ingest` reverse proxy (`api_host: '/ingest'`), added `ui_host`, enabled `capture_exceptions: true` for automatic error tracking, and enabled `debug` mode in development.
- **`vite.config.ts`** — Added a Vite dev server proxy for `/ingest``VITE_PUBLIC_POSTHOG_HOST`, routing PostHog calls through the dev server to avoid ad blockers.
- **`.env` / `.env.local`** — Set `VITE_PUBLIC_POSTHOG_KEY` and `VITE_PUBLIC_POSTHOG_HOST` with the correct EU cloud values.
- **`src/contexts/AuthContext.tsx`** — Added `usePostHog()`, `posthog.identify()` on login and register (using user ID as distinct ID with username, email, role properties), `posthog.capture()` for `user_logged_in`, `user_registered`, and `user_logged_out` events, and `posthog.reset()` on logout.
- **`src/components/features/social-share/SocialShareButtons.tsx`** — Added `posthog.capture('article_shared', ...)` with platform, article ID, title, and URL properties.
- **`src/components/features/comments/ReactionButtons.tsx`** — Added `posthog.capture('article_reaction_added', ...)` with reaction type, target IDs, and target type (article/live_blog/comment).
- **`src/components/features/comments/CommentSection.tsx`** — Added `posthog.capture('comment_submitted', ...)` with article/live blog ID, target type, and comment length.
- **`src/components/admin/PushNotificationManager.tsx`** — Added `posthog.capture('push_notification_sent', ...)` with notification title, sent/failed counts, and subscriber count.
- **`src/components/features/live-blog/LiveBlogViewer.tsx`** — Added `posthog.capture('live_blog_viewed', ...)` once per mount (guarded with a ref), and `posthog.capture('live_blog_reconnected', ...)` on the Reconnect button click.
## Events instrumented
| Event name | Description | File |
|---|---|---|
| `user_logged_in` | Fired when a user successfully logs in | `src/contexts/AuthContext.tsx` |
| `user_registered` | Fired when a user successfully completes registration | `src/contexts/AuthContext.tsx` |
| `user_logged_out` | Fired when a user logs out | `src/contexts/AuthContext.tsx` |
| `article_shared` | Fired when a user shares an article on a social platform | `src/components/features/social-share/SocialShareButtons.tsx` |
| `article_reaction_added` | Fired when a user reacts (like or dislike) to an article or comment | `src/components/features/comments/ReactionButtons.tsx` |
| `comment_submitted` | Fired when a user successfully posts a comment on an article or live blog | `src/components/features/comments/CommentSection.tsx` |
| `push_notification_sent` | Fired when an admin successfully sends a push notification to all subscribers | `src/components/admin/PushNotificationManager.tsx` |
| `live_blog_viewed` | Fired when a user opens a live blog page (top of engagement funnel for live coverage) | `src/components/features/live-blog/LiveBlogViewer.tsx` |
| `live_blog_reconnected` | Fired when a user manually reconnects to a live blog stream | `src/components/features/live-blog/LiveBlogViewer.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:
- 📊 **Dashboard — Analytics basics**: https://eu.posthog.com/project/133810/dashboard/546519
- 📈 **User Authentication Trends** (logins, registrations, logouts over time): https://eu.posthog.com/project/133810/insights/pxodr2zQ
- 🔽 **New User Engagement Funnel** (registration → first comment → first reaction): https://eu.posthog.com/project/133810/insights/zK5n3YKc
- 🔗 **Article Shares by Platform** (breakdown of shares per social platform): https://eu.posthog.com/project/133810/insights/pplQTyt8
- 💬 **Content Engagement Activity** (comments, reactions, and shares over time): https://eu.posthog.com/project/133810/insights/wn7cQy26
- 📡 **Live Blog Engagement** (live blog views and reconnect attempts): https://eu.posthog.com/project/133810/insights/6QtI23Hm
### Agent skill
We've left an agent skill folder in your project at `.claude/skills/posthog-integration-react-tanstack-router-code-based/`. 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.
</wizard-report>

View File

@ -2,6 +2,7 @@ import { useState } from 'react';
import { usePushStats, useSendPushNotification } from '@/queries/push';
import { Button } from '@/components/ui/button';
import { Bell, Send, Users, AlertCircle, CheckCircle } from 'lucide-react';
import { usePostHog } from '@posthog/react';
export function PushNotificationManager() {
const [title, setTitle] = useState('');
@ -11,6 +12,7 @@ export function PushNotificationManager() {
const [result, setResult] = useState<{ sent: number; failed: number } | null>(
null,
);
const posthog = usePostHog();
const { data: stats, isLoading: loadingStats } = usePushStats();
const sendMutation = useSendPushNotification();
@ -27,6 +29,13 @@ export function PushNotificationManager() {
setResult(result);
setShowSuccess(true);
setTimeout(() => setShowSuccess(false), 5000);
posthog.capture('push_notification_sent', {
notification_title: title.trim(),
has_url: !!url.trim(),
sent_count: result.sent,
failed_count: result.failed,
total_subscribers: stats?.totalSubscribers,
});
} catch (error) {
console.error('Failed to send notification:', error);
}

View File

@ -5,6 +5,7 @@ import { Button } from '../../ui/button';
import { Textarea } from '../../ui/textarea';
import { Card, CardContent } from '../../ui/card';
import { CommentItem } from './CommentItem';
import { usePostHog } from '@posthog/react';
interface CommentSectionProps {
articleId?: string;
@ -15,6 +16,7 @@ export function CommentSection({ articleId, liveBlogId }: CommentSectionProps) {
const { isAuthenticated } = useAuth();
const [newComment, setNewComment] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const posthog = usePostHog();
const { data: commentsData, isLoading } = useComments({
articleId,
@ -28,9 +30,9 @@ export function CommentSection({ articleId, liveBlogId }: CommentSectionProps) {
const handleSubmitComment = async (e: React.FormEvent) => {
e.preventDefault();
if (!newComment.trim() || !isAuthenticated) return;
setIsSubmitting(true);
try {
await createCommentMutation.mutateAsync({
@ -38,6 +40,12 @@ export function CommentSection({ articleId, liveBlogId }: CommentSectionProps) {
articleId,
liveBlogId,
});
posthog.capture('comment_submitted', {
article_id: articleId,
live_blog_id: liveBlogId,
target_type: liveBlogId ? 'live_blog' : 'article',
comment_length: newComment.trim().length,
});
setNewComment('');
} catch (error) {
console.error('Failed to post comment:', error);

View File

@ -3,6 +3,7 @@ import { useAuth } from '../../../contexts/AuthContext';
import { useReactionCounts, useUserReaction, useAddReaction } from '../../../queries/comments';
import { Button } from '../../ui/button';
import { ThumbsUp, ThumbsDown } from 'lucide-react';
import { usePostHog } from '@posthog/react';
interface ReactionButtonsProps {
articleId?: string;
@ -11,26 +12,27 @@ interface ReactionButtonsProps {
compact?: boolean;
}
export function ReactionButtons({
articleId,
liveBlogId,
export function ReactionButtons({
articleId,
liveBlogId,
commentId,
compact = false
compact = false
}: ReactionButtonsProps) {
const { isAuthenticated } = useAuth();
const posthog = usePostHog();
const { data: counts } = useReactionCounts(articleId, liveBlogId, commentId);
const { data: userReaction } = useUserReaction(articleId, liveBlogId, commentId);
const addReactionMutation = useAddReaction();
const userReactionType = userReaction?.type;
const handleReaction = async (type: 'like' | 'dislike') => {
if (!isAuthenticated) {
window.location.href = '/auth';
return;
}
try {
await addReactionMutation.mutateAsync({
type,
@ -38,6 +40,13 @@ export function ReactionButtons({
liveBlogId,
commentId,
});
posthog.capture('article_reaction_added', {
reaction_type: type,
article_id: articleId,
live_blog_id: liveBlogId,
comment_id: commentId,
target_type: commentId ? 'comment' : liveBlogId ? 'live_blog' : 'article',
});
} catch (error) {
console.error('Failed to add reaction:', error);
}

View File

@ -5,6 +5,7 @@ import type { LiveBlogUpdate as ApiLiveBlogUpdate } from '@/lib/api';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { cn } from '@/lib/utils';
import { usePostHog } from '@posthog/react';
interface LiveBlogViewerProps {
slug: string;
@ -15,23 +16,25 @@ export function LiveBlogViewer({ slug, className }: LiveBlogViewerProps) {
const [autoScroll, setAutoScroll] = useState(true);
const [newUpdatesCount, setNewUpdatesCount] = useState(0);
const [isScrolledUp, setIsScrolledUp] = useState(false);
const posthog = usePostHog();
const hasTrackedView = useRef(false);
const updatesContainerRef = useRef<HTMLDivElement>(null);
const lastUpdateCountRef = useRef(0);
const { data: liveBlog, isLoading: blogLoading, error: blogError } = useLiveBlog(slug);
const {
data: updatesData,
isLoading: updatesLoading,
refetch: refetchUpdates
const {
data: updatesData,
isLoading: updatesLoading,
refetch: refetchUpdates
} = useLiveBlogUpdates(liveBlog?.id || '', 1, 100);
const {
isConnected,
lastEvent,
const {
isConnected,
lastEvent,
connectionError,
reconnectAttempts,
connect
connect
} = useLiveBlogStream(liveBlog?.id || '');
const scrollToBottom = useCallback(() => {
@ -95,16 +98,29 @@ export function LiveBlogViewer({ slug, className }: LiveBlogViewerProps) {
useEffect(() => {
if (updatesData?.data && updatesData.data.length > 0) {
const currentUpdateCount = updatesData.data.length;
// Only auto-scroll if this is the initial load or user is at bottom
if (currentUpdateCount > lastUpdateCountRef.current && !isScrolledUp) {
setTimeout(scrollToBottom, 100);
}
lastUpdateCountRef.current = currentUpdateCount;
}
}, [updatesData, scrollToBottom, isScrolledUp]);
// Track live blog view once data is loaded
useEffect(() => {
if (liveBlog && !hasTrackedView.current) {
hasTrackedView.current = true;
posthog.capture('live_blog_viewed', {
live_blog_id: liveBlog.id,
live_blog_slug: slug,
live_blog_title: liveBlog.title,
live_blog_status: liveBlog.status,
});
}
}, [liveBlog, slug, posthog]);
if (blogLoading) {
return (
<Card className={cn('w-full max-w-4xl mx-auto', className)}>
@ -185,7 +201,14 @@ export function LiveBlogViewer({ slug, className }: LiveBlogViewerProps) {
<Button
variant="outline"
size="sm"
onClick={connect}
onClick={() => {
connect();
posthog.capture('live_blog_reconnected', {
live_blog_id: liveBlog.id,
live_blog_slug: slug,
reconnect_attempts: reconnectAttempts,
});
}}
>
Reconnect
</Button>

View File

@ -3,6 +3,7 @@ import { ShareButton } from './ShareButton';
import { CopyLinkButton } from './CopyLinkButton';
import { type SharePlatform, type ShareData, getShareUrl } from '@/lib/social-utils';
import { trackShare } from '@/lib/analytics';
import { usePostHog } from '@posthog/react';
export type SocialShareVariant = 'default' | 'compact' | 'footer' | 'floating';
@ -28,6 +29,7 @@ export function SocialShareButtons({
}: SocialShareButtonsProps) {
const [isTracking, setIsTracking] = useState(false);
const [isExpanded, setIsExpanded] = useState(false);
const posthog = usePostHog();
const shareData: ShareData = {
title,
@ -48,6 +50,12 @@ export function SocialShareButtons({
// Note: We don't send IP address from frontend for privacy reasons
// Backend should extract it from the request if needed
});
posthog.capture('article_shared', {
article_id: articleId,
platform,
article_title: title,
article_url: url,
});
// Call the onShare callback if provided
if (onShare) {

View File

@ -3,6 +3,7 @@ import { createContext, useContext, useState, useEffect } from 'react';
import type { ReactNode } from 'react';
import * as api from '../lib/api';
import type { User } from '@/types';
import { usePostHog } from '@posthog/react';
interface AuthContextType {
user: User | null;
@ -25,6 +26,7 @@ export function AuthProvider({ children }: AuthProviderProps) {
const [user, setUser] = useState<User | null>(null);
const [token, setToken] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const posthog = usePostHog();
useEffect(() => {
const initializeAuth = () => {
@ -56,6 +58,15 @@ export function AuthProvider({ children }: AuthProviderProps) {
setToken(response.access_token);
setUser(response.user);
setIsLoading(false);
posthog.identify(response.user.id, {
username: response.user.username,
email: response.user.email,
role: response.user.role,
});
posthog.capture('user_logged_in', {
username: response.user.username,
role: response.user.role,
});
};
const register = async (username: string, email: string, password: string) => {
@ -66,9 +77,20 @@ export function AuthProvider({ children }: AuthProviderProps) {
setToken(response.access_token);
setUser(response.user);
setIsLoading(false);
posthog.identify(response.user.id, {
username: response.user.username,
email: response.user.email,
role: response.user.role,
});
posthog.capture('user_registered', {
username: response.user.username,
email: response.user.email,
});
};
const logout = () => {
posthog.capture('user_logged_out');
posthog.reset();
localStorage.removeItem('token');
localStorage.removeItem('user');
setToken(null);

View File

@ -13,20 +13,17 @@ initializeTheme();
const queryClient = new QueryClient()
const posthogOptions = {
api_host: import.meta.env.VITE_PUBLIC_POSTHOG_HOST,
api_host: '/ingest',
ui_host: import.meta.env.VITE_PUBLIC_POSTHOG_HOST || 'https://eu.posthog.com',
defaults: '2026-01-30',
capture_exceptions: true,
debug: import.meta.env.DEV,
} as const
// Debug PostHog configuration
console.log('PostHog Config:', {
apiKey: import.meta.env.VITE_PUBLIC_POSTHOG_KEY ? '✓ Set' : '✗ Missing',
apiHost: import.meta.env.VITE_PUBLIC_POSTHOG_HOST,
})
ReactDOM.createRoot(document.getElementById('root')!).render(
<StrictMode>
<PostHogProvider
apiKey={import.meta.env.VITE_PUBLIC_POSTHOG_KEY}
<PostHogProvider
apiKey={import.meta.env.VITE_PUBLIC_POSTHOG_KEY}
options={posthogOptions}
>
<QueryClientProvider client={queryClient}>

View File

@ -1,28 +1,39 @@
import { defineConfig } from 'vite'
import { defineConfig, loadEnv } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
import path from 'path'
// https://vite.dev/config/
export default defineConfig({
plugins: [
react(),
tailwindcss(),
],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), '')
return {
plugins: [
react(),
tailwindcss(),
],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
},
// For npm workspaces - look for dependencies in parent node_modules
preserveSymlinks: true,
},
// For npm workspaces - look for dependencies in parent node_modules
preserveSymlinks: true,
},
// For npm workspaces - optimize dependencies from root
optimizeDeps: {
include: ['react', 'react-dom', 'react-markdown'],
},
server: {
host: true, // Listen on all addresses
port: 5173,
strictPort: true,
},
// For npm workspaces - optimize dependencies from root
optimizeDeps: {
include: ['react', 'react-dom', 'react-markdown'],
},
server: {
host: true, // Listen on all addresses
port: 5173,
strictPort: true,
proxy: {
'/ingest': {
target: env.VITE_PUBLIC_POSTHOG_HOST || 'https://eu.i.posthog.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/ingest/, ''),
},
},
},
}
})