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://mp-staging.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-astro-hybrid.md
PostHog astro-hybrid Example Project
Repository: https://github.com/PostHog/context-mill Path: example-apps/astro-hybrid
README.md
PostHog Astro Hybrid Example
This is an Astro hybrid rendering example demonstrating PostHog integration with both static and on-demand rendered pages.
Hybrid mode allows you to have most pages prerendered (static) while opting specific pages into server-side rendering (SSR) when needed.
It uses:
Client-side: PostHog web snippet for browser analytics
Server-side:
posthog-nodefor API route event tracking
This shows how to:
Configure Astro for hybrid rendering (static default with per-page SSR opt-in)
Opt specific pages into SSR with
export const prerender = falseKeep most pages static for performance
Track events from API routes using
posthog-nodeLink client and server sessions automatically with the
tracing_headersoption
Features
Hybrid rendering: Static pages by default, SSR when needed
API routes: Server-side endpoints for auth and event tracking
Dual tracking: Events captured on both client and server
Session continuity: Session and distinct ID forwarded automatically via
tracing_headersProduct analytics: Track login and burrito consideration events
Error tracking: Manual error capture sent to PostHog
Getting started
1. Install dependencies
npm install
# or
pnpm install2. Configure environment variables
Create a .env file in the project root:
PUBLIC_POSTHOG_PROJECT_TOKEN=your_posthog_project_token
PUBLIC_POSTHOG_HOST=https://us.i.posthog.comGet your PostHog project token from your project settings in PostHog.
3. Run the development server
npm run dev
# or
pnpm devOpen http://localhost:4321 in your browser.
Project structure
src/
components/
posthog.astro # PostHog snippet for client-side tracking
Header.astro # Navigation + logout, calls posthog.reset()
layouts/
PostHogLayout.astro # Root layout that includes PostHog + Header
lib/
auth.ts # Client-side auth utilities
posthog-server.ts # Server-side PostHog client singleton
pages/
index.astro # Static (prerendered) - login form
burrito.astro # SSR (prerender=false) - calls API routes
profile.astro # Static (prerendered) - user profile
api/
auth/
login.ts # Server-side login endpoint with PostHog tracking
events/
burrito.ts # Server-side event capture endpoint
styles/
global.css # Global stylesKey integration points
Hybrid mode configuration (astro.config.mjs)
In Astro 5, output: 'static' is the default and supports per-page SSR opt-in. You need an adapter for the SSR pages to work:
import { defineConfig } from "astro/config";
import node from "@astrojs/node";
export default defineConfig({
// 'static' is the default - pages are prerendered unless they opt out
output: "static",
adapter: node({ mode: "standalone" }),
});Opting a page into SSR (src/pages/burrito.astro)
---
// Opt this page into on-demand rendering (SSR)
// In hybrid mode, pages are static by default
export const prerender = false;
---Server-side PostHog client (src/lib/posthog-server.ts)
A singleton pattern ensures only one PostHog client is created:
import { PostHog } from "posthog-node";
let posthogClient: PostHog | null = null;
export function getPostHogServer(): PostHog {
if (!posthogClient) {
posthogClient = new PostHog(import.meta.env.PUBLIC_POSTHOG_PROJECT_TOKEN, {
host: import.meta.env.PUBLIC_POSTHOG_HOST,
flushAt: 1,
flushInterval: 0,
});
}
return posthogClient;
}API route with server-side tracking (src/pages/api/events/burrito.ts)
import { getPostHogServer } from "../../../lib/posthog-server";
export const POST: APIRoute = async ({ request }) => {
const body = await request.json();
const sessionId = request.headers.get("X-PostHog-Session-Id");
const posthog = getPostHogServer();
posthog.capture({
distinctId: body.username,
event: "burrito_considered",
properties: {
$session_id: sessionId || undefined,
source: "api",
},
});
return new Response(JSON.stringify({ success: true }));
};When to use Hybrid mode
Use hybrid mode when you want:
Performance: Most pages prerendered as static HTML
Flexibility: Some pages need server-side logic (auth, personalization)
API routes: Server-side endpoints for data processing
Scripts
# Run dev server
npm run dev
# Build for production
npm run build
# Preview production build
npm run previewLearn more
.env.example
PUBLIC_POSTHOG_PROJECT_TOKEN=your_posthog_project_token_here
PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
astro.config.mjs
import { defineConfig } from "astro/config";
import node from "@astrojs/node";
export default defineConfig({
// In Astro 5, 'static' is the default and supports per-page SSR opt-in
// Use `export const prerender = false` in pages that need server rendering
output: "static",
adapter: node({
mode: "standalone",
}),
image: {
service: { entrypoint: "astro/assets/services/noop" },
},
});
src/components/Header.astro
---
// Header component with navigation and logout functionality
---
<header class="header">
<div class="header-container">
<nav>
<a href="/">Home</a>
<a href="/burrito" class="auth-link" style="display: none;">Burrito Consideration</a>
<a href="/profile" class="auth-link" style="display: none;">Profile</a>
</nav>
<div class="user-section">
<span class="welcome-text" style="display: none;">Welcome, <span class="username"></span>!</span>
<span class="not-logged-in">Not logged in</span>
<button class="btn-logout" style="display: none;">Logout</button>
</div>
</div>
</header>
<script is:inline>
function updateHeader() {
const currentUser = localStorage.getItem('currentUser');
const authLinks = document.querySelectorAll('.auth-link');
const welcomeText = document.querySelector('.welcome-text');
const notLoggedIn = document.querySelector('.not-logged-in');
const logoutBtn = document.querySelector('.btn-logout');
const usernameSpan = document.querySelector('.username');
if (currentUser) {
authLinks.forEach(link => link.style.display = 'inline');
welcomeText.style.display = 'inline';
notLoggedIn.style.display = 'none';
logoutBtn.style.display = 'inline';
usernameSpan.textContent = currentUser;
} else {
authLinks.forEach(link => link.style.display = 'none');
welcomeText.style.display = 'none';
notLoggedIn.style.display = 'inline';
logoutBtn.style.display = 'none';
}
}
function handleLogout() {
const currentUser = localStorage.getItem('currentUser');
if (currentUser) {
window.posthog?.capture('user_logged_out');
}
localStorage.removeItem('currentUser');
localStorage.removeItem('burritoConsiderations');
// IMPORTANT: Reset the PostHog instance to clear the user session
window.posthog?.reset();
window.location.href = '/';
}
document.addEventListener('DOMContentLoaded', () => {
updateHeader();
document.querySelector('.btn-logout')?.addEventListener('click', handleLogout);
});
// Listen for storage changes (login/logout in other tabs)
window.addEventListener('storage', updateHeader);
</script>
<style>
.header {
background-color: #333;
color: white;
padding: 1rem;
}
.header-container {
max-width: 1200px;
margin: 0 auto;
display: flex;
justify-content: space-between;
align-items: center;
}
.header nav {
display: flex;
gap: 1rem;
}
.header a {
color: white;
text-decoration: none;
padding: 0.5rem 1rem;
border-radius: 4px;
transition: background-color 0.2s;
}
.header a:hover {
background-color: #555;
text-decoration: none;
}
.user-section {
display: flex;
align-items: center;
gap: 1rem;
}
.btn-logout {
background-color: #dc3545;
color: white;
border: none;
padding: 0.5rem 1rem;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
}
.btn-logout:hover {
background-color: #c82333;
}
</style>
src/components/posthog.astro
---
// PostHog analytics snippet for client-side tracking
// Uses is:inline to prevent Astro from processing the script
---
<script is:inline define:vars={{ apiKey: import.meta.env.PUBLIC_POSTHOG_PROJECT_TOKEN, apiHost: import.meta.env.PUBLIC_POSTHOG_HOST }}>
// POSTHOG_BROWSER_SNIPPET_START
!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],Object.defineProperty(u,"toString",{configurable:!0,enumerable:!0,writable:!0,value:function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e}}),Object.defineProperty(u.people,"toString",{configurable:!0,enumerable:!0,writable:!0,value:function(){return u.toString(1)+".people (stub)"}}),o="capture identify alias people.set people.set_once set_config register register_once unregister opt_out_capturing has_opted_out_capturing opt_in_capturing reset isFeatureEnabled onFeatureFlags getFeatureFlag getFeatureFlagPayload reloadFeatureFlags group updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures getActiveMatchingSurveys getSurveys getNextSurveyStep onSessionId".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);
// POSTHOG_BROWSER_SNIPPET_END
posthog.init(apiKey || '', {
api_host: apiHost || 'https://us.i.posthog.com',
defaults: '2026-01-30',
// Automatically add X-POSTHOG-SESSION-ID and X-POSTHOG-DISTINCT-ID headers
// to same-origin requests so server-side events join the same session.
tracing_headers: [window.location.hostname]
})
</script>
src/layouts/PostHogLayout.astro
---
import PostHog from '../components/posthog.astro';
import Header from '../components/Header.astro';
import '../styles/global.css';
interface Props {
title: string;
}
const { title } = Astro.props;
---
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="description" content="Astro PostHog SSR Integration Example" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<title>{title}</title>
<PostHog />
</head>
<body>
<Header />
<main>
<slot />
</main>
</body>
</html>
src/lib/auth.ts
// Client-side auth utilities for localStorage-based authentication
export interface User {
username: string;
burritoConsiderations: number;
}
export function getCurrentUser(): User | null {
if (typeof window === "undefined") return null;
const username = localStorage.getItem("currentUser");
if (!username) return null;
const considerations = parseInt(
localStorage.getItem("burritoConsiderations") || "0",
10,
);
return {
username,
burritoConsiderations: considerations,
};
}
export function login(username: string, password: string): boolean {
if (!username || !password) return false;
localStorage.setItem("currentUser", username);
// Initialize burrito considerations if not set
if (!localStorage.getItem("burritoConsiderations")) {
localStorage.setItem("burritoConsiderations", "0");
}
return true;
}
export function logout(): void {
localStorage.removeItem("currentUser");
localStorage.removeItem("burritoConsiderations");
}
export function incrementBurritoConsiderations(): number {
const current = parseInt(
localStorage.getItem("burritoConsiderations") || "0",
10,
);
const newCount = current + 1;
localStorage.setItem("burritoConsiderations", newCount.toString());
return newCount;
}
src/lib/posthog-server.ts
import { PostHog } from "posthog-node";
let posthogClient: PostHog | null = null;
/**
* Get the PostHog server-side client.
* Uses a singleton pattern to avoid creating multiple clients.
*/
export function getPostHogServer(): PostHog {
if (!posthogClient) {
posthogClient = new PostHog(import.meta.env.PUBLIC_POSTHOG_PROJECT_TOKEN || "", {
host: import.meta.env.PUBLIC_POSTHOG_HOST || "https://us.i.posthog.com",
// Flush immediately for demo purposes
// In production, you might want to batch events
flushAt: 1,
flushInterval: 0,
});
}
return posthogClient;
}
/**
* Shutdown the PostHog client gracefully.
* Call this when your server is shutting down.
*/
export async function shutdownPostHog(): Promise<void> {
if (posthogClient) {
await posthogClient.shutdown();
posthogClient = null;
}
}
src/pages/api/auth/login.ts
import type { APIRoute } from "astro";
import { getPostHogServer } from "../../../lib/posthog-server";
export const prerender = false;
// In-memory user store for demo purposes
const users = new Map<string, { username: string; createdAt: string }>();
export const POST: APIRoute = async ({ request }) => {
try {
const body = await request.json();
const { username, password } = body;
if (!username || !password) {
return new Response(
JSON.stringify({ error: "Username and password are required" }),
{ status: 400, headers: { "Content-Type": "application/json" } },
);
}
// Check if this is a new user
const isNewUser = !users.has(username);
if (isNewUser) {
users.set(username, {
username,
createdAt: new Date().toISOString(),
});
}
// Get the PostHog server client
const posthog = getPostHogServer();
// Get session ID from client if available (passed via header)
const sessionId = request.headers.get("X-PostHog-Session-Id");
// Capture server-side login event
posthog.capture({
distinctId: username,
event: "server_login",
properties: {
$session_id: sessionId || undefined,
isNewUser,
source: "api",
timestamp: new Date().toISOString(),
},
});
// Also identify the user server-side
posthog.identify({
distinctId: username,
properties: {
username,
createdAt: isNewUser ? new Date().toISOString() : undefined,
},
});
// This endpoint is short-lived; flush so the enqueued events send before it returns
await posthog.flush();
return new Response(
JSON.stringify({
success: true,
username,
isNewUser,
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
} catch (error) {
console.error("Login error:", error);
return new Response(JSON.stringify({ error: "Internal server error" }), {
status: 500,
headers: { "Content-Type": "application/json" },
});
}
};
src/pages/api/events/burrito.ts
import type { APIRoute } from "astro";
import { getPostHogServer } from "../../../lib/posthog-server";
export const prerender = false;
export const POST: APIRoute = async ({ request }) => {
try {
const body = await request.json();
const { username, totalConsiderations } = body;
if (!username) {
return new Response(JSON.stringify({ error: "Username is required" }), {
status: 400,
headers: { "Content-Type": "application/json" },
});
}
// Get the PostHog server client
const posthog = getPostHogServer();
// Get session ID from client if available (passed via header)
const sessionId = request.headers.get("X-PostHog-Session-Id");
// Capture server-side burrito consideration event
posthog.capture({
distinctId: username,
event: "burrito_considered",
properties: {
$session_id: sessionId || undefined,
total_considerations: totalConsiderations,
source: "api",
timestamp: new Date().toISOString(),
},
});
// This endpoint is short-lived; flush so the enqueued event sends before it returns
await posthog.flush();
return new Response(
JSON.stringify({
success: true,
totalConsiderations,
}),
{ status: 200, headers: { "Content-Type": "application/json" } },
);
} catch (error) {
console.error("Burrito event error:", error);
return new Response(JSON.stringify({ error: "Internal server error" }), {
status: 500,
headers: { "Content-Type": "application/json" },
});
}
};
src/pages/burrito.astro
---
import PostHogLayout from '../layouts/PostHogLayout.astro';
// Opt this page into on-demand rendering (SSR)
// In hybrid mode, pages are static by default
export const prerender = false;
---
<PostHogLayout title="Burrito Consideration - Astro PostHog Hybrid Example">
<div class="container">
<h1>Burrito consideration zone</h1>
<p>Take a moment to truly consider the potential of burritos.</p>
<div style="text-align: center;">
<button id="consider-btn" class="btn-burrito">
I have considered the burrito potential
</button>
<p id="success-message" class="success" style="display: none;">
Thank you for your consideration! Count: <span id="consideration-count"></span>
</p>
</div>
<div class="stats">
<h3>Consideration stats</h3>
<p>Total considerations: <span id="total-considerations">0</span></p>
</div>
<p class="note" style="margin-top: 1rem;">
Events are tracked both client-side and server-side for demonstration.
</p>
</div>
</PostHogLayout>
<script is:inline>
function checkAuth() {
const currentUser = localStorage.getItem('currentUser');
if (!currentUser) {
window.location.href = '/';
return false;
}
return true;
}
function updateStats() {
const count = localStorage.getItem('burritoConsiderations') || '0';
document.getElementById('total-considerations').textContent = count;
}
async function handleConsideration() {
const currentUser = localStorage.getItem('currentUser');
if (!currentUser) return;
// Increment the count
const currentCount = parseInt(localStorage.getItem('burritoConsiderations') || '0', 10);
const newCount = currentCount + 1;
localStorage.setItem('burritoConsiderations', newCount.toString());
// Update the UI
updateStats();
const successMessage = document.getElementById('success-message');
const considerationCount = document.getElementById('consideration-count');
considerationCount.textContent = newCount;
successMessage.style.display = 'block';
// Hide success message after 2 seconds
setTimeout(() => {
successMessage.style.display = 'none';
}, 2000);
// Client-side event tracking
window.posthog?.capture('burrito_considered', {
total_considerations: newCount,
username: currentUser,
source: 'client'
});
// Also send to server-side API for server tracking. The session and distinct
// ID are added automatically by the tracing_headers option in posthog.init.
try {
await fetch('/api/events/burrito', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: currentUser,
totalConsiderations: newCount
})
});
} catch (error) {
console.error('Failed to send server-side event:', error);
}
}
document.addEventListener('DOMContentLoaded', () => {
if (!checkAuth()) return;
updateStats();
document.getElementById('consider-btn')?.addEventListener('click', handleConsideration);
});
</script>
src/pages/index.astro
---
import PostHogLayout from '../layouts/PostHogLayout.astro';
// This page is prerendered (static) by default in hybrid mode
// No need to set prerender = true explicitly
---
<PostHogLayout title="Home - Astro PostHog Hybrid Example">
<div class="container">
<div id="logged-in-view" style="display: none;">
<h1>Welcome back, <span id="welcome-username"></span>!</h1>
<p>You are logged in. Feel free to explore:</p>
<ul>
<li>Consider the potential of burritos</li>
<li>View your profile and statistics</li>
</ul>
</div>
<div id="logged-out-view">
<h1>Welcome to Burrito Consideration App</h1>
<p>Please sign in to begin your burrito journey</p>
<form id="login-form" class="form">
<div class="form-group">
<label for="username">Username:</label>
<input
type="text"
id="username"
placeholder="Enter any username"
required
/>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input
type="password"
id="password"
placeholder="Enter any password"
required
/>
</div>
<p id="error-message" class="error" style="display: none;"></p>
<button type="submit" class="btn-primary">Sign In</button>
</form>
<p class="note">
Note: This is a demo app with server-side tracking. Use any username and password to sign in.
</p>
</div>
</div>
</PostHogLayout>
<script is:inline>
function updateView() {
const currentUser = localStorage.getItem('currentUser');
const loggedInView = document.getElementById('logged-in-view');
const loggedOutView = document.getElementById('logged-out-view');
const welcomeUsername = document.getElementById('welcome-username');
if (currentUser) {
loggedInView.style.display = 'block';
loggedOutView.style.display = 'none';
welcomeUsername.textContent = currentUser;
} else {
loggedInView.style.display = 'none';
loggedOutView.style.display = 'block';
}
}
async function handleLogin(event) {
event.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
const errorMessage = document.getElementById('error-message');
if (!username || !password) {
errorMessage.textContent = 'Please provide both username and password';
errorMessage.style.display = 'block';
return;
}
try {
// Call the server-side login API. The session and distinct ID are added
// automatically by the tracing_headers option configured in posthog.init.
const response = await fetch('/api/auth/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.error || 'Login failed');
}
// Store in localStorage for client-side state
localStorage.setItem('currentUser', username);
if (!localStorage.getItem('burritoConsiderations')) {
localStorage.setItem('burritoConsiderations', '0');
}
// Also identify on the client side (for session continuity)
window.posthog?.identify(username);
window.posthog?.capture('user_logged_in');
// Clear form
document.getElementById('username').value = '';
document.getElementById('password').value = '';
errorMessage.style.display = 'none';
// Update view
updateView();
// Trigger header update
window.dispatchEvent(new Event('storage'));
} catch (error) {
errorMessage.textContent = error.message || 'Login failed';
errorMessage.style.display = 'block';
}
}
document.addEventListener('DOMContentLoaded', () => {
updateView();
document.getElementById('login-form')?.addEventListener('submit', handleLogin);
});
// Listen for storage changes
window.addEventListener('storage', updateView);
</script>
src/pages/profile.astro
---
import PostHogLayout from '../layouts/PostHogLayout.astro';
// This page is prerendered (static) by default in hybrid mode
---
<PostHogLayout title="Profile - Astro PostHog Hybrid Example">
<div class="container">
<h1>User Profile</h1>
<div class="stats">
<h2>Your Information</h2>
<p><strong>Username:</strong> <span id="profile-username"></span></p>
<p><strong>Burrito Considerations:</strong> <span id="profile-considerations">0</span></p>
</div>
<div style="margin-top: 2rem;">
<h3>Your Burrito Journey</h3>
<p id="journey-message"></p>
</div>
<div style="margin-top: 2rem;">
<h3>Error Tracking Demo</h3>
<p>Click the button below to trigger a test error and send it to PostHog:</p>
<button id="error-btn" class="btn-error">
Trigger Test Error
</button>
<p id="error-feedback" class="success" style="display: none;">
Error captured and sent to PostHog!
</p>
</div>
</div>
</PostHogLayout>
<script is:inline>
function checkAuth() {
const currentUser = localStorage.getItem('currentUser');
if (!currentUser) {
window.location.href = '/';
return false;
}
return true;
}
function updateProfile() {
const username = localStorage.getItem('currentUser') || '';
const considerations = parseInt(localStorage.getItem('burritoConsiderations') || '0', 10);
document.getElementById('profile-username').textContent = username;
document.getElementById('profile-considerations').textContent = considerations;
// Update journey message based on consideration count
const journeyMessage = document.getElementById('journey-message');
if (considerations === 0) {
journeyMessage.textContent = "You haven't considered any burritos yet. Visit the Burrito Consideration page to start!";
} else if (considerations === 1) {
journeyMessage.textContent = "You've considered the burrito potential once. Keep going!";
} else if (considerations < 5) {
journeyMessage.textContent = "You're getting the hang of burrito consideration!";
} else if (considerations < 10) {
journeyMessage.textContent = "You're becoming a burrito consideration expert!";
} else {
journeyMessage.textContent = "You are a true burrito consideration master!";
}
}
function triggerTestError() {
try {
throw new Error('Test error for PostHog error tracking');
} catch (err) {
// Capture the error in PostHog
window.posthog?.captureException(err);
console.error('Captured error:', err);
// Show feedback to user
const feedback = document.getElementById('error-feedback');
feedback.style.display = 'block';
setTimeout(() => {
feedback.style.display = 'none';
}, 3000);
}
}
document.addEventListener('DOMContentLoaded', () => {
if (!checkAuth()) return;
updateProfile();
document.getElementById('error-btn')?.addEventListener('click', triggerTestError);
});
</script>
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.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download instrument-product-analytics.zip