Generated banner for Omnibus Instrument Product Analytics
Generated logo for Omnibus Instrument Product Analytics

Omnibus Instrument Product Analytics

PostHogOfficialCreated by PostHog

  • Skill
  • Tool integration
  • Data and AI
  • MIT
  • Low risk

From the author

Add PostHog product analytics events to track user behavior. Use after implementing new features or reviewing PRs to ensure meaningful user actions are captured. Also handles initial PostHog SDK setup if not yet installed.
— the description by PostHog

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

This skill provides a structured, step-by-step procedure for integrating PostHog product analytics into a wide variety of web, mobile, and backend frameworks. It handles the full lifecycle of the integration, from detecting the project's technology stack and installing the necessary SDKs to implementing event tracking, user identification, and error monitoring. The skill emphasizes non-intrusive changes, ensuring that new analytics code is added alongside existing logic without disrupting the project's architecture.

What it does

  • Detects the project framework and language to determine the correct PostHog SDK.
  • Installs the required PostHog SDK package automatically.
  • Initializes the PostHog instance according to framework-specific best practices.
  • Implements targeted event tracking for key user actions and business logic.
  • Configures user identification flows for login and signup events.
  • Sets up environment variables for secure API key and host management.

When to use it

  • After implementing new features that require tracking for user engagement analysis.
  • When reviewing pull requests to ensure critical user behaviors are being captured.
  • When setting up product analytics for a new project from scratch.
  • When migrating or adding analytics to an existing application.

Advantages

  • Supports a broad range of modern frontend, backend, and mobile frameworks.
  • Ensures consistent event naming and property capture across the codebase.
  • Maintains architectural integrity by requiring minimal, targeted code additions.
  • Automates the tedious aspects of SDK initialization and environment configuration.

Usage examples

“Add PostHog analytics to my Next.js project.”
The agent will detect the Next.js environment, install the PostHog SDK, initialize it in the appropriate root file, and guide you through adding capture calls to key user flows.
“I need to track user signups in my Django application using PostHog.”
The agent will identify the Django setup, configure the PostHog Python SDK, and implement identify calls within your authentication logic.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/posthog/omnibus-instrument-product-analytics/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip omnibus-instrument-product-analytics.zip -d .agents/skills

Documentation by PostHog

Add PostHog product analytics events

Use this skill to add product analytics events (capture calls) that track meaningful user actions in new or changed code. Use it after implementing features or reviewing PRs to ensure key user behaviors are captured. If PostHog is not yet installed, this skill also covers initial SDK setup. Supports any framework or language.

Supported frameworks: Next.js, React Router, Nuxt, Vue, TanStack Start, SvelteKit, Astro, Angular, Django, Flask, FastAPI, Laravel, Ruby on Rails, Android, iOS, React Native, Expo, and more.

Instructions

Follow these steps IN ORDER:

STEP 1: Analyze the codebase and detect the platform.

  • Look for dependency files (package.json, requirements.txt, Gemfile, composer.json, go.mod, etc.) to determine the framework and language.

  • Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb) to determine the package manager.

  • Check for existing PostHog setup. If PostHog is already installed and initialized, skip to STEP 5.

STEP 2: Research integration. (Skip if PostHog is already set up.) 2.1. Find the reference file below that matches the detected framework — it is the source of truth for SDK initialization, provider setup, and event capture patterns. Read it now. 2.2. If no reference matches, fall back to your general knowledge and web search. Use posthog.com/docs as the primary search source.

STEP 3: Install the PostHog SDK. (Skip if PostHog is already set up.)

  • Add the PostHog SDK package for the detected platform. Do not manually edit package.json — use the package manager's install command.

  • Always install packages as a background task. Don't await completion; proceed with other work immediately after starting the installation.

STEP 4: Initialize PostHog. (Skip if PostHog is already set up.)

  • Follow the framework reference for where and how to initialize. This varies significantly by framework (e.g., instrumentation-client.ts for Next.js 15.3+, AppConfig.ready() for Django, create_app() for Flask).

