posthog-sdk-patterns
Production-ready PostHog SDK patterns: singleton client, typed events, React hooks, Next.js App Router integration, and Python patterns. Trigger: "posthog SDK patterns", "posthog best practices", "posthog React hook", "posthog Next.js", "posthog typescript".
Best use case
posthog-sdk-patterns is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Production-ready PostHog SDK patterns: singleton client, typed events, React hooks, Next.js App Router integration, and Python patterns. Trigger: "posthog SDK patterns", "posthog best practices", "posthog React hook", "posthog Next.js", "posthog typescript".
Teams using posthog-sdk-patterns should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/posthog-sdk-patterns/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How posthog-sdk-patterns Compares
| Feature / Agent | posthog-sdk-patterns | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Production-ready PostHog SDK patterns: singleton client, typed events, React hooks, Next.js App Router integration, and Python patterns. Trigger: "posthog SDK patterns", "posthog best practices", "posthog React hook", "posthog Next.js", "posthog typescript".
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
Related Guides
AI Agents for Coding
Browse AI agent skills for coding, debugging, testing, refactoring, code review, and developer workflows across Claude, Cursor, and Codex.
Best AI Skills for Claude
Explore the best AI skills for Claude and Claude Code across coding, research, workflow automation, documentation, and agent operations.
ChatGPT vs Claude for Agent Skills
Compare ChatGPT and Claude for AI agent skills across coding, writing, research, and reusable workflow execution.
SKILL.md Source
# PostHog SDK Patterns
## Overview
Production-ready patterns for PostHog integrations: singleton client, type-safe event capture, React hooks for feature flags, Next.js App Router provider, and Python integration patterns.
## Prerequisites
- `posthog-js` and/or `posthog-node` installed
- TypeScript project with strict mode
- React/Next.js (for frontend patterns)
## Instructions
### Step 1: Singleton Server Client
```typescript
// lib/posthog-server.ts
import { PostHog } from 'posthog-node';
let client: PostHog | null = null;
export function getPostHogServer(): PostHog {
if (!client) {
client = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
host: process.env.POSTHOG_HOST || 'https://us.i.posthog.com',
personalApiKey: process.env.POSTHOG_PERSONAL_API_KEY,
flushAt: 20,
flushInterval: 10000,
});
}
return client;
}
// Graceful shutdown hook
process.on('SIGTERM', async () => {
if (client) await client.shutdown();
process.exit(0);
});
```
### Step 2: Type-Safe Event Capture
```typescript
// lib/analytics/events.ts
type EventMap = {
user_signed_up: { method: 'email' | 'google' | 'github' };
feature_used: { feature_name: string; duration_ms?: number };
subscription_started: { plan: string; interval: 'monthly' | 'annual'; mrr: number };
item_created: { item_type: string; source: 'web' | 'api' };
search_performed: { query: string; results_count: number };
};
export function capture<K extends keyof EventMap>(
distinctId: string,
event: K,
properties: EventMap[K]
) {
const ph = getPostHogServer();
ph.capture({ distinctId, event, properties });
}
// Usage: fully type-checked
capture('user-123', 'subscription_started', {
plan: 'pro',
interval: 'annual',
mrr: 99,
});
```
### Step 3: React Feature Flag Hook
```typescript
// hooks/useFeatureFlag.ts
'use client';
import { useEffect, useState } from 'react';
import posthog from 'posthog-js';
export function useFeatureFlag(flagKey: string): boolean | undefined {
const [enabled, setEnabled] = useState<boolean | undefined>(undefined);
useEffect(() => {
// Check immediately if flags are already loaded
const current = posthog.isFeatureEnabled(flagKey);
if (current !== undefined) {
setEnabled(current);
}
// Listen for flag updates (initial load or remote changes)
posthog.onFeatureFlags(() => {
setEnabled(posthog.isFeatureEnabled(flagKey) ?? false);
});
}, [flagKey]);
return enabled;
}
// Multivariate variant hook
export function useFeatureFlagVariant(flagKey: string): string | undefined {
const [variant, setVariant] = useState<string | undefined>(undefined);
useEffect(() => {
posthog.onFeatureFlags(() => {
const value = posthog.getFeatureFlag(flagKey);
setVariant(typeof value === 'string' ? value : undefined);
});
}, [flagKey]);
return variant;
}
// Usage in a component
function CheckoutButton() {
const newCheckout = useFeatureFlag('new-checkout-v2');
if (newCheckout === undefined) return <Skeleton />; // Loading
return newCheckout ? <NewCheckout /> : <LegacyCheckout />;
}
```
### Step 4: Next.js App Router Provider
```typescript
// app/providers.tsx
'use client';
import posthog from 'posthog-js';
import { PostHogProvider } from 'posthog-js/react';
import { usePathname, useSearchParams } from 'next/navigation';
import { useEffect, Suspense } from 'react';
function PostHogPageView() {
const pathname = usePathname();
const searchParams = useSearchParams();
useEffect(() => {
if (pathname) {
let url = window.origin + pathname;
if (searchParams.toString()) {
url += '?' + searchParams.toString();
}
posthog.capture('$pageview', { $current_url: url });
}
}, [pathname, searchParams]);
return null;
}
export function PHProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com',
capture_pageview: false, // We handle manually in PostHogPageView
capture_pageleave: true,
loaded: (ph) => {
if (process.env.NODE_ENV === 'development') ph.debug();
},
});
}, []);
return (
<PostHogProvider client={posthog}>
<Suspense fallback={null}>
<PostHogPageView />
</Suspense>
{children}
</PostHogProvider>
);
}
// app/layout.tsx
// import { PHProvider } from './providers';
// export default function RootLayout({ children }) {
// return <html><body><PHProvider>{children}</PHProvider></body></html>;
// }
```
### Step 5: Reverse Proxy for Ad Blocker Bypass
```typescript
// next.config.js — proxy PostHog through your domain
module.exports = {
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*' },
{ source: '/ingest/decide', destination: 'https://us.i.posthog.com/decide' },
];
},
};
// Then in your posthog.init:
// posthog.init('phc_...', { api_host: '/ingest' });
```
### Step 6: Python Patterns
```python
# analytics/posthog_client.py
import posthog
import os
import atexit
from functools import lru_cache
@lru_cache(maxsize=1)
def get_posthog():
"""Singleton PostHog client."""
posthog.project_api_key = os.environ['POSTHOG_PROJECT_KEY']
posthog.host = os.getenv('POSTHOG_HOST', 'https://us.i.posthog.com')
posthog.personal_api_key = os.getenv('POSTHOG_PERSONAL_API_KEY')
posthog.debug = os.getenv('ENVIRONMENT') == 'development'
return posthog
# Ensure flush on exit
atexit.register(lambda: get_posthog().shutdown())
# Type-safe capture helper
def track(distinct_id: str, event: str, properties: dict | None = None):
ph = get_posthog()
ph.capture(distinct_id, event, properties or {})
# Feature flag check
def is_enabled(flag_key: str, distinct_id: str, default: bool = False) -> bool:
ph = get_posthog()
result = ph.feature_enabled(flag_key, distinct_id)
return result if result is not None else default
```
## Error Handling
| Pattern | Use Case | Benefit |
|---------|----------|---------|
| Singleton client | All SDK usage | Prevents multiple initializations |
| Type-safe events | Event capture | Compile-time property validation |
| Feature flag hooks | React components | Auto-updates on flag changes |
| Reverse proxy | Production | Bypasses ad blockers |
| Graceful shutdown | Server processes | No lost events on SIGTERM |
## Output
- Singleton PostHog server client with shutdown hook
- Type-safe event capture with TypeScript generics
- React hooks for feature flags (boolean and multivariate)
- Next.js App Router provider with pageview tracking
- Reverse proxy configuration for ad blocker bypass
## Resources
- [posthog-js Reference](https://posthog.com/docs/libraries/js)
- [posthog-node Reference](https://posthog.com/docs/libraries/node)
- [Next.js Integration](https://posthog.com/docs/libraries/next-js)
- [React SDK](https://posthog.com/docs/libraries/react)
## Next Steps
Apply patterns in `posthog-core-workflow-a` for real-world usage.Related Skills
workhuman-sdk-patterns
Workhuman sdk patterns for employee recognition and rewards API. Use when integrating Workhuman Social Recognition, or building recognition workflows with HRIS systems. Trigger: "workhuman sdk patterns".
wispr-sdk-patterns
Wispr Flow sdk patterns for voice-to-text API integration. Use when integrating Wispr Flow dictation, WebSocket streaming, or building voice-powered applications. Trigger: "wispr sdk patterns".
windsurf-sdk-patterns
Apply production-ready Windsurf workspace configuration and Cascade interaction patterns. Use when configuring .windsurfrules, workspace rules, MCP servers, or establishing team coding standards for Windsurf AI. Trigger with phrases like "windsurf patterns", "windsurf best practices", "windsurf config patterns", "windsurfrules", "windsurf workspace".
windsurf-reliability-patterns
Implement reliable Cascade workflows with checkpoints, rollback, and incremental editing. Use when building fault-tolerant AI coding workflows, preventing Cascade from breaking builds, or establishing safe practices for multi-file AI edits. Trigger with phrases like "windsurf reliability", "cascade safety", "windsurf rollback", "cascade checkpoint", "safe cascade workflow".
webflow-sdk-patterns
Apply production-ready Webflow SDK patterns — singleton client, typed error handling, pagination helpers, and raw response access for the webflow-api package. Use when implementing Webflow integrations, refactoring SDK usage, or establishing team coding standards. Trigger with phrases like "webflow SDK patterns", "webflow best practices", "webflow code patterns", "idiomatic webflow", "webflow typescript".
vercel-sdk-patterns
Production-ready Vercel REST API patterns with typed fetch wrappers and error handling. Use when integrating with the Vercel API programmatically, building deployment tools, or establishing team coding standards for Vercel API calls. Trigger with phrases like "vercel SDK patterns", "vercel API wrapper", "vercel REST API client", "vercel best practices", "idiomatic vercel API".
vercel-reliability-patterns
Implement reliability patterns for Vercel deployments including circuit breakers, retry logic, and graceful degradation. Use when building fault-tolerant serverless functions, implementing retry strategies, or adding resilience to production Vercel services. Trigger with phrases like "vercel reliability", "vercel circuit breaker", "vercel resilience", "vercel fallback", "vercel graceful degradation".
veeva-sdk-patterns
Veeva Vault sdk patterns for REST API and clinical operations. Use when working with Veeva Vault document management and CRM. Trigger: "veeva sdk patterns".
vastai-sdk-patterns
Apply production-ready Vast.ai SDK patterns for Python and REST API. Use when implementing Vast.ai integrations, refactoring SDK usage, or establishing coding standards for GPU cloud operations. Trigger with phrases like "vastai SDK patterns", "vastai best practices", "vastai code patterns", "idiomatic vastai".
twinmind-sdk-patterns
Apply production-ready TwinMind SDK patterns for TypeScript and Python. Use when implementing TwinMind integrations, refactoring API usage, or establishing team coding standards for meeting AI integration. Trigger with phrases like "twinmind SDK patterns", "twinmind best practices", "twinmind code patterns", "idiomatic twinmind".
together-sdk-patterns
Together AI sdk patterns for inference, fine-tuning, and model deployment. Use when working with Together AI's OpenAI-compatible API. Trigger: "together sdk patterns".
techsmith-sdk-patterns
TechSmith sdk patterns for Snagit COM API and Camtasia automation. Use when working with TechSmith screen capture and video editing automation. Trigger: "techsmith sdk patterns".