Instrument Product Analytics
PostHogOfficialCreated by PostHog
- Skill
- Tool integration
- Data and AI
- MIT
- Low risk
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
This skill provides a structured, multi-step workflow to integrate PostHog product analytics into a wide variety of software projects. It guides the user through detecting the project's framework, installing the appropriate SDK, initializing the service, and strategically placing event capture calls. The skill emphasizes non-intrusive implementation, requiring that new analytics code be added alongside existing logic without altering the project's fundamental architecture. It also covers user identification, error tracking, and secure environment variable management.
What it does
- Detects the project's framework and language to determine the correct PostHog SDK.
- Handles initial SDK installation and initialization based on framework-specific patterns.
- Identifies key user actions and business-critical events for tracking.
- Implements event capture calls and user identification logic.
- Configures environment variables securely for API tokens and host URLs.
- Verifies the integration and performs targeted linting on modified files.
When to use it
- After implementing new features that require tracking for product analytics.
- When reviewing pull requests to ensure meaningful user behaviors are captured.
- During the initial setup of a new project that needs product analytics.
- When migrating or adding analytics to an existing application.
Advantages
- Supports a broad range of frontend, backend, and mobile frameworks.
- Ensures consistent event naming and property usage across the codebase.
- Prioritizes non-breaking changes and minimal impact on existing code structure.
- Automates the complex setup of environment variables and SDK initialization.
Usage examples
- “Add PostHog analytics to my Next.js project.”
- The agent will analyze the project structure, install the PostHog SDK, initialize it in the appropriate client/server files, and prompt you to identify key events to track.
- “I need to track user signups and errors in my Django backend.”
- The agent will locate your authentication logic, add identify calls, implement exception capture, and ensure the PostHog project tokens are managed via environment variables.
Install
Download the skill as a ZIP:
https://autogineer.com/agent-skills/posthog/instrument-product-analytics/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip 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 and languages: Next.js, React Router, Nuxt, Vue, TanStack Start, SvelteKit, Astro, Angular, Django, Flask, FastAPI, Laravel, PHP, Ruby on Rails, Go, Elixir, Android, iOS, Flutter, 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, pubspec.yaml, Podfile, Package.swift, requirements.txt, Gemfile, composer.json, go.mod, mix.exs, etc.) to determine the framework and language.
Look for lockfiles (pnpm-lock.yaml, package-lock.json, yarn.lock, bun.lockb, go.sum, pubspec.lock, Podfile.lock, Package.resolved, mix.lock) 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.
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-IDandX-POSTHOG-SESSION-IDheaders 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.
Check if the project already has PostHog environment variables configured (e.g. in
.env,.env.local, or framework-specific env files). If valid values already exist, skip this step.If the PostHog project token is missing, use the PostHog MCP server's
projects-gettool to retrieve the project'sapi_token. If multiple projects are returned, ask the user which project to use. If the MCP server is not connected or not authenticated, ask the user for their PostHog project token instead.For the PostHog host URL: check the
projects-getMCP response for aregionfield —USmaps tohttps://us.i.posthog.com,EUmaps tohttps://eu.i.posthog.com. If the region is not available from the MCP response or from existing project configuration, ask the user: "Are you on PostHog US Cloud or EU Cloud?" Do not assume US Cloud.Write these values to the appropriate env file using the framework's naming convention.
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, but ONLY on the files you have edited or created during this session. Never run formatting or linting across the entire project's codebase.
Reference files
references/EXAMPLE-next-app-router.md- next-app-router example project codereferences/EXAMPLE-next-pages-router.md- next-pages-router example project codereferences/EXAMPLE-react-react-router-6.md- react-react-router-6 example project codereferences/EXAMPLE-react-react-router-7-framework.md- react-react-router-7-framework example project codereferences/EXAMPLE-react-react-router-7-data.md- react-react-router-7-data example project codereferences/EXAMPLE-react-react-router-7-declarative.md- react-react-router-7-declarative example project codereferences/EXAMPLE-nuxt-3-6.md- nuxt-3-6 example project codereferences/EXAMPLE-nuxt-4.md- nuxt-4 example project codereferences/EXAMPLE-vue-3.md- vue-3 example project codereferences/EXAMPLE-react-tanstack-router-file-based.md- react-tanstack-router-file-based example project codereferences/EXAMPLE-react-tanstack-router-code-based.md- react-tanstack-router-code-based example project codereferences/EXAMPLE-tanstack-start.md- tanstack-start example project codereferences/EXAMPLE-sveltekit.md- sveltekit example project codereferences/EXAMPLE-astro-static.md- astro-static example project codereferences/EXAMPLE-astro-view-transitions.md- astro-view-transitions example project codereferences/EXAMPLE-astro-ssr.md- astro-ssr example project codereferences/EXAMPLE-astro-hybrid.md- astro-hybrid example project codereferences/EXAMPLE-angular.md- angular example project codereferences/EXAMPLE-django.md- django example project codereferences/EXAMPLE-flask.md- flask example project codereferences/EXAMPLE-fastapi.md- fastapi example project codereferences/EXAMPLE-python.md- python example project codereferences/EXAMPLE-laravel.md- laravel example project codereferences/EXAMPLE-php.md- php example project codereferences/EXAMPLE-ruby-on-rails.md- ruby-on-rails example project codereferences/EXAMPLE-ruby.md- ruby example project codereferences/EXAMPLE-android.md- android example project codereferences/EXAMPLE-swift.md- swift example project codereferences/EXAMPLE-react-native.md- react-native example project codereferences/EXAMPLE-expo.md- expo example project codereferences/next-js.md- Next.jsreferences/react-router-v6.md- React router v6references/react-router-v7-framework-mode.md- React router v7 framework mode (remix v3)references/react-router-v7-data-mode.md- React router v7 data modereferences/react-router-v7-declarative-mode.md- React router v7 declarative modereferences/nuxt-js-3-6.md- Nuxt.js (v3.0 to v3.6)references/nuxt-js.md- Nuxt.jsreferences/vue-js.md- Vue.jsreferences/tanstack-start.md- Tanstack startreferences/svelte.md- Sveltereferences/astro.md- Astroreferences/angular.md- Angularreferences/django.md- Djangoreferences/flask.md- Flaskreferences/python.md- Pythonreferences/posthog-python.md- PostHog python SDKreferences/dotnet.md- .netreferences/elixir.md- Elixirreferences/go.md- Goreferences/laravel.md- Laravelreferences/php.md- Phpreferences/ruby-on-rails.md- Ruby on railsreferences/ruby.md- Rubyreferences/android.md- Androidreferences/ios.md- Iosreferences/usage.md- Ios SDK usagereferences/configuration.md- Ios SDK configurationreferences/flutter.md- Flutterreferences/react-native.md- React nativereferences/identify-users.md- Identify usersreferences/COMMANDMENTS.md- Framework-specific rules the integration must follow
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
- ATTRIBUTION.mdAdded by AutoGineer970 B
- LICENSELicence file added by AutoGineer1.0 KiB
- SKILL.md9.6 KiB
- references/COMMANDMENTS.md1.5 KiB
- references/EXAMPLE-android.md49.8 KiB
- references/EXAMPLE-angular.md23.1 KiB
- references/EXAMPLE-astro-hybrid.md27.5 KiB
- references/EXAMPLE-astro-ssr.md27.6 KiB
- references/EXAMPLE-astro-static.md19.6 KiB
- references/EXAMPLE-astro-view-transitions.md23.3 KiB
- references/EXAMPLE-django.md30.7 KiB
- references/EXAMPLE-expo.md35.1 KiB
- references/EXAMPLE-fastapi.md40.9 KiB
- references/EXAMPLE-flask.md32.4 KiB
- references/EXAMPLE-laravel.md59.3 KiB
- references/EXAMPLE-next-app-router.md17.6 KiB
- references/EXAMPLE-next-pages-router.md19.1 KiB
- references/EXAMPLE-nuxt-3-6.md22.3 KiB
- references/EXAMPLE-nuxt-4.md28.9 KiB
- references/EXAMPLE-php.md13.0 KiB
- references/EXAMPLE-python.md11.6 KiB
- references/EXAMPLE-react-native.md46.0 KiB
- references/EXAMPLE-react-react-router-6.md13.5 KiB
- references/EXAMPLE-react-react-router-7-data.md20.1 KiB
- references/EXAMPLE-react-react-router-7-declarative.md15.0 KiB
- references/EXAMPLE-react-react-router-7-framework.md32.5 KiB
- references/EXAMPLE-react-tanstack-router-code-based.md19.6 KiB
- references/EXAMPLE-react-tanstack-router-file-based.md18.3 KiB
- references/EXAMPLE-ruby-on-rails.md38.0 KiB
- references/EXAMPLE-ruby.md10.0 KiB
- references/EXAMPLE-sveltekit.md18.6 KiB
- references/EXAMPLE-swift.md18.8 KiB
- references/EXAMPLE-tanstack-start.md29.9 KiB
- references/EXAMPLE-vue-3.md17.9 KiB
- references/android.md33.3 KiB
- references/angular.md16.5 KiB
- references/astro.md15.8 KiB
- references/configuration.md17.2 KiB
- references/django.md14.9 KiB
- references/dotnet.md25.8 KiB
- references/elixir.md17.6 KiB
- references/flask.md8.1 KiB
- references/flutter.md42.8 KiB
- references/go.md20.1 KiB
- references/identify-users.md12.2 KiB
- references/ios.md8.0 KiB
- references/laravel.md13.1 KiB
- references/next-js.md18.3 KiB
- references/nuxt-js-3-6.md11.4 KiB
- references/nuxt-js.md15.1 KiB
- references/php.md23.7 KiB
- references/posthog-python.md69.3 KiB
- references/python.md52.2 KiB
- references/react-native.md59.9 KiB
- references/react-router-v6.md13.6 KiB
- references/react-router-v7-data-mode.md13.5 KiB
- references/react-router-v7-declarative-mode.md13.7 KiB
- references/react-router-v7-framework-mode.md20.2 KiB
- references/ruby-on-rails.md19.7 KiB
- references/ruby.md25.5 KiB
- references/svelte.md14.6 KiB
- references/tanstack-start.md12.8 KiB
- references/usage.md29.2 KiB
- references/vue-js.md13.4 KiB
references/EXAMPLE-flask.md
PostHog flask Example Project
Repository: https://github.com/PostHog/context-mill Path: example-apps/flask
README.md
PostHog Flask Example
A Flask application demonstrating PostHog integration for analytics, feature flags, and error tracking.
Features
User registration and authentication with Flask-Login
SQLite database persistence with Flask-SQLAlchemy
User identification and property tracking
Custom event tracking
Feature flags with payload support
Error tracking with manual exception capture
Quick Start
Create and activate a virtual environment:
python -m venv venv source venv/bin/activate # On Windows: venv\Scripts\activateInstall dependencies:
pip install -r requirements.txtCopy the environment file and configure:
cp .env.example .env # Edit .env with your PostHog project keyRun the application:
python run.pyOpen http://localhost:5001 and either:
Login with default credentials:
[email protected]/adminOr click "Sign up here" to create a new account
PostHog Integration Points
User Registration
New users are identified and tracked on signup using the context-based API:
with new_context():
identify_context(user.email)
tag('email', user.email)
tag('is_staff', user.is_staff)
capture('user_signed_up', properties={'signup_method': 'form'})User Identification
Users are identified on login with their properties:
with new_context():
identify_context(user.email)
tag('email', user.email)
tag('is_staff', user.is_staff)
capture('user_logged_in', properties={'login_method': 'password'})Event Tracking
Custom events are captured throughout the app:
with new_context():
identify_context(current_user.email)
capture('burrito_considered', properties={'total_considerations': count})Feature Flags
The dashboard demonstrates feature flag checking:
show_new_feature = posthog.feature_enabled(
'new-dashboard-feature',
current_user.email,
person_properties={'email': current_user.email, 'is_staff': current_user.is_staff}
)
feature_config = posthog.get_feature_flag_payload('new-dashboard-feature', current_user.email)Error Tracking
The example demonstrates two approaches to error tracking:
Manual capture for specific critical operations** (app/api/routes.py).
try:
# Critical operation that might fail
result = process_payment()
except Exception as e:
# Manually capture this specific exception
with new_context():
identify_context(current_user.email)
event_id = posthog.capture_exception(e)
return jsonify({
"error": "Operation failed",
"error_id": event_id,
"message": f"Error captured in PostHog. Reference ID: {event_id}"
}), 500The /api/test-error endpoint demonstrates manual exception capture. Use ?capture=true to capture in PostHog, or ?capture=false to skip tracking.
Project Structure
example-apps/flask/
├── app/
│ ├── __init__.py # Application factory
│ ├── config.py # Configuration classes
│ ├── extensions.py # Extension instances
│ ├── models.py # User model (SQLAlchemy)
│ ├── main/
│ │ ├── __init__.py # Main blueprint
│ │ └── routes.py # View functions
│ ├── templates/ # HTML templates
│ └── api/
│ ├── __init__.py # API blueprint
│ └── routes.py # API endpoints
├── .env.example
├── .gitignore
├── requirements.txt
├── README.md
└── run.py # Entry point.env.example
POSTHOG_PROJECT_TOKEN=<ph_project_token>
POSTHOG_HOST=https://us.i.posthog.com
FLASK_SECRET_KEY=your-secret-key-here
FLASK_DEBUG=True
POSTHOG_DISABLED=False
app/init.py
"""Flask application factory."""
import posthog
from flask import Flask, g, jsonify, render_template, request
from flask_login import current_user
from posthog import identify_context, new_context
from werkzeug.exceptions import HTTPException
from app.config import config
from app.extensions import db, login_manager
def create_app(config_name="default"):
"""Application factory."""
app = Flask(__name__)
app.config.from_object(config[config_name])
# Initialize extensions
db.init_app(app)
login_manager.init_app(app)
# Initialize PostHog
if not app.config["POSTHOG_DISABLED"]:
posthog.api_key = app.config["POSTHOG_PROJECT_TOKEN"]
posthog.host = app.config["POSTHOG_HOST"]
posthog.debug = app.config["DEBUG"]
# Import models after db is initialized
from app.models import User
# User loader for Flask-Login
@login_manager.user_loader
def load_user(user_id):
return User.get_by_id(user_id)
# Simple error handlers - no automatic PostHog capture
# Capture exceptions manually only where it makes sense (e.g., test endpoints)
@app.errorhandler(404)
def page_not_found(e):
if request.path.startswith('/api/'):
return jsonify({"error": "Not found"}), 404
return render_template('errors/404.html'), 404
@app.errorhandler(500)
def internal_server_error(e):
if request.path.startswith('/api/'):
return jsonify({"error": "Internal server error"}), 500
return render_template('errors/500.html'), 500
# Register blueprints
from app.api import api_bp
from app.main import main_bp
app.register_blueprint(main_bp)
app.register_blueprint(api_bp, url_prefix="/api")
# Create database tables and seed default admin user
with app.app_context():
db.create_all()
if not User.get_by_email("[email protected]"):
User.create_user(
email="[email protected]",
password="admin",
is_staff=True,
)
return app
app/api/init.py
"""API blueprint registration."""
from flask import Blueprint
api_bp = Blueprint("api", __name__)
from app.api import routes # noqa: E402, F401
app/api/routes.py
"""API endpoints demonstrating PostHog integration patterns."""
import posthog
from flask import jsonify, request, session
from flask_login import current_user, login_required
from posthog import capture, identify_context, new_context
from app.api import api_bp
@api_bp.route("/burrito/consider", methods=["POST"])
@login_required
def consider_burrito():
"""Track burrito consideration event."""
# Increment session counter
burrito_count = session.get("burrito_count", 0) + 1
session["burrito_count"] = burrito_count
# PostHog: Capture custom event
with new_context():
identify_context(str(current_user.id))
capture("burrito_considered", properties={"total_considerations": burrito_count})
return jsonify({"success": True, "count": burrito_count})
@api_bp.route("/test-error", methods=["POST"])
@login_required
def test_error():
"""Test endpoint demonstrating manual exception capture in PostHog.
Shows how to intentionally capture specific errors in PostHog.
Use this pattern for critical operations where you want error tracking.
Query params:
- capture: "true" to capture the exception in PostHog, "false" to just raise it
"""
should_capture = request.args.get("capture", "true").lower() == "true"
try:
# Simulate a critical operation failure
raise Exception("Test exception from critical operation")
except Exception as e:
if should_capture:
# Manually capture this specific exception in PostHog
with new_context():
identify_context(str(current_user.id))
event_id = posthog.capture_exception(e)
return jsonify({
"error": "Operation failed",
"error_id": event_id,
"message": f"Error captured in PostHog. Reference ID: {event_id}"
}), 500
else:
# Just return error without PostHog capture
return jsonify({"error": str(e)}), 500
app/config.py
"""Flask application configuration."""
import os
from dotenv import load_dotenv
load_dotenv()
class Config:
"""Base configuration."""
SECRET_KEY = os.environ.get("FLASK_SECRET_KEY", "dev-secret-key-change-in-production")
# Database configuration (SQLite like Django example)
SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL", "sqlite:///db.sqlite3")
SQLALCHEMY_TRACK_MODIFICATIONS = False
# PostHog configuration
POSTHOG_PROJECT_TOKEN = os.environ.get("POSTHOG_PROJECT_TOKEN", "<ph_project_token>")
POSTHOG_HOST = os.environ.get("POSTHOG_HOST", "https://us.i.posthog.com")
POSTHOG_DISABLED = os.environ.get("POSTHOG_DISABLED", "False").lower() == "true"
class DevelopmentConfig(Config):
"""Development configuration."""
DEBUG = True
class ProductionConfig(Config):
"""Production configuration."""
DEBUG = False
config = {
"development": DevelopmentConfig,
"production": ProductionConfig,
"default": DevelopmentConfig,
}
app/extensions.py
"""Flask extensions initialized without binding to app."""
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
login_manager = LoginManager()
login_manager.login_view = "main.home"
login_manager.login_message = "Please log in to access this page."
app/main/init.py
"""Main blueprint registration."""
from flask import Blueprint
main_bp = Blueprint("main", __name__, template_folder="../templates")
from app.main import routes # noqa: E402, F401
app/main/routes.py
"""Core view functions demonstrating PostHog integration patterns."""
import posthog
from flask import flash, redirect, render_template, request, session, url_for
from flask_login import current_user, login_required, login_user, logout_user
from posthog import capture, identify_context, new_context
from app.main import main_bp
from app.models import User
@main_bp.route("/", methods=["GET", "POST"])
def home():
"""Home/login page."""
if current_user.is_authenticated:
return redirect(url_for("main.dashboard"))
if request.method == "POST":
email = request.form.get("email")
password = request.form.get("password")
user = User.authenticate(email, password)
if user:
login_user(user)
# PostHog: Identify user and capture login event
with new_context():
identify_context(str(user.id))
# PII belongs in person properties, never in event properties
posthog.set(
distinct_id=str(user.id),
properties={
"email": user.email,
"is_staff": user.is_staff,
"date_joined": user.date_joined.isoformat(),
},
)
capture("user_logged_in", properties={"login_method": "password"})
return redirect(url_for("main.dashboard"))
else:
flash("Invalid email or password", "error")
return render_template("home.html")
@main_bp.route("/signup", methods=["GET", "POST"])
def signup():
"""User registration page."""
if current_user.is_authenticated:
return redirect(url_for("main.dashboard"))
if request.method == "POST":
email = request.form.get("email")
password = request.form.get("password")
password_confirm = request.form.get("password_confirm")
# Validation
if not email or not password:
flash("Email and password are required", "error")
elif password != password_confirm:
flash("Passwords do not match", "error")
elif User.get_by_email(email):
flash("Email already registered", "error")
else:
# Create new user
user = User.create_user(
email=email,
password=password,
is_staff=False,
)
# PostHog: Identify new user and capture signup event
with new_context():
identify_context(str(user.id))
posthog.set(
distinct_id=str(user.id),
properties={
"email": user.email,
"is_staff": user.is_staff,
"date_joined": user.date_joined.isoformat(),
},
)
capture("user_signed_up", properties={"signup_method": "form"})
# Log the user in
login_user(user)
flash("Account created successfully!", "success")
return redirect(url_for("main.dashboard"))
return render_template("signup.html")
@main_bp.route("/logout")
@login_required
def logout():
"""Logout and capture event."""
# PostHog: Capture logout event before session ends
with new_context():
identify_context(str(current_user.id))
capture("user_logged_out")
logout_user()
return redirect(url_for("main.home"))
@main_bp.route("/dashboard")
@login_required
def dashboard():
"""Dashboard with feature flag demonstration."""
# PostHog: Capture dashboard view
with new_context():
identify_context(str(current_user.id))
capture("dashboard_viewed", properties={"is_staff": current_user.is_staff})
# Check feature flag
show_new_feature = posthog.feature_enabled(
"new-dashboard-feature",
current_user.email,
person_properties={
"email": current_user.email,
"is_staff": current_user.is_staff,
},
)
# Get feature flag payload
feature_config = posthog.get_feature_flag_payload(
"new-dashboard-feature", current_user.email
)
return render_template(
"dashboard.html",
show_new_feature=show_new_feature,
feature_config=feature_config,
)
@main_bp.route("/burrito")
@login_required
def burrito():
"""Burrito consideration tracker page."""
burrito_count = session.get("burrito_count", 0)
return render_template("burrito.html", burrito_count=burrito_count)
@main_bp.route("/profile")
@login_required
def profile():
"""User profile page."""
# PostHog: Capture profile view
with new_context():
identify_context(str(current_user.id))
capture("profile_viewed")
return render_template("profile.html")
app/models.py
"""User model with SQLite persistence (similar to Django's auth.User)."""
from datetime import datetime, timezone
from flask_login import UserMixin
from werkzeug.security import check_password_hash, generate_password_hash
from app.extensions import db
class User(UserMixin, db.Model):
"""User model with SQLite persistence."""
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String(254), unique=True, nullable=False)
password_hash = db.Column(db.String(256), nullable=False)
is_staff = db.Column(db.Boolean, default=False)
is_active = db.Column(db.Boolean, default=True)
date_joined = db.Column(db.DateTime, default=lambda: datetime.now(timezone.utc))
def set_password(self, password):
"""Hash and set the user's password."""
self.password_hash = generate_password_hash(password)
def check_password(self, password):
"""Verify the password against the hash."""
return check_password_hash(self.password_hash, password)
@classmethod
def create_user(cls, email, password, is_staff=False):
"""Create and save a new user."""
user = cls(email=email, is_staff=is_staff)
# nosemgrep: python.django.security.audit.unvalidated-password.unvalidated-password
user.set_password(password)
db.session.add(user)
db.session.commit()
return user
@classmethod
def get_by_id(cls, user_id):
"""Get user by ID."""
return cls.query.get(int(user_id))
@classmethod
def get_by_email(cls, email):
"""Get user by email."""
return cls.query.filter_by(email=email).first()
@classmethod
def authenticate(cls, email, password):
"""Authenticate user with email and password."""
user = cls.get_by_email(email)
if user and user.check_password(password):
return user
return None
def __repr__(self):
return f"<User {self.email}>"
app/templates/base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}PostHog Flask Example{% endblock %}</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
line-height: 1.6;
background-color: #f5f5f5;
color: #333;
}
.container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
nav {
background: #1d4ed8;
padding: 15px 20px;
margin-bottom: 30px;
}
nav a {
color: white;
text-decoration: none;
margin-right: 20px;
}
nav a:hover {
text-decoration: underline;
}
.card {
background: white;
border-radius: 8px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
h1, h2, h3 {
margin-bottom: 15px;
color: #1d4ed8;
}
button, .btn {
background: #1d4ed8;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
display: inline-block;
text-decoration: none;
}
button:hover, .btn:hover {
background: #1e40af;
}
button.danger {
background: #dc2626;
}
button.danger:hover {
background: #b91c1c;
}
input {
width: 100%;
padding: 10px;
margin-bottom: 15px;
border: 1px solid #ddd;
border-radius: 5px;
font-size: 14px;
}
.messages {
margin-bottom: 20px;
}
.message {
padding: 10px 15px;
border-radius: 5px;
margin-bottom: 10px;
}
.message.error {
background: #fee2e2;
color: #dc2626;
}
.message.success {
background: #d1fae5;
color: #059669;
}
.feature-flag {
background: #fef3c7;
border: 2px dashed #f59e0b;
padding: 15px;
border-radius: 8px;
margin: 20px 0;
}
code {
background: #f3f4f6;
padding: 2px 6px;
border-radius: 3px;
font-family: monospace;
}
pre {
background: #1e293b;
color: #e2e8f0;
padding: 16px;
border-radius: 8px;
overflow-x: auto;
font-size: 13px;
}
.count {
font-size: 48px;
font-weight: bold;
color: #1d4ed8;
text-align: center;
padding: 20px;
}
table {
width: 100%;
border-collapse: collapse;
margin: 16px 0;
}
th, td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #eee;
}
th {
background: #f8fafc;
font-weight: 600;
}
</style>
</head>
<body>
{% if current_user.is_authenticated %}
<nav>
<a href="{{ url_for('main.dashboard') }}">Dashboard</a>
<a href="{{ url_for('main.burrito') }}">Burrito</a>
<a href="{{ url_for('main.profile') }}">Profile</a>
<a href="{{ url_for('main.logout') }}" style="float: right;">Logout ({{ current_user.email }})</a>
</nav>
{% endif %}
<div class="container">
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
<div class="messages">
{% for category, message in messages %}
<div class="message {{ category }}">{{ message }}</div>
{% endfor %}
</div>
{% endif %}
{% endwith %}
{% block content %}{% endblock %}
</div>
{% block scripts %}{% endblock %}
</body>
</html>
app/templates/burrito.html
{% extends "base.html" %}
{% block title %}Burrito - PostHog Flask Example{% endblock %}
{% block content %}
<div class="card">
<h1>Burrito Consideration Tracker</h1>
<p>This page demonstrates custom event tracking with PostHog.</p>
<div class="count" id="burrito-count">{{ burrito_count }}</div>
<p style="text-align: center; color: #666;">Times you've considered a burrito</p>
<div style="text-align: center; margin-top: 20px;">
<button onclick="considerBurrito()">Consider a Burrito</button>
</div>
</div>
<div class="card">
<h3>Code Example</h3>
<pre>
# API endpoint captures the event
with new_context():
identify_context(current_user.email)
capture('burrito_considered', properties={
'total_considerations': burrito_count
})</pre>
</div>
{% endblock %}
{% block scripts %}
<script>
async function considerBurrito() {
try {
const response = await fetch('/api/burrito/consider', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
const data = await response.json();
if (data.success) {
document.getElementById('burrito-count').textContent = data.count;
}
} catch (error) {
console.error('Error:', error);
}
}
</script>
{% endblock %}
app/templates/dashboard.html
{% extends "base.html" %}
{% block title %}Dashboard - PostHog Flask Example{% endblock %}
{% block content %}
<div class="card">
<h1>Dashboard</h1>
<p>Welcome back, {{ current_user.username }}!</p>
</div>
<div class="card">
<h2>Feature Flags</h2>
{% if show_new_feature %}
<div class="feature-flag">
<strong>New Feature Enabled!</strong>
<p>You're seeing this because the <code>new-dashboard-feature</code> flag is enabled for you.</p>
{% if feature_config %}
<p><strong>Feature Configuration:</strong></p>
<pre>{{ feature_config | tojson(indent=2) }}</pre>
{% endif %}
</div>
{% else %}
<p>The <code>new-dashboard-feature</code> flag is not enabled for your account.</p>
{% endif %}
<h3 style="margin-top: 20px;">Code Example</h3>
<pre>
# Check if feature flag is enabled
show_new_feature = posthog.feature_enabled(
'new-dashboard-feature',
user_id,
person_properties={
'email': current_user.email,
'is_staff': current_user.is_staff
}
)
# Get feature flag payload
feature_config = posthog.get_feature_flag_payload(
'new-dashboard-feature',
user_id
)</pre>
</div>
{% endblock %}
app/templates/errors/404.html
{% extends "base.html" %}
{% block title %}404 - Page Not Found{% endblock %}
{% block content %}
<div class="card" style="text-align: center; padding: 60px 20px;">
<h1 style="font-size: 72px; color: #dc2626; margin-bottom: 10px;">404</h1>
<h2 style="color: #333; margin-bottom: 20px;">Page Not Found</h2>
<p style="font-size: 18px; color: #666; margin-bottom: 30px;">
The page you're looking for doesn't exist or has been moved.
</p>
{% if error_id %}
<div style="background: #fef3c7; border: 1px solid #fbbf24; border-radius: 8px; padding: 15px; margin: 30px 0;">
<p style="color: #92400e; margin-bottom: 5px; font-weight: 600;">Error Reference ID:</p>
<code style="background: #fff; padding: 5px 10px; border-radius: 4px; font-family: monospace; color: #1e40af;">{{ error_id }}</code>
<p style="color: #92400e; margin-top: 10px; font-size: 14px;">
Share this ID with support if you need assistance.
</p>
</div>
{% endif %}
<div style="margin-top: 40px;">
<a href="{{ url_for('main.home') }}" class="btn" style="margin-right: 10px;">Go to Home</a>
{% if current_user.is_authenticated %}
<a href="{{ url_for('main.dashboard') }}" class="btn">Go to Dashboard</a>
{% endif %}
</div>
</div>
{% endblock %}
app/templates/errors/500.html
{% extends "base.html" %}
{% block title %}500 - Internal Server Error{% endblock %}
{% block content %}
<div class="card" style="text-align: center; padding: 60px 20px;">
<h1 style="font-size: 72px; color: #dc2626; margin-bottom: 10px;">500</h1>
<h2 style="color: #333; margin-bottom: 20px;">Internal Server Error</h2>
<p style="font-size: 18px; color: #666; margin-bottom: 30px;">
Something went wrong on our end. We've been notified and are looking into it.
</p>
{% if error_id %}
<div style="background: #fef3c7; border: 1px solid #fbbf24; border-radius: 8px; padding: 15px; margin: 30px 0;">
<p style="color: #92400e; margin-bottom: 5px; font-weight: 600;">Error Reference ID:</p>
<code style="background: #fff; padding: 5px 10px; border-radius: 4px; font-family: monospace; color: #1e40af;">{{ error_id }}</code>
<p style="color: #92400e; margin-top: 10px; font-size: 14px;">
Share this ID with support if you need assistance. This error has been logged in PostHog.
</p>
</div>
{% endif %}
{% if error and config.DEBUG %}
<div style="background: #fee2e2; border: 1px solid #dc2626; border-radius: 8px; padding: 15px; margin: 30px 0; text-align: left;">
<p style="color: #7f1d1d; margin-bottom: 5px; font-weight: 600;">Debug Information:</p>
<code style="background: #fff; padding: 10px; border-radius: 4px; font-family: monospace; color: #dc2626; display: block; overflow-x: auto;">{{ error }}</code>
</div>
{% endif %}
<div style="margin-top: 40px;">
<a href="{{ url_for('main.home') }}" class="btn" style="margin-right: 10px;">Go to Home</a>
{% if current_user.is_authenticated %}
<a href="{{ url_for('main.dashboard') }}" class="btn">Go to Dashboard</a>
{% endif %}
</div>
</div>
{% endblock %}
app/templates/home.html
{% extends "base.html" %}
{% block title %}Login - PostHog Flask Example{% endblock %}
{% block content %}
<div class="card">
<h1>Welcome to PostHog Flask Example</h1>
<p>This example demonstrates how to integrate PostHog with a Flask application.</p>
<form method="POST">
<label for="email">Email</label>
<input type="email" id="email" name="email" required>
<label for="password">Password</label>
<input type="password" id="password" name="password" required>
<button type="submit">Login</button>
</form>
<p style="margin-top: 16px; font-size: 14px; color: #666;">
Don't have an account? <a href="{{ url_for('main.signup') }}">Sign up here</a>
</p>
<p style="font-size: 14px; color: #666;">
<strong>Tip:</strong> Default credentials are [email protected]/admin
</p>
</div>
<div class="card">
<h2>Features Demonstrated</h2>
<ul style="margin-left: 20px; color: #666;">
<li>User registration and identification</li>
<li>Event tracking</li>
<li>Feature flags</li>
<li>Error tracking</li>
<li>Group analytics</li>
</ul>
</div>
{% endblock %}
app/templates/profile.html
{% extends "base.html" %}
{% block title %}Profile - PostHog Flask Example{% endblock %}
{% block content %}
<div class="card">
<h1>Your Profile</h1>
<p>This page demonstrates error tracking with PostHog.</p>
<table>
<tr>
<th>Email</th>
<td>{{ current_user.email }}</td>
</tr>
<tr>
<th>Date Joined</th>
<td>{{ current_user.date_joined.strftime('%Y-%m-%d %H:%M') }}</td>
</tr>
<tr>
<th>Staff Status</th>
<td>{{ 'Yes' if current_user.is_staff else 'No' }}</td>
</tr>
</table>
</div>
<div class="card">
<h2>Error Tracking Demo</h2>
<p>Click a button to trigger an error and see it captured in PostHog:</p>
<div style="margin: 20px 0;">
<button class="danger" onclick="triggerError('value')">
Trigger ValueError
</button>
<button class="danger" onclick="triggerError('key')">
Trigger KeyError
</button>
<button class="danger" onclick="triggerError('generic')">
Trigger Generic Error
</button>
</div>
<div id="error-result" style="display: none;" class="message"></div>
</div>
<div class="card">
<h3>Code Example</h3>
<pre>
try:
raise ValueError('Invalid value provided')
except Exception as e:
# Capture exception and event with user context
with new_context():
identify_context(current_user.email)
posthog.capture_exception(e)
capture('error_triggered', properties={
'error_type': 'value',
'error_message': str(e)
})</pre>
</div>
{% endblock %}
{% block scripts %}
<script>
async function triggerError(errorType) {
const resultDiv = document.getElementById('error-result');
try {
const formData = new FormData();
formData.append('error_type', errorType);
const response = await fetch('/api/trigger-error', {
method: 'POST',
body: formData
});
const data = await response.json();
resultDiv.style.display = 'block';
resultDiv.className = 'message ' + (data.success ? 'success' : 'error');
resultDiv.textContent = data.message + ': ' + data.error;
} catch (error) {
console.error('Error:', error);
resultDiv.style.display = 'block';
resultDiv.className = 'message error';
resultDiv.textContent = 'Request failed: ' + error.message;
}
}
</script>
{% endblock %}
app/templates/signup.html
{% extends "base.html" %}
{% block title %}Sign Up - PostHog Flask Example{% endblock %}
{% block content %}
<div class="card">
<h1>Create an Account</h1>
<p>Sign up to explore the PostHog Flask integration example.</p>
<form method="POST">
<label for="email">Email *</label>
<input type="email" id="email" name="email" required>
<label for="password">Password *</label>
<input type="password" id="password" name="password" required>
<label for="password_confirm">Confirm Password *</label>
<input type="password" id="password_confirm" name="password_confirm" required>
<button type="submit">Sign Up</button>
</form>
<p style="margin-top: 16px; font-size: 14px; color: #666;">
Already have an account? <a href="{{ url_for('main.home') }}">Login here</a>
</p>
</div>
<div class="card">
<h2>PostHog Integration</h2>
<p>When you sign up, the following PostHog events are captured:</p>
<ul style="margin-left: 20px; color: #666;">
<li><code>identify_context()</code> - Associates your email with the context</li>
<li><code>tag()</code> - Sets person properties (email, etc.)</li>
<li><code>user_signed_up</code> event - Tracks the signup action</li>
</ul>
<h3 style="margin-top: 20px;">Code Example</h3>
<pre>
# After creating the user
with new_context():
identify_context(user.email)
tag('email', user.email)
tag('is_staff', user.is_staff)
tag('date_joined', user.date_joined.isoformat())
capture('user_signed_up', properties={'signup_method': 'form'})</pre>
</div>
{% endblock %}
requirements.txt
Flask>=3.1.0
Flask-Login>=0.6.3
Flask-SQLAlchemy>=3.1.0
python-dotenv>=1.0.0
posthog>=3.0.0
Werkzeug>=3.0.0
run.py
"""Development server entry point."""
from app import create_app
app = create_app()
if __name__ == "__main__":
app.run(port=5001)
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 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/omnibus/instrument-product-analytics · commit a5d30e7
- Licence
- MIT License (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
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 instrument-product-analytics.zip