| name | posthog-sdk-patterns |
| description | 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".
|
| allowed-tools | Read, Write, Edit |
| version | 1.12.0 |
| license | MIT |
| author | Jeremy Longshore <jeremy@intentsolutions.io> |
| tags | ["saas","posthog","python","typescript"] |
| compatibility | Designed for Claude Code, also compatible with Codex and OpenClaw |
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
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;
}
process.on('SIGTERM', async () => {
if (client) await client.shutdown();
process.exit();
});