Agent skill

Posthog SDK Patterns

by jeremylongshore in jeremylongshore/tons-of-skills-marketplace

Implement typed, lifecycle-safe PostHog SDK adapters for browser, Node.js, React, Next.js, or Python.

MITAuto-check passedDevelopment

Install Posthog SDK Patterns

skills CLI
$ npx skills add jeremylongshore/tons-of-skills-marketplace --skill posthog-sdk-patterns -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install jeremylongshore/tons-of-skills-marketplace posthog-sdk-patterns --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/jeremylongshore/tons-of-skills-marketplace.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/.curated/posthog-sdk-patterns .claude/skills/posthog-sdk-patterns && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
posthog-sdk-patterns
GitHub stars
2.8k
Token cost
~2.1k tokens
SKILL.md length
263 words
Files
2 (incl. references)
Skills in repo
3,342
Repo updated
First seen
Licence
MIT

At a glance

Implement typed, lifecycle-safe PostHog SDK adapters for browser, Node.js, React, Next.js, or Python.

  • Works in 6 steps: Singleton Server Client → Type-Safe Event Capture → React Feature Flag Hook → …
  • Application code needs a reusable analytics boundary
  • SKILL.md covers Overview, Prerequisites, Instructions and Error Handling, plus 4 more sections
  • Reaches us.i.posthog.com and us-assets.i.posthog.com; needs NEXT_PUBLIC_POSTHOG_KEY and POSTHOG_FEATURE_FLAGS_SECURE_API_KEY

What it does

Posthog SDK Patterns is an agent skill from jeremylongshore/tons-of-skills-marketplace. Implement typed, lifecycle-safe PostHog SDK adapters for browser, Node.js, React, Next.js, or Python. Use when application code needs a reusable analytics boundary. Trigger with "PostHog SDK pattern", "PostHog React", or "PostHog TypeScript".

Its SKILL.md is about 2.1k tokens, which your agent loads only when the skill is triggered. The skill folder holds 2 other files, including reference files (for example `references/official-docs.md`). Compatibility notes: Designed for Claude Code

It sits in Development, covering Type safety. It works with PostHog, React, Next.js and Python. The repository describes itself as: Model-agnostic agent-skills platform with a harness-free canonical layer, verified adapters, and the ccpi package manager. Explore at tonsofskills.com. The licence is MIT.

When your agent uses it

  • Application code needs a reusable analytics boundary
  • With PostHog SDK pattern
  • PostHog TypeScript

Example prompts

  • “PostHog SDK pattern”
  • “PostHog React”
  • “PostHog TypeScript”
  • “/posthog-sdk-patterns”

Requirements

  • Python 3
  • Node.js
  • A credential in NEXT_PUBLIC_POSTHOG_KEY
  • A credential in POSTHOG_FEATURE_FLAGS_SECURE_API_KEY
  • Compatibility (from SKILL.md): Designed for Claude Code
  • Pre-approved tools (allowed-tools): Read, Write, Edit

Workflow steps

6 steps, taken from the step headings in SKILL.md.

  1. Singleton Server Client
  2. Type-Safe Event Capture
  3. React Feature Flag Hook
  4. Next.js App Router Provider
  5. Reverse Proxy for Ad Blocker Bypass
  6. Python Patterns

What it can do on your machine

Read from SKILL.md and the folder at commit 80f86df. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves these tools, so the agent can use them without asking each time:

    • Read
    • Write
    • Edit

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    No scripts in the folder and no shell commands in SKILL.md (its code samples are typescript and python).

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    Hosts in commands or code, which the agent is likely to contact:

    • us.i.posthog.com
    • us-assets.i.posthog.com

    Also links to:

    • posthog.com

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names these keys or tokens, usually read from environment variables:

    • NEXT_PUBLIC_POSTHOG_KEY
    • POSTHOG_FEATURE_FLAGS_SECURE_API_KEY
    • POSTHOG_PROJECT_KEY

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

  • Compatibility

    Designed for Claude Code

    From compatibility in the SKILL.md frontmatter.

Context cost

Posthog SDK Patterns loads about 2.1k tokens when it runs, and up to ~2.3k if it reads all its reference files. Until then it costs about 66 tokens; SKILL.md has 263 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~66
When it runs · the whole SKILL.md, loaded when a task matches
~2.1k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~2.3k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); files beside SKILL.md are not scanned.

SKILL.md

The full file from jeremylongshore/tons-of-skills-marketplace at commit 80f86df, republished under its MIT licence (© jeremylongshore). 263 words, ~2,129 tokens.

