posthog-local-dev-loop

Configure PostHog local development with mocking, debug mode, and testing. Use when setting up a development environment, mocking PostHog for tests, or establishing a fast iteration cycle with posthog-js or posthog-node. Trigger: "posthog dev setup", "posthog local development", "posthog dev environment", "mock posthog", "test posthog".

1,868 stars

Best use case

posthog-local-dev-loop is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Configure PostHog local development with mocking, debug mode, and testing. Use when setting up a development environment, mocking PostHog for tests, or establishing a fast iteration cycle with posthog-js or posthog-node. Trigger: "posthog dev setup", "posthog local development", "posthog dev environment", "mock posthog", "test posthog".

Teams using posthog-local-dev-loop 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

$curl -o ~/.claude/skills/posthog-local-dev-loop/SKILL.md --create-dirs "https://raw.githubusercontent.com/jeremylongshore/claude-code-plugins-plus-skills/main/plugins/saas-packs/posthog-pack/skills/posthog-local-dev-loop/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/posthog-local-dev-loop/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How posthog-local-dev-loop Compares

Feature / Agentposthog-local-dev-loopStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Configure PostHog local development with mocking, debug mode, and testing. Use when setting up a development environment, mocking PostHog for tests, or establishing a fast iteration cycle with posthog-js or posthog-node. Trigger: "posthog dev setup", "posthog local development", "posthog dev environment", "mock posthog", "test posthog".

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

SKILL.md Source

# PostHog Local Dev Loop

## Overview

Set up a fast local development workflow for PostHog integrations. Covers debug mode for event inspection, mocking posthog-node for unit tests, and a dev/test PostHog project to avoid polluting production data.

## Prerequisites

- Completed `posthog-install-auth` setup
- Node.js 20+ with npm/pnpm
- Vitest or Jest for testing
- Separate PostHog project for development (recommended)

## Instructions

### Step 1: Project Structure

```
my-posthog-app/
├── src/
│   ├── analytics/
│   │   ├── posthog.ts         # Singleton client
│   │   ├── events.ts          # Event taxonomy (typed constants)
│   │   └── flags.ts           # Feature flag keys
│   └── index.ts
├── tests/
│   ├── analytics.test.ts      # Unit tests with mocked PostHog
│   └── integration.test.ts    # Integration tests (real PostHog dev project)
├── .env.local                 # Dev keys (git-ignored)
├── .env.example               # Template: NEXT_PUBLIC_POSTHOG_KEY=phc_...
└── package.json
```

### Step 2: PostHog Client with Dev Mode

```typescript
// src/analytics/posthog.ts
import { PostHog } from 'posthog-node';

let client: PostHog | null = null;

export function getPostHog(): PostHog {
  if (!client) {
    client = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
      host: process.env.POSTHOG_HOST || 'https://us.i.posthog.com',
      flushAt: process.env.NODE_ENV === 'development' ? 1 : 20,
      flushInterval: process.env.NODE_ENV === 'development' ? 0 : 10000,
      // In dev, flush immediately so events appear instantly in dashboard
    });
  }
  return client;
}

export async function shutdown() {
  if (client) {
    await client.shutdown();
    client = null;
  }
}
```

### Step 3: Browser Debug Mode

```typescript
// Enable PostHog debug mode in development
import posthog from 'posthog-js';

posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
  api_host: 'https://us.i.posthog.com',
  loaded: (ph) => {
    if (process.env.NODE_ENV === 'development') {
      ph.debug();
      // All events logged to browser console:
      // [PostHog.js] Sending event: {"event":"$pageview","properties":{...}}
    }
  },
});

// Disable capture entirely in test environments
if (process.env.NODE_ENV === 'test') {
  posthog.opt_out_capturing();
}
```

### Step 4: Mock PostHog for Unit Tests

