/analytics
An event plan with metric contracts, plus error tracking and health checks wired in.
Then type /analytics in Claude Code, or describe the task and let it pick the skill.
What you get back recorded run · 10 Oct 2026
- Query strings scrubbed
- Local dev not counted
- Tracing off to keep costs down
- PostHog and Sentry are set up and the production build passes, but nothing has reached either service yet. The values in
.env.localare marked as fake fixture values, so no real events or errors were sent and I haven't confirmed anything in the PostHog or Sentry dashboards. - Plan clicks: a new
plan_selectedevent with aplanproperty (plusorhousehold), sent from the two "Choose" buttons. - Funnel: in PostHog, build a funnel of page view on
/pricing→plan_selected, counting unique users. - Set up a Sentry alert rule (email or Slack) for new issues. Errors are only collected, not sent to you, until you do.
Input → output from the run
"use client";
import { checkoutUrl } from "../../lib/checkout";
export default function CheckoutButton({ plan, children }) {
return (
<a className="mini-btn" href={checkoutUrl(plan)}>
{children}
</a>
);
}"use client";
import { checkoutUrl } from "../../lib/checkout";
import { trackPlanSelected } from "../../lib/analytics";
export default function CheckoutButton({ plan, children }) {
return (
<a className="mini-btn" href={checkoutUrl(plan)} onClick={() => trackPlanSelected(plan)}>
{children}
</a>
);
}When to use it
Use when designing events, consent-aware tracking, error monitoring, health checks or dashboards.
Skip it for A/B tests and staged rollouts; product-experiments owns assignment and exposure.
The thinking behind itYou can't improve what you don't measure. Define the events that matter, wire them correctly, and decisions start from real numbers.
Output contract from the skill's Output section
Report:
- questions the system now answers and the event/monitoring plan;
- metric contracts for activation, retention, or other implemented measures;
- providers reused, added, or deliberately omitted;
- files and environment-variable names changed;
- dashboard routes/components, aggregate queries, access policy, freshness, and rendered states when applicable;
- privacy, consent, identity, sampling, and retention decisions;
- verification performed with event IDs or observed responses;
- dashboard, DNS, token, alerting, and production checks still required.
How it checks its own work from the instructions
- Event names and properties confirmed in the provider
- Logout reset never merges the wrong people
- Test errors are redacted, tagged, and source-mapped
- Anything needing production credentials is reported as manual setup
Requirements what it needs
- Works in
- Codex, Claude Code, Cursor
- Needs
- project files, terminal commands, network access
The instructions SKILL.md · 56 lines
Instructions & references
Back to overview ↑On this page 4 sections
Analytics
Build the smallest measurement system that answers explicit product or operational questions. Preserve existing providers and schemas unless a migration is part of the request.
Workflow
- Inspect the framework, router/runtime, deployment target, auth model, existing analytics and monitoring packages, environment-variable examples, privacy controls, and existing event calls. Read the resolved SDK versions from the lockfile.
- Define the decisions the data must support: acquisition, activation, retention, adoption, revenue, reliability, or incident response. For every metric, record its unit, eligible population and exclusions, numerator/event, denominator, cohort anchor where relevant, observation window, maturity/censoring rule, timezone, owner, and decision threshold. Record event names, required properties, identity rules, retention needs, and sensitive fields to exclude.
- Separate four concerns before choosing tools:
- traffic analytics;
- product analytics and experimentation;
- errors, traces, and logs;
- liveness, readiness, and business reporting.
- Reuse an installed provider. If none exists, recommend the minimum stack and explain the tradeoff. Ask only for unresolved choices that materially affect implementation, such as consent requirements, data residency, provider preference, or whether a database dependency belongs in readiness checks. Never ask the user to paste secrets into chat; scaffold names in
.env.exampleand let the user set values in the deployment environment. - Create or update a measurement plan before adding calls. Use stable event names, typed properties, server-side capture for authoritative outcomes, and a documented anonymous-to-authenticated identity transition.
- Implement only the selected paths:
- Read PostHog before changing PostHog browser/server setup, identity, page views, events, or server flushing.
- Read Sentry before changing Sentry initialization, data collection, boundaries, logging, replay, tracing, or source maps, and before any Sentry major upgrade.
- Provider facts in these references carry a check date. Re-check the cited source before acting on one if the date is more than about 90 days old or the installed version differs.
- Read health endpoints before adding liveness/readiness routes or uptime monitoring.
- When an internal dashboard is requested, implement it as an authenticated product surface, not a public health endpoint. Use server-owned aggregate queries; define freshness and caching; reconcile each tile to its metric contract; enforce role/tenant access; suppress or coarsen small sensitive groups; and cover loading, empty, stale, partial, and error states. Keep operational status separate from product metrics even when they share a page.
- Apply privacy controls before capture: minimize properties, exclude credentials/payment data/content by default, avoid URLs or query strings that contain personal data, honor applicable consent/opt-out rules, and review replay masking and log scrubbing. Do not assume an unset privacy option means off. From
@sentry/nextjs11.0.0 (23 Sep 2026), an unsetdataCollectioncollects user identity, cookies, headers, request and response bodies, query params, GenAI content, DB query data, and local variables (checked 2026-11-04: https://docs.sentry.io/platforms/javascript/guides/nextjs/migration/v10-to-v11/). On v11 or later, setdataCollectionexplicitly to the minimum the metric and debug plan needs; on v10, keep collection opt-in. Treat any SDK major upgrade as a privacy review. - Preserve secrets and deployment boundaries. Public ingestion tokens may be exposed only when the provider defines them as public; source-map tokens, service-role keys, and personal API keys stay server-side and out of logs and git.
Verification
Verify only systems actually implemented:
- Trigger a known page view and typed product event; confirm exact names/properties in the provider.
- Test anonymous activity, sign-in identification, account switching, and logout reset without merging the wrong people.
- Trigger a controlled client and server error; record event IDs, verify environment/release tags and resolved source maps, then remove the test path.
- Verify redaction against a request built to leak: a cookie, an
Authorizationheader, a body with a personal field, and a personal query param. Confirm the stored error event omits each restricted category, including local variables, instead of trusting the config. - Test liveness independently from dependencies. Test readiness with a forced dependency failure, a short timeout, and the expected non-2xx response.
- For dashboards, test authorization and tenant boundaries, reconcile aggregate queries to source fixtures, verify timezone/window/maturity behavior, and render loading, empty, stale, partial, error, and populated states.
- Run the project’s lint/type/test/build commands and test in the target runtime when serverless or edge behavior matters.
- Record anything that requires dashboard access or production credentials as manual setup, not as verified.
Output
Report:
- questions the system now answers and the event/monitoring plan;
- metric contracts for activation, retention, or other implemented measures;
- providers reused, added, or deliberately omitted;
- files and environment-variable names changed;
- dashboard routes/components, aggregate queries, access policy, freshness, and rendered states when applicable;
- privacy, consent, identity, sampling, and retention decisions, including installed SDK versions and the explicit data collection settings;
- verification performed with event IDs or observed responses;
- dashboard, DNS, token, alerting, and production checks still required.
Health endpoints
Read this reference when the selected observability plan needs liveness, readiness, or external uptime monitoring.
Contents
Choose the signal
- Liveness answers whether the process can serve. Keep it cheap and independent of downstream services.
- Readiness answers whether this instance can perform essential work. Probe only critical dependencies, use short timeouts, and return a non-2xx response when unavailable.
- Business checks belong in synthetic monitoring, not a public health response.
Do not expose environment names, versions, connection details, exception text, row counts, or dependency topology publicly. In serverless runtimes, process uptime is instance-local and usually not a useful service metric.
Next.js pattern
// app/api/health/live/route.ts
export async function GET() {
return Response.json(
{ status: 'ok', timestamp: new Date().toISOString() },
{ headers: { 'Cache-Control': 'no-store' } },
);
}
For readiness, inject a project-specific dependency check rather than assuming a users table or creating a new service-role client on every request:
// app/api/health/ready/route.ts
import { checkDatabase } from '@/lib/health/check-database';
export async function GET() {
const result = await checkDatabase({ timeoutMs: 1_500 });
return Response.json(
{ status: result.ok ? 'ok' : 'unavailable' },
{
status: result.ok ? 200 : 503,
headers: { 'Cache-Control': 'no-store' },
},
);
}
Reuse the application’s server-only database client. The check should be bounded, non-mutating, and inexpensive. Protect readiness with network policy or a monitoring token if exposing dependency status creates risk.
FastAPI pattern
from datetime import datetime, timezone
from fastapi import Response
@app.get('/health/live')
async def live():
return {
'status': 'ok',
'timestamp': datetime.now(timezone.utc).isoformat(),
}
@app.get('/health/ready')
async def ready(response: Response):
ok = await check_database(timeout_seconds=1.5)
response.status_code = 200 if ok else 503
return {'status': 'ok' if ok else 'unavailable'}
Verification
- Liveness returns quickly while a downstream dependency is unavailable.
- Readiness returns 200 normally and 503 under a forced dependency failure or timeout.
- Responses contain no sensitive internals and are not cached.
- The external monitor uses the expected path, interval, regions, and alert contacts.
- Record dashboard/monitor configuration as manual until actually observed.
PostHog implementation
Read this reference before changing PostHog browser/server setup, identity, page views, or events. It is the one PostHog setup reference: the product-experiments skill defers here for setup and owns only experiment exposure and flag rollout.
For raw API shapes, use PostHog's official agent skill (posthog-instrumentation from posthog/posthog-for-claude) if installed, otherwise the docs listed under Sources. Vendor facts here were checked on 2026-11-04. Re-check a source before acting on it if that date is more than about 90 days old or the installed posthog-js/posthog-node version differs materially from the ones named.
Contents
- Plan events and privacy
- Initialize
- Identity
- Typed capture
- Server capture
- Verification
- Sources checked 2026-11-04
Plan events and privacy
Define stable event names and required properties before installation. Avoid credentials, payment data, message/content bodies, raw prompts, unrestricted URLs/query strings, and unnecessary personal data. Email addresses are personal data; capture them only when justified by the product's privacy/consent policy. Configure opt-out/consent, retention, replay masking, and region before production.
Initialize
PostHog's Next.js guide initializes the browser SDK in instrumentation-client.ts at the app root, for both App and Pages Router:
// instrumentation-client.ts
import posthog from 'posthog-js';
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, {
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
defaults: '2026-08-30',
});
Rules this shape hides:
defaultsis a dated bundle of SDK behavior. Keep the date already in the project; changing it changes behavior, so review what the new date enables, including navigation page views, before adding manual page-view capture.- Values passed to
inithere stay fixed for the session. Bootstrapped flags only work when evaluated before render, usually on the server with the samedistinct_id. - An existing
'use client'Provider setup still works. Keep it unless migration is in scope, and never initialize twice.@posthog/reacthooks work with theinstrumentation-clientsingleton. - Keep the project's existing env var name (older projects use
NEXT_PUBLIC_POSTHOG_KEY). Set it in the host as well as.env.local. - A Content-Security-Policy that does not allow
https://*.posthog.cominscript-srcandconnect-srcdrops every event silently. Check the CSP or set up a reverse proxy. @posthog/nextwas pre-release when checked. Do not adopt it unless asked.
The browser project token is designed for ingestion; do not confuse it with a personal API key. Keep personal keys and management API credentials server-only.
Identity
Use the stable internal application user ID as distinct_id. Identify only after authoritative authentication, reset on logout, and test account switching and impersonation.
posthog.identify(user.id, {
// Include personal properties only when approved by the measurement/privacy plan.
plan: user.plan,
});
posthog.reset();
Do not identify from untrusted query/body fields, and never with a shared literal such as "anonymous". Define how anonymous pre-login activity merges and how deletion/opt-out requests are handled. To link server events to the browser person, pass the same distinct ID to the server (PostHog's tracing_headers option adds it to requests for listed hostnames).
Typed capture
type ProductEvent =
| { event: 'project_created'; properties: { projectId: string } }
| { event: 'generation_completed'; properties: { generationId: string; latencyMs: number } };
export function captureProductEvent(value: ProductEvent) {
posthog.capture(value.event, value.properties);
}
Capture authoritative outcomes on the server when a browser event could be blocked, forged, or duplicated.
Server capture
posthog-node queues and batches in the background. Vercel Functions and Lambda can freeze the runtime once the handler returns, which drops queued events with no error. Pick one delivery pattern per call site:
| Pattern | Use when | Delivery |
|---|---|---|
| Shared client created outside the handler | the runtime reuses instances | await client.flush() before returning, including on error paths |
| Disposable client per request (PostHog's Next.js guide) | short-lived functions, simple setup | construct with flushAt: 1, flushInterval: 0, then await client.shutdown() after the last call |
await client.captureImmediate({ distinctId, event, properties }) |
one authoritative event that must be attempted before responding | waits for that event's delivery attempt |
flushAt: 1 and flushInterval: 0 alone start a flush but do not wait for it. Never call shutdown() on a shared client per request. Bound the wait to the request deadline and catch and log flush failures so telemetry cannot fail the request. Neither flush nor shutdown guarantees ingestion.
Verification
- Confirm exactly one expected page-view event per navigation strategy and
defaultsdate. - Confirm typed custom events and property shapes.
- Test anonymous-to-authenticated merge, logout reset, and account switching.
- Confirm development/test traffic is separated or disabled.
- Inspect a real event for accidental personal/sensitive properties.
- For server capture, deploy or run in the target runtime and confirm the event arrives from a handler that returns immediately after capture. Verify duplicate-request behavior.
Sources checked 2026-11-04
- PostHog Next.js guide (
instrumentation-client.ts,defaults: '2026-08-30', env names, CSP,flushAt: 1, flushInterval: 0withawait shutdown(),@posthog/nextpre-release): https://posthog.com/docs/libraries/next-js - PostHog Node.js SDK (shared client
flush(), disposable clientshutdown(),captureImmediate, serverless freezing): https://posthog.com/docs/libraries/node - npm registry:
posthog-js1.445.4,posthog-node5.61.2.
Sentry implementation
Read this reference before changing Sentry initialization, data collection, source maps, boundaries, structured errors, logs, replay, or tracing. For raw setup API shapes, use Sentry's official agent skill (sentry-sdk-setup from getsentry/sentry-for-ai) if installed, otherwise the docs listed under Sources. This file keeps the decisions those sources leave to you.
Vendor facts here were checked on 2026-11-04. Before acting on one, re-check its source if that date is more than about 90 days old or the installed major version differs from the one named.
Contents
- Detect the installed major
- Install and configure
- Data collection
- Sampling, tracing, and logs
- Boundaries and logging
- Source maps
- Verification
- Sources checked 2026-11-04
Detect the installed major
Read the resolved @sentry/nextjs version from the lockfile, not the package.json range. The privacy default flips between majors:
| Installed | Unset privacy option means | Your job |
|---|---|---|
| 11.x (11.0.0 published 23 Sep 2026) | dataCollection unset collects everything: user identity, cookies, request and response headers and bodies, query params, GenAI inputs and outputs, DB query data, and local variables. sendDefaultPii no longer exists. |
Restrict. Set dataCollection explicitly to the minimum the metric and debug plan needs. |
| 10.57 to 10.x | sendDefaultPii unset is restrictive. dataCollection exists but its defaults apply only when you set it. |
Keep the opt-in reasoning. Set dataCollection explicitly now so the v11 upgrade cannot widen collection. |
| below 10.57 | sendDefaultPii unset is restrictive. |
Keep the opt-in reasoning. Enable each category only when the plan needs it. |
An upgrade from 10 to 11 that only bumps the version silently turns on cookies, bodies, user identity, GenAI content, and DB query data. Treat it as a privacy change and review it as one. If the project set sendDefaultPii: true, remove it: the v11 default already matches it, which still means it needs restricting.
Install and configure
The Next.js wizard may generate instrumentation-client.ts, sentry.server.config.ts, sentry.edge.config.ts, instrumentation.ts with onRequestError, app/global-error.tsx, and a withSentryConfig wrapper in the Next config. Run it only when dependency installation and generated changes are in scope, then inspect the diff. The wizard does not choose your data collection policy.
On v11:
- import
withSentryConfigfrom@sentry/nextjs/config, not@sentry/nextjs; the build options deprecated in 10.30.0 are removed, most now live underwebpack; - Next.js 14 is the minimum;
- on Vercel,
environmentdefaults toVERCEL_TARGET_ENV(production,preview) instead ofvercel-production/vercel-preview; set it explicitly if alerts or dashboards use the old names.
Keep DSNs where the SDK expects them. Keep source-map auth tokens and organization/project management credentials server-side and out of the application bundle.
Data collection
Start from the plan: which errors must be debuggable, and what context does that need? Collect that and nothing else. A safe v11 starting point for a product that handles personal data:
Sentry.init({
dsn: process.env.NEXT_PUBLIC_SENTRY_DSN,
dataCollection: {
userInfo: false, // set an internal ID yourself with Sentry.setUser({ id })
cookies: false,
httpHeaders: { allow: ['content-type', 'user-agent'] },
httpBodies: [],
urlQueryParams: { deny: ['email', 'phone', 'forwarded', '-ip', 'remote-', 'via', '-user'] },
genAI: { inputs: false, outputs: false },
databaseQueryData: false,
graphQL: { document: true, variables: false },
stackFrameVariables: false,
},
});
Loosen a category only with a named debugging need, and record why in the output. Rules the defaults hide:
- The built-in denylist (
auth,token,secret,password,session,jwtand similar) matches key names only. A credential in a field namednotestill ships. Bodies and local variables are where this bites. Sentry.setUser()data is always sent, whateveruserInfosays. Send the internal user ID, not email or name.requestDataIntegration({ include: { ... } })overridesdataCollection: an explicittruethere attaches the category even whendataCollectionturns it off. Search for it before trusting the config.mcp(11.9.0+) falls back togenAIwhen unset.queuescollects task arguments by default.dataCollectiondoes not cover Session Replay. Configure replay masking and blocking separately.
Apply the same policy in client, server, and edge configs. A restrictive client config with a default server config still ships request bodies.
Sampling, tracing, and logs
Choose trace and replay sampling from traffic, incident needs, and budget rather than hard-coding 10%. Error-triggered replay can still collect personal data; it is not automatically safe because normal session replay sampling is zero.
On v11, span streaming is the default (traceLifecycle: 'stream'). Transactions no longer exist, so beforeSendTransaction and ignoreTransactions do nothing, and scope tags and extras reach errors but not spans. Use Sentry.setAttribute() for anything that must be searchable on spans, and check alerts and dashboards built on transaction names. traceLifecycle: 'static' keeps the old model as a temporary bridge only.
Logs: from 10.71.0, logs are sent whenever code calls Sentry.logger.* or a logging integration such as consoleLoggingIntegration() is added. enableLogs is no longer needed and v11 removes it. A console integration ships every console line, so scrub with beforeSendLog or capture only deliberate Sentry.logger calls.
Tag environment and release consistently across client, server, and edge.
Boundaries and logging
Use framework error files/boundaries for user recovery and capture unexpected exceptions once. Avoid duplicate capture in nested boundaries. Preserve a safe user-facing message and a retry/reset path.
import * as Sentry from '@sentry/nextjs';
export function captureAppError(
error: unknown,
context: { action?: string; requestId?: string; metadata?: Record<string, unknown> } = {},
) {
const normalized = error instanceof Error ? error : new Error(String(error));
Sentry.withScope((scope) => {
if (context.action) scope.setTag('action', context.action);
if (context.requestId) scope.setTag('request_id', context.requestId);
if (context.metadata) scope.setExtras(context.metadata);
Sentry.captureException(normalized);
});
}
Metadata must be allow-listed and scrubbed. Do not attach entire request bodies or user objects. On v11 these tags and extras land on the error event only.
Source maps
Upload source maps during the production build using the provider's supported integration. Do not expose source-map tokens at runtime. Verify with a real event/release, because a successful build alone does not prove frames resolve.
Verification
- Record the installed
@sentry/nextjsversion and thedataCollection(orsendDefaultPii) policy in client, server, and edge configs. - Send a test request that carries a cookie, an
Authorizationheader, a JSON body with a personal field, and a personal query param, and throw from its handler. Open the event and confirm every restricted category is absent or[Filtered], including local variables. - Trigger controlled client and server errors and record their event IDs.
- Confirm each error is captured once with correct environment/release tags.
- Inspect replay for masking and logs for scrubbing when either is enabled.
- Confirm the boundary recovery/reset path works.
- Verify source frames resolve to authored code, then remove the test path.
- Exercise tracing only at the configured sampling behavior and confirm cost-sensitive data is not attached to spans.
Sources checked 2026-11-04
- Sentry v10 to v11 migration for Next.js (
dataCollectiondefault table,withSentryConfigpath, span streaming, logs options, Vercel environment): https://docs.sentry.io/platforms/javascript/guides/nextjs/migration/v10-to-v11/ - Sentry Next.js options (
dataCollectionkeys and defaults, available since 10.57.0, denylist, replay exclusion, logs opt-in below 10.71.0): https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/options/ - npm registry
@sentry/nextjs: 10.57.0 on 9 Jun 2026, 10.71.0 on 24 Aug 2026, 11.0.0 on 23 Sep 2026, latest 11.10.0: https://www.npmjs.com/package/@sentry/nextjs
Claude app, ChatGPT and ZIP download
local coding agent required
This skill requires project files, terminal commands, and network access. Uploading it to a chat app does not provide equivalent execution.
ChatGPT Skills
This workflow needs a local coding environment or capabilities that a chat-only Skills upload does not provide.
Package details
- Package
- analytics/SKILL.md
- Author
- @tushaarmehtaa
- Added
- 7 Mar 2026
- Tags