Download SKILL.mdSave it as .claude/skills/posthog-sdk-patterns/SKILL.md (or your agent's skills folder). This skill also uses 1 other file; get the full folder from GitHub.
name
posthog-sdk-patterns
description
Implement typed, lifecycle-safe PostHog SDK adapters for browser, Node.js, React, Next.js, or Python. Use when application code needs a reusable analytics boundary. Trigger with "PostHog SDK pattern", "PostHog React", or "PostHog TypeScript".
allowed-tools
Read, Write, Edit
compatibility
Designed for Claude Code
argument-hint
[project-path] [sdk-or-framework]
version
1.14.0
license
MIT
author
Jeremy Longshore <jeremy@intentsolutions.io>
tags
saas, posthog, python, typescript

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

Tool discipline

Use Read to inspect the relevant configuration and implementation before proposing changes. Use Write only for a new, explicitly requested artifact inside the target project. Use Edit for minimal changes to existing project files after the evidence pass.

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_FEATURE_FLAGS_SECURE_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/flags', destination: 'https://us.i.posthog.com/flags' },
    ];
  },
};

// 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_FEATURE_FLAGS_SECURE_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

PatternUse CaseBenefit
Singleton clientAll SDK usagePrevents multiple initializations
Type-safe eventsEvent captureCompile-time property validation
Feature flag hooksReact componentsAuto-updates on flag changes
Reverse proxyProductionBypasses ad blockers
Graceful shutdownServer processesNo 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

Examples

For a Next.js application, create separate client and server adapters, keep private credentials server-only, type business events, handle pageviews deliberately, and test capture plus flag fallbacks. Verify current framework guidance before copying any proxy or initialization pattern.

Resources

See official PostHog references for current authority and verification boundaries.

Next Steps

Apply patterns in posthog-core-workflow-a for real-world usage.

© jeremylongshore, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 1 other file (references) in skills/.curated/posthog-sdk-patterns of jeremylongshore/tons-of-skills-marketplace.

  • SKILL.md
  • references/official-docs.md

Open the folder on GitHubat commit 80f86df

Compare with similar skills

Posthog SDK Patterns next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Posthog SDK Patterns compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Posthog SDK Patterns this skilljeremylongshore/tons-of-skills-marketplace2.8k—~2.1kAutomated safety check: PassMIT
Typescriptericrisco/rsc-harness174—~2.8kAutomated safety check: PassMIT
Spiceflowremorses/spiceflow167—~1.9kAutomated safety check: PassMIT
Fullstack DevHHU3637kr/skills1453 repos~8.6kAutomated safety check: NotesMIT
Tech Stack Recommenderalirezarezvani/claude-cto-team117—~4.3kAutomated safety check: PassMIT
Env Managerbobmatnyc/claude-mpm155—~3.9kAutomated safety check: NotesCustom licence

Similar skills

  • Typescript

    ericrisco/rsc-harness

    A skill your agent uses when writing or fixing TypeScript type code (.ts/.tsx/.d.ts), modeling data with generics/unions/branded types, diagnosing narrowing failures, or configuring tsconfig and the…

    174 GitHub stars~2.8k tokensUpdated yesterday
    DatabasesAuto-check passed
  • Spiceflow

    remorses/spiceflow

    Spiceflow is a super simple, fast, and type-safe API and React Server Components framework for TypeScript.

    167 GitHub stars~1.9k tokensUpdated 3 days ago
    Backend & APIsAuto-check passed
  • Fullstack Dev

    HHU3637kr/skills

    Full-stack backend architecture and frontend-backend integration guide.

    145 GitHub starsUsed in 3 repos~8.6k tokens
    Backend & APIsAuto-check: notes
  • Tech Stack Recommender

    alirezarezvani/claude-cto-team

    Recommend technology stacks based on project requirements, team expertise, and constraints.

    117 GitHub stars~4.3k tokensUpdated 9 mo ago
    Backend & APIsAuto-check passed
  • Env Manager

    bobmatnyc/claude-mpm

    Environment variable validation, security scanning, and management for Next.js, Vite, React, and Node.js applications

    155 GitHub stars~3.9k tokensUpdated 1 mo ago
    DevOps & CloudAuto-check: notes
  • Javascript SDK

    aiskillstore/marketplace

    JavaScript/TypeScript SDK for inference.sh - run AI apps, build agents, integrate with all models.

    430 GitHub starsUsed in 1 repo~3.3k tokens
    Backend & APIsAuto-check passed

More from jeremylongshore/tons-of-skills-marketplace

