Verified SOP & TutorialAudited Score 98/100

The Complete Production SOP: How to Deploy and Run PostHog Product Analytics, Feature Flags & Session Replay in Autonomous AI Agents

Production SOP to install and run PostHog Analytics, Feature Flags & Session Replay in Codex, Claude Code, and Cursor. Verified prompts and guardrails.

Target Runtimes:codexclaude-codecursorwindsurf
5 min read • Updated for 2026

Technical Overview & Architectural Context

Autonomous coding agents frequently create telemetry debt when implementing product instrumentation. Left unconstrained, LLMs often initialize redundant SDK instances across client and server boundaries, omit crucial person profile configurations (such as 'person_profiles: identified_only' leading to bill shock), evaluate feature flags asynchronously without handling race conditions or hydration mismatches, and inadvertently record unmasked PII during session replays. Without explicit procedural boundaries, agents also confuse the client-side `posthog-js` SDK with backend `posthog-node` calls, leaking write keys or breaking Next.js / Remix SSR streaming boundaries. The 'posthog-feature-flags-analytics' skill forces coding agents into strict operational compliance: standardizing single-instance initialization, enforcing deterministic user identification upon authentication lifecycle transitions, applying robust input masking selectors (`.ph-no-capture`) across DOM forms, and verifying client-side feature flag caching before rendering UI variants.

Prerequisites & Environment Requirements

Codex Desktop, Claude Code CLI, Cursor, or Windsurf installed with active workspace access
Node.js 20+ runtime in workspace sandbox with package manager (pnpm/npm/yarn)
PostHog Cloud account or self-hosted instance with valid Project API Key and Host URL
Git 2.40+ initialized with clean working tree

Verified Search Intents & Long-Tail Queries Solved

SEO Audit Score: 98/100

This operational tutorial is engineered to provide deterministic solutions for these developer search queries:

#install posthog-feature-flags-analytics in cursor ide#claude code posthog-feature-flags-analytics rules#codex desktop posthog-feature-flags-analytics setup tutorial#how to fix posthog-feature-flags-analytics agent execution error#deterministic fullstack agent SOP#posthog-feature-flags-analytics sandbox permissions and security score#posthog-feature-flags-analytics prompt examples and triggers#posthog mask sensitive data session replay agent prompt

Step-by-Step Execution Playbook

1

Local Environment Setup & SKILL.md Mounting

Create the local agent skill manifest directory and inject verified procedural rules into your project or user agent path.

Autonomous coding runtimes (Claude Code, Cursor, Windsurf, Codex) parse frontmatter triggers and execution SOPs from dedicated skill directories. We place the skill manifest in `.agents/skills/posthog-feature-flags-analytics/SKILL.md` within the workspace root or global agent directory so that any analytics or feature flag query triggers deterministic execution.

Terminal Command
mkdir -p .agents/skills/posthog-feature-flags-analytics && curl -fsSL https://askills.dev/api/skills/posthog-feature-flags-analytics/raw -o .agents/skills/posthog-feature-flags-analytics/SKILL.md
.agents/skills/posthog-feature-flags-analytics/SKILL.md
---
name: "posthog-feature-flags-analytics"
description: "Instrument product analytics events, feature flags, A/B experiments, and session recordings."
metadata:
  author: "PostHog"
  version: "1.0.0"
  runtime_compatibility:
    - "codex"
    - "claude-code"
    - "cursor"
    - "windsurf"
triggers:
  - "evaluate feature flag posthog"
  - "track event posthog"
  - "mask sensitive data session replay"
permissions:
  fs_read: true
  fs_write: "workspace"
  shell_exec: false
  net_access: false
---
Production Pro-Tip

Setting `person_profiles: 'identified_only'` in your initialization logic reduces PostHog ingested profile volumes by up to 70%, dramatically conserving both cloud quotas and LLM context overhead.

Sandbox Gotcha

Ensure `fs_write` is scoped strictly to `workspace`. Granting unconstrained file system writes allows LLMs to accidentally overwrite global environment configurations outside your repository.

2

Dependency Installation & Secret Configuration

Install posthog-js or posthog-node and configure public environment variables safely.

Ensure the agent installs the official SDKs while injecting only the project API key (safe for public clients) into the environment file. Do not expose private PostHog Personal API Keys in client-side bundles.

Terminal Command
npm install posthog-js && echo 'NEXT_PUBLIC_POSTHOG_KEY=phc_test_token_123' >> .env.local && echo 'NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com' >> .env.local
Production Pro-Tip

Instruct the agent to verify `.gitignore` contains `.env*.local` before it writes any token mock into temporary test files.

Sandbox Gotcha

