mirror of
https://github.com/formbricks/formbricks.git
synced 2026-03-14 02:12:43 -05:00
Compare commits
1 Commits
4.8.0-rc.1
...
feat/add-p
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6da40e490d |
@@ -0,0 +1,58 @@
|
||||
---
|
||||
name: integration-nextjs-pages-router
|
||||
description: PostHog integration for Next.js Pages Router applications
|
||||
metadata:
|
||||
author: PostHog
|
||||
version: 1.8.1
|
||||
---
|
||||
|
||||
# PostHog integration for Next.js Pages Router
|
||||
|
||||
This skill helps you add PostHog analytics to Next.js Pages Router 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` - Next.js Pages Router example project code
|
||||
- `next-js.md` - Next.js - 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 Next.js 15.3+, initialize PostHog in instrumentation-client.ts for the simplest setup
|
||||
- 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)
|
||||
|
||||
## 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.
|
||||
@@ -0,0 +1,761 @@
|
||||
# PostHog Next.js Pages Router Example Project
|
||||
|
||||
Repository: https://github.com/PostHog/context-mill
|
||||
Path: basics/next-pages-router
|
||||
|
||||
---
|
||||
|
||||
## README.md
|
||||
|
||||
# PostHog Next.js pages router example
|
||||
|
||||
This is a [Next.js](https://nextjs.org) Pages Router example demonstrating PostHog integration with product analytics, session replay, feature flags, and error tracking.
|
||||
|
||||
## 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
|
||||
- **Server-side & Client-side Tracking**: Examples of both tracking methods
|
||||
- **Reverse Proxy**: PostHog ingestion through Next.js rewrites
|
||||
|
||||
## Getting Started
|
||||
|
||||
### 1. Install Dependencies
|
||||
|
||||
```bash
|
||||
npm install
|
||||
# or
|
||||
pnpm install
|
||||
```
|
||||
|
||||
### 2. Configure Environment Variables
|
||||
|
||||
Create a `.env.local` file in the root directory:
|
||||
|
||||
```bash
|
||||
NEXT_PUBLIC_POSTHOG_KEY=your_posthog_project_api_key
|
||||
NEXT_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
|
||||
# or
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
Open [http://localhost:3000](http://localhost:3000) with your browser to see the app.
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
src/
|
||||
├── components/
|
||||
│ └── Header.tsx # Navigation header with auth state
|
||||
├── contexts/
|
||||
│ └── AuthContext.tsx # Authentication context with PostHog integration
|
||||
├── lib/
|
||||
│ └── posthog-server.ts # Server-side PostHog client
|
||||
├── pages/
|
||||
│ ├── _app.tsx # App wrapper with Auth provider
|
||||
│ ├── _document.tsx # Document wrapper
|
||||
│ ├── index.tsx # Home/Login page
|
||||
│ ├── burrito.tsx # Demo feature page with event tracking
|
||||
│ ├── profile.tsx # User profile with error tracking demo
|
||||
│ └── api/
|
||||
│ └── auth/
|
||||
│ └── login.ts # Login API with server-side tracking
|
||||
└── styles/
|
||||
└── globals.css # Global styles
|
||||
|
||||
instrumentation-client.ts # Client-side PostHog initialization
|
||||
```
|
||||
|
||||
## Key Integration Points
|
||||
|
||||
### Client-side initialization (instrumentation-client.ts)
|
||||
|
||||
```typescript
|
||||
import posthog from "posthog-js"
|
||||
|
||||
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
|
||||
api_host: "/ingest",
|
||||
ui_host: "https://us.posthog.com",
|
||||
defaults: '2026-01-30',
|
||||
capture_exceptions: true,
|
||||
debug: process.env.NODE_ENV === "development",
|
||||
});
|
||||
```
|
||||
|
||||
### User identification (AuthContext.tsx)
|
||||
|
||||
```typescript
|
||||
posthog.identify(username, {
|
||||
username: username,
|
||||
});
|
||||
```
|
||||
|
||||
### Event tracking (burrito.tsx)
|
||||
|
||||
```typescript
|
||||
posthog.capture('burrito_considered', {
|
||||
total_considerations: count,
|
||||
username: username,
|
||||
});
|
||||
```
|
||||
|
||||
### Error tracking (profile.tsx)
|
||||
|
||||
```typescript
|
||||
posthog.captureException(error);
|
||||
```
|
||||
|
||||
### Server-side tracking (api/auth/login.ts)
|
||||
|
||||
```typescript
|
||||
const posthog = getPostHogClient();
|
||||
posthog.capture({
|
||||
distinctId: username,
|
||||
event: 'server_login',
|
||||
properties: { ... }
|
||||
});
|
||||
```
|
||||
|
||||
## Pages router differences from app router
|
||||
|
||||
This example uses Next.js Pages Router instead of App Router. Key differences:
|
||||
|
||||
1. **File-based routing**: Pages in `src/pages/` instead of `src/app/`
|
||||
2. **_app.tsx**: Custom App component wraps all pages
|
||||
3. **API Routes**: Located in `src/pages/api/`
|
||||
4. **No 'use client'**: All pages are client-side by default
|
||||
5. **useRouter**: From `next/router` instead of `next/navigation`
|
||||
6. **Head component**: Using `next/head` for metadata instead of `metadata` export
|
||||
|
||||
## Learn More
|
||||
|
||||
- [PostHog Documentation](https://posthog.com/docs)
|
||||
- [Next.js Pages Router Documentation](https://nextjs.org/docs/pages)
|
||||
- [PostHog Next.js Integration Guide](https://posthog.com/docs/libraries/next-js)
|
||||
|
||||
## Deploy on Vercel
|
||||
|
||||
The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new).
|
||||
|
||||
Check out the [Next.js deployment documentation](https://nextjs.org/docs/pages/building-your-application/deploying) for more details.
|
||||
|
||||
---
|
||||
|
||||
## instrumentation-client.ts
|
||||
|
||||
```ts
|
||||
import posthog from "posthog-js"
|
||||
|
||||
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
|
||||
api_host: "/ingest",
|
||||
ui_host: "https://us.posthog.com",
|
||||
// Include the defaults option as required by PostHog
|
||||
defaults: '2026-01-30',
|
||||
// Enables capturing unhandled exceptions via Error Tracking
|
||||
capture_exceptions: true,
|
||||
// Turn on debug in development mode
|
||||
debug: process.env.NODE_ENV === "development",
|
||||
});
|
||||
|
||||
//IMPORTANT: Never combine this approach with other client-side PostHog initialization approaches, especially components like a PostHogProvider. instrumentation-client.ts is the correct solution for initializating client-side PostHog in Next.js 15.3+ apps.
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## next.config.ts
|
||||
|
||||
```ts
|
||||
import type { NextConfig } from "next";
|
||||
|
||||
const nextConfig: NextConfig = {
|
||||
/* config options here */
|
||||
reactStrictMode: true,
|
||||
async rewrites() {
|
||||
return [
|
||||
{
|
||||
source: "/ingest/static/:path*",
|
||||
destination: "https://us-assets.i.posthog.com/static/:path*",
|
||||
},
|
||||
{
|
||||
source: "/ingest/:path*",
|
||||
destination: "https://us.i.posthog.com/:path*",
|
||||
},
|
||||
];
|
||||
},
|
||||
// This is required to support PostHog trailing slash API requests
|
||||
skipTrailingSlashRedirect: true,
|
||||
};
|
||||
|
||||
export default nextConfig;
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## src/components/Header.tsx
|
||||
|
||||
```tsx
|
||||
import Link from 'next/link';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
|
||||
export default function Header() {
|
||||
const { user, logout } = useAuth();
|
||||
|
||||
return (
|
||||
<header className="header">
|
||||
<div className="header-container">
|
||||
<nav>
|
||||
<Link href="/">Home</Link>
|
||||
{user && (
|
||||
<>
|
||||
<Link href="/burrito">Burrito Consideration</Link>
|
||||
<Link href="/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>
|
||||
);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## src/contexts/AuthContext.tsx
|
||||
|
||||
```tsx
|
||||
import { createContext, useContext, useState, ReactNode } from 'react';
|
||||
import posthog from 'posthog-js';
|
||||
|
||||
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 login = async (username: string, password: string): Promise<boolean> => {
|
||||
try {
|
||||
const response = await fetch('/api/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username, password }),
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const { user: userData } = await response.json();
|
||||
|
||||
// Get or create user in local map
|
||||
let localUser = users.get(username);
|
||||
if (!localUser) {
|
||||
localUser = userData as User;
|
||||
users.set(username, localUser);
|
||||
}
|
||||
|
||||
setUser(localUser);
|
||||
localStorage.setItem('currentUser', username);
|
||||
|
||||
// Identify user in PostHog using username as distinct ID
|
||||
posthog.identify(username, {
|
||||
username: username,
|
||||
});
|
||||
|
||||
// Capture login event
|
||||
posthog.capture('user_logged_in', {
|
||||
username: username,
|
||||
});
|
||||
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
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/lib/posthog-server.ts
|
||||
|
||||
```ts
|
||||
import { PostHog } from 'posthog-node';
|
||||
|
||||
let posthogClient: PostHog | null = null;
|
||||
|
||||
export function getPostHogClient() {
|
||||
if (!posthogClient) {
|
||||
posthogClient = new PostHog(
|
||||
process.env.NEXT_PUBLIC_POSTHOG_KEY!,
|
||||
{
|
||||
host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
|
||||
flushAt: 1,
|
||||
flushInterval: 0
|
||||
}
|
||||
);
|
||||
}
|
||||
return posthogClient;
|
||||
}
|
||||
|
||||
export async function shutdownPostHog() {
|
||||
if (posthogClient) {
|
||||
await posthogClient.shutdown();
|
||||
}
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## src/pages/_app.tsx
|
||||
|
||||
```tsx
|
||||
import "@/styles/globals.css";
|
||||
import type { AppProps } from "next/app";
|
||||
import { AuthProvider } from "@/contexts/AuthContext";
|
||||
|
||||
export default function App({ Component, pageProps }: AppProps) {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<Component {...pageProps} />
|
||||
</AuthProvider>
|
||||
);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## src/pages/_document.tsx
|
||||
|
||||
```tsx
|
||||
import { Html, Head, Main, NextScript } from "next/document";
|
||||
|
||||
export default function Document() {
|
||||
return (
|
||||
<Html lang="en">
|
||||
<Head />
|
||||
<body>
|
||||
<Main />
|
||||
<NextScript />
|
||||
</body>
|
||||
</Html>
|
||||
);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## src/pages/api/auth/login.ts
|
||||
|
||||
```ts
|
||||
import type { NextApiRequest, NextApiResponse } from 'next';
|
||||
import { getPostHogClient } from '@/lib/posthog-server';
|
||||
|
||||
const users = new Map<string, { username: string; burritoConsiderations: number }>();
|
||||
|
||||
export default async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
) {
|
||||
if (req.method !== 'POST') {
|
||||
return res.status(405).json({ error: 'Method not allowed' });
|
||||
}
|
||||
|
||||
const { username, password } = req.body;
|
||||
|
||||
if (!username || !password) {
|
||||
return res.status(400).json({ error: 'Username and password required' });
|
||||
}
|
||||
|
||||
let user = users.get(username);
|
||||
const isNewUser = !user;
|
||||
|
||||
if (!user) {
|
||||
user = { username, burritoConsiderations: 0 };
|
||||
users.set(username, user);
|
||||
}
|
||||
|
||||
// Capture server-side login event
|
||||
const posthog = getPostHogClient();
|
||||
posthog.capture({
|
||||
distinctId: username,
|
||||
event: 'server_login',
|
||||
properties: {
|
||||
username: username,
|
||||
isNewUser: isNewUser,
|
||||
source: 'api'
|
||||
}
|
||||
});
|
||||
|
||||
// Identify user on server side
|
||||
posthog.identify({
|
||||
distinctId: username,
|
||||
properties: {
|
||||
username: username,
|
||||
createdAt: isNewUser ? new Date().toISOString() : undefined
|
||||
}
|
||||
});
|
||||
|
||||
return res.status(200).json({ success: true, user });
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## src/pages/api/hello.ts
|
||||
|
||||
```ts
|
||||
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
|
||||
import type { NextApiRequest, NextApiResponse } from "next";
|
||||
|
||||
type Data = {
|
||||
name: string;
|
||||
};
|
||||
|
||||
export default function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse<Data>,
|
||||
) {
|
||||
res.status(200).json({ name: "John Doe" });
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## src/pages/burrito.tsx
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
import Head from 'next/head';
|
||||
import { useRouter } from 'next/router';
|
||||
import posthog from 'posthog-js';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import Header from '@/components/Header';
|
||||
|
||||
export default function BurritoPage() {
|
||||
const { user, incrementBurritoConsiderations } = useAuth();
|
||||
const router = useRouter();
|
||||
const [hasConsidered, setHasConsidered] = useState(false);
|
||||
|
||||
// Redirect to home if not logged in
|
||||
if (!user) {
|
||||
router.push('/');
|
||||
return null;
|
||||
}
|
||||
|
||||
const handleConsideration = () => {
|
||||
incrementBurritoConsiderations();
|
||||
setHasConsidered(true);
|
||||
setTimeout(() => setHasConsidered(false), 2000);
|
||||
|
||||
// Capture burrito consideration event
|
||||
posthog.capture('burrito_considered', {
|
||||
total_considerations: user.burritoConsiderations + 1,
|
||||
username: user.username,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Burrito Consideration - Burrito Consideration App</title>
|
||||
<meta name="description" content="Consider the potential of burritos" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<Header />
|
||||
<main>
|
||||
<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>
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## src/pages/index.tsx
|
||||
|
||||
```tsx
|
||||
import { useState } from 'react';
|
||||
import Head from 'next/head';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import Header from '@/components/Header';
|
||||
|
||||
export default 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');
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Head>
|
||||
<title>Burrito Consideration App</title>
|
||||
<meta name="description" content="Consider the potential of burritos" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<Header />
|
||||
<main>
|
||||
{user ? (
|
||||
<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>
|
||||
) : (
|
||||
<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>
|
||||
)}
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## src/pages/profile.tsx
|
||||
|
||||
```tsx
|
||||
import Head from 'next/head';
|
||||
import { useRouter } from 'next/router';
|
||||
import posthog from 'posthog-js';
|
||||
import { useAuth } from '@/contexts/AuthContext';
|
||||
import Header from '@/components/Header';
|
||||
|
||||
export default function ProfilePage() {
|
||||
const { user } = useAuth();
|
||||
const router = useRouter();
|
||||
|
||||
// Redirect to home if not logged in
|
||||
if (!user) {
|
||||
router.push('/');
|
||||
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 (
|
||||
<>
|
||||
<Head>
|
||||
<title>Profile - Burrito Consideration App</title>
|
||||
<meta name="description" content="Your burrito consideration profile" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<Header />
|
||||
<main>
|
||||
<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>
|
||||
</main>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -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]
|
||||
@@ -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
|
||||
@@ -0,0 +1,377 @@
|
||||
# Next.js - Docs
|
||||
|
||||
PostHog makes it easy to get data about traffic and usage of your [Next.js](https://nextjs.org/) app. Integrating PostHog into your site enables analytics about user behavior, custom events capture, session recordings, feature flags, and more.
|
||||
|
||||
This guide walks you through integrating PostHog into your Next.js app using the [React](/docs/libraries/react.md) and the [Node.js](/docs/libraries/node.md) SDKs.
|
||||
|
||||
> You can see a working example of this integration in our [Next.js demo app](https://github.com/PostHog/posthog-js/tree/main/playground/nextjs).
|
||||
|
||||
Next.js has both client and server-side rendering, as well as pages and app routers. We'll cover all of these options in this guide.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
To follow this guide along, you need:
|
||||
|
||||
1. A PostHog instance (either [Cloud](https://app.posthog.com/signup) or [self-hosted](/docs/self-host.md))
|
||||
2. A Next.js application
|
||||
|
||||
## Beta: integration via LLM
|
||||
|
||||
Install PostHog for Next.js in seconds with our wizard by running this prompt with [LLM coding agents](/blog/envoy-wizard-llm-agent.md) like Cursor and Bolt, or by running it in your terminal.
|
||||
|
||||
`npx @posthog/wizard@latest`
|
||||
|
||||
[Learn more](/wizard.md)
|
||||
|
||||
Or, to integrate manually, continue with the rest of this guide.
|
||||
|
||||
## Client-side setup
|
||||
|
||||
Install `posthog-js` using your package manager:
|
||||
|
||||
PostHog AI
|
||||
|
||||
### npm
|
||||
|
||||
```bash
|
||||
npm install --save posthog-js
|
||||
```
|
||||
|
||||
### Yarn
|
||||
|
||||
```bash
|
||||
yarn add posthog-js
|
||||
```
|
||||
|
||||
### pnpm
|
||||
|
||||
```bash
|
||||
pnpm add posthog-js
|
||||
```
|
||||
|
||||
### Bun
|
||||
|
||||
```bash
|
||||
bun add posthog-js
|
||||
```
|
||||
|
||||
Add your environment variables to your `.env.local` file and to your hosting provider (e.g. Vercel, Netlify, AWS). You can find your project token in your [project settings](https://app.posthog.com/project/settings).
|
||||
|
||||
.env.local
|
||||
|
||||
PostHog AI
|
||||
|
||||
```shell
|
||||
NEXT_PUBLIC_POSTHOG_TOKEN=<ph_project_token>
|
||||
NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
|
||||
```
|
||||
|
||||
These values need to start with `NEXT_PUBLIC_` to be accessible on the client-side.
|
||||
|
||||
## Integration
|
||||
|
||||
Next.js provides the [`instrumentation-client.ts|js`](https://nextjs.org/docs/app/api-reference/file-conventions/instrumentation-client) file for client-side setup. Add it to the root of your Next.js app (for both app and pages router) and initialize PostHog in it like this:
|
||||
|
||||
PostHog AI
|
||||
|
||||
### instrumentation-client.js
|
||||
|
||||
```javascript
|
||||
import posthog from 'posthog-js'
|
||||
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_TOKEN, {
|
||||
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
|
||||
defaults: '2026-01-30'
|
||||
});
|
||||
```
|
||||
|
||||
### instrumentation-client.ts
|
||||
|
||||
```typescript
|
||||
import posthog from 'posthog-js'
|
||||
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_TOKEN!, {
|
||||
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
|
||||
defaults: '2026-01-30'
|
||||
});
|
||||
```
|
||||
|
||||
Bootstrapping with `instrumentation-client`
|
||||
|
||||
When using `instrumentation-client`, the values you pass to `posthog.init` remain fixed for the entire session. This means bootstrapping only works if you evaluate flags **before your app renders** (for example, on the server).
|
||||
|
||||
If you need flag values after the app has rendered, you’ll want to:
|
||||
|
||||
- Evaluate the flag on the server and pass the value into your app, or
|
||||
- Evaluate the flag in an earlier page/state, then store and re-use it when needed.
|
||||
|
||||
Both approaches avoid flicker and give you the same outcome as bootstrapping, as long as you use the same `distinct_id` across client and server.
|
||||
|
||||
See the [bootstrapping guide](/docs/feature-flags/bootstrapping.md) for more information.
|
||||
|
||||
Set up a reverse proxy (recommended)
|
||||
|
||||
We recommend [setting up a reverse proxy](/docs/advanced/proxy.md), so that events are less likely to be intercepted by tracking blockers.
|
||||
|
||||
We have our [own managed reverse proxy service](/docs/advanced/proxy/managed-reverse-proxy.md), which is free for all PostHog Cloud users, routes through our infrastructure, and makes setting up your proxy easy.
|
||||
|
||||
If you don't want to use our managed service then there are several other options for creating a reverse proxy, including using [Cloudflare](/docs/advanced/proxy/cloudflare.md), [AWS Cloudfront](/docs/advanced/proxy/cloudfront.md), and [Vercel](/docs/advanced/proxy/vercel.md).
|
||||
|
||||
Grouping products in one project (recommended)
|
||||
|
||||
If you have multiple customer-facing products (e.g. a marketing website + mobile app + web app), it's best to install PostHog on them all and [group them in one project](/docs/settings/projects.md).
|
||||
|
||||
This makes it possible to track users across their entire journey (e.g. from visiting your marketing website to signing up for your product), or how they use your product across multiple platforms.
|
||||
|
||||
Add IPs to Firewall/WAF allowlists (recommended)
|
||||
|
||||
For certain features like [heatmaps](/docs/toolbar/heatmaps.md), your Web Application Firewall (WAF) may be blocking PostHog’s requests to your site. Add these IP addresses to your WAF allowlist or rules to let PostHog access your site.
|
||||
|
||||
**EU**: `3.75.65.221`, `18.197.246.42`, `3.120.223.253`
|
||||
|
||||
**US**: `44.205.89.55`, `52.4.194.122`, `44.208.188.173`
|
||||
|
||||
These are public, stable IPs used by PostHog services (e.g., Celery tasks for snapshots).
|
||||
|
||||
## Accessing PostHog
|
||||
|
||||
Once initialized in `instrumentation-client.js|ts`, import `posthog` from `posthog-js` anywhere and call the methods you need on the `posthog` object.
|
||||
|
||||
JavaScript
|
||||
|
||||
PostHog AI
|
||||
|
||||
```javascript
|
||||
'use client'
|
||||
import posthog from 'posthog-js'
|
||||
export default function Home() {
|
||||
return (
|
||||
<div>
|
||||
<button onClick={() => posthog.capture('test_event')}>
|
||||
Click me for an event
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Using React hooks
|
||||
|
||||
The [React feature flag hooks](/docs/libraries/react#feature-flags.md) work automatically when PostHog is initialized via `instrumentation-client.ts`. The hooks use the initialized posthog-js singleton:
|
||||
|
||||
JavaScript
|
||||
|
||||
PostHog AI
|
||||
|
||||
```javascript
|
||||
'use client'
|
||||
import { useFeatureFlagEnabled } from 'posthog-js/react'
|
||||
export default function FeatureComponent() {
|
||||
const showNewFeature = useFeatureFlagEnabled('new-feature')
|
||||
return showNewFeature ? <NewFeature /> : <OldFeature />
|
||||
}
|
||||
```
|
||||
|
||||
### Usage
|
||||
|
||||
See the [React SDK docs](/docs/libraries/react.md) for examples of how to use:
|
||||
|
||||
- [`posthog-js` functions like custom event capture, user identification, and more.](/docs/libraries/react#using-posthog-js-functions.md)
|
||||
- [Feature flags including variants and payloads.](/docs/libraries/react#feature-flags.md)
|
||||
|
||||
You can also read [the full `posthog-js` documentation](/docs/libraries/js/features.md) for all the usable functions.
|
||||
|
||||
## Server-side analytics
|
||||
|
||||
Next.js enables you to both server-side render pages and add server-side functionality. To integrate PostHog into your Next.js app on the server-side, you can use the [Node SDK](/docs/libraries/node.md).
|
||||
|
||||
First, install the `posthog-node` library:
|
||||
|
||||
PostHog AI
|
||||
|
||||
### npm
|
||||
|
||||
```bash
|
||||
npm install posthog-node --save
|
||||
```
|
||||
|
||||
### Yarn
|
||||
|
||||
```bash
|
||||
yarn add posthog-node
|
||||
```
|
||||
|
||||
### pnpm
|
||||
|
||||
```bash
|
||||
pnpm add posthog-node
|
||||
```
|
||||
|
||||
### Bun
|
||||
|
||||
```bash
|
||||
bun add posthog-node
|
||||
```
|
||||
|
||||
### Router-specific instructions
|
||||
|
||||
## App router
|
||||
|
||||
For the app router, we can initialize the `posthog-node` SDK once with a `PostHogClient` function, and import it into files.
|
||||
|
||||
This enables us to send events and fetch data from PostHog on the server – without making client-side requests.
|
||||
|
||||
JavaScript
|
||||
|
||||
PostHog AI
|
||||
|
||||
```javascript
|
||||
// app/posthog.js
|
||||
import { PostHog } from 'posthog-node'
|
||||
export default function PostHogClient() {
|
||||
const posthogClient = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_TOKEN, {
|
||||
host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
|
||||
flushAt: 1,
|
||||
flushInterval: 0
|
||||
})
|
||||
return posthogClient
|
||||
}
|
||||
```
|
||||
|
||||
> **Note:** Because server-side functions in Next.js can be short-lived, we set `flushAt` to `1` and `flushInterval` to `0`.
|
||||
>
|
||||
> - `flushAt` sets how many capture calls we should flush the queue (in one batch).
|
||||
> - `flushInterval` sets how many milliseconds we should wait before flushing the queue. Setting them to the lowest number ensures events are sent immediately and not batched. We also need to call `await posthog.shutdown()` once done.
|
||||
|
||||
To use this client, we import it into our pages and call it with the `PostHogClient` function:
|
||||
|
||||
JavaScript
|
||||
|
||||
PostHog AI
|
||||
|
||||
```javascript
|
||||
import Link from 'next/link'
|
||||
import PostHogClient from '../posthog'
|
||||
export default async function About() {
|
||||
const posthog = PostHogClient()
|
||||
const flags = await posthog.getAllFlags(
|
||||
'user_distinct_id' // replace with a user's distinct ID
|
||||
);
|
||||
await posthog.shutdown()
|
||||
return (
|
||||
<main>
|
||||
<h1>About</h1>
|
||||
<Link href="/">Go home</Link>
|
||||
{ flags['main-cta'] &&
|
||||
<Link href="http://posthog.com/">Go to PostHog</Link>
|
||||
}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
## Pages router
|
||||
|
||||
For the pages router, we can use the `getServerSideProps` function to access PostHog on the server-side, send events, evaluate feature flags, and more.
|
||||
|
||||
This looks like this:
|
||||
|
||||
JavaScript
|
||||
|
||||
PostHog AI
|
||||
|
||||
```javascript
|
||||
// pages/posts/[id].js
|
||||
import { useContext, useEffect, useState } from 'react'
|
||||
import { getServerSession } from "next-auth/next"
|
||||
import { PostHog } from 'posthog-node'
|
||||
export default function Post({ post, flags }) {
|
||||
const [ctaState, setCtaState] = useState()
|
||||
useEffect(() => {
|
||||
if (flags) {
|
||||
setCtaState(flags['blog-cta'])
|
||||
}
|
||||
})
|
||||
return (
|
||||
<div>
|
||||
<h1>{post.title}</h1>
|
||||
<p>By: {post.author}</p>
|
||||
<p>{post.content}</p>
|
||||
{ctaState &&
|
||||
<p><a href="/">Go to PostHog</a></p>
|
||||
}
|
||||
<button onClick={likePost}>Like</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
export async function getServerSideProps(ctx) {
|
||||
const session = await getServerSession(ctx.req, ctx.res)
|
||||
let flags = null
|
||||
if (session) {
|
||||
const client = new PostHog(
|
||||
process.env.NEXT_PUBLIC_POSTHOG_TOKEN,
|
||||
{
|
||||
host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
|
||||
}
|
||||
)
|
||||
flags = await client.getAllFlags(session.user.email);
|
||||
client.capture({
|
||||
distinctId: session.user.email,
|
||||
event: 'loaded blog article',
|
||||
properties: {
|
||||
$current_url: ctx.req.url,
|
||||
},
|
||||
});
|
||||
await client.shutdown()
|
||||
}
|
||||
const { posts } = await import('../../blog.json')
|
||||
const post = posts.find((post) => post.id.toString() === ctx.params.id)
|
||||
return {
|
||||
props: {
|
||||
post,
|
||||
flags
|
||||
},
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> **Note**: Make sure to *always* call `await client.shutdown()` after sending events from the server-side. PostHog queues events into larger batches, and this call forces all batched events to be flushed immediately.
|
||||
|
||||
### Server-side configuration
|
||||
|
||||
Next.js overrides the default `fetch` behavior on the server to introduce their own cache. PostHog ignores that cache by default, as this is Next.js's default behavior for any fetch call.
|
||||
|
||||
You can override that configuration when initializing PostHog, but make sure you understand the pros/cons of using Next.js's cache and that you might get cached results rather than the actual result our server would return. This is important for feature flags, for example.
|
||||
|
||||
TSX
|
||||
|
||||
PostHog AI
|
||||
|
||||
```jsx
|
||||
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_TOKEN, {
|
||||
// ... your configuration
|
||||
fetch_options: {
|
||||
cache: 'force-cache', // Use Next.js cache
|
||||
next_options: { // Passed to the `next` option for `fetch`
|
||||
revalidate: 60, // Cache for 60 seconds
|
||||
tags: ['posthog'], // Can be used with Next.js `revalidateTag` function
|
||||
},
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
## Configuring a reverse proxy to PostHog
|
||||
|
||||
To improve the reliability of client-side tracking and make requests less likely to be intercepted by tracking blockers, you can setup a reverse proxy in Next.js. Read more about deploying a reverse proxy using [Next.js rewrites](/docs/advanced/proxy/nextjs.md), [Next.js middleware](/docs/advanced/proxy/nextjs-middleware.md), and [Vercel rewrites](/docs/advanced/proxy/vercel.md).
|
||||
|
||||
## Further reading
|
||||
|
||||
- [How to set up Next.js analytics, feature flags, and more](/tutorials/nextjs-analytics.md)
|
||||
- [How to set up Next.js pages router analytics, feature flags, and more](/tutorials/nextjs-pages-analytics.md)
|
||||
- [How to set up Next.js A/B tests](/tutorials/nextjs-ab-tests.md)
|
||||
|
||||
### Community questions
|
||||
|
||||
Ask a question
|
||||
|
||||
### Was this page useful?
|
||||
|
||||
HelpfulCould be better
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -66,3 +66,4 @@ i18n.cache
|
||||
stats.html
|
||||
# next-agents-md
|
||||
.next-docs/
|
||||
.env
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
} from "date-fns";
|
||||
import { TFunction } from "i18next";
|
||||
import { Loader2 } from "lucide-react";
|
||||
import posthog from "posthog-js";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -257,6 +258,12 @@ export const CustomFilter = ({ survey }: CustomFilterProps) => {
|
||||
responsesDownloadUrlResponse.data.fileContents,
|
||||
fileType
|
||||
);
|
||||
posthog.capture("responses_exported", {
|
||||
surveyId: survey.id,
|
||||
surveyName: survey.name,
|
||||
format: fileType,
|
||||
filterType: filter === FilterDownload.ALL ? "all" : "filtered",
|
||||
});
|
||||
} else {
|
||||
toast.error(t("environments.surveys.responses.error_downloading_responses"));
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { z } from "zod";
|
||||
import { ZId } from "@formbricks/types/common";
|
||||
import { ZIntegrationInput } from "@formbricks/types/integration";
|
||||
import { createOrUpdateIntegration, deleteIntegration } from "@/lib/integration/service";
|
||||
import { getPostHogClient } from "@/lib/posthog-server";
|
||||
import { authenticatedActionClient } from "@/lib/utils/action-client";
|
||||
import { checkAuthorizationUpdated } from "@/lib/utils/action-client/action-client-middleware";
|
||||
import { AuthenticatedActionClientCtx } from "@/lib/utils/action-client/types/context";
|
||||
@@ -58,6 +59,18 @@ export const createOrUpdateIntegrationAction = authenticatedActionClient
|
||||
);
|
||||
ctx.auditLoggingCtx.integrationId = result.id;
|
||||
ctx.auditLoggingCtx.newObject = result;
|
||||
|
||||
const posthog = getPostHogClient();
|
||||
posthog.capture({
|
||||
distinctId: ctx.user.email,
|
||||
event: "integration_connected",
|
||||
properties: {
|
||||
integrationType: parsedInput.integrationData.type,
|
||||
environmentId: parsedInput.environmentId,
|
||||
organizationId,
|
||||
},
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
)
|
||||
|
||||
@@ -5,6 +5,7 @@ import { ResourceNotFoundError } from "@formbricks/types/errors";
|
||||
import { responses } from "@/app/lib/api/response";
|
||||
import { transformErrorToDetails } from "@/app/lib/api/validator";
|
||||
import { withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
|
||||
import { getPostHogClient } from "@/lib/posthog-server";
|
||||
import { getIsContactsEnabled } from "@/modules/ee/license-check/lib/utils";
|
||||
import { createDisplay } from "./lib/display";
|
||||
|
||||
@@ -58,6 +59,17 @@ export const POST = withV1ApiWrapper({
|
||||
try {
|
||||
const response = await createDisplay(inputValidation.data);
|
||||
|
||||
const posthog = getPostHogClient();
|
||||
posthog.capture({
|
||||
distinctId: params.environmentId,
|
||||
event: "survey_displayed",
|
||||
properties: {
|
||||
surveyId: inputValidation.data.surveyId,
|
||||
environmentId: params.environmentId,
|
||||
hasUserId: !!inputValidation.data.userId,
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
response: responses.successResponse(response, true),
|
||||
};
|
||||
|
||||
@@ -5,6 +5,7 @@ import { TJsEnvironmentState } from "@formbricks/types/js";
|
||||
import { cache } from "@/lib/cache";
|
||||
import { IS_FORMBRICKS_CLOUD, IS_RECAPTCHA_CONFIGURED, RECAPTCHA_SITE_KEY } from "@/lib/constants";
|
||||
import { getMonthlyOrganizationResponseCount } from "@/lib/organization/service";
|
||||
import { getPostHogClient } from "@/lib/posthog-server";
|
||||
import { getEnvironmentStateData } from "./data";
|
||||
|
||||
/**
|
||||
@@ -32,6 +33,15 @@ export const getEnvironmentState = async (
|
||||
where: { id: environmentId },
|
||||
data: { appSetupCompleted: true },
|
||||
});
|
||||
|
||||
getPostHogClient().capture({
|
||||
distinctId: environmentId,
|
||||
event: "formbricks_js_connected",
|
||||
properties: {
|
||||
environmentId,
|
||||
projectId: environment.project?.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Check monthly response limits for Formbricks Cloud
|
||||
|
||||
@@ -7,6 +7,7 @@ import { responses } from "@/app/lib/api/response";
|
||||
import { transformErrorToDetails } from "@/app/lib/api/validator";
|
||||
import { withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
|
||||
import { sendToPipeline } from "@/app/lib/pipelines";
|
||||
import { getPostHogClient } from "@/lib/posthog-server";
|
||||
import { getResponse } from "@/lib/response/service";
|
||||
import { getSurvey } from "@/lib/survey/service";
|
||||
import { formatValidationErrorsForV1Api, validateResponseData } from "@/modules/api/lib/validation";
|
||||
@@ -195,6 +196,19 @@ export const PUT = withV1ApiWrapper({
|
||||
surveyId: survey.id,
|
||||
response: responseData,
|
||||
});
|
||||
|
||||
const posthog = getPostHogClient();
|
||||
posthog.capture({
|
||||
distinctId: survey.environmentId,
|
||||
event: "survey_response_finished",
|
||||
properties: {
|
||||
surveyId: survey.id,
|
||||
surveyName: survey.name,
|
||||
surveyType: survey.type,
|
||||
environmentId: survey.environmentId,
|
||||
responseId: responseData.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const quotaObj = createQuotaFullObject(quotaFull);
|
||||
|
||||
@@ -11,6 +11,7 @@ import { responses } from "@/app/lib/api/response";
|
||||
import { transformErrorToDetails } from "@/app/lib/api/validator";
|
||||
import { withV1ApiWrapper } from "@/app/lib/api/with-api-logging";
|
||||
import { sendToPipeline } from "@/app/lib/pipelines";
|
||||
import { getPostHogClient } from "@/lib/posthog-server";
|
||||
import { getSurvey } from "@/lib/survey/service";
|
||||
import { getClientIpFromHeaders } from "@/lib/utils/client-ip";
|
||||
import { formatValidationErrorsForV1Api, validateResponseData } from "@/modules/api/lib/validation";
|
||||
@@ -197,6 +198,20 @@ export const POST = withV1ApiWrapper({
|
||||
response: responseData,
|
||||
});
|
||||
|
||||
const posthog = getPostHogClient();
|
||||
posthog.capture({
|
||||
distinctId: survey.environmentId,
|
||||
event: "survey_response_created",
|
||||
properties: {
|
||||
surveyId: survey.id,
|
||||
surveyName: survey.name,
|
||||
surveyType: survey.type,
|
||||
environmentId: survey.environmentId,
|
||||
responseId: responseData.id,
|
||||
finished: !!responseInput.finished,
|
||||
},
|
||||
});
|
||||
|
||||
if (responseInput.finished) {
|
||||
sendToPipeline({
|
||||
event: "responseFinished",
|
||||
@@ -204,6 +219,18 @@ export const POST = withV1ApiWrapper({
|
||||
surveyId: responseData.surveyId,
|
||||
response: responseData,
|
||||
});
|
||||
|
||||
posthog.capture({
|
||||
distinctId: survey.environmentId,
|
||||
event: "survey_response_finished",
|
||||
properties: {
|
||||
surveyId: survey.id,
|
||||
surveyName: survey.name,
|
||||
surveyType: survey.type,
|
||||
environmentId: survey.environmentId,
|
||||
responseId: responseData.id,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
const quotaObj = createQuotaFullObject(quotaFull);
|
||||
|
||||
9
apps/web/instrumentation-client.ts
Normal file
9
apps/web/instrumentation-client.ts
Normal file
@@ -0,0 +1,9 @@
|
||||
import posthog from "posthog-js";
|
||||
|
||||
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_TOKEN!, {
|
||||
api_host: "/ingest",
|
||||
ui_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
|
||||
defaults: "2026-01-30",
|
||||
capture_exceptions: true,
|
||||
debug: process.env.NODE_ENV === "development",
|
||||
});
|
||||
20
apps/web/lib/posthog-server.ts
Normal file
20
apps/web/lib/posthog-server.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { PostHog } from "posthog-node";
|
||||
|
||||
let posthogClient: PostHog | null = null;
|
||||
|
||||
export function getPostHogClient(): PostHog {
|
||||
if (!posthogClient) {
|
||||
posthogClient = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_TOKEN!, {
|
||||
host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
|
||||
flushAt: 1,
|
||||
flushInterval: 0,
|
||||
});
|
||||
}
|
||||
return posthogClient;
|
||||
}
|
||||
|
||||
export async function shutdownPostHog(): Promise<void> {
|
||||
if (posthogClient) {
|
||||
await posthogClient.shutdown();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { Copy, SquareArrowOutUpRight } from "lucide-react";
|
||||
import posthog from "posthog-js";
|
||||
import { toast } from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { TSurvey } from "@formbricks/types/surveys/types";
|
||||
@@ -69,6 +70,12 @@ export const ShareSurveyLink = ({
|
||||
aria-label={t("environments.surveys.copy_survey_link_to_clipboard")}
|
||||
onClick={() => {
|
||||
navigator.clipboard.writeText(surveyUrl);
|
||||
posthog.capture("survey_link_copied", {
|
||||
surveyId: survey.id,
|
||||
surveyName: survey.name,
|
||||
surveyType: survey.type,
|
||||
singleUse: survey.singleUse?.enabled ?? false,
|
||||
});
|
||||
toast.success(t("common.copied_to_clipboard"));
|
||||
}}>
|
||||
{t("common.copy")}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { signIn } from "next-auth/react";
|
||||
import Link from "next/dist/client/link";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import posthog from "posthog-js";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { FormProvider, SubmitHandler, useForm } from "react-hook-form";
|
||||
import { toast } from "react-hot-toast";
|
||||
@@ -119,9 +120,17 @@ export const LoginForm = ({
|
||||
}
|
||||
|
||||
if (!signInResponse?.error) {
|
||||
posthog.identify(data.email.toLowerCase(), {
|
||||
email: data.email.toLowerCase(),
|
||||
});
|
||||
posthog.capture("user_logged_in", {
|
||||
email: data.email.toLowerCase(),
|
||||
login_method: "email",
|
||||
});
|
||||
router.push(searchParams?.get("callbackUrl") ?? "/");
|
||||
}
|
||||
} catch (error) {
|
||||
posthog.captureException(error);
|
||||
toast.error(error.toString());
|
||||
}
|
||||
};
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import Link from "next/link";
|
||||
import { useRouter, useSearchParams } from "next/navigation";
|
||||
import posthog from "posthog-js";
|
||||
import { useMemo, useState } from "react";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import toast from "react-hot-toast";
|
||||
@@ -128,6 +129,17 @@ export const SignupForm = ({
|
||||
: `/auth/verification-requested?token=${token}`;
|
||||
|
||||
if (createUserResponse?.data) {
|
||||
posthog.identify(data.email, {
|
||||
email: data.email,
|
||||
name: data.name,
|
||||
});
|
||||
posthog.capture("user_signed_up", {
|
||||
email: data.email,
|
||||
name: data.name,
|
||||
email_verification_disabled: emailVerificationDisabled,
|
||||
has_invite_token: !!inviteToken,
|
||||
is_formbricks_cloud: isFormbricksCloud,
|
||||
});
|
||||
router.push(url);
|
||||
|
||||
if (!emailTokenActionResponse?.data) {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { logger } from "@formbricks/logger";
|
||||
import { ResourceNotFoundError } from "@formbricks/types/errors";
|
||||
import { BILLING_LIMITS, PROJECT_FEATURE_KEYS } from "@/lib/constants";
|
||||
import { getOrganization, updateOrganization } from "@/lib/organization/service";
|
||||
import { getPostHogClient } from "@/lib/posthog-server";
|
||||
import { getStripeClient } from "./stripe-client";
|
||||
|
||||
export const handleCheckoutSessionCompleted = async (event: Stripe.Event) => {
|
||||
@@ -54,6 +55,19 @@ export const handleCheckoutSessionCompleted = async (event: Stripe.Event) => {
|
||||
"Subscription activated"
|
||||
);
|
||||
|
||||
const posthog = getPostHogClient();
|
||||
posthog.capture({
|
||||
distinctId: checkoutSession.metadata.organizationId,
|
||||
event: "subscription_upgraded",
|
||||
properties: {
|
||||
organization_id: checkoutSession.metadata.organizationId,
|
||||
plan: PROJECT_FEATURE_KEYS.STARTUP,
|
||||
period,
|
||||
checkout_session_id: checkoutSession.id,
|
||||
},
|
||||
});
|
||||
await posthog.shutdown();
|
||||
|
||||
const stripeCustomer = await stripe.customers.retrieve(checkoutSession.customer as string);
|
||||
if (stripeCustomer && !stripeCustomer.deleted) {
|
||||
await stripe.customers.update(stripeCustomer.id, {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { logger } from "@formbricks/logger";
|
||||
import { ResourceNotFoundError } from "@formbricks/types/errors";
|
||||
import { BILLING_LIMITS, PROJECT_FEATURE_KEYS } from "@/lib/constants";
|
||||
import { getOrganization, updateOrganization } from "@/lib/organization/service";
|
||||
import { getPostHogClient } from "@/lib/posthog-server";
|
||||
|
||||
export const handleSubscriptionDeleted = async (event: Stripe.Event) => {
|
||||
const stripeSubscriptionObject = event.data.object as Stripe.Subscription;
|
||||
@@ -38,4 +39,16 @@ export const handleSubscriptionDeleted = async (event: Stripe.Event) => {
|
||||
},
|
||||
"Subscription cancelled - downgraded to FREE plan"
|
||||
);
|
||||
|
||||
const posthog = getPostHogClient();
|
||||
posthog.capture({
|
||||
distinctId: organizationId,
|
||||
event: "subscription_cancelled",
|
||||
properties: {
|
||||
organization_id: organizationId,
|
||||
subscription_id: stripeSubscriptionObject.id,
|
||||
downgraded_to_plan: PROJECT_FEATURE_KEYS.FREE,
|
||||
},
|
||||
});
|
||||
await posthog.shutdown();
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"use client";
|
||||
|
||||
import { useRouter } from "next/navigation";
|
||||
import posthog from "posthog-js";
|
||||
import { useEffect, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -107,6 +108,13 @@ export const PricingTable = ({
|
||||
};
|
||||
|
||||
const onUpgrade = async (planId: string) => {
|
||||
posthog.capture("upgrade_plan_clicked", {
|
||||
plan_id: planId,
|
||||
billing_period: planPeriod,
|
||||
current_plan: organization.billing.plan,
|
||||
organization_id: organization.id,
|
||||
});
|
||||
|
||||
if (planId === "startup") {
|
||||
await upgradePlan(
|
||||
planPeriod === "monthly"
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { parse } from "csv-parse/sync";
|
||||
import { ArrowUpFromLineIcon, FileUpIcon, PlusIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import posthog from "posthog-js";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -225,6 +226,11 @@ export const UploadContactsCSVButton = ({
|
||||
}
|
||||
|
||||
setError("");
|
||||
posthog.capture("contacts_imported", {
|
||||
environmentId,
|
||||
contactCount: csvResponse.length,
|
||||
duplicateAction: duplicateContactsAction,
|
||||
});
|
||||
toast.success(t("environments.contacts.upload_contacts_success"));
|
||||
resetState(true);
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { FilterIcon, PlusIcon, UsersIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import posthog from "posthog-js";
|
||||
import { useMemo, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -92,6 +93,10 @@ export function CreateSegmentModal({
|
||||
});
|
||||
|
||||
if (createSegmentResponse?.data) {
|
||||
posthog.capture("segment_created", {
|
||||
environmentId,
|
||||
filterCount: segment.filters.length,
|
||||
});
|
||||
toast.success(t("environments.segments.segment_saved_successfully"));
|
||||
handleResetState();
|
||||
router.refresh();
|
||||
|
||||
@@ -4,6 +4,7 @@ import { PipelineTriggers, Webhook } from "@prisma/client";
|
||||
import clsx from "clsx";
|
||||
import { Webhook as WebhookIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import posthog from "posthog-js";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import toast from "react-hot-toast";
|
||||
@@ -155,6 +156,11 @@ export const AddWebhookModal = ({ environmentId, surveys, open, setOpen }: AddWe
|
||||
if (createWebhookActionResult?.data) {
|
||||
router.refresh();
|
||||
setCreatedWebhook(createWebhookActionResult.data);
|
||||
posthog.capture("webhook_created", {
|
||||
environmentId,
|
||||
triggers: selectedTriggers,
|
||||
surveyCount: selectedAllSurveys ? "all" : selectedSurveys.length,
|
||||
});
|
||||
toast.success(t("environments.integrations.webhooks.webhook_added_successfully"));
|
||||
} else {
|
||||
const errorMessage = getFormattedErrorMessage(createWebhookActionResult);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { ApiKeyPermission } from "@prisma/client";
|
||||
import { ChevronDownIcon, Trash2Icon } from "lucide-react";
|
||||
import posthog from "posthog-js";
|
||||
import { useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "react-hot-toast";
|
||||
@@ -173,6 +174,10 @@ export const AddApiKeyModal = ({
|
||||
organizationAccess: selectedOrganizationAccess,
|
||||
});
|
||||
|
||||
posthog.capture("api_key_created", {
|
||||
permissionCount: environmentPermissions.length,
|
||||
});
|
||||
|
||||
reset();
|
||||
setSelectedPermissions({});
|
||||
setSelectedOrganizationAccess(defaultOrganizationAccess);
|
||||
|
||||
@@ -4,6 +4,7 @@ import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { OrganizationRole } from "@prisma/client";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import posthog from "posthog-js";
|
||||
import { FormProvider, useForm } from "react-hook-form";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { z } from "zod";
|
||||
@@ -90,6 +91,11 @@ export const IndividualInviteTab = ({
|
||||
const submitEventClass = async () => {
|
||||
const data = getValues();
|
||||
data.role = data.role || OrganizationRole.owner;
|
||||
posthog.capture("member_invited", {
|
||||
invitee_email: data.email,
|
||||
invitee_role: data.role,
|
||||
team_count: data.teamIds?.length ?? 0,
|
||||
});
|
||||
onSubmit([data]);
|
||||
router.refresh();
|
||||
setOpen(false);
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useRouter } from "next/navigation";
|
||||
import posthog from "posthog-js";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { toast } from "react-hot-toast";
|
||||
@@ -102,6 +103,13 @@ export const CreateProjectModal = ({
|
||||
);
|
||||
|
||||
if (productionEnvironment) {
|
||||
posthog.capture("workspace_created", {
|
||||
project_id: createProjectResponse.data.id,
|
||||
project_name: data.name,
|
||||
organization_id: organizationId,
|
||||
environment_id: productionEnvironment.id,
|
||||
team_count: data.teamIds?.length ?? 0,
|
||||
});
|
||||
toast.success(t("common.workspace_created_successfully"));
|
||||
setOpen(false);
|
||||
form.reset();
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import { zodResolver } from "@hookform/resolvers/zod";
|
||||
import { useRouter } from "next/navigation";
|
||||
import posthog from "posthog-js";
|
||||
import { useState } from "react";
|
||||
import { SubmitHandler, useForm } from "react-hook-form";
|
||||
import { toast } from "react-hot-toast";
|
||||
@@ -36,9 +37,14 @@ export const CreateOrganization = () => {
|
||||
setIsSubmitting(true);
|
||||
const createOrganizationResponse = await createOrganizationAction({ organizationName });
|
||||
if (createOrganizationResponse?.data) {
|
||||
posthog.capture("organization_created", {
|
||||
organization_id: createOrganizationResponse.data.id,
|
||||
organization_name: organizationName,
|
||||
});
|
||||
router.push(`/setup/organization/${createOrganizationResponse.data.id}/invite`);
|
||||
}
|
||||
} catch (error) {
|
||||
posthog.captureException(error);
|
||||
toast.error("Some error occurred while creating organization");
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useAutoAnimate } from "@formkit/auto-animate/react";
|
||||
import { Environment } from "@prisma/client";
|
||||
import * as Collapsible from "@radix-ui/react-collapsible";
|
||||
import { CheckIcon, LinkIcon, MonitorIcon } from "lucide-react";
|
||||
import posthog from "posthog-js";
|
||||
import { useEffect, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { TSegment } from "@formbricks/types/segment";
|
||||
@@ -42,6 +43,11 @@ export const HowToSendCard = ({ localSurvey, setLocalSurvey, environment }: HowT
|
||||
endings: endingsTemp,
|
||||
}));
|
||||
|
||||
posthog.capture("survey_type_selected", {
|
||||
surveyId: localSurvey.id,
|
||||
surveyType: type,
|
||||
});
|
||||
|
||||
// if the type is "app" and the local survey does not already have a segment, we create a new temporary segment
|
||||
if (type === "app" && !localSurvey.segment) {
|
||||
const tempSegment: TSegment = {
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Project } from "@prisma/client";
|
||||
import { isEqual } from "lodash";
|
||||
import { ArrowLeftIcon, SettingsIcon } from "lucide-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import posthog from "posthog-js";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -379,6 +380,12 @@ export const SurveyMenuBar = ({
|
||||
setIsSurveySaving(false);
|
||||
if (updatedSurveyResponse?.data) {
|
||||
setLocalSurvey(updatedSurveyResponse.data);
|
||||
posthog.capture("survey_saved", {
|
||||
survey_id: localSurvey.id,
|
||||
survey_name: localSurvey.name,
|
||||
survey_type: localSurvey.type,
|
||||
environment_id: environmentId,
|
||||
});
|
||||
toast.success(t("environments.surveys.edit.changes_saved"));
|
||||
// Set flag to prevent beforeunload warning during router.refresh()
|
||||
isSuccessfullySavedRef.current = true;
|
||||
@@ -391,6 +398,7 @@ export const SurveyMenuBar = ({
|
||||
|
||||
return true;
|
||||
} catch (e) {
|
||||
posthog.captureException(e);
|
||||
console.error(e);
|
||||
setIsSurveySaving(false);
|
||||
toast.error(t("environments.surveys.edit.error_saving_changes"));
|
||||
@@ -438,11 +446,18 @@ export const SurveyMenuBar = ({
|
||||
return;
|
||||
}
|
||||
|
||||
posthog.capture("survey_published", {
|
||||
survey_id: localSurvey.id,
|
||||
survey_name: localSurvey.name,
|
||||
survey_type: localSurvey.type,
|
||||
environment_id: environmentId,
|
||||
});
|
||||
setIsSurveyPublishing(false);
|
||||
// Set flag to prevent beforeunload warning during navigation
|
||||
isSuccessfullySavedRef.current = true;
|
||||
router.push(`/environments/${environmentId}/surveys/${localSurvey.id}/summary?success=true`);
|
||||
} catch (error) {
|
||||
posthog.captureException(error);
|
||||
console.error(error);
|
||||
toast.error(t("environments.surveys.edit.error_publishing_survey"));
|
||||
setIsSurveyPublishing(false);
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from "lucide-react";
|
||||
import Link from "next/link";
|
||||
import { useRouter } from "next/navigation";
|
||||
import posthog from "posthog-js";
|
||||
import { useMemo, useState } from "react";
|
||||
import toast from "react-hot-toast";
|
||||
import { useTranslation } from "react-i18next";
|
||||
@@ -74,9 +75,16 @@ export const SurveyDropDownMenu = ({
|
||||
toast.error(getFormattedErrorMessage(result));
|
||||
return;
|
||||
}
|
||||
posthog.capture("survey_deleted", {
|
||||
survey_id: surveyId,
|
||||
survey_name: survey.name,
|
||||
survey_type: survey.type,
|
||||
environment_id: environmentId,
|
||||
});
|
||||
deleteSurvey(surveyId);
|
||||
toast.success(t("environments.surveys.survey_deleted_successfully"));
|
||||
} catch (error) {
|
||||
posthog.captureException(error);
|
||||
toast.error(t("environments.surveys.error_deleting_survey"));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
@@ -112,12 +120,20 @@ export const SurveyDropDownMenu = ({
|
||||
if (transformedDuplicatedSurvey?.data) {
|
||||
onSurveysCopied?.();
|
||||
}
|
||||
posthog.capture("survey_duplicated", {
|
||||
original_survey_id: surveyId,
|
||||
new_survey_id: duplicatedSurveyResponse.data.id,
|
||||
survey_name: survey.name,
|
||||
survey_type: survey.type,
|
||||
environment_id: environmentId,
|
||||
});
|
||||
toast.success(t("environments.surveys.survey_duplicated_successfully"));
|
||||
} else {
|
||||
const errorMessage = getFormattedErrorMessage(duplicatedSurveyResponse);
|
||||
toast.error(errorMessage);
|
||||
}
|
||||
} catch (error) {
|
||||
posthog.captureException(error);
|
||||
toast.error(t("environments.surveys.survey_duplication_error"));
|
||||
}
|
||||
setLoading(false);
|
||||
|
||||
@@ -48,6 +48,7 @@ const nextConfig = {
|
||||
],
|
||||
},
|
||||
turbopack: {},
|
||||
skipTrailingSlashRedirect: true,
|
||||
experimental: {},
|
||||
transpilePackages: ["@formbricks/database"],
|
||||
images: {
|
||||
@@ -406,6 +407,14 @@ const nextConfig = {
|
||||
},
|
||||
async rewrites() {
|
||||
return [
|
||||
{
|
||||
source: "/ingest/static/:path*",
|
||||
destination: "https://eu-assets.i.posthog.com/static/:path*",
|
||||
},
|
||||
{
|
||||
source: "/ingest/:path*",
|
||||
destination: "https://eu.i.posthog.com/:path*",
|
||||
},
|
||||
{
|
||||
source: "/api/packages/website",
|
||||
destination: "/js/formbricks.umd.cjs",
|
||||
|
||||
@@ -102,6 +102,8 @@
|
||||
"nodemailer": "8.0.1",
|
||||
"otplib": "12.0.1",
|
||||
"papaparse": "5.5.3",
|
||||
"posthog-js": "1.360.0",
|
||||
"posthog-node": "5.28.0",
|
||||
"prismjs": "1.30.0",
|
||||
"qr-code-styling": "1.9.2",
|
||||
"qrcode": "1.5.4",
|
||||
|
||||
185
pnpm-lock.yaml
generated
185
pnpm-lock.yaml
generated
@@ -360,6 +360,12 @@ importers:
|
||||
papaparse:
|
||||
specifier: 5.5.3
|
||||
version: 5.5.3
|
||||
posthog-js:
|
||||
specifier: 1.360.0
|
||||
version: 1.360.0
|
||||
posthog-node:
|
||||
specifier: 5.28.0
|
||||
version: 5.28.0(rxjs@7.8.2)
|
||||
prismjs:
|
||||
specifier: 1.30.0
|
||||
version: 1.30.0
|
||||
@@ -2795,6 +2801,12 @@ packages:
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': '>=1.0.0 <1.10.0'
|
||||
|
||||
'@opentelemetry/core@2.2.0':
|
||||
resolution: {integrity: sha512-FuabnnUm8LflnieVxs6eP7Z383hgQU4W1e3KJS6aOG3RxWxcHyBxH8fDMHNgu/gFx/M2jvTOW/4/PHhLz6bjWw==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': '>=1.0.0 <1.10.0'
|
||||
|
||||
'@opentelemetry/core@2.5.0':
|
||||
resolution: {integrity: sha512-ka4H8OM6+DlUhSAZpONu0cPBtPPTQKxbxVzC4CzVx5+K4JnroJVBtDzLAMx4/3CDTJXRvVFhpFjtl4SaiTNoyQ==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
@@ -2825,6 +2837,12 @@ packages:
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': ^1.3.0
|
||||
|
||||
'@opentelemetry/exporter-logs-otlp-http@0.208.0':
|
||||
resolution: {integrity: sha512-jOv40Bs9jy9bZVLo/i8FwUiuCvbjWDI+ZW13wimJm4LjnlwJxGgB+N/VWOZUTpM+ah/awXeQqKdNlpLf2EjvYg==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': ^1.3.0
|
||||
|
||||
'@opentelemetry/exporter-logs-otlp-http@0.212.0':
|
||||
resolution: {integrity: sha512-JidJasLwG/7M9RTxV/64xotDKmFAUSBc9SNlxI32QYuUMK5rVKhHNWMPDzC7E0pCAL3cu+FyiKvsTwLi2KqPYw==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
@@ -3311,6 +3329,12 @@ packages:
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': ^1.3.0
|
||||
|
||||
'@opentelemetry/otlp-exporter-base@0.208.0':
|
||||
resolution: {integrity: sha512-gMd39gIfVb2OgxldxUtOwGJYSH8P1kVFFlJLuut32L6KgUC4gl1dMhn+YC2mGn0bDOiQYSk/uHOdSjuKp58vvA==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': ^1.3.0
|
||||
|
||||
'@opentelemetry/otlp-exporter-base@0.212.0':
|
||||
resolution: {integrity: sha512-HoMv5pQlzbuxiMS0hN7oiUtg8RsJR5T7EhZccumIWxYfNo/f4wFc7LPDfFK6oHdG2JF/+qTocfqIHoom+7kLpw==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
@@ -3347,6 +3371,12 @@ packages:
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': ^1.3.0
|
||||
|
||||
'@opentelemetry/otlp-transformer@0.208.0':
|
||||
resolution: {integrity: sha512-DCFPY8C6lAQHUNkzcNT9R+qYExvsk6C5Bto2pbNxgicpcSWbe2WHShLxkOxIdNcBiYPdVHv/e7vH7K6TI+C+fQ==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': ^1.3.0
|
||||
|
||||
'@opentelemetry/otlp-transformer@0.212.0':
|
||||
resolution: {integrity: sha512-bj7zYFOg6Db7NUwsRZQ/WoVXpAf41WY2gsd3kShSfdpZQDRKHWJiRZIg7A8HvWsf97wb05rMFzPbmSHyjEl9tw==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
@@ -3417,6 +3447,12 @@ packages:
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': '>=1.0.0 <1.10.0'
|
||||
|
||||
'@opentelemetry/resources@2.2.0':
|
||||
resolution: {integrity: sha512-1pNQf/JazQTMA0BiO5NINUzH0cbLbbl7mntLa4aJNmCCXSj0q03T5ZXXL0zw4G55TjdL9Tz32cznGClf+8zr5A==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': '>=1.3.0 <1.10.0'
|
||||
|
||||
'@opentelemetry/resources@2.5.1':
|
||||
resolution: {integrity: sha512-BViBCdE/GuXRlp9k7nS1w6wJvY5fnFX5XvuEtWsTAOQFIO89Eru7lGW3WbfbxtCuZ/GbrJfAziXG0w0dpxL7eQ==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
@@ -3429,6 +3465,12 @@ packages:
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': '>=1.3.0 <1.10.0'
|
||||
|
||||
'@opentelemetry/sdk-logs@0.208.0':
|
||||
resolution: {integrity: sha512-QlAyL1jRpOeaqx7/leG1vJMp84g0xKP6gJmfELBpnI4O/9xPX+Hu5m1POk9Kl+veNkyth5t19hRlN6tNY1sjbA==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': '>=1.4.0 <1.10.0'
|
||||
|
||||
'@opentelemetry/sdk-logs@0.212.0':
|
||||
resolution: {integrity: sha512-qglb5cqTf0mOC1sDdZ7nfrPjgmAqs2OxkzOPIf2+Rqx8yKBK0pS7wRtB1xH30rqahBIut9QJDbDePyvtyqvH/Q==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
@@ -3453,6 +3495,12 @@ packages:
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': '>=1.3.0 <1.10.0'
|
||||
|
||||
'@opentelemetry/sdk-metrics@2.2.0':
|
||||
resolution: {integrity: sha512-G5KYP6+VJMZzpGipQw7Giif48h6SGQ2PFKEYCybeXJsOCB4fp8azqMAAzE5lnnHK3ZVwYQrgmFbsUJO/zOnwGw==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': '>=1.9.0 <1.10.0'
|
||||
|
||||
'@opentelemetry/sdk-metrics@2.5.1':
|
||||
resolution: {integrity: sha512-RKMn3QKi8nE71ULUo0g/MBvq1N4icEBo7cQSKnL3URZT16/YH3nSVgWegOjwx7FRBTrjOIkMJkCUn/ZFIEfn4A==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
@@ -3477,6 +3525,12 @@ packages:
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': '>=1.0.0 <1.10.0'
|
||||
|
||||
'@opentelemetry/sdk-trace-base@2.2.0':
|
||||
resolution: {integrity: sha512-xWQgL0Bmctsalg6PaXExmzdedSp3gyKV8mQBwK/j9VGdCDu2fmXIb2gAehBKbkXCpJ4HPkgv3QfoJWRT4dHWbw==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
peerDependencies:
|
||||
'@opentelemetry/api': '>=1.3.0 <1.10.0'
|
||||
|
||||
'@opentelemetry/sdk-trace-base@2.5.1':
|
||||
resolution: {integrity: sha512-iZH3Gw8cxQn0gjpOjJMmKLd9GIaNh/E3v3ST67vyzLSxHBs14HsG4dy7jMYyC5WXGdBVEcM7U/XTF5hCQxjDMw==}
|
||||
engines: {node: ^18.19.0 || >=20.6.0}
|
||||
@@ -3553,6 +3607,12 @@ packages:
|
||||
engines: {node: '>=18'}
|
||||
hasBin: true
|
||||
|
||||
'@posthog/core@1.23.2':
|
||||
resolution: {integrity: sha512-zTDdda9NuSHrnwSOfFMxX/pyXiycF4jtU1kTr8DL61dHhV+7LF6XF1ndRZZTuaGGbfbb/GJYkEsjEX9SXfNZeQ==}
|
||||
|
||||
'@posthog/types@1.360.0':
|
||||
resolution: {integrity: sha512-roypbiJ49V3jWlV/lzhXGf0cKLLRj69L4H4ZHW6YsITHlnjQ12cgdPhPS88Bb9nW9xZTVSGWWDjfNGsdgAxsNg==}
|
||||
|
||||
'@preact/preset-vite@2.10.3':
|
||||
resolution: {integrity: sha512-1SiS+vFItpkNdBs7q585PSAIln0wBeBdcpJYbzPs1qipsb/FssnkUioNXuRsb8ZnU8YEQHr+3v8+/mzWSnTQmg==}
|
||||
peerDependencies:
|
||||
@@ -6946,6 +7006,9 @@ packages:
|
||||
core-js-compat@3.47.0:
|
||||
resolution: {integrity: sha512-IGfuznZ/n7Kp9+nypamBhvwdwLsW6KC8IOaURw2doAK5e98AG3acVLdh0woOnEqCfUtS+Vu882JE4k/DAm3ItQ==}
|
||||
|
||||
core-js@3.48.0:
|
||||
resolution: {integrity: sha512-zpEHTy1fjTMZCKLHUZoVeylt9XrzaIN2rbPXEt0k+q7JE5CkCZdo6bNq55bn24a69CH7ErAVLKijxJja4fw+UQ==}
|
||||
|
||||
core-util-is@1.0.3:
|
||||
resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==}
|
||||
|
||||
@@ -7214,6 +7277,10 @@ packages:
|
||||
dompurify@3.3.1:
|
||||
resolution: {integrity: sha512-qkdCKzLNtrgPFP1Vo+98FRzJnBRGe4ffyCea9IwHB1fyxPOeNTHpLKYGd4Uk9xvNoH0ZoOjwZxNptyMwqrId1Q==}
|
||||
|
||||
dompurify@3.3.2:
|
||||
resolution: {integrity: sha512-6obghkliLdmKa56xdbLOpUZ43pAR6xFy1uOrxBaIDjT+yaRuuybLjGS9eVBoSR/UPU5fq3OXClEHLJNGvbxKpQ==}
|
||||
engines: {node: '>=20'}
|
||||
|
||||
domutils@3.2.2:
|
||||
resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==}
|
||||
|
||||
@@ -7728,6 +7795,9 @@ packages:
|
||||
resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==}
|
||||
engines: {node: ^12.20 || >= 14.13}
|
||||
|
||||
fflate@0.4.8:
|
||||
resolution: {integrity: sha512-FJqqoDBR00Mdj9ppamLa/Y7vxm+PRmNWA67N846RvsoYVMKB4q3y/de5PA7gUmRMYK/8CMz2GDZQmCRN1wBcWA==}
|
||||
|
||||
file-entry-cache@6.0.1:
|
||||
resolution: {integrity: sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==}
|
||||
engines: {node: ^10.12.0 || >=12.0.0}
|
||||
@@ -9584,6 +9654,18 @@ packages:
|
||||
resolution: {integrity: sha512-Jtc2612XINuBjIl/QTWsV5UvE8UHuNblcO3vVADSrKsrc6RqGX6lOW1cEo3CM2v0XG4Nat8nI+YM7/f26VxXLw==}
|
||||
engines: {node: '>=12'}
|
||||
|
||||
posthog-js@1.360.0:
|
||||
resolution: {integrity: sha512-jkyO+T97yi6RuiexOaXC7AnEGiC+yIfGU5DIUzI5rqBH6MltmtJw/ve2Oxc4jeua2WDr5sXMzo+SS+acbpueAA==}
|
||||
|
||||
posthog-node@5.28.0:
|
||||
resolution: {integrity: sha512-EETYV0zA+7BLQmXzY+vGyDMoQK8uHf8f/1utbRjKncI41gPkw+4piGP7l4UT5Luld+4vQpJPOR1q1YrbXm7XjQ==}
|
||||
engines: {node: ^20.20.0 || >=22.22.0}
|
||||
peerDependencies:
|
||||
rxjs: ^7.0.0
|
||||
peerDependenciesMeta:
|
||||
rxjs:
|
||||
optional: true
|
||||
|
||||
powershell-utils@0.1.0:
|
||||
resolution: {integrity: sha512-dM0jVuXJPsDN6DvRpea484tCUaMiXWjuCn++HGTqUWzGDjv5tZkEZldAJ/UMlqRYGFrD/etByo4/xOuC/snX2A==}
|
||||
engines: {node: '>=20'}
|
||||
@@ -9802,6 +9884,9 @@ packages:
|
||||
quansync@0.2.11:
|
||||
resolution: {integrity: sha512-AifT7QEbW9Nri4tAwR5M/uzpBuqfZf+zwaEM/QkzEjj7NBuFD2rBuy0K3dE+8wltbezDV7JMA0WfnCPYRSYbXA==}
|
||||
|
||||
query-selector-shadow-dom@1.0.1:
|
||||
resolution: {integrity: sha512-lT5yCqEBgfoMYpf3F2xQRK7zEr1rhIIZuceDK6+xRkJQ4NMbHTwXqk4NkwDwQMNqXgG9r9fyHnzwNVs6zV5KRw==}
|
||||
|
||||
queue-microtask@1.2.3:
|
||||
resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==}
|
||||
|
||||
@@ -11186,6 +11271,9 @@ packages:
|
||||
resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}
|
||||
engines: {node: '>= 8'}
|
||||
|
||||
web-vitals@5.1.0:
|
||||
resolution: {integrity: sha512-ArI3kx5jI0atlTtmV0fWU3fjpLmq/nD3Zr1iFFlJLaqa5wLBkUSzINwBPySCX/8jRyjlmy1Volw1kz1g9XE4Jg==}
|
||||
|
||||
webidl-conversions@3.0.1:
|
||||
resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==}
|
||||
|
||||
@@ -13971,6 +14059,11 @@ snapshots:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
'@opentelemetry/semantic-conventions': 1.28.0
|
||||
|
||||
'@opentelemetry/core@2.2.0(@opentelemetry/api@1.9.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
'@opentelemetry/semantic-conventions': 1.40.0
|
||||
|
||||
'@opentelemetry/core@2.5.0(@opentelemetry/api@1.9.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
@@ -14006,6 +14099,15 @@ snapshots:
|
||||
'@opentelemetry/otlp-transformer': 0.213.0(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/sdk-logs': 0.213.0(@opentelemetry/api@1.9.0)
|
||||
|
||||
'@opentelemetry/exporter-logs-otlp-http@0.208.0(@opentelemetry/api@1.9.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
'@opentelemetry/api-logs': 0.208.0
|
||||
'@opentelemetry/core': 2.2.0(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/otlp-exporter-base': 0.208.0(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/otlp-transformer': 0.208.0(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/api@1.9.0)
|
||||
|
||||
'@opentelemetry/exporter-logs-otlp-http@0.212.0(@opentelemetry/api@1.9.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
@@ -14719,6 +14821,12 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@opentelemetry/otlp-exporter-base@0.208.0(@opentelemetry/api@1.9.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
'@opentelemetry/core': 2.2.0(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/otlp-transformer': 0.208.0(@opentelemetry/api@1.9.0)
|
||||
|
||||
'@opentelemetry/otlp-exporter-base@0.212.0(@opentelemetry/api@1.9.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
@@ -14761,6 +14869,17 @@ snapshots:
|
||||
'@opentelemetry/otlp-exporter-base': 0.57.1(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/otlp-transformer': 0.57.1(@opentelemetry/api@1.9.0)
|
||||
|
||||
'@opentelemetry/otlp-transformer@0.208.0(@opentelemetry/api@1.9.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
'@opentelemetry/api-logs': 0.208.0
|
||||
'@opentelemetry/core': 2.2.0(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/resources': 2.2.0(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/sdk-metrics': 2.2.0(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/sdk-trace-base': 2.2.0(@opentelemetry/api@1.9.0)
|
||||
protobufjs: 7.5.4
|
||||
|
||||
'@opentelemetry/otlp-transformer@0.212.0(@opentelemetry/api@1.9.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
@@ -14847,6 +14966,12 @@ snapshots:
|
||||
'@opentelemetry/core': 1.30.1(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/semantic-conventions': 1.28.0
|
||||
|
||||
'@opentelemetry/resources@2.2.0(@opentelemetry/api@1.9.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
'@opentelemetry/core': 2.2.0(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/semantic-conventions': 1.40.0
|
||||
|
||||
'@opentelemetry/resources@2.5.1(@opentelemetry/api@1.9.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
@@ -14859,6 +14984,13 @@ snapshots:
|
||||
'@opentelemetry/core': 2.6.0(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/semantic-conventions': 1.40.0
|
||||
|
||||
'@opentelemetry/sdk-logs@0.208.0(@opentelemetry/api@1.9.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
'@opentelemetry/api-logs': 0.208.0
|
||||
'@opentelemetry/core': 2.2.0(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/resources': 2.2.0(@opentelemetry/api@1.9.0)
|
||||
|
||||
'@opentelemetry/sdk-logs@0.212.0(@opentelemetry/api@1.9.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
@@ -14887,6 +15019,12 @@ snapshots:
|
||||
'@opentelemetry/core': 1.30.1(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/resources': 1.30.1(@opentelemetry/api@1.9.0)
|
||||
|
||||
'@opentelemetry/sdk-metrics@2.2.0(@opentelemetry/api@1.9.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
'@opentelemetry/core': 2.2.0(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/resources': 2.2.0(@opentelemetry/api@1.9.0)
|
||||
|
||||
'@opentelemetry/sdk-metrics@2.5.1(@opentelemetry/api@1.9.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
@@ -14936,6 +15074,13 @@ snapshots:
|
||||
'@opentelemetry/resources': 1.30.1(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/semantic-conventions': 1.28.0
|
||||
|
||||
'@opentelemetry/sdk-trace-base@2.2.0(@opentelemetry/api@1.9.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
'@opentelemetry/core': 2.2.0(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/resources': 2.2.0(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/semantic-conventions': 1.40.0
|
||||
|
||||
'@opentelemetry/sdk-trace-base@2.5.1(@opentelemetry/api@1.9.0)':
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
@@ -15008,6 +15153,12 @@ snapshots:
|
||||
dependencies:
|
||||
playwright: 1.58.2
|
||||
|
||||
'@posthog/core@1.23.2':
|
||||
dependencies:
|
||||
cross-spawn: 7.0.6
|
||||
|
||||
'@posthog/types@1.360.0': {}
|
||||
|
||||
'@preact/preset-vite@2.10.3(@babel/core@7.29.0)(preact@10.28.2)(rollup@4.59.0)(vite@7.3.1(@types/node@25.3.3)(jiti@2.6.1)(lightningcss@1.31.1)(terser@5.46.0)(tsx@4.21.0)(yaml@2.8.2))':
|
||||
dependencies:
|
||||
'@babel/core': 7.29.0
|
||||
@@ -18788,6 +18939,8 @@ snapshots:
|
||||
dependencies:
|
||||
browserslist: 4.28.1
|
||||
|
||||
core-js@3.48.0: {}
|
||||
|
||||
core-util-is@1.0.3: {}
|
||||
|
||||
cors@2.8.5:
|
||||
@@ -19028,6 +19181,10 @@ snapshots:
|
||||
optionalDependencies:
|
||||
'@types/trusted-types': 2.0.7
|
||||
|
||||
dompurify@3.3.2:
|
||||
optionalDependencies:
|
||||
'@types/trusted-types': 2.0.7
|
||||
|
||||
domutils@3.2.2:
|
||||
dependencies:
|
||||
dom-serializer: 2.0.0
|
||||
@@ -19792,6 +19949,8 @@ snapshots:
|
||||
node-domexception: 1.0.0
|
||||
web-streams-polyfill: 3.3.3
|
||||
|
||||
fflate@0.4.8: {}
|
||||
|
||||
file-entry-cache@6.0.1:
|
||||
dependencies:
|
||||
flat-cache: 3.2.0
|
||||
@@ -21784,6 +21943,28 @@ snapshots:
|
||||
postgres@3.4.7:
|
||||
optional: true
|
||||
|
||||
posthog-js@1.360.0:
|
||||
dependencies:
|
||||
'@opentelemetry/api': 1.9.0
|
||||
'@opentelemetry/api-logs': 0.208.0
|
||||
'@opentelemetry/exporter-logs-otlp-http': 0.208.0(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/resources': 2.6.0(@opentelemetry/api@1.9.0)
|
||||
'@opentelemetry/sdk-logs': 0.208.0(@opentelemetry/api@1.9.0)
|
||||
'@posthog/core': 1.23.2
|
||||
'@posthog/types': 1.360.0
|
||||
core-js: 3.48.0
|
||||
dompurify: 3.3.2
|
||||
fflate: 0.4.8
|
||||
preact: 10.28.2
|
||||
query-selector-shadow-dom: 1.0.1
|
||||
web-vitals: 5.1.0
|
||||
|
||||
posthog-node@5.28.0(rxjs@7.8.2):
|
||||
dependencies:
|
||||
'@posthog/core': 1.23.2
|
||||
optionalDependencies:
|
||||
rxjs: 7.8.2
|
||||
|
||||
powershell-utils@0.1.0: {}
|
||||
|
||||
preact-render-to-string@5.2.6(preact@10.28.2):
|
||||
@@ -21970,6 +22151,8 @@ snapshots:
|
||||
|
||||
quansync@0.2.11: {}
|
||||
|
||||
query-selector-shadow-dom@1.0.1: {}
|
||||
|
||||
queue-microtask@1.2.3: {}
|
||||
|
||||
quick-format-unescaped@4.0.4: {}
|
||||
@@ -23556,6 +23739,8 @@ snapshots:
|
||||
|
||||
web-streams-polyfill@3.3.3: {}
|
||||
|
||||
web-vitals@5.1.0: {}
|
||||
|
||||
webidl-conversions@3.0.1: {}
|
||||
|
||||
webidl-conversions@7.0.0: {}
|
||||
|
||||
245
posthog-setup-report.md
Normal file
245
posthog-setup-report.md
Normal file
@@ -0,0 +1,245 @@
|
||||
# PostHog Integration Setup Report
|
||||
|
||||
## Overview
|
||||
|
||||
PostHog has been integrated into the Formbricks web app (`apps/web/`) for product analytics, user identification, and error tracking.
|
||||
|
||||
- **PostHog Project ID:** 138028
|
||||
- **PostHog Host:** https://eu.i.posthog.com (EU region)
|
||||
- **Dashboard:** [Analytics basics](https://eu.posthog.com/project/138028/dashboard/560936)
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
### Environment Variables
|
||||
|
||||
Set in root `.env`:
|
||||
|
||||
```
|
||||
NEXT_PUBLIC_POSTHOG_TOKEN=phc_ies97ZFTIL3f8T1sQOTCWQycBzqqPvkPcOkpxYJ1sOA
|
||||
NEXT_PUBLIC_POSTHOG_HOST=https://eu.i.posthog.com
|
||||
```
|
||||
|
||||
### Packages Installed
|
||||
|
||||
```
|
||||
apps/web: posthog-js@1.360.0, posthog-node@5.28.0
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## New Files
|
||||
|
||||
| File | Purpose |
|
||||
|------|---------|
|
||||
| `apps/web/instrumentation-client.ts` | Client-side PostHog initialization (Next.js 15.3+ pattern) |
|
||||
| `apps/web/lib/posthog-server.ts` | Server-side PostHog singleton for API routes and Server Actions |
|
||||
|
||||
### `apps/web/instrumentation-client.ts`
|
||||
|
||||
Client-side init with reverse proxy, exception capture, and EU region:
|
||||
|
||||
```typescript
|
||||
import posthog from "posthog-js";
|
||||
|
||||
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_TOKEN!, {
|
||||
api_host: "/ingest",
|
||||
ui_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
|
||||
defaults: "2026-01-30",
|
||||
capture_exceptions: true,
|
||||
debug: process.env.NODE_ENV === "development",
|
||||
});
|
||||
```
|
||||
|
||||
### `apps/web/lib/posthog-server.ts`
|
||||
|
||||
Singleton for server-side use (`flushAt: 1, flushInterval: 0` for short-lived serverless functions):
|
||||
|
||||
```typescript
|
||||
import { PostHog } from "posthog-node";
|
||||
|
||||
let posthogClient: PostHog | null = null;
|
||||
|
||||
export function getPostHogClient(): PostHog {
|
||||
if (!posthogClient) {
|
||||
posthogClient = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_TOKEN!, {
|
||||
host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
|
||||
flushAt: 1,
|
||||
flushInterval: 0,
|
||||
});
|
||||
}
|
||||
return posthogClient;
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Modified Files
|
||||
|
||||
### `apps/web/next.config.mjs`
|
||||
|
||||
Added PostHog reverse proxy rewrites (EU region) and `skipTrailingSlashRedirect`:
|
||||
|
||||
```javascript
|
||||
// Added to rewrites():
|
||||
{ source: "/ingest/static/:path*", destination: "https://eu-assets.i.posthog.com/static/:path*" },
|
||||
{ source: "/ingest/:path*", destination: "https://eu.i.posthog.com/:path*" },
|
||||
|
||||
// Added to nextConfig:
|
||||
skipTrailingSlashRedirect: true,
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Tracked Events
|
||||
|
||||
### Auth & Onboarding
|
||||
|
||||
| Event | File | Trigger | Side |
|
||||
|-------|------|---------|------|
|
||||
| `user_signed_up` | `modules/auth/signup/components/signup-form.tsx` | User completes signup form | Client |
|
||||
| `user_logged_in` | `modules/auth/login/components/login-form.tsx` | User logs in with email | Client |
|
||||
| `organization_created` | `modules/setup/organization/create/components/create-organization.tsx` | New org created during onboarding | Client |
|
||||
| `workspace_created` | `modules/projects/components/create-project-modal/index.tsx` | New project/workspace created | Client |
|
||||
|
||||
### Survey Lifecycle
|
||||
|
||||
| Event | File | Trigger | Side |
|
||||
|-------|------|---------|------|
|
||||
| `survey_type_selected` | `modules/survey/editor/components/how-to-send-card.tsx` | User selects link or in-app survey type | Client |
|
||||
| `survey_saved` | `modules/survey/editor/components/survey-menu-bar.tsx` | Survey saved (non-draft) | Client |
|
||||
| `survey_published` | `modules/survey/editor/components/survey-menu-bar.tsx` | Survey published (draft → inProgress) | Client |
|
||||
| `survey_deleted` | `modules/survey/list/components/survey-dropdown-menu.tsx` | Survey deleted from list | Client |
|
||||
| `survey_duplicated` | `modules/survey/list/components/survey-dropdown-menu.tsx` | Survey duplicated | Client |
|
||||
| `survey_link_copied` | `modules/analysis/components/ShareSurveyLink/index.tsx` | User copies the survey share link | Client |
|
||||
|
||||
### Survey Responses (Server-side — captures both link & in-app surveys)
|
||||
|
||||
| Event | File | Trigger | Side |
|
||||
|-------|------|---------|------|
|
||||
| `survey_displayed` | `app/api/v1/client/[environmentId]/displays/route.ts` | Survey impression created (in-app or link) | Server |
|
||||
| `survey_response_created` | `app/api/v1/client/[environmentId]/responses/route.ts` | New response submitted (any survey type) | Server |
|
||||
| `survey_response_finished` | `app/api/v1/client/.../responses/route.ts` & `.../responses/[responseId]/route.ts` | Response marked as finished (initial or update) | Server |
|
||||
|
||||
### Formbricks JS (Website / App SDK)
|
||||
|
||||
| Event | File | Trigger | Side |
|
||||
|-------|------|---------|------|
|
||||
| `formbricks_js_connected` | `app/api/v1/client/.../environment/lib/environmentState.ts` | First time the Formbricks JS SDK loads and fetches environment state (sets `appSetupCompleted`) | Server |
|
||||
|
||||
### Billing
|
||||
|
||||
| Event | File | Trigger | Side |
|
||||
|-------|------|---------|------|
|
||||
| `upgrade_plan_clicked` | `modules/ee/billing/components/pricing-table.tsx` | Upgrade button clicked on billing page | Client |
|
||||
| `subscription_upgraded` | `modules/ee/billing/api/lib/checkout-session-completed.ts` | Stripe checkout session completed | Server |
|
||||
| `subscription_cancelled` | `modules/ee/billing/api/lib/subscription-deleted.ts` | Stripe subscription deleted webhook | Server |
|
||||
|
||||
### Integrations & Webhooks
|
||||
|
||||
| Event | File | Trigger | Side |
|
||||
|-------|------|---------|------|
|
||||
| `integration_connected` | `app/(app)/.../workspace/integrations/actions.ts` | Integration created/updated (Slack, Google Sheets, Notion, Airtable) | Server |
|
||||
| `webhook_created` | `modules/integrations/webhooks/components/add-webhook-modal.tsx` | Webhook successfully created | Client |
|
||||
|
||||
### Contacts & Segments
|
||||
|
||||
| Event | File | Trigger | Side |
|
||||
|-------|------|---------|------|
|
||||
| `contacts_imported` | `modules/ee/contacts/components/upload-contacts-button.tsx` | Contacts imported via CSV upload | Client |
|
||||
| `segment_created` | `modules/ee/contacts/segments/components/create-segment-modal.tsx` | New segment created | Client |
|
||||
|
||||
### Data Export
|
||||
|
||||
| Event | File | Trigger | Side |
|
||||
|-------|------|---------|------|
|
||||
| `responses_exported` | `app/(app)/.../surveys/[surveyId]/components/CustomFilter.tsx` | Responses downloaded as CSV or XLSX | Client |
|
||||
|
||||
### Team & API
|
||||
|
||||
| Event | File | Trigger | Side |
|
||||
|-------|------|---------|------|
|
||||
| `member_invited` | `modules/organization/settings/teams/components/invite-member/individual-invite-tab.tsx` | Team member invited | Client |
|
||||
| `api_key_created` | `modules/organization/settings/api-keys/components/add-api-key-modal.tsx` | API key created | Client |
|
||||
|
||||
---
|
||||
|
||||
### Event Properties Reference
|
||||
|
||||
| Event | Key Properties |
|
||||
|-------|---------------|
|
||||
| `survey_type_selected` | `surveyId`, `surveyType` (link/app) |
|
||||
| `survey_link_copied` | `surveyId`, `surveyName`, `surveyType`, `singleUse` |
|
||||
| `survey_displayed` | `surveyId`, `environmentId`, `hasUserId` |
|
||||
| `survey_response_created` | `surveyId`, `surveyName`, `surveyType`, `environmentId`, `responseId`, `finished` |
|
||||
| `survey_response_finished` | `surveyId`, `surveyName`, `surveyType`, `environmentId`, `responseId` |
|
||||
| `formbricks_js_connected` | `environmentId`, `projectId` |
|
||||
| `integration_connected` | `integrationType`, `environmentId`, `organizationId` |
|
||||
| `webhook_created` | `environmentId`, `triggers`, `surveyCount` |
|
||||
| `responses_exported` | `surveyId`, `surveyName`, `format` (csv/xlsx), `filterType` (all/filtered) |
|
||||
| `segment_created` | `environmentId`, `filterCount` |
|
||||
| `contacts_imported` | `environmentId`, `contactCount`, `duplicateAction` |
|
||||
| `api_key_created` | `permissionCount` |
|
||||
|
||||
---
|
||||
|
||||
### User Identification
|
||||
|
||||
`posthog.identify()` is called on signup and login with `email` as the `distinctId`:
|
||||
|
||||
```typescript
|
||||
posthog.identify(data.email, { email: data.email, name: data.name });
|
||||
```
|
||||
|
||||
### Exception Capture
|
||||
|
||||
`posthog.captureException(error)` is called in catch blocks across:
|
||||
- Login form
|
||||
- Organization creation
|
||||
- Survey save/publish
|
||||
- Survey delete/duplicate
|
||||
|
||||
---
|
||||
|
||||
## Recommended Dashboard Insights
|
||||
|
||||
### 1. Survey Response Volume (Daily)
|
||||
- **Type:** Trend
|
||||
- **Events:** `survey_response_created` broken down by `surveyType` (link vs app)
|
||||
- **Purpose:** Track total response volume and compare link vs in-app surveys
|
||||
|
||||
### 2. Survey Completion Funnel
|
||||
- **Type:** Funnel
|
||||
- **Steps:** `survey_displayed` → `survey_response_created` → `survey_response_finished`
|
||||
- **Purpose:** Measure drop-off between impressions and completions
|
||||
|
||||
### 3. Full User Journey Funnel
|
||||
- **Type:** Funnel
|
||||
- **Steps:** `user_signed_up` → `survey_published` → `survey_response_finished`
|
||||
- **Purpose:** Track activation from signup to first completed response
|
||||
|
||||
### 4. Integration Adoption
|
||||
- **Type:** Trend (bar)
|
||||
- **Events:** `integration_connected` broken down by `integrationType`
|
||||
- **Purpose:** Track which integrations are most popular
|
||||
|
||||
### 5. Feature Adoption Overview
|
||||
- **Type:** Trend (table)
|
||||
- **Events:** `webhook_created`, `segment_created`, `contacts_imported`, `api_key_created`, `responses_exported`
|
||||
- **Purpose:** Track power-user feature adoption
|
||||
|
||||
### 6. Survey Distribution Methods
|
||||
- **Type:** Trend (pie)
|
||||
- **Events:** `survey_type_selected` broken down by `surveyType`
|
||||
- **Purpose:** Understand link vs in-app survey preference
|
||||
|
||||
---
|
||||
|
||||
## Notes
|
||||
|
||||
- The reverse proxy (`/ingest`) routes PostHog requests through the Next.js server, avoiding ad-blocker issues and keeping first-party data collection.
|
||||
- Server-side billing events (Stripe webhooks) use `organizationId` as `distinctId` since there is no active user session in webhook handlers.
|
||||
- Server-side response/display events use `environmentId` as `distinctId` to group activity by environment.
|
||||
- The existing `instrumentation.ts` (Sentry/OpenTelemetry) was not modified — `instrumentation-client.ts` is a separate client-only file.
|
||||
- Server-side events for responses (`survey_response_created`, `survey_response_finished`, `survey_displayed`) capture ALL survey types (link surveys, in-app surveys, and API-created responses) in a single pipeline.
|
||||
Reference in New Issue
Block a user