All 3,342 skills in this repo
  • Performing Security Code Review

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to conduct a security-focused code review using the security-agent plugin.

    2.8k GitHub starsUsed in 2 repos~1.3k tokens
    Auto-check: notes
  • Adapting Transfer Learning Models

    jeremylongshore/tons-of-skills-marketplace

    Build this skill automates the adaptation of pre-trained machine learning models using transfer learning techniques.

    2.8k GitHub stars~1.1k tokensUpdated today
    Auto-check passed
  • Agent Context Loader

    jeremylongshore/tons-of-skills-marketplace

    Execute proactive auto-loading: automatically detects and loads agents.md files.

    2.8k GitHub stars~1.1k tokensUpdated today
    Auto-check passed
  • Aggregating Performance Metrics

    jeremylongshore/tons-of-skills-marketplace

    Aggregate and centralize performance metrics from applications, systems, databases, caches, and services.

    2.8k GitHub stars~1.2k tokensUpdated today
    Auto-check passed
  • Analyzing Capacity Planning

    jeremylongshore/tons-of-skills-marketplace

    Execute this skill enables AI assistant to analyze capacity requirements and plan for future growth.

    2.8k GitHub stars~947 tokensUpdated today
    Auto-check passed
  • Analyzing Database Indexes

    jeremylongshore/tons-of-skills-marketplace

    Process use when you need to work with database indexing. An agent skill from jeremylongshore/tons-of-skills-marketplace.

    2.8k GitHub stars~2k tokensUpdated today
    Auto-check passed

Categories

Questions about Posthog SDK Patterns

What does Posthog SDK Patterns do?

Implement typed, lifecycle-safe PostHog SDK adapters for browser, Node.js, React, Next.js, or Python. Posthog SDK Patterns is an agent skill from jeremylongshore/tons-of-skills-marketplace.js, or Python.

When should I use Posthog SDK Patterns?

Posthog SDK Patterns fits situations like: application code needs a reusable analytics boundary; with PostHog SDK pattern; postHog TypeScript.

How do I install Posthog SDK Patterns in Claude Code?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill posthog-sdk-patterns -a claude-code`. Or copy the skill folder (skills/.curated/posthog-sdk-patterns in jeremylongshore/tons-of-skills-marketplace) into .claude/skills/posthog-sdk-patterns in your project. Claude Code loads it when a task matches its description.

How do I install Posthog SDK Patterns in Codex?

Run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill posthog-sdk-patterns -a codex`. Or copy the skill folder (skills/.curated/posthog-sdk-patterns in jeremylongshore/tons-of-skills-marketplace) into .agents/skills/posthog-sdk-patterns in your project. Codex loads it when a task matches its description.

Can I use Posthog SDK Patterns in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add jeremylongshore/tons-of-skills-marketplace --skill posthog-sdk-patterns -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/posthog-sdk-patterns, .gemini/skills/posthog-sdk-patterns, .github/skills/posthog-sdk-patterns and .opencode/skills/posthog-sdk-patterns in your project.

What does Posthog SDK Patterns need to run?

Going by SKILL.md and its folder, Posthog SDK Patterns needs credentials named NEXT_PUBLIC_POSTHOG_KEY, POSTHOG_FEATURE_FLAGS_SECURE_API_KEY and POSTHOG_PROJECT_KEY. Our summary lists: Python 3; Node.js; A credential in NEXT_PUBLIC_POSTHOG_KEY; A credential in POSTHOG_FEATURE_FLAGS_SECURE_API_KEY. Its frontmatter pre-approves these tools: Read, Write, Edit. Compatibility (from SKILL.md): Designed for Claude Code.

Does Posthog SDK Patterns access the network?

SKILL.md names 3 domains. In commands or code: us.i.posthog.com and us-assets.i.posthog.com; the agent is likely to contact these when it follows the instructions. As links in the text: posthog.com. This is read from the text; nothing was executed.

Is Posthog SDK Patterns safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. Review the folder before installing.

What licence does Posthog SDK Patterns use?

Posthog SDK Patterns is published under the MIT licence (declared in SKILL.md). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Posthog SDK Patterns use?

About 2.1k tokens (SKILL.md is roughly 8.5k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 202 tokens, read only when the agent opens those files.

What are the alternatives to Posthog SDK Patterns?

Skills that share tags, products or a category with Posthog SDK Patterns: Typescript (ericrisco/rsc-harness, 174 stars), Spiceflow (remorses/spiceflow, 167 stars), Fullstack Dev (HHU3637kr/skills, 145 stars) and Tech Stack Recommender (alirezarezvani/claude-cto-team, 117 stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Posthog SDK Patterns?

jeremylongshore (a GitHub user) maintains it in jeremylongshore/tons-of-skills-marketplace, which has 2,825 GitHub stars. The repository holds 3,342 skills in this directory. The repository was last updated on October 9, 2026.

Source: jeremylongshore/tons-of-skills-marketplace on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.