Do not configure `posthog-node` using client public tokens. Server-side capture requires distinct batching timeouts and correct personal or project write keys.

3

Intent Matching & Trigger Invocation

Trigger the skill deterministically using tested natural language phrasing matching frontmatter triggers.

Provide the agent with a targeted user command matching one of the declared trigger phrases: 'evaluate feature flag posthog', 'track event posthog', or 'mask sensitive data session replay'. The runtime pattern matcher will load the SOP rules into context.

Production Pro-Tip

Include the specific UI component path and event schema in your initial prompt to prevent the agent from hallucinating arbitrary event property names.

Sandbox Gotcha

Avoid vague prompts like 'add analytics'. Use precise trigger tokens like 'track event posthog for checkout completed' to guarantee this skill takes precedence over generic telemetry handlers.

4

Verification, Linting & Output Quality Gate

Execute automated self-healing checks and type-checking before committing the generated instrumentation.

The skill requires the agent to run TypeScript compilation and local linting to ensure feature flag keys, session replay masking CSS classes (`ph-no-capture`), and event payload types pass static analysis.

Terminal Command
npx tsc --noEmit && npm run lint
Production Pro-Tip

Run `posthog.onFeatureFlags(() => ...)` when unit testing client-side flag evaluation to prevent race conditions where assertions run before bootstrap flags resolve.

Sandbox Gotcha

Session replay will capture form input values unless `.ph-no-capture` or `maskAllInputs: true` is explicitly passed in `posthog.init` options.

Real-World Scenario: Safely instrument a Next.js payment checkout with feature flagging and session recording privacy masks

Tested Trigger Prompt (Feed directly into Codex, Claude, or Cursor):

“Using posthog-feature-flags-analytics: initialize posthog-js with person_profiles 'identified_only', evaluate feature flag posthog for 'beta-stripe-checkout', track event posthog 'checkout_initiated' with cart totals, and mask sensitive data session replay on all billing inputs.”

Deterministic Agent Verification Pipeline:
Generates `lib/posthog.ts` with client-safe `posthog.init` containing `mask_all_element_attributes: true` and `mask_all_text: false` but masking password and credit card selectors with `.ph-no-capture`.
Creates a React context provider checking `posthog.isFeatureEnabled('beta-stripe-checkout')` with a fallback state for loading phases to avoid layout shift.
Instruments the checkout form submit handler calling `posthog.capture('checkout_initiated', { order_id: cart.id, total_amount: cart.total, currency: 'USD' })`.
Runs `npx tsc --noEmit` to verify type safety and confirms zero secret leakage.

Runtime Troubleshooting & Failure Modes

Error: PostHog Error: Flag evaluated before flags were loaded. Called isFeatureEnabled('beta-stripe-checkout') before posthog.onFeatureFlags callback.

Root Cause: The agent attempted a synchronous `isFeatureEnabled` check immediately after initialization before PostHog received the remote flag payload from the CDN endpoint.

Resolution Command / Fix:
posthog.onFeatureFlags(() => { if (posthog.isFeatureEnabled('beta-stripe-checkout')) { setStripeEnabled(true); } }); // Alternatively pass bootstrap: { featureFlags: { 'beta-stripe-checkout': false } } to posthog.init
Error: Uncaught Error: [PostHog.js] "api_host" must be set to a valid URL. Got undefined or invalid host.

Root Cause: The agent referenced an uninitialized process.env variable on the client browser bundle without the required framework prefix (e.g., using `POSTHOG_HOST` instead of `NEXT_PUBLIC_POSTHOG_HOST`).

Resolution Command / Fix:
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com'

Frequently Asked Questions (PostHog Product Analytics, Feature Flags & Session Replay SOP)

Q:Can I use PostHog Product Analytics, Feature Flags & Session Replay across Codex, Claude Code, and Cursor simultaneously?

Yes. The skill conforms to the universal SKILL.md specification. Whether using Claude Code's CLI, Cursor's agent pane, Windsurf cascades, or Codex desktop runtimes, the frontmatter triggers and SOP validation gates are ingested and executed identically.

Q:How does PostHog Product Analytics, Feature Flags & Session Replay prevent context window overflow during long agent sessions?

By providing atomic, procedural instructions with clear initialization patterns (`person_profiles: 'identified_only'`, standard masking rules, single-line capture calls) instead of dumping entire SDK documentation into the agent context.

Q:Does this skill require escalated root or container permissions?

No. The skill is verified with a security score of 98/100. It requires read and write permissions limited strictly to the workspace directory (`fs_write: 'workspace'`) and operates without elevated root or persistent external shell network escalation.

Ready to equip your autonomous agent with PostHog Product Analytics, Feature Flags & Session Replay?

Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.

Get 1-Click Install Spec