Preface¶
After a product launches, the most common next step is to add analytics: track who views pages, how far users get through the registration flow, and where users drop off during payment. This task itself is not complex, but it easily becomes scattered across a codebase: Next.js App Router and Pages Router have different initialization locations, SPA route changes often fail to log $pageview events, project keys get hardcoded into source code, and Feature Flag and session replay implementations each get their own custom code.
When asking an AI coding assistant to “add PostHog”, without a fixed workflow it might forget to install the server-side SDK, use the wrong environment variable prefix, or rely on default full-page refresh tracking for single-page applications. adding-analytics formalizes this “analytics instrumentation” process into an Agent Skill, guiding assistants to follow a consistent checklist: identify the framework, install the SDK, initialize the client, track page views, add custom events, and optionally enable Feature Flags and session replay.
What it is¶
adding-analytics is a generic SKILL.md file, with frontmatter defining its name as adding-analytics and description as: “Integrate PostHog analytics into web applications, covering event tracking, page views, Feature Flags, and session replay.” Its trigger conditions are explicitly written: use when the user mentions adding analytics, event tracking, page views, feature flags, or session replay.
It is included in the resources/adding-analytics/ directory of spencerpauly/awesome-cursor-skills, a curated list of Cursor Skills licensed under Creative Commons Zero (CC0). The original repository only contains a single SKILL.md file, with no additional scripts/ or references/ directories. In the Analytics & Tracking group of this repository, posthog-llm-analytics and posthog-migrations point to official PostHog Skill repositories; adding-analytics itself is an independent short workflow in this curated list, and is not an official plugin from the PostHog/skills repository.
It solves a specific problem: instead of having the AI agent cobble together an ad-hoc instrumentation solution every time, first identify the tech stack, install the appropriate SDK, store credentials in environment variables, fix page view tracking for SPAs, then add custom events and optional features as requested by the user.
Core Workflow¶
The Skill body follows a fixed 8-step sequence:
- Identify the Framework. First check
next.config.*,vite.config.*, the scripts inpackage.json, orindex.htmlto determine if the project uses Next.js, React (Vite/CRA), Vue, Svelte, or plain HTML. The initialization code is most detailed for Next.js, while other frameworks only cover the stack detection and package installation steps. - Install the SDK. Select packages based on runtime environment, with hardcoded commands in the Skill:
# Next.js / React client-side
npm install posthog-js
# For server-side tracking in Next.js
npm install posthog-js posthog-node
# Python
pip install posthog
# Node.js backend
npm install posthog-node
These commands match the official PostHog documentation: use `posthog-js` for web clients, `posthog-node` for Next.js server-side code, and `posthog` for the official Python library.
- Create a Provider / Initialization Module. Next.js App Router requires initialization in
app/providers.tsxwith the"use client"directive, sinceposthog-jscan only run in the browser. Pages Router should be initialized in auseEffecthook inside_app.tsx. Wrap the{children}component tree with the provider in the root layout. - Fix Page View Tracking. SPAs do not trigger full page reloads on route changes. The Skill’s solution is to disable automatic pageview tracking, then manually call
posthog.capture('$pageview')when the router detects a route change, using the framework’s built-in router events. - Set Up Environment Variables. Prompt the user for their PostHog project API key and host, then write them to
.envand sync the variables to.env.example. Never commit API keys to source code. - Add Custom Events. For user-specified tracked behaviors (such as sign-up, purchase), call
posthog.capture("event_name", { ...properties })in the corresponding event handler. - Feature Flag (Optional). Only add this when explicitly requested by the user, using either
posthog.isFeatureEnabled("flag-name")or the ReactuseFeatureFlagEnabledhook. - Session Replay (Optional). Only add this when explicitly requested by the user, by including the
session_recordingconfiguration in theinitcall.
There are three additional constraints:
1. Always use environment variables for API keys
2. If the project uses a Content Security Policy, add the posthog-js related domains to the allowlist
3. For monorepos, install the package in the actual UI-rendering package, not just the repository root without referencing it properly.
Installation and Activation¶
This Skill follows the standard Agent Skills directory structure: the folder name matches the name field in the YAML frontmatter, and contains a single SKILL.md file. Simply copy it to the location scanned by your AI coding tool. The awesome-cursor-skills repository documentation recommends copying it to .cursor/skills/.
To copy it from the repository into your local project (for Cursor project-level use):
git clone https://github.com/spencerpauly/awesome-cursor-skills.git
mkdir -p .cursor/skills/adding-analytics
cp awesome-cursor-skills/resources/adding-analytics/SKILL.md \
.cursor/skills/adding-analytics/SKILL.md
The scan directories for each tool are as follows (refer to official documentation for the latest details):
- Cursor: Project-level .cursor/skills/ or .agents/skills/, user-level ~/.cursor/skills/ or ~/.agents/skills/. For compatibility, it also loads .claude/skills/, .codex/skills/ and their corresponding user-level directories. The agent can automatically select the Skill based on its description, or you can manually trigger it by searching the Skill name with a / command in chat.
- Claude Code: Project-level .claude/skills/adding-analytics/SKILL.md, user-level ~/.claude/skills/adding-analytics/SKILL.md.
- Codex CLI: Scans upwards from the current working directory to the repository root for .agents/skills directories, with a user-level directory at $HOME/.agents/skills.
The directory name must be adding-analytics, matching the name field in the frontmatter, otherwise some tools will not be able to locate the Skill by name.
If you want to use officially maintained PostHog integration Skills that cover more frameworks, that is a separate workflow: add the PostHog/skills repository to the Claude Code plugin marketplace, then install posthog-integration. It has a similar goal to adding-analytics, but is a separate file, and you should follow the process and examples from its own repository.
Typical Usage¶
After activation, trigger the Skill using natural language, no need to memorize commands first. For example:
Add PostHog to this Next.js App Router project:
Track page views, plus two custom events for successful registration and completed purchases.
Use environment variables for credentials, do not hardcode them into code.
Specify your need for Flags or replay explicitly to trigger steps 7 and 8:
Similarly add PostHog, and also enable the 'new-checkout' feature flag,
plus session replay.
Below is code from the original Skill, which is what the AI agent should implement:
Next.js App Router app/providers.tsx:
"use client";
import posthog from "posthog-js";
import { PostHogProvider as PHProvider } from "posthog-js/react";
import { useEffect } from "react";
export function PostHogProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST ?? "https://us.i.posthog.com",
capture_pageview: false, // we capture manually for SPAs
});
}, []);
return <PHProvider client={posthog}>{children}</PHProvider>;
}
Environment variables (the variable names used by the Skill):
NEXT_PUBLIC_POSTHOG_KEY=phc_...
NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com
The NEXT_PUBLIC_ prefix allows Next.js to expose these values to the browser. The host address should match the one listed in your PostHog project settings; the example https://us.i.posthog.com is just a US Cloud sample from the Skill and official documentation, and should not be used as a fixed value for all projects.
Calling custom events, page views, and Feature Flags:
posthog.capture("$pageview");
posthog.capture("sign_up", { plan: "pro" });
posthog.capture("purchase", { amount: 99 });
if (posthog.isFeatureEnabled("flag-name")) {
// Enable new feature
}
Session replay is configured by adding this to the init call in the Skill:
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST ?? "https://us.i.posthog.com",
capture_pageview: false,
session_recording: { maskAllInputs: false },
});
适用场景与注意事项¶
Suitable for teams that already have a web frontend (especially Next.js/React) and plan to integrate PostHog, but do not want to have the AI agent search documentation from scratch every time. The Skill formalizes the process of “identify framework → install packages → add provider → set up environment variables → add events” into a checklist, making it straightforward for first-time instrumentation work or upgrading from only automatic采集 to tracked key business events.
There are several points where you should cross-reference the official PostHog documentation, and do not treat the Skill’s examples as the only correct current PostHog implementation:
- Environment Variable Names: The Skill uses
NEXT_PUBLIC_POSTHOG_KEY. The current official PostHog Next.js documentation usesNEXT_PUBLIC_POSTHOG_PROJECT_TOKEN. Both require theNEXT_PUBLIC_prefix; when integrating into an existing project, check which variable name is already in use in the repository, and do not use two conflicting sets of variables. - React Package Path: The Skill imports
PostHogProviderfromposthog-js/react. The current official Next.js/React documentation now uses@posthog/react. If your installedposthog-jsversion has split the React package into a separate dependency, adjust the import to match the package you installed and the official documentation, rather than copying the code verbatim. - Page View Tracking: The Skill sets
capture_pageview: falseand manually sends$pageviewevents on route changes, which is an older pattern for SPAs. The current PostHog documentation recommends settingdefaults(for example'2026-05-30') in theinitcall, at which pointcapture_pageviewdefaults to'history_change', which listens for History API events and automatically tracks page views for single-page navigations. Both approaches work; new projects can follow the officialdefaultspattern, while existing projects that already use manual tracking should not enable both, otherwise events will be counted twice. - Session Replay and Input Masking: PostHog documentation states that session recording is enabled by default in the SDK (
disable_session_recordingdefaults tofalse), and input field content is masked by default (maskAllInputsdefaults totrue). The Skill example usesmaskAllInputs: false, which actively disables input masking. Official privacy guidelines consider input fields as high-sensitivity areas, and password fields will always be masked regardless of this setting, but it is still recommended to keep at least password-type inputs masked. Do not copymaskAllInputs: falseverbatim in production environments unless you have independently evaluated compliance requirements. - CSP: The Skill only reminds developers to add
posthog-jsdomains to their Content Security Policy if one is in use. PostHog’s official documentation provides more specific details: the SDK will also lazy-load session replay and other scripts from CDNs, and send requests to the collection domain. The official wildcard examples are as follows (domains are subject to change, refer to official documentation):
script-src 'self' https://*.posthog.com;
connect-src 'self' https://*.posthog.com;
worker-src 'self' blob: data:;
Missing the `connect-src` directive will result in events failing to send, even if the code appears to be set up correctly.
- Coverage Scope: The Skill mentions Vue, Svelte, plain HTML, and Python/Node.js backend package installation, but only provides runnable provider examples for Next.js. Other frameworks will require the AI agent to reference the corresponding PostHog documentation to implement initialization, and this single
SKILL.mdcannot cover all use cases. Next.js 15.3+ also providesinstrumentation-client.tsas an alternative client-side initialization method, which is not covered by this Skill. - It will not design your event model for you: Event names, properties, and whether to identify users still need to be determined by the product team. PostHog’s documentation requires calling
identifywith a stable user ID after login, andreseton logout; these steps are not included in theadding-analyticsworkflow.
Summary¶
adding-analytics does not provide a new analytics product, but rather packages the process of “integrating PostHog into a web application” into a reusable agent workflow: identify the framework, install the SDK, initialize the client, fix page view tracking for SPAs, manage credentials with environment variables, then add custom events, Feature Flags, and session replay as needed. The file is short with clear steps, making it ideal as a project-level skill for Cursor, Claude Code, or Codex CLI.
When implementing, follow the original Skill text, and use configuration values from the current PostHog documentation. In cases of discrepancy between the Skill and official docs (variable names, React package names, default pageview behavior, input masking), choose the option that matches your project’s existing setup, and do not mix conflicting approaches.
Original Skill text: https://github.com/spencerpauly/awesome-cursor-skills/blob/main/resources/adding-analytics/SKILL.md
Official PostHog Next.js integration: https://posthog.com/docs/libraries/next-js
Official PostHog Skills repository: https://github.com/PostHog/skills