Add PostHog to a Next.js app with client and server event capture, user identification, feature flags, session replay privacy controls, reverse-proxy planning, and production analytics validation.
The download URL is PostHog's external source archive, not a HeyClaude-packaged skill archive; review source provenance before using it in automated workflows., Do not commit PostHog personal API keys, project API keys, write keys for other services, session cookies, OAuth credentials, data warehouse credentials, or copied dashboard values., A PostHog project token is normally exposed to client-side code, but it still must be scoped to the intended project and environment; do not confuse it with private API credentials., Analytics code can change route behavior, client bundle size, network requests, cookies, local storage, feature-flag rollout behavior, and server-side request timing., Feature flags and experiments can alter production behavior for real users. Add owner, rollout, fallback, kill-switch, and cache/bootstrapping review before shipping., Session replay, autocapture, heatmaps, and network capture can record sensitive product screens if masking and exclusion rules are incomplete., Do not enable replay or autocapture on auth, payment, healthcare, education, finance, admin, internal tooling, or support-data screens without explicit privacy review., If using a reverse proxy to improve event delivery, review CDN, middleware, rewrite, cache, rate-limit, WAF, and data-routing implications before deploying.
Privacy notes
PostHog can process user identifiers, account or organization IDs, event names, event properties, page URLs, referrers, device data, IP-derived context, cookies, local storage values, feature-flag evaluations, experiment assignments, and session recordings., Session replay can capture rendered text, URLs, form states, clicks, scrolls, console context, and optional network metadata depending on configuration., Mask inputs, sensitive text, query strings, authentication tokens, email addresses, IDs, payment fields, admin data, and support/customer content before enabling replay in production., Use `ph-no-capture`, `maskTextSelector`, input masking, URL redaction, and recording start/stop controls for sensitive views instead of assuming defaults cover every custom component., Use synthetic users and non-production PostHog projects for examples, screenshots, demos, issue reports, and AI-assisted debugging., Avoid pasting raw recordings, person profiles, event exports, feature-flag targeting lists, customer identifiers, or dashboard screenshots into prompts or public issues., Review PostHog Cloud/self-hosted retention, regional hosting, data-processing, team access, export, and deletion behavior before sending real customer data.
8 safety and 7 privacy notes across 7 risk areas. Review closely: credentials & tokens, permissions & scopes, network access.
7 areas
SafetyNetwork accessThe download URL is PostHog's external source archive, not a HeyClaude-packaged skill archive; review source provenance before using it in automated workflows.
SafetyCredentials & tokensDo not commit PostHog personal API keys, project API keys, write keys for other services, session cookies, OAuth credentials, data warehouse credentials, or copied dashboard values.
SafetyCredentials & tokensA PostHog project token is normally exposed to client-side code, but it still must be scoped to the intended project and environment; do not confuse it with private API credentials.
SafetyNetwork accessAnalytics code can change route behavior, client bundle size, network requests, cookies, local storage, feature-flag rollout behavior, and server-side request timing.
SafetyData retentionFeature flags and experiments can alter production behavior for real users. Add owner, rollout, fallback, kill-switch, and cache/bootstrapping review before shipping.
SafetyCredentials & tokensSession replay, autocapture, heatmaps, and network capture can record sensitive product screens if masking and exclusion rules are incomplete.
SafetyPermissions & scopesDo not enable replay or autocapture on auth, payment, healthcare, education, finance, admin, internal tooling, or support-data screens without explicit privacy review.
SafetyData retentionIf using a reverse proxy to improve event delivery, review CDN, middleware, rewrite, cache, rate-limit, WAF, and data-routing implications before deploying.
PrivacyCredentials & tokensPostHog can process user identifiers, account or organization IDs, event names, event properties, page URLs, referrers, device data, IP-derived context, cookies, local storage values, feature-flag evaluations, experiment assignments, and session recordings.
PrivacyCredentials & tokensSession replay can capture rendered text, URLs, form states, clicks, scrolls, console context, and optional network metadata depending on configuration.
PrivacyCredentials & tokensMask inputs, sensitive text, query strings, authentication tokens, email addresses, IDs, payment fields, admin data, and support/customer content before enabling replay in production.
PrivacyGeneralUse `ph-no-capture`, `maskTextSelector`, input masking, URL redaction, and recording start/stop controls for sensitive views instead of assuming defaults cover every custom component.
PrivacyGeneralUse synthetic users and non-production PostHog projects for examples, screenshots, demos, issue reports, and AI-assisted debugging.
PrivacyLocal filesAvoid pasting raw recordings, person profiles, event exports, feature-flag targeting lists, customer identifiers, or dashboard screenshots into prompts or public issues.
PrivacyExecution & processesReview PostHog Cloud/self-hosted retention, regional hosting, data-processing, team access, export, and deletion behavior before sending real customer data.
Safety notes
The download URL is PostHog's external source archive, not a HeyClaude-packaged skill archive; review source provenance before using it in automated workflows.
Do not commit PostHog personal API keys, project API keys, write keys for other services, session cookies, OAuth credentials, data warehouse credentials, or copied dashboard values.
A PostHog project token is normally exposed to client-side code, but it still must be scoped to the intended project and environment; do not confuse it with private API credentials.
Analytics code can change route behavior, client bundle size, network requests, cookies, local storage, feature-flag rollout behavior, and server-side request timing.
Feature flags and experiments can alter production behavior for real users. Add owner, rollout, fallback, kill-switch, and cache/bootstrapping review before shipping.
Session replay, autocapture, heatmaps, and network capture can record sensitive product screens if masking and exclusion rules are incomplete.
Do not enable replay or autocapture on auth, payment, healthcare, education, finance, admin, internal tooling, or support-data screens without explicit privacy review.
If using a reverse proxy to improve event delivery, review CDN, middleware, rewrite, cache, rate-limit, WAF, and data-routing implications before deploying.
Privacy notes
PostHog can process user identifiers, account or organization IDs, event names, event properties, page URLs, referrers, device data, IP-derived context, cookies, local storage values, feature-flag evaluations, experiment assignments, and session recordings.
Session replay can capture rendered text, URLs, form states, clicks, scrolls, console context, and optional network metadata depending on configuration.
Mask inputs, sensitive text, query strings, authentication tokens, email addresses, IDs, payment fields, admin data, and support/customer content before enabling replay in production.
Use `ph-no-capture`, `maskTextSelector`, input masking, URL redaction, and recording start/stop controls for sensitive views instead of assuming defaults cover every custom component.
Use synthetic users and non-production PostHog projects for examples, screenshots, demos, issue reports, and AI-assisted debugging.
Avoid pasting raw recordings, person profiles, event exports, feature-flag targeting lists, customer identifiers, or dashboard screenshots into prompts or public issues.
Review PostHog Cloud/self-hosted retention, regional hosting, data-processing, team access, export, and deletion behavior before sending real customer data.
Prerequisites
Next.js application with known App Router or Pages Router structure, package manager, deployment provider, and environment-variable path.
PostHog Cloud or self-hosted PostHog project, project token, region or host URL, and environment separation for local, preview, staging, and production.
Consent, cookie, retention, and data-classification requirements for the jurisdictions, customers, and product surfaces being tracked.
Inventory of public routes, authenticated routes, admin routes, checkout/payment screens, support screens, account settings, and any pages that display sensitive data.
Event taxonomy plan covering page views, user actions, conversion funnels, account or organization identifiers, feature flags, experiments, and server-side events.
Decision on session replay, autocapture, rageclicks, heatmaps, network capture, feature flags, reverse proxy, and whether PostHog should run in preview deployments.
Access-control plan for who can view PostHog dashboards, persons, recordings, feature flags, experiments, cohorts, and exported analytics data.
.gemini/skills/<skill-name>/SKILL.md or .agents/skills/<skill-name>/SKILL.md
cursor
Adapter
.cursor/rules/<skill-name>.mdc
cli
Manual
AGENTS.md or tool-specific context file
Full copyable content
# Trigger
"Apply the PostHog Next.js product analytics skill to this app."
# Required output
1) Current analytics, routing, auth, consent, and data-classification inventory
2) PostHog client, server, feature flag, replay, proxy, and environment plan
3) Event taxonomy, identify/group, privacy masking, and validation checklist
4) Safety, privacy, retention, access-control, and rollback notes
About this resource
Knowledge Freshness
This skill is based on PostHog's official Next.js guide, JavaScript SDK docs,
session replay docs, session replay privacy controls, feature flag docs,
feature flag bootstrapping guide, and PostHog/posthog-js repository reviewed
on 2026-06-04. The current Next.js guide covers posthog-js,
posthog-node, client initialization through instrumentation-client.js or
instrumentation-client.ts, NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN,
NEXT_PUBLIC_POSTHOG_HOST, user identification, server-side analytics,
feature flag access, and reverse-proxy options.
Prefer the live PostHog docs and official repository over model memory for
package names, initialization files, SDK options, feature-flag APIs, replay
masking behavior, reverse-proxy guidance, and privacy-control defaults.
Scope Note
Use this skill for PostHog-backed product analytics in a Next.js application.
It is not a generic analytics comparison, not a legal compliance checklist, and
not permission to record real user sessions without consent, retention, access,
and masking review.
Core Workflow
Inventory the current Next.js version, App Router or Pages Router usage,
package manager, /src layout, server/client component boundaries,
middleware, rewrites, analytics code, auth provider, and deployment platform.
Identify existing analytics, session replay, tag manager, feature flag,
error tracking, experiment, customer-data, and consent-management code before
adding PostHog.
Confirm the PostHog project, region or host, project token, environment
separation, team access, data retention, and whether local or preview
deployments should send events.
Add posthog-js for browser capture and posthog-node for server-side
capture only where both are needed. Add @posthog/react only when React
feature flag hooks are part of the implementation.
Initialize the browser SDK from the documented Next.js client
instrumentation file and keep NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN and
NEXT_PUBLIC_POSTHOG_HOST environment-specific.
Decide whether to enable autocapture, page views, session replay, heatmaps,
network capture, surveys, error tracking, and feature flags deliberately.
Do not accept broad capture defaults without route and data review.
Build an event taxonomy before instrumenting. Name events consistently,
keep properties low-cardinality where possible, and avoid storing raw
secrets, prompts, emails, payment data, addresses, or support messages.
Map identity behavior. Decide when to call identify, how to handle
anonymous users, how to reset on logout, how to represent organizations or
workspaces, and how backend events use the same stable IDs.
For server-side events and feature flags, initialize a server-only PostHog
client, keep private environment variables out of the browser, flush or
shut down clients correctly in short-lived server contexts, and avoid
caching stale flag decisions accidentally.
For feature flags, decide bootstrap strategy, fallback behavior, rollout
owner, kill switch, cache behavior, experiment exposure events, and how to
avoid client/server flicker.
For session replay, review input masking, text masking, URL redaction,
ph-no-capture, sensitive third-party widgets, and recording controls
before enabling production recordings.
If a reverse proxy is used, review Next.js rewrites or middleware, CDN
caching, WAF behavior, request headers, rate limits, region routing, and
failure behavior.
Produce a validation plan that checks local opt-out behavior, preview
isolation, production event delivery, feature-flag decisions, replay
masking, consent behavior, dashboard access, and rollback.
Required Inputs
Next.js version, router mode, package manager, deployment provider, and
whether the app uses instrumentation-client.
Existing analytics, logging, replay, feature flag, A/B testing, tag manager,
and consent-management stack.
PostHog project token, host URL, region, environment mapping, retention
policy, and team access model.
Consent, opt-out, cookie, DNT, privacy-policy, and data-processing
requirements owned by the product or legal team.
Production Rules
Keep private PostHog API keys and account-level credentials out of browser
bundles. Client project tokens should still be scoped to the intended
PostHog project and environment.
Do not send raw passwords, auth tokens, session cookies, API keys, OAuth
codes, payment data, health records, education records, support transcripts,
private prompts, or customer content as event properties.
Treat session replay as sensitive user data. Review every tracked route,
form, modal, command palette, checkout surface, and admin/support view before
turning it on in production.
Mask or exclude sensitive content with code-level controls. Do not rely on a
screenshot review of a happy path to prove that all user data is protected.
Keep feature flag reads and writes deterministic enough for product
behavior. Server-rendered pages should avoid visible flicker and stale cached
flags.
Give every production flag or experiment an owner, rollout target, fallback,
monitoring plan, and removal plan. Remove stale flags after rollout.
Validate logout and account-switching behavior. Anonymous and identified
events should not leak one user's identity into another user's session.
Keep analytics dashboards, recordings, cohorts, and exports restricted to
the minimum team that needs them.
Use non-production projects and synthetic users for demos, public examples,
issue reports, and AI-assisted troubleshooting.
Compatibility
Native
Claude Code / Claude: use as a reusable Agent Skill for planning,
implementing, reviewing, and operating PostHog analytics in Next.js apps.
Codex/OpenAI workflows: use as SKILL.md-style instructions when editing
Next.js projects that add PostHog SDKs, feature flags, replay, or analytics
validation.
Manual Adaptation
Cursor, Windsurf, Gemini, and Generic AGENTS files: adapt the trigger,
workflow, safety notes, privacy notes, and output contract into repository
rules for analytics and feature flag work.
Output Contract
Source evidence: PostHog docs and repository URLs reviewed, with date.
App inventory: router, routes, auth, consent, existing analytics, feature
flags, replay surfaces, deployment environments, and sensitive data zones.
Safety and privacy review: tokens, private API keys, event properties,
recordings, URLs, masking, retention, access control, exports, prompts, and
real-user data handling.
Validation checklist: local no-send behavior, preview isolation, event
delivery, identify/reset, server capture, flag bootstrap, replay masking,
consent/opt-out, dashboard access, and rollback.
Troubleshooting
Issue: Events appear locally but not in the intended PostHog project
Fix: Check NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN, NEXT_PUBLIC_POSTHOG_HOST,
environment-specific build variables, ad blockers, reverse-proxy rewrites, and
whether preview deployments are intentionally disabled.
Issue: Feature flags flicker between server and client
Fix: Review server-side evaluation, bootstrapping, distinct ID consistency,
client hydration order, cache settings, and fallback behavior. Avoid rendering
user-visible decisions before the intended flag value is available.
Issue: Recordings show sensitive text, URLs, or account details
Fix: Disable recording for the affected route until masking is fixed. Add
input masking, text masking, URL redaction, ph-no-capture, and explicit
recording controls, then validate with synthetic data.
Issue: Server-side events are missing from route handlers or server actions
Fix: Confirm the server client is initialized with server-only values, the
runtime can reach the PostHog host, event capture is awaited where needed, and
short-lived contexts flush or shut down the client before returning.
Issue: Logout or account switching links events to the wrong user
Fix: Review identify, anonymous ID handling, reset behavior, cookies,
local storage, organization IDs, and backend distinct IDs. Test switching
between two synthetic accounts in the same browser.
Duplicate And Source Review
Current HeyClaude content has incidental PostHog mentions in Mintlify
documentation automation and telemetry notes, plus generic product-management
analytics content. There is no dedicated PostHog, posthog-js, posthog-node,
PostHog Next.js, session replay privacy, or PostHog feature flag skill entry.
This entry is specifically scoped to official PostHog integration work for
Next.js apps and is source-backed by PostHog docs and the PostHog/posthog-js
repository.
Editorial Disclosure
This is a source-backed community content entry submitted by oktofeesh1.
There is no paid placement, affiliate link, sponsorship, or maintainer-verified
package artifact attached to this listing.
Show that PostHog Next.js Product Analytics Skill is listed on HeyClaude. Paste this Markdown into your README — it renders the badge and links back to this page.
[](https://heyclau.de/entry/skills/posthog-nextjs-product-analytics)
How it compares
PostHog Next.js Product Analytics Skill side by side with 3 alternatives on trust, install, platform support, and disclosed safety notes — all from reviewed registry metadata.
Add PostHog to a Next.js app with client and server event capture, user identification, feature flags, session replay privacy controls, reverse-proxy planning, and production analytics validation.
Add or maintain Auth.js authentication in a Next.js app with next-auth, auth.ts, route handlers, providers, sessions, adapters, protected resources, proxy or middleware behavior, deployment configuration, and migration review.
Add Better Auth to a Next.js App Router project with API route handlers, database-backed sessions, client helpers, protected route checks, and production auth safety review.
Add Clerk authentication to a Next.js App Router project with middleware, route protection, session-aware UI, environment hygiene, and production auth safety checks.
✓The download URL is PostHog's external source archive, not a HeyClaude-packaged skill archive; review source provenance before using it in automated workflows.
Do not commit PostHog personal API keys, project API keys, write keys for other services, session cookies, OAuth credentials, data warehouse credentials, or copied dashboard values.
A PostHog project token is normally exposed to client-side code, but it still must be scoped to the intended project and environment; do not confuse it with private API credentials.
Analytics code can change route behavior, client bundle size, network requests, cookies, local storage, feature-flag rollout behavior, and server-side request timing.
Feature flags and experiments can alter production behavior for real users. Add owner, rollout, fallback, kill-switch, and cache/bootstrapping review before shipping.
Session replay, autocapture, heatmaps, and network capture can record sensitive product screens if masking and exclusion rules are incomplete.
Do not enable replay or autocapture on auth, payment, healthcare, education, finance, admin, internal tooling, or support-data screens without explicit privacy review.
If using a reverse proxy to improve event delivery, review CDN, middleware, rewrite, cache, rate-limit, WAF, and data-routing implications before deploying.
✓The download URL is the external `nextauthjs/next-auth` source archive, not a HeyClaude-packaged skill archive; review source provenance before using it in automated workflows.
Auth.js is now part of Better Auth, and the official README recommends Better Auth for many new projects. Confirm why Auth.js remains the intended choice before adding it to a greenfield app.
Do not commit `AUTH_SECRET`, OAuth client secrets, adapter connection strings, email SMTP credentials, WebAuthn secrets, session tokens, cookies, or copied dashboard values.
Authentication changes can alter sign-in, sign-out, callback URLs, cookie names, session lifetime, authorization behavior, provider access, and account-linking semantics.
Proxy or middleware protection is not a substitute for checking authorization close to data access. Server actions, route handlers, loaders, and database queries still need session and permission checks.
Provider callbacks, JWT/session callbacks, adapter customizations, and account-linking rules can create authorization bypasses or identity confusion if reviewed only through the UI happy path.
Edge runtime, proxy, middleware, database adapters, and provider SDKs have compatibility constraints. Verify runtime support before moving auth code into edge-executed paths.
Test OAuth in non-production first. Callback URL mismatches, domain changes, preview deployments, and secret rotation can lock users out or route tokens to the wrong environment.
✓The download URL is Better Auth's external source archive, not a HeyClaude-packaged skill archive; review source provenance before using it in automated workflows.
Do not commit Better Auth secrets, OAuth provider secrets, database URLs, email-provider credentials, API-key plugin secrets, or copied dashboard values.
Run schema generation or migrations only against the intended database environment; auth tables, sessions, accounts, and verification records are production-critical.
Treat route protection as server-side authorization work. UI hiding, optimistic middleware redirects, or cookie existence checks are not full access control.
Review `proxy.ts` or `middleware.ts` behavior by Next.js version before relying on database-backed session checks inside request middleware.
Keep OAuth callback URLs, base URLs, trusted origins, and cookie settings environment-specific to avoid broken login loops or cross-environment session confusion.
Track Better Auth release notes and security advisories before introducing auth flows or enabling advanced plugins in production.
Add rollback steps before replacing an existing auth provider because user, account, session, and verification tables can affect active logins.
✓The download URL is Clerk's external JavaScript SDK source archive, not a HeyClaude-packaged skill archive; review source provenance before using it in automated workflows.
Clerk middleware does not protect routes by default; require an explicit protected-route matcher before assuming a page, API route, or tRPC endpoint is private.
Do not commit `CLERK_SECRET_KEY`, webhook signing secrets, OAuth provider secrets, or copied dashboard values to source control, issue comments, screenshots, or chat transcripts.
Review middleware matchers carefully. A broad matcher can affect static assets and public routes, while a narrow matcher can leave sensitive routes unauthenticated.
Treat organization roles, custom permissions, and metadata checks as authorization logic that needs tests, not just UI hiding.
Webhook handlers can mutate user, membership, subscription, and organization state. Make handlers idempotent and verify signatures before processing events.
Confirm production domains and redirect URLs before deploy; wrong origins can break sign-in, leak users into the wrong environment, or create confusing callback loops.
Privacy notes
✓PostHog can process user identifiers, account or organization IDs, event names, event properties, page URLs, referrers, device data, IP-derived context, cookies, local storage values, feature-flag evaluations, experiment assignments, and session recordings.
Session replay can capture rendered text, URLs, form states, clicks, scrolls, console context, and optional network metadata depending on configuration.
Mask inputs, sensitive text, query strings, authentication tokens, email addresses, IDs, payment fields, admin data, and support/customer content before enabling replay in production.
Use `ph-no-capture`, `maskTextSelector`, input masking, URL redaction, and recording start/stop controls for sensitive views instead of assuming defaults cover every custom component.
Use synthetic users and non-production PostHog projects for examples, screenshots, demos, issue reports, and AI-assisted debugging.
Avoid pasting raw recordings, person profiles, event exports, feature-flag targeting lists, customer identifiers, or dashboard screenshots into prompts or public issues.
Review PostHog Cloud/self-hosted retention, regional hosting, data-processing, team access, export, and deletion behavior before sending real customer data.
✓Auth.js can process user profile data, email addresses, OAuth account IDs, provider tokens, refresh tokens, session tokens, cookies, adapter records, verification tokens, WebAuthn data, and callback payloads.
Auth callbacks, debug logs, server logs, failed sign-in logs, screenshots, issue reports, and AI prompts can expose provider IDs, token claims, user metadata, cookies, callback URLs, or database identifiers.
Use synthetic accounts and non-production providers for demos, public examples, screenshots, and AI-assisted troubleshooting.
Avoid pasting raw OAuth payloads, cookies, JWTs, session objects, adapter rows, production user records, or provider dashboard screenshots into prompts or public issues.
Review Auth.js, provider, database, deployment-platform, email-provider, analytics, and AI-assistant retention behavior before using real customer identity data in troubleshooting.
✓Better Auth handles user identity, email addresses, password-auth state, OAuth profile data, sessions, cookies, accounts, verification tokens, and plugin-specific user data.
Application logs, error trackers, request traces, AI prompts, and screenshots can retain user IDs, emails, callback URLs, cookies, session state, or OAuth provider details.
Use synthetic users and test OAuth applications for examples, demos, issue reports, screenshots, and AI-assisted troubleshooting.
If organization, API key, two-factor, passkey, or SSO plugins are enabled, treat membership, roles, credentials, and device metadata as sensitive authorization data.
Review Better Auth, database, deployment-provider, analytics, email-provider, and AI-assistant retention policies before using real customer identity data.
✓Clerk processes user identity, email addresses, sessions, cookies, authentication factors, OAuth profile data, organization membership, and optional user metadata.
Application logs, error reports, webhook payloads, request traces, and AI chat transcripts can retain user IDs, email addresses, session state, redirect URLs, or organization names.
Keep public examples synthetic. Do not paste real Clerk keys, dashboard screenshots, webhook payloads, user records, or organization metadata into prompts or PRs.
Review Clerk, deployment-provider, analytics, and AI-assistant retention policies before using real customer identity data in troubleshooting sessions.
If custom metadata stores roles, billing flags, internal account IDs, or entitlement data, treat it as sensitive authorization data and avoid exposing it client-side unless intended.
Prerequisites
Next.js application with known App Router or Pages Router structure, package manager, deployment provider, and environment-variable path.
PostHog Cloud or self-hosted PostHog project, project token, region or host URL, and environment separation for local, preview, staging, and production.
Consent, cookie, retention, and data-classification requirements for the jurisdictions, customers, and product surfaces being tracked.
Inventory of public routes, authenticated routes, admin routes, checkout/payment screens, support screens, account settings, and any pages that display sensitive data.
Next.js application with known App Router or Pages Router usage, package manager, deployment provider, and runtime targets.
Decision that Auth.js or NextAuth.js is the right fit for this app, especially when maintaining an existing install or requiring Auth.js-specific session behavior.