```typescript
// tests/analytics.test.ts
import { describe, it, expect, vi, beforeEach } from 'vitest';

// Mock posthog-node
vi.mock('posthog-node', () => {
  const mockCapture = vi.fn();
  const mockIdentify = vi.fn();
  const mockGetFeatureFlag = vi.fn().mockResolvedValue(true);
  const mockShutdown = vi.fn().mockResolvedValue(undefined);
  const mockFlush = vi.fn().mockResolvedValue(undefined);

  return {
    PostHog: vi.fn().mockImplementation(() => ({
      capture: mockCapture,
      identify: mockIdentify,
      getFeatureFlag: mockGetFeatureFlag,
      getAllFlags: vi.fn().mockResolvedValue({ 'new-feature': true }),
      shutdown: mockShutdown,
      flush: mockFlush,
    })),
  };
});

import { PostHog } from 'posthog-node';

describe('Analytics', () => {
  let ph: InstanceType<typeof PostHog>;

  beforeEach(() => {
    vi.clearAllMocks();
    ph = new PostHog('phc_test_key');
  });

  it('captures events with correct properties', () => {
    ph.capture({
      distinctId: 'user-1',
      event: 'button_clicked',
      properties: { button: 'signup' },
    });

    expect(ph.capture).toHaveBeenCalledWith({
      distinctId: 'user-1',
      event: 'button_clicked',
      properties: { button: 'signup' },
    });
  });

  it('evaluates feature flags', async () => {
    const result = await ph.getFeatureFlag('new-feature', 'user-1');
    expect(result).toBe(true);
  });
});
```

### Step 5: Integration Test with Real Dev Project

```typescript
// tests/integration.test.ts
import { describe, it, expect, afterAll } from 'vitest';
import { PostHog } from 'posthog-node';

const POSTHOG_KEY = process.env.POSTHOG_TEST_KEY;

describe.skipIf(!POSTHOG_KEY)('PostHog Integration', () => {
  const ph = new PostHog(POSTHOG_KEY!, {
    host: 'https://us.i.posthog.com',
    flushAt: 1,
    flushInterval: 0,
  });

  afterAll(async () => {
    await ph.shutdown();
  });

  it('should capture and flush an event', async () => {
    ph.capture({
      distinctId: `test-${Date.now()}`,
      event: 'integration_test',
      properties: { test: true },
    });
    // Flush returns successfully if network is reachable
    await expect(ph.flush()).resolves.not.toThrow();
  });

  it('should evaluate feature flags', async () => {
    const flags = await ph.getAllFlags(`test-${Date.now()}`);
    expect(typeof flags).toBe('object');
  });
});
```

### Step 6: Package Scripts

```json
{
  "scripts": {
    "dev": "tsx watch src/index.ts",
    "test": "vitest run",
    "test:watch": "vitest --watch",
    "test:integration": "POSTHOG_TEST_KEY=$NEXT_PUBLIC_POSTHOG_KEY vitest run tests/integration"
  }
}
```

## Error Handling

| Error | Cause | Solution |
|-------|-------|----------|
| Events not in dev dashboard | Wrong project key | Verify `.env.local` has dev project `phc_` key |
| Mock not intercepting | Wrong import path | Ensure `vi.mock` path matches actual import |
| Integration test timeout | PostHog unreachable | Check network, increase vitest timeout |
| Debug mode too noisy | `ph.debug()` in prod | Guard with `NODE_ENV === 'development'` |

## Output

- Development PostHog client with instant flush
- Browser debug mode for event inspection
- Mocked posthog-node for unit tests
- Integration test suite for real PostHog connectivity

## Resources