STEP 5: Plan event tracking.

  • 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 files related to login that could be used for identifying users, along with error handling.

  • Find any existing posthog.capture() code. Make note of event name formatting. Don't duplicate existing events; supplement them.

  • Track actions only, not pageviews (those can be captured automatically). Exceptions can be made for "viewed"-type events at the top of a conversion funnel.

  • Server-side events are REQUIRED if the project includes any instrumentable server-side code (API routes, server actions, webhook handlers, payment/checkout completion, authentication endpoints).

STEP 6: Implement event capture.

  • For each planned event, add posthog.capture() calls with useful properties.

  • 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.

  • Do not alter the fundamental architecture of existing files. Make additions minimal and targeted.

  • You must read a file immediately before attempting to write it.

STEP 7: Identify users.

  • Add PostHog identify() calls on the client side during login and signup events. Use the contents of login and signup forms to identify users on submit.

  • If both frontend and backend exist, pass the client-side session and distinct ID using X-POSTHOG-DISTINCT-ID and X-POSTHOG-SESSION-ID headers to the server-side code. On the server side, make sure events have a matching distinct ID.

STEP 8: Add error tracking.

  • Add PostHog exception capture error tracking to relevant files, particularly around critical user flows and API boundaries.

STEP 9: Set up environment variables.

  • If an env-file-tools MCP server is connected, use check_env_keys to see which keys already exist, then use set_env_values to create or update the PostHog API key and host.

  • Reference these environment variables in code instead of hardcoding them.

STEP 10: Verify and clean up.

  • Check the project for errors. Look for type checking or build scripts in package.json.

  • Ensure any components created were actually used.

  • Run any linter or prettier-like scripts found in the package.json.

Reference files

  • references/EXAMPLE-next-app-router.md - next-app-router example project code

  • references/EXAMPLE-next-pages-router.md - next-pages-router example project code

  • references/EXAMPLE-react-react-router-6.md - react-react-router-6 example project code

  • references/EXAMPLE-react-react-router-7-framework.md - react-react-router-7-framework example project code

  • references/EXAMPLE-react-react-router-7-data.md - react-react-router-7-data example project code

  • references/EXAMPLE-react-react-router-7-declarative.md - react-react-router-7-declarative example project code

  • references/EXAMPLE-nuxt-3.6.md - nuxt-3.6 example project code

  • references/EXAMPLE-nuxt-4.md - nuxt-4 example project code

  • references/EXAMPLE-vue-3.md - vue-3 example project code

  • references/EXAMPLE-react-tanstack-router-file-based.md - react-tanstack-router-file-based example project code

  • references/EXAMPLE-react-tanstack-router-code-based.md - react-tanstack-router-code-based example project code

  • references/EXAMPLE-tanstack-start.md - tanstack-start example project code

  • references/EXAMPLE-sveltekit.md - sveltekit example project code

  • references/EXAMPLE-astro-static.md - astro-static example project code

  • references/EXAMPLE-astro-view-transitions.md - astro-view-transitions example project code

  • references/EXAMPLE-astro-ssr.md - astro-ssr example project code

  • references/EXAMPLE-astro-hybrid.md - astro-hybrid example project code

  • references/EXAMPLE-angular.md - angular example project code

  • references/EXAMPLE-django.md - django example project code

  • references/EXAMPLE-flask.md - flask example project code

  • references/EXAMPLE-fastapi.md - fastapi example project code

  • references/EXAMPLE-python.md - python example project code

  • references/EXAMPLE-laravel.md - laravel example project code

  • references/EXAMPLE-ruby-on-rails.md - ruby-on-rails example project code

  • references/EXAMPLE-ruby.md - ruby example project code

  • references/EXAMPLE-android.md - android example project code

  • references/EXAMPLE-swift.md - swift example project code

  • references/EXAMPLE-react-native.md - react-native example project code

  • references/EXAMPLE-expo.md - expo example project code

  • references/next-js.md - Next.js - docs

  • references/react-router-v6.md - React router v6 - docs

  • references/react-router-v7-framework-mode.md - React router v7 framework mode (remix v3) - docs

  • references/react-router-v7-data-mode.md - React router v7 data mode - docs

  • references/react-router-v7-declarative-mode.md - React router v7 declarative mode - docs

  • references/nuxt-js-3-6.md - Nuxt.js (v3.0 to v3.6) - docs

  • references/nuxt-js.md - Nuxt.js - docs

  • references/vue-js.md - Vue.js - docs

  • references/tanstack-start.md - Tanstack start - docs

  • references/svelte.md - Svelte - docs

  • references/astro.md - Astro - docs

  • references/angular.md - Angular - docs

  • references/django.md - Django - docs

  • references/flask.md - Flask - docs

  • references/python.md - Python - docs

  • references/posthog-python.md - PostHog python SDK

  • references/laravel.md - Laravel - docs

  • references/ruby-on-rails.md - Ruby on rails - docs

  • references/ruby.md - Ruby - docs

  • references/android.md - Android - docs

  • references/ios.md - Ios - docs

  • references/react-native.md - React native - docs

  • references/identify-users.md - Identify users - docs