- [posthog-node Documentation](https://posthog.com/docs/libraries/node)
- [posthog-js Debug Mode](https://posthog.com/docs/libraries/js)
- [Vitest Mocking](https://vitest.dev/guide/mocking)

## Next Steps

See `posthog-sdk-patterns` for production-ready code patterns.

Related Skills

workhuman-local-dev-loop

1868
from jeremylongshore/claude-code-plugins-plus-skills

Workhuman local dev loop for employee recognition and rewards API. Use when integrating Workhuman Social Recognition, or building recognition workflows with HRIS systems. Trigger: "workhuman local dev loop".

wispr-local-dev-loop

1868
from jeremylongshore/claude-code-plugins-plus-skills

Wispr Flow local dev loop for voice-to-text API integration. Use when integrating Wispr Flow dictation, WebSocket streaming, or building voice-powered applications. Trigger: "wispr local dev loop".

windsurf-local-dev-loop

1868
from jeremylongshore/claude-code-plugins-plus-skills

Configure Windsurf local development workflow with Cascade, Previews, and terminal integration. Use when setting up a development environment, configuring Turbo mode, or establishing a fast iteration cycle with Windsurf AI. Trigger with phrases like "windsurf dev setup", "windsurf local development", "windsurf dev environment", "windsurf workflow", "develop with windsurf".

webflow-local-dev-loop

1868
from jeremylongshore/claude-code-plugins-plus-skills

Configure a Webflow local development workflow with TypeScript, hot reload, mocked API tests, and webhook tunneling via ngrok. Use when setting up a development environment, configuring test workflows, or establishing a fast iteration cycle with the Webflow Data API. Trigger with phrases like "webflow dev setup", "webflow local development", "webflow dev environment", "develop with webflow".

vercel-local-dev-loop

1868
from jeremylongshore/claude-code-plugins-plus-skills

Configure Vercel local development with vercel dev, environment variables, and hot reload. Use when setting up a development environment, testing serverless functions locally, or establishing a fast iteration cycle with Vercel. Trigger with phrases like "vercel dev setup", "vercel local development", "vercel dev environment", "develop with vercel locally".

veeva-local-dev-loop

1868
from jeremylongshore/claude-code-plugins-plus-skills

Veeva Vault local dev loop for REST API and clinical operations. Use when working with Veeva Vault document management and CRM. Trigger: "veeva local dev loop".

vastai-local-dev-loop

1868
from jeremylongshore/claude-code-plugins-plus-skills

Configure Vast.ai local development with testing and fast iteration. Use when setting up a development environment, testing instance provisioning, or building a fast iteration cycle for GPU workloads. Trigger with phrases like "vastai dev setup", "vastai local development", "vastai dev environment", "develop with vastai".

twinmind-local-dev-loop

1868
from jeremylongshore/claude-code-plugins-plus-skills

Set up local development workflow with TwinMind API integration. Use when building applications that integrate TwinMind transcription, testing API calls locally, or developing meeting automation tools. Trigger with phrases like "twinmind dev setup", "twinmind local development", "twinmind API testing", "build with twinmind".

together-local-dev-loop

1868
from jeremylongshore/claude-code-plugins-plus-skills

Together AI local dev loop for inference, fine-tuning, and model deployment. Use when working with Together AI's OpenAI-compatible API. Trigger: "together local dev loop".

techsmith-local-dev-loop

1868
from jeremylongshore/claude-code-plugins-plus-skills

TechSmith local dev loop for Snagit COM API and Camtasia automation. Use when working with TechSmith screen capture and video editing automation. Trigger: "techsmith local dev loop".

supabase-local-dev-loop

1868
from jeremylongshore/claude-code-plugins-plus-skills

Configure Supabase local development with the CLI, Docker, and migration workflow. Use when initializing a Supabase project locally, starting the local stack, writing migrations, seeding data, or iterating on schema changes. Trigger with phrases like "supabase local dev", "supabase start", "supabase init", "supabase db reset", "supabase local setup".

stackblitz-local-dev-loop

1868
from jeremylongshore/claude-code-plugins-plus-skills

Configure local development for WebContainer applications with hot reload and testing. Use when building browser-based IDEs, testing WebContainer file operations, or setting up development workflows for WebContainer projects. Trigger: "stackblitz dev setup", "webcontainer local", "test webcontainers locally".