Each framework reference contains SDK-specific installation, initialization, and usage patterns. Find the one matching the user's stack.

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 docs: Follow the framework reference's initialization and capture patterns exactly.

Files

references/EXAMPLE-javascript-web.md

PostHog javascript-web Example Project

Repository: https://github.com/PostHog/context-mill Path: basics/javascript-web


README.md

PostHog JavaScript Example - Browser Todo App

A simple browser-based todo application built with vanilla JavaScript and Vite, demonstrating PostHog integration for non-framework JavaScript projects.

Purpose

This example serves as:

  • Verification that the context-mill wizard works for plain JavaScript projects

  • Reference implementation of PostHog best practices for vanilla JS browser apps

  • Working example you can run and modify

Features Demonstrated

  • PostHog initialization - posthog.init() with api_host configuration

  • Autocapture - Automatic tracking of clicks, form submissions, and pageviews (enabled by default)

  • Custom event tracking - Manual posthog.capture() calls with event properties

  • User identification - posthog.identify() on login and posthog.reset() on logout

  • Error tracking - posthog.captureException() for unhandled errors and promise rejections

Quick Start

1. Install Dependencies
npm install
2. Configure PostHog
# Copy environment template
cp .env.example .env

# Edit .env and add your PostHog project token
# VITE_POSTHOG_PROJECT_TOKEN=phc_your_project_token_here
# VITE_POSTHOG_HOST=https://us.i.posthog.com
3. Run the App
npm run dev

Open http://localhost:3000 in your browser.

What Gets Tracked

The app tracks these custom events in PostHog (in addition to autocaptured clicks and pageviews):

EventPropertiesPurpose
todo_addedtodo_id, text_length, total_todosWhen user adds a new todo
todo_completedtodo_id, time_to_complete_hoursWhen user completes a todo
todo_deletedtodo_id, was_completedWhen user deletes a todo
user_logged_in(none)When user logs in
user_logged_out(none)When user logs out

Code Structure

basics/javascript/
├── index.html           # Entry HTML page
├── package.json         # Dependencies (posthog-js, vite)
├── vite.config.js       # Vite configuration
├── .env.example         # Environment variable template
├── .gitignore           # Git ignore rules
├── README.md            # This file
└── src/
    ├── posthog.js       # PostHog initialization (import this first)
    ├── main.js          # Todo app logic with event tracking
    └── style.css        # App styles

Key Implementation Patterns

1. Initialization (posthog.js)
import posthog from 'posthog-js'

posthog.init('your-project-token', {
  api_host: 'https://us.i.posthog.com',
})

Initialize PostHog once, early in your app. All other modules import the same instance.

2. Event Tracking
// Track events with properties — never send PII or user-generated content
posthog.capture('event_name', {
  item_count: 5,           // Metadata is OK
  action_type: 'create',   // Categories are OK
})
3. User Identification
// On login — links events to a known user
posthog.identify('user_123')

// On logout — resets to a new anonymous distinct_id
posthog.reset()
4. Error Tracking
// Global error handlers
window.addEventListener('error', (event) => {
  posthog.captureException(event.error)
})

window.addEventListener('unhandledrejection', (event) => {
  posthog.captureException(event.reason)
})

Running Without PostHog

The app works fine without PostHog configured. You'll see a console warning but the app continues to function normally.

Next Steps

  • Modify the app to experiment with PostHog tracking

  • Explore feature flags: posthog.isFeatureEnabled('flag-key')

  • Check your PostHog dashboard to see tracked events and autocaptured data

  • Try session recording (enable in PostHog project settings)

Learn More


.env.example

# PostHog Configuration
VITE_POSTHOG_PROJECT_TOKEN=phc_your_project_token_here
VITE_POSTHOG_HOST=https://us.i.posthog.com

# Optional: Enable debug mode to see PostHog requests in console
# VITE_POSTHOG_DEBUG=true

index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Todo App - PostHog JavaScript Example</title>
    <link rel="stylesheet" href="/src/style.css" />
  </head>
  <body>
    <div id="app">
      <header>
        <h1>Todo App</h1>
        <div id="auth-section">
          <div id="logged-out">
            <input type="text" id="username-input" placeholder="Enter username" />
            <button id="login-btn">Log In</button>
          </div>
          <div id="logged-in" hidden>
            <span id="username-display"></span>
            <button id="logout-btn">Log Out</button>
          </div>
        </div>
      </header>

      <main>
        <form id="todo-form">
          <input type="text" id="todo-input" placeholder="What needs to be done?" required />
          <button type="submit">Add</button>
        </form>

        <ul id="todo-list"></ul>

        <div id="stats">
          <span id="total-count">0 items</span>
          <span id="completed-count">0 completed</span>
        </div>
      </main>
    </div>

    <script type="module" src="/src/main.js"></script>
  </body>
</html>

src/main.js

/**
 * Simple Todo App with PostHog Analytics
 *
 * A minimal vanilla JavaScript application demonstrating PostHog integration
 * for non-framework browser JavaScript projects.
 */
import posthog from './posthog.js';

// --- State ---

let todos = JSON.parse(localStorage.getItem('todos') || '[]');
let currentUser = localStorage.getItem('currentUser') || null;

// --- DOM Elements ---

const todoForm = document.getElementById('todo-form');
const todoInput = document.getElementById('todo-input');
const todoList = document.getElementById('todo-list');
const totalCount = document.getElementById('total-count');
const completedCount = document.getElementById('completed-count');
const loginBtn = document.getElementById('login-btn');
const logoutBtn = document.getElementById('logout-btn');
const usernameInput = document.getElementById('username-input');
const usernameDisplay = document.getElementById('username-display');
const loggedOutSection = document.getElementById('logged-out');
const loggedInSection = document.getElementById('logged-in');

// --- Auth ---

function login() {
  const username = usernameInput.value.trim();
  if (!username) return;

  currentUser = username;
  localStorage.setItem('currentUser', username);

  // Identify user in PostHog — links all future events to this user
  // Pass person properties as second arg (this is where name/email belong, NOT in capture())
  posthog.identify(username, { name: username });

  posthog.capture('user_logged_in');

  updateAuthUI();
  usernameInput.value = '';
}

function logout() {
  currentUser = null;
  localStorage.removeItem('currentUser');

  // Reset PostHog — unlinks future events from the current user
  // and generates a new anonymous distinct_id
  posthog.reset();

  posthog.capture('user_logged_out');

  updateAuthUI();
}

function updateAuthUI() {
  if (currentUser) {
    loggedOutSection.hidden = true;
    loggedInSection.hidden = false;
    usernameDisplay.textContent = currentUser;
  } else {
    loggedOutSection.hidden = false;
    loggedInSection.hidden = true;
  }
}

// --- Todos ---

function addTodo(text) {
  const todo = {
    id: Date.now(),
    text,
    completed: false,
    createdAt: new Date().toISOString(),
  };

  todos.push(todo);
  saveTodos();
  renderTodos();

  // Track the event — only metadata, never PII or user-generated content
  posthog.capture('todo_added', {
    todo_id: todo.id,
    text_length: text.length,
    total_todos: todos.length,
  });
}

function toggleTodo(id) {
  const todo = todos.find((t) => t.id === id);
  if (!todo) return;

  todo.completed = !todo.completed;
  saveTodos();
  renderTodos();

  if (todo.completed) {
    const timeToComplete =
      (Date.now() - new Date(todo.createdAt).getTime()) / 3600000;

    posthog.capture('todo_completed', {
      todo_id: todo.id,
      time_to_complete_hours: Math.round(timeToComplete * 100) / 100,
    });
  }
}

function deleteTodo(id) {
  const todo = todos.find((t) => t.id === id);
  if (!todo) return;

  todos = todos.filter((t) => t.id !== id);
  saveTodos();
  renderTodos();

  posthog.capture('todo_deleted', {
    todo_id: todo.id,
    was_completed: todo.completed,
  });
}

function saveTodos() {
  localStorage.setItem('todos', JSON.stringify(todos));
}

// --- Rendering ---

function renderTodos() {
  todoList.innerHTML = '';

  for (const todo of todos) {
    const li = document.createElement('li');
    li.className = `todo-item${todo.completed ? ' completed' : ''}`;

    const checkbox = document.createElement('input');
    checkbox.type = 'checkbox';
    checkbox.checked = todo.completed;
    checkbox.addEventListener('change', () => toggleTodo(todo.id));

    const text = document.createElement('span');
    text.className = 'todo-text';
    text.textContent = todo.text;

    const deleteBtn = document.createElement('button');
    deleteBtn.className = 'delete-btn';
    deleteBtn.textContent = 'Delete';
    deleteBtn.addEventListener('click', () => deleteTodo(todo.id));

    li.append(checkbox, text, deleteBtn);
    todoList.appendChild(li);
  }

  // Update stats
  const completed = todos.filter((t) => t.completed).length;
  totalCount.textContent = `${todos.length} item${todos.length !== 1 ? 's' : ''}`;
  completedCount.textContent = `${completed} completed`;
}

// --- Error Tracking ---

// Capture unhandled errors with PostHog
window.addEventListener('error', (event) => {
  posthog.captureException(event.error);
});

window.addEventListener('unhandledrejection', (event) => {
  posthog.captureException(event.reason);
});

// --- Event Listeners ---

todoForm.addEventListener('submit', (e) => {
  e.preventDefault();
  const text = todoInput.value.trim();
  if (text) {
    addTodo(text);
    todoInput.value = '';
  }
});

loginBtn.addEventListener('click', login);
usernameInput.addEventListener('keydown', (e) => {
  if (e.key === 'Enter') login();
});
logoutBtn.addEventListener('click', logout);

// --- Init ---

// Restore auth state and re-identify if already logged in
if (currentUser) {
  posthog.identify(currentUser, { name: currentUser });
}

updateAuthUI();
renderTodos();

src/posthog.js

/**
 * PostHog initialization for vanilla JavaScript.
 *
 * Initializes posthog-js once and exports the instance for use across the app.
 * This file should be imported before any other modules that call PostHog methods.
 */
import posthog from 'posthog-js';

const apiKey = import.meta.env.VITE_POSTHOG_PROJECT_TOKEN;
const apiHost = import.meta.env.VITE_POSTHOG_HOST || 'https://us.i.posthog.com';

if (!apiKey) {
  console.warn(
    'PostHog not configured (VITE_POSTHOG_PROJECT_TOKEN not set).',
    'App will work but analytics will not be tracked.',
  );
} else {
  posthog.init(apiKey, {
    api_host: apiHost,
    // Autocapture is ON by default — tracks clicks, form submissions, pageviews
    // capture_pageview: true (default) — captures $pageview on init
    // For SPAs with History API routing, use: capture_pageview: 'history_change'
  });
}

export default posthog;

vite.config.js

import { defineConfig } from 'vite';

export default defineConfig({
  server: {
    port: 3000,
  },
});

Requirements and compatibility

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Needs an MCP server, Needs an API key, Needs Python, Needs Node.js

Security

What our scanner noticed· Low risk

  • Instructions that use the network

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
PostHog
Publisher
PostHog (Official)
Source
PostHog/skills · skills/posthog/integration/skills/all · commit a5d30e7
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced
Also distributed in
PostHog/skills

AutoGineer is not affiliated with or endorsed by PostHog or PostHog.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download omnibus-instrument-product-analytics.zip