diff --git a/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/.posthog-wizard b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/.posthog-wizard new file mode 100644 index 000000000..e69de29bb diff --git a/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/SKILL.md b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/SKILL.md new file mode 100644 index 000000000..bec0dc0b7 --- /dev/null +++ b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/SKILL.md @@ -0,0 +1,69 @@ +--- +name: integration-nuxt-4 +description: PostHog integration for Nuxt 4 applications +metadata: + author: PostHog + version: dev +--- + +# PostHog integration for Nuxt 4 + +This skill helps you add PostHog analytics to Nuxt 4 applications. + +## Workflow + +Follow these steps in order to complete the integration: + +1. `references/1-begin.md` - PostHog Setup - Begin ← **Start here** +2. `references/2-edit.md` - PostHog Setup - Edit +3. `references/3-revise.md` - PostHog Setup - Revise +4. `references/4-conclude.md` - PostHog Setup - Conclusion + +## Reference files + +- `references/EXAMPLE.md` - Nuxt 4 example project code +- `references/1-begin.md` - Start the event tracking setup process by analyzing the project and creating an event tracking plan +- `references/2-edit.md` - Implement PostHog event tracking in the identified files, following best practices and the example project +- `references/3-revise.md` - Review and fix any errors in the PostHog integration implementation +- `references/4-conclude.md` - Review and fix any errors in the PostHog integration implementation +- `references/nuxt-js.md` - Nuxt.js - docs +- `references/identify-users.md` - Identify users - docs +- `references/COMMANDMENTS.md` - Framework-specific rules the integration must follow + +The example project shows the target implementation pattern. Consult the documentation for API details. + +## 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 example**: Your implementation should follow the example project's patterns as closely as possible. + +## Framework guidelines + +- Remember that source code is available in the node_modules directory +- Check package.json for type checking or build scripts to validate changes +- When a reverse proxy is configured, both /static/* AND /array/* must route to the assets origin (us-assets.i.posthog.com or eu-assets.i.posthog.com). +- posthog-js is the JavaScript SDK package name +- posthog.init() MUST be called before any other PostHog methods (capture, identify, etc.) +- posthog-js is browser-only — do NOT import it in Node.js or server-side contexts (use posthog-node instead) +- Autocapture is ON by default with posthog-js (tracks clicks, form submissions, pageviews). Keep autocapture enabled unless the user explicitly asks to turn it off. +- NEVER send PII in posthog.capture() event properties — no emails, full names, phone numbers, physical addresses, IP addresses, or user-generated content +- PII belongs in posthog.identify() person properties (email, name, role), NOT in capture() event properties +- Call posthog.identify(userId, { email, name, role }) on login AND on page refresh if the user is already logged in +- Call posthog.reset() on logout to unlink future events from the current user +- For SPAs without a framework router, capture pageviews with posthog.capture($pageview) or use the capture_pageview history_change option in init for History API routing +- posthog-node is the Node.js server-side SDK package name; posthog-js is browser-only, so use posthog-node on the server instead +- Include enableExceptionAutocapture: true in the PostHog constructor options +- Add posthog.capture() calls in route handlers for meaningful user actions – every route that creates, updates, or deletes data should track an event with contextual properties +- Add posthog.captureException(err, distinctId) in the application's error handler (e.g., Express error middleware, Fastify setErrorHandler, Koa app.on('error')) +- The SDK batches events and flushes asynchronously. await flush() or await shutdown() before letting that process exit. If unsure, set flushAt 1 and flushInterval 0. +- `posthog.capture()` enqueues synchronously and returns; the batched HTTP send happens afterwards. Treat every per-request handler as short-lived even when the framework feels like a server: Next.js / Nuxt / SvelteKit / Remix route handlers, serverless and edge functions, and Lambda are torn down per invocation before the send runs. Create the client with flushAt 1 and flushInterval 0, then await the send before returning. Always use `await posthog.flush()` for a shared/singleton client, `await posthog.shutdown()` for a per-request client. Never skip the awaited flush or risk the enqueued event being silently dropped. +- Reverse proxy is NOT needed for server-side Node.js – only client-side JavaScript needs a proxy to avoid ad blockers + +## Identifying users + +Identify users during login and signup events. Refer to the example code and documentation for the correct identify pattern for this framework. If both frontend and backend code exist, pass the client-side session and distinct ID using `X-POSTHOG-DISTINCT-ID` and `X-POSTHOG-SESSION-ID` headers to maintain correlation. + +## Error tracking + +Add PostHog error tracking to relevant files, particularly around critical user flows and API boundaries. diff --git a/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/1-begin.md b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/1-begin.md new file mode 100644 index 000000000..55f0a8326 --- /dev/null +++ b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/1-begin.md @@ -0,0 +1,56 @@ +--- +title: PostHog Setup - Begin +description: Start the event tracking setup process by analyzing the project and creating an event tracking plan +--- + +We're making an event tracking plan for this project. + +This is the first of several phases — plan the events, implement them, revise and validate changes, then conclude by creating a dashboard and writing a setup report. + +## Task list + +As soon as you've read this description and have a rough sense of the work, make a single **call `TaskCreate` immediately** before reading any reference file or beginning analysis. The user is watching the task pane and shouldn't see it sit empty. + +It's fine if your first list is incomplete or imprecise. Seed it with whatever high-level items you can infer from the overview above, then call `TaskCreate` again (or `TaskUpdate` to refine existing items) every time your understanding sharpens: after a phase reveals work you didn't anticipate, after planning surfaces concrete sub-items, after you hit something new. Use `TaskUpdate` to mark items `in_progress` when you start them and `completed` when you finish. Keeping the list current matters more than getting it right on the first call. + +Keep task titles broad and job-oriented. Describe the purpose or area of work with wording like "Planning event tracking", "Identifying users", "Installing PostHog", "Capturing events", or "Creating dashboards", not the specific files, paths, or symbols involved. Adjust the task names according to the user's project and context. + +Before proceeding, find any existing `posthog.capture()` code. Make note of event name formatting. + +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 additional files related to login that could be used for identifying users, along with error handling. Read the files. If a file is already well-covered by PostHog events, replace it with another option. Do not spawn subagents. + +Look for opportunities to track client-side events. + +**IMPORTANT: Server-side events are REQUIRED** if the project includes any instrumentable server-side code. If the project has API routes (e.g., `app/api/**/route.ts`) or Server Actions, you MUST include server-side events for critical business operations like: + + - Payment/checkout completion + - Webhook handlers + - Authentication endpoints + +Do not skip server-side events - they capture actions that cannot be tracked client-side. + +Create a new file with a JSON array at the root of the project: .posthog-events.json. It should include one object for each event we want to add with these exact field names: `event_name` (the event name), `event_description` (one sentence), and `file` (the file path the event goes in). The wizard reads this file to surface the plan in the UI. If events already exist, don't duplicate them; supplement them. + +Track actions only, not pageviews. These can be captured automatically. Exceptions can be made for "viewed"-type events that correspond to the top of a conversion funnel. + +As you review files, make an internal note of opportunities to identify users and catch errors. We'll need them for the next step. + +## Status + +Before beginning a phase of the setup, you will send a status message with the exact prefix '[STATUS]', as in: + +[STATUS] Checking project structure. + +Status to report in this phase: + +- Checking project structure +- Verifying PostHog dependencies +- Generating events based on project + +## Abort statuses + +If and only if the instructions have `[ABORT]` states specified, and you clearly match the conditions for an abort, emit the abort message. Do NOT attempt to exit or halt yourself — the wizard's middleware catches `[ABORT]` and terminates the run for you. + +--- + +**Upon completion, continue with:** [2-edit.md](2-edit.md) \ No newline at end of file diff --git a/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/2-edit.md b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/2-edit.md new file mode 100644 index 000000000..e5f7ffd16 --- /dev/null +++ b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/2-edit.md @@ -0,0 +1,36 @@ +--- +title: PostHog Setup - Edit +description: Implement PostHog event tracking in the identified files, following best practices and the example project +--- + +For each of the files and events noted in .posthog-events.json, make edits to capture events using PostHog. Make sure to set up any helper files needed. Carefully examine the included example project code: your implementation should match it as closely as possible. Do not spawn subagents. + +Use environment variables for PostHog keys. Do not hardcode PostHog keys. + +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. + +For each event, add useful properties, and use your access to the PostHog source code to ensure correctness. You also have access to documentation about creating new events with PostHog. Consider this documentation carefully and follow it closely before adding events. Your integration should be based on documented best practices. Carefully consider how the user project's framework version may impact the correct PostHog integration approach. + +Remember that you can find the source code for any dependency in the node_modules directory. This may be necessary to properly populate property names. There are also example project code files available via the PostHog MCP; use these for reference. + +Where possible, add calls for PostHog's identify() function on the client side upon events like logins and signups. Use the contents of login and signup forms to identify users on submit. If there is server-side code, pass the client-side session and distinct ID to the server-side code to identify the user. On the server side, make sure events have a matching distinct ID where relevant. + +It's essential to do this in both client code and server code, so that user behavior from both domains is easy to correlate. + +You should also add PostHog exception capture error tracking to these files where relevant. + +Remember: Do not alter the fundamental architecture of existing files. Make your additions minimal and targeted. + +Remember the documentation and example project resources you were provided at the beginning. Read them now. + +## Status + +Status to report in this phase: + +- Inserting PostHog capture code +- A status message for each file whose edits you are planning, including a high level summary of changes +- A status message for each file you have edited + +--- + +**Upon completion, continue with:** [3-revise.md](3-revise.md) \ No newline at end of file diff --git a/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/3-revise.md b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/3-revise.md new file mode 100644 index 000000000..3b07f5069 --- /dev/null +++ b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/3-revise.md @@ -0,0 +1,22 @@ +--- +title: PostHog Setup - Revise +description: Review and fix any errors in the PostHog integration implementation +--- + +Check the project for errors. Read the package.json file for any type checking or build scripts that may provide input about what to fix. Remember that you can find the source code for any dependency in the node_modules directory. Do not spawn subagents. + +Ensure that any components created were actually used. + +Once all other tasks are complete, 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. Do not run formatting or linting across the entire project's codebase. + +## Status + +Status to report in this phase: + +- Finding and correcting errors +- Report details of any errors you fix +- Linting, building and prettying + +--- + +**Upon completion, continue with:** [4-conclude.md](4-conclude.md) \ No newline at end of file diff --git a/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/4-conclude.md b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/4-conclude.md new file mode 100644 index 000000000..747adcdc9 --- /dev/null +++ b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/4-conclude.md @@ -0,0 +1,139 @@ +--- +title: PostHog Setup - Conclusion +description: Review and fix any errors in the PostHog integration implementation +--- + +Create a live PostHog dashboard named "Analytics basics (wizard)" from the events you just instrumented, then populate it with up to five insights — lead with the business-critical views: conversion funnels, churn events, and other key signals. Use the exact same event names as implemented in the code. Keep the `(wizard)` tag with that exact casing so anyone browsing PostHog can see the wizard created this dashboard, and so a quick search for `(wizard)` surfaces every wizard-created artifact in one go. + +## How to call PostHog MCP tools + +The PostHog MCP server exposes a single `exec` tool. Every PostHog operation is driven by a CLI-style command string passed in its `command` parameter — the tool may be namespaced by the host (`mcp__posthog__exec`, `mcp__posthog-wizard__exec`), but the command grammar is the same. Tool names and schemas are not predictable, so discover and inspect before you call. + +**Grammar** — run in this order: + +```text +exec({ "command": "search " }) # find tools by name/title/description; `tools` lists them all +exec({ "command": "info " }) # REQUIRED before every call — description + input schema +exec({ "command": "schema " }) # drill into a field the schema flags with a `hint` +exec({ "command": "call " }) # run the tool +``` + +Running `info ` before `call ` is mandatory, the same way you read a file before editing it. `info` returns the full schema for simple tools; for large ones it summarizes and attaches `hint` entries pointing at fields to drill into with `schema`. Dot-notation descends objects (`query.source`), array items (`series.0.properties`), and unions. Never guess the structure of a field that carries a hint — drill first. + +Every PostHog tool goes through `exec` this way — there is no separate named tool to call directly. The inner tool names and JSON payloads below are what you pass to `call`. + +**Errors** carry a suggestion and similar tool names — read it before retrying. If a name isn't found it may have been renamed; run `search ` or `tools` again to find the current one. + +Create the parent dashboard first with `dashboard-create`, capture its returned `id`, then attach every insight to it via `dashboards: []`: + +```json +{ + "name": "Analytics basics (wizard)", + "description": "Key views for the events instrumented by the PostHog wizard.", + "tags": ["wizard"] +} +``` + +When calling `insight-create`, use these known-good query shapes — they are verified against the MCP schema, and the common variations around them are rejected: + +A trends insight with a breakdown (breakdowns go in `breakdownFilter.breakdowns`, an array — there is NO top-level `breakdown` field on `TrendsQuery`): + +```json +{ + "name": "Signups by plan (wizard)", + "dashboards": [], + "query": { + "kind": "InsightVizNode", + "source": { + "kind": "TrendsQuery", + "series": [{ "kind": "EventsNode", "event": "user_signed_up", "math": "total" }], + "interval": "day", + "dateRange": { "date_from": "-30d" }, + "breakdownFilter": { "breakdowns": [{ "type": "event", "property": "plan" }] }, + "trendsFilter": { "display": "ActionsBar" } + } + } +} +``` + +A conversion funnel (the window fields are camelCase and live INSIDE `funnelsFilter` — not at the top level of `FunnelsQuery`, and not snake_case): + +```json +{ + "name": "Signup funnel (wizard)", + "dashboards": [], + "query": { + "kind": "InsightVizNode", + "source": { + "kind": "FunnelsQuery", + "series": [ + { "kind": "EventsNode", "event": "page_viewed" }, + { "kind": "EventsNode", "event": "user_signed_up" } + ], + "dateRange": { "date_from": "-30d" }, + "funnelsFilter": { + "funnelVizType": "steps", + "funnelOrderType": "ordered", + "funnelWindowInterval": 14, + "funnelWindowIntervalUnit": "day" + } + } + } +} +``` + +Valid `trendsFilter.display` values are `ActionsLineGraph`, `ActionsBar`, `ActionsAreaGraph`, `ActionsPie`, `ActionsStackedBar`, `BoldNumber`, and `ActionsTable` — names like `ActionsBarChart` or `ActionsBarGraph` are rejected. If an insight call is rejected anyway, fix the payload against these examples rather than retrying variations. + +Once the dashboard exists, emit its URL on its own line in your assistant message using this exact marker: `[DASHBOARD_URL] `. The wizard parses this marker from your visible message and surfaces the link in the success summary. Mentioning the URL only in thinking or in prose without the marker means the link is dropped. + +Search for a file called `.posthog-events.json` and read it for available events. + +Do not spawn subagents. + +Create the file posthog-setup-report.md. It should include a summary of the integration edits, a table with the event names, event descriptions, and files where events were added, a list of links for the dashboard and insights created, and a "Verify before merging" checklist (see below). Follow this format: + + +# PostHog post-wizard report + +The wizard has completed a deep integration of your project. [Detailed summary of changes] + +[table of events/descriptions/files] + +## Next steps + +We've built some insights and a dashboard for you to keep an eye on user behavior, based on the events we just instrumented: + +[links] + +## Verify before merging + +[checklist] + +### Agent skill + +We've left an agent skill folder in your project. You can use this context for further agent development when using Claude Code. This will help ensure the model provides the most up-to-date approaches for integrating PostHog. + + + +For the "Verify before merging" checklist, write GitHub-style checkboxes (`- [ ] ...`) covering what the developer (or their coding agent) still needs to do to take this from "wizard finished" to "merged". Include ONLY the items that actually apply to the integration you just performed — judge each against the code you changed in this run, and drop any that don't fit. Phrase each item as a concrete, checkable action. Candidate items, with the condition for including each: + +- Always: "Run a full production build (the wizard only verified the files it touched) and fix any lint or type errors introduced by the generated code." +- Always: "Run the test suite — call sites that were rewritten or instrumented may need updated mocks or fixtures." +- If you added environment variables: "Add the exact PostHog env var names you added to `.env.example` and any monorepo/bootstrap scripts so collaborators know what to set." +- If this integration ships a minified production browser bundle (most SPA/SSR web frameworks — e.g. Next.js, Nuxt, SvelteKit, Astro, Vite-based apps): "Wire source-map upload (`posthog-cli sourcemap` or your bundler's upload step) into CI so production stack traces de-minify." +- If LLM analytics was set up in this run: "Trigger the LLM call path(s) you instrumented and confirm `$ai_generation` events appear in PostHog AI Observability." +- If the app has user auth and an `identify` call was added: "Confirm the returning-visitor path also calls `identify` — a handler that only identifies on fresh login can leave returning sessions on anonymous distinct IDs." + +Do not invent items beyond what applies. If only the two "Always" items apply, the checklist is just those two. + +Then mirror the report into a shareable PostHog notebook so the user has an in-app copy to link and comment on. Call `notebooks-create` with a `title` (e.g. `PostHog setup (wizard) – `) and `content` set to a single markdown node wrapping the report verbatim — `{"type":"doc","content":[{"type":"ph-markdown-notebook","attrs":{"nodeId":"markdown-notebook-v2","markdown":""}}]}`. Take the `short_id` from the response, build the notebook URL as `/project//notebooks/`, and emit it on its own line so the wizard can surface it: `[NOTEBOOK_URL]` followed by that URL. Keep the local `posthog-setup-report.md` — the notebook is an extra copy, not a replacement. + +Upon completion, update `.posthog-events.json` so it matches the events you actually implemented, then remove it with your file tools. If removal is blocked or fails in your environment, leave the file in place and move on — the wizard host cleans it up after the run. Do not retry the removal or reach for shell commands to force it. + +## Status + +Status to report in this phase: + +- Configured dashboard: [insert PostHog dashboard URL] +- Created setup report: [insert full local file path] +- Created notebook: [insert PostHog notebook URL] \ No newline at end of file diff --git a/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/COMMANDMENTS.md b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/COMMANDMENTS.md new file mode 100644 index 000000000..eacfcd5e2 --- /dev/null +++ b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/COMMANDMENTS.md @@ -0,0 +1,23 @@ +# Framework rules + +Follow these when integrating PostHog into this framework. + +- Remember that source code is available in the node_modules directory +- Check package.json for type checking or build scripts to validate changes +- When a reverse proxy is configured, both /static/* AND /array/* must route to the assets origin (us-assets.i.posthog.com or eu-assets.i.posthog.com). +- posthog-js is the JavaScript SDK package name +- posthog.init() MUST be called before any other PostHog methods (capture, identify, etc.) +- posthog-js is browser-only — do NOT import it in Node.js or server-side contexts (use posthog-node instead) +- Autocapture is ON by default with posthog-js (tracks clicks, form submissions, pageviews). Keep autocapture enabled unless the user explicitly asks to turn it off. +- NEVER send PII in posthog.capture() event properties — no emails, full names, phone numbers, physical addresses, IP addresses, or user-generated content +- PII belongs in posthog.identify() person properties (email, name, role), NOT in capture() event properties +- Call posthog.identify(userId, { email, name, role }) on login AND on page refresh if the user is already logged in +- Call posthog.reset() on logout to unlink future events from the current user +- For SPAs without a framework router, capture pageviews with posthog.capture($pageview) or use the capture_pageview history_change option in init for History API routing +- posthog-node is the Node.js server-side SDK package name; posthog-js is browser-only, so use posthog-node on the server instead +- Include enableExceptionAutocapture: true in the PostHog constructor options +- Add posthog.capture() calls in route handlers for meaningful user actions – every route that creates, updates, or deletes data should track an event with contextual properties +- Add posthog.captureException(err, distinctId) in the application's error handler (e.g., Express error middleware, Fastify setErrorHandler, Koa app.on('error')) +- The SDK batches events and flushes asynchronously. await flush() or await shutdown() before letting that process exit. If unsure, set flushAt 1 and flushInterval 0. +- `posthog.capture()` enqueues synchronously and returns; the batched HTTP send happens afterwards. Treat every per-request handler as short-lived even when the framework feels like a server: Next.js / Nuxt / SvelteKit / Remix route handlers, serverless and edge functions, and Lambda are torn down per invocation before the send runs. Create the client with flushAt 1 and flushInterval 0, then await the send before returning. Always use `await posthog.flush()` for a shared/singleton client, `await posthog.shutdown()` for a per-request client. Never skip the awaited flush or risk the enqueued event being silently dropped. +- Reverse proxy is NOT needed for server-side Node.js – only client-side JavaScript needs a proxy to avoid ad blockers diff --git a/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/EXAMPLE.md b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/EXAMPLE.md new file mode 100644 index 000000000..a9c73e300 --- /dev/null +++ b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/EXAMPLE.md @@ -0,0 +1,1078 @@ +# PostHog Nuxt 4 Example Project + +Repository: https://github.com/PostHog/context-mill +Path: example-apps/nuxt-4 + +--- + +## README.md + +# PostHog Nuxt 4 example + +This is a [Nuxt 4](https://nuxt.com) example demonstrating PostHog integration with product analytics, session replay, feature flags, and error tracking. + +Nuxt 4 supports the `@posthog/nuxt` package, which provides automatic PostHog integration with built-in error tracking, source map uploads, and simplified configuration. This is the recommended approach for Nuxt 4+. + +For Nuxt 3.0 - 3.6, you must use the `posthog-js` and `posthog-node` packages directly instead. See the [Nuxt 3.6 example](../nuxt-3-6) for that approach. + +## Features + +- **Product Analytics**: Track user events and behaviors +- **Session Replay**: Record and replay user sessions +- **Error Tracking**: Automatic error capture on both client and server +- **Source Maps**: Automatic source map uploads when *building for production* +- **User Authentication**: Demo login system with PostHog user identification +- **Server-side & Client-side Tracking**: Examples of both tracking methods +- **SSR Support**: Server-side rendering with Nuxt 4 + +## Getting Started + +### 1. Install Dependencies + +```bash +npm install +# or +pnpm install +``` + +### 2. Configure Environment Variables + +Create a `.env` file in the root directory: + +```bash +NUXT_PUBLIC_POSTHOG_PROJECT_TOKEN=your_posthog_project_token +NUXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com + +# Optional: For source map uploads +PROJECT_ID=your_project_id +PERSONAL_API_KEY=your_personal_api_key +``` + +Get your PostHog project token from your [PostHog project settings](https://app.posthog.com/project/settings). + +For source map uploads, get your project ID from [PostHog environment variables](https://app.posthog.com/settings/environment#variables) and your personal API key from [PostHog user API keys](https://app.posthog.com/settings/user-api-keys) (requires `organization:read` and `error_tracking:write` scopes). + +### 3. Run the Development Server + +```bash +npm run dev +# or +pnpm dev +``` + +Open [http://localhost:3000](http://localhost:3000) with your browser to see the app. + +## Project Structure + +``` +├── app/ +│ ├── components/ +│ │ └── AppHeader.vue # Navigation header with auth state +│ ├── composables/ +│ │ └── useAuth.ts # Authentication composable +│ ├── middleware/ +│ │ └── auth.ts # Authentication middleware +│ ├── pages/ +│ │ ├── index.vue # Home/Login page +│ │ ├── burrito.vue # Demo feature page with event tracking +│ │ └── profile.vue # User profile with error tracking demo +│ ├── utils/ +│ │ └── formValidation.ts # Form validation utilities +│ └── app.vue # Root component +├── assets/ +│ └── css/ +│ └── main.css # Global styles +├── server/ +│ ├── api/ +│ │ ├── auth/ +│ │ │ └── login.post.ts # Login API with server-side tracking +│ │ └── burrito/ +│ │ └── consider.post.ts # Burrito consideration API with server-side tracking +│ └── utils/ +│ ├── posthog.ts # Server-side PostHog utility +│ └── users.ts # In-memory user storage utilities +├── nuxt.config.ts # Nuxt configuration with PostHog module +└── package.json +``` + +## Key Integration Points + +### Module Configuration (nuxt.config.ts) + +Nuxt 4 uses the `@posthog/nuxt` module for automatic PostHog integration: + +```typescript +export default defineNuxtConfig({ + modules: ['@posthog/nuxt'], + runtimeConfig: { + public: { + posthog: { + publicKey: process.env.NUXT_PUBLIC_POSTHOG_PROJECT_TOKEN || '', + host: process.env.NUXT_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com', + }, + }, + }, + posthogConfig: { + publicKey: process.env.NUXT_PUBLIC_POSTHOG_PROJECT_TOKEN || '', + host: process.env.NUXT_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com', + clientConfig: { + capture_exceptions: true, // Enables automatic exception capture on the client side (Vue) + __add_tracing_headers: ['localhost', 'yourdomain.com'], // Add your domain here + }, + serverConfig: { + enableExceptionAutocapture: true, // Enables automatic exception capture on the server side (Nitro) + }, + sourcemaps: { + enabled: true, + envId: process.env.PROJECT_ID || '', + personalApiKey: process.env.PERSONAL_API_KEY || '', + project: 'my-application', + version: '1.0.0', + }, + }, +}) +``` + +**Key Points:** +- The `@posthog/nuxt` module handles PostHog initialization automatically +- Client-side error tracking is enabled via `capture_exceptions: true` +- Server-side error tracking is enabled via `enableExceptionAutocapture: true` +- Source map uploads are configured for better error tracking +- The `__add_tracing_headers` option automatically adds `X-POSTHOG-SESSION-ID` and `X-POSTHOG-DISTINCT-ID` headers to requests + +**Important**: do not identify users on the server-side. + +### User identification (app/pages/index.vue) + +The user is identified when the user logs in on the **client-side**. + +```typescript +const posthog = usePostHog() + +const handleSubmit = async () => { + const success = await auth.login(formData.username, formData.password) + if (success) { + // Identifying the user once on login/sign up is enough. + posthog?.identify(formData.username) + + // Capture login event + posthog?.capture('user_logged_in') + } +} +``` + +The session and distinct ID are automatically passed to the backend via the `X-POSTHOG-SESSION-ID` and `X-POSTHOG-DISTINCT-ID` headers because we set the `__add_tracing_headers` option in the PostHog configuration. + +**Important**: do not identify users on the server-side. + +### Server-side API routes (server/api/auth/login.post.ts) + +Server-side API routes use the `useServerPostHog()` utility to get a PostHog Node client and extract session and user context from request headers: + +```typescript +import { useServerPostHog } from '../../utils/posthog' +import { getOrCreateUser, users } from '../../utils/users' + +export default defineEventHandler(async (event) => { + const body = await readBody<{ username: string; password: string }>(event) + const { username, password } = body || {} + + if (!username || !password) { + throw createError({ + statusCode: 400, + message: 'Username and password required', + }) + } + + const user = getOrCreateUser(username) + const isNewUser = !users.has(username) + + const sessionId = getHeader(event, 'x-posthog-session-id') + const distinctId = getHeader(event, 'x-posthog-distinct-id') + + // Capture server-side login event + const posthog = useServerPostHog() + + posthog.capture({ + distinctId: distinctId, + event: 'server_login', + properties: { + $session_id: sessionId, + username: username, + isNewUser: isNewUser, + source: 'api', + }, + }) + + return { + success: true, + user, + } +}) +``` + +**Key Points:** +- Uses `useServerPostHog()` utility to get a shared PostHog Node client instance +- Extracts `sessionId` and `distinctId` from request headers using `getHeader()` (auto-imported from h3) +- The PostHog client is reused across requests (singleton pattern) +- h3 functions like `defineEventHandler`, `readBody`, `createError`, `getHeader` are auto-imported in server routes + +### Event tracking (app/pages/burrito.vue) + +The burrito consideration page demonstrates both client-side and server-side event tracking: + +```typescript +const posthog = usePostHog() + +const handleConsideration = async () => { + if (!user.value) return + + try { + // Call server-side API route + const response = await $fetch('/api/burrito/consider', { + method: 'POST', + body: { username: user.value.username }, + }) + + if (response.success && response.user) { + auth.setUser(response.user) + hasConsidered.value = true + + // Client-side tracking (in addition to server-side tracking) + posthog?.capture('burrito_considered', { + total_considerations: response.user.burritoConsiderations, + username: response.user.username, + }) + + setTimeout(() => { + hasConsidered.value = false + }, 2000) + } + } catch (err) { + console.error('Error considering burrito:', err) + } +} +``` + +The server-side route (`server/api/burrito/consider.post.ts`) also captures the event, demonstrating dual tracking. + +### Error tracking + +Errors are captured automatically in multiple ways: + +1. **Automatic client-side capture** - The `@posthog/nuxt` module automatically captures Vue errors when `capture_exceptions: true` is set in `posthogConfig.clientConfig`. + +2. **Automatic server-side capture** - The module automatically captures Nitro errors when `enableExceptionAutocapture: true` is set in `posthogConfig.serverConfig`. + +3. **Manual error capture** in components (app/pages/profile.vue): +```typescript +const posthog = usePostHog() + +const triggerTestError = () => { + try { + throw new Error('Test error for PostHog error tracking') + } catch (err) { + posthog?.captureException(err) + } +} +``` + +### Server-side tracking (server/api/auth/login.post.ts) + +Server-side events use the shared PostHog Node client. Note that h3 functions are auto-imported in Nuxt server routes: + +```typescript +import { useServerPostHog } from '../../utils/posthog' +import { getOrCreateUser, users } from '../../utils/users' + +export default defineEventHandler(async (event) => { + const body = await readBody<{ username: string; password: string }>(event) + const { username, password } = body || {} + + // ... validation logic ... + + // Extract headers using getHeader (auto-imported from h3) + const sessionId = getHeader(event, 'x-posthog-session-id') + const distinctId = getHeader(event, 'x-posthog-distinct-id') + + // Capture server-side event + const posthog = useServerPostHog() + + posthog.capture({ + distinctId: distinctId, + event: 'server_login', + properties: { + $session_id: sessionId, + username: username, + isNewUser: isNewUser, + source: 'api', + }, + }) + + return { success: true, user } +}) +``` + +**Key Points:** +- The PostHog Node client is shared across requests via `useServerPostHog()` utility +- `getHeader()` is auto-imported from h3 in Nuxt server routes (no need to import from 'h3') +- h3 functions like `defineEventHandler`, `readBody`, `createError` are also auto-imported +- The `distinctId` and `sessionId` are extracted from request headers and used to maintain context between client and server +- No need to manually shutdown the client (it's managed by the module) + +### Accessing PostHog in components + +PostHog is accessed via the `usePostHog()` composable provided by `@posthog/nuxt`: + +```typescript +const posthog = usePostHog() +posthog?.capture('event_name', { property: 'value' }) +``` + +The composable is automatically typed and available throughout your Nuxt application. + +### Server-side PostHog utility (server/utils/posthog.ts) + +The server utility provides a shared PostHog Node client instance: + +```typescript +import { PostHog } from 'posthog-node' + +let client: PostHog | null = null + +export function useServerPostHog(): PostHog { + if (!client) { + const config = useRuntimeConfig() + const posthogConfig = config.public.posthog + client = new PostHog(posthogConfig.publicKey, { + host: posthogConfig.host, + }) + } + return client +} +``` + +This ensures a single PostHog client instance is reused across all server requests, improving performance. + +## Differences from Nuxt 3.6 + +- **Module-based**: Uses `@posthog/nuxt` module instead of manual plugin setup +- **Automatic error tracking**: Built-in error capture on both client and server +- **Source map uploads**: Automatic source map uploads for better error tracking +- **Simplified API**: Uses `usePostHog()` composable instead of `useNuxtApp().$posthog` +- **Shared server client**: Reuses PostHog Node client across requests instead of creating per-request +- **Automatic imports**: In Nuxt 4 server routes, h3 functions (`defineEventHandler`, `readBody`, `createError`, `getHeader`, etc.) are auto-imported - no need to import them explicitly + +## Learn More + +- [PostHog Documentation](https://posthog.com/docs) +- [Nuxt 4 Documentation](https://nuxt.com/docs) +- [PostHog Nuxt Integration Guide](https://posthog.com/docs/libraries/nuxt-js) +- [@posthog/nuxt Package](https://www.npmjs.com/package/@posthog/nuxt) + +--- + +## .env.example + +```example +NUXT_PUBLIC_POSTHOG_PROJECT_TOKEN= +NUXT_PUBLIC_POSTHOG_HOST= +PROJECT_ID= +PERSONAL_API_KEY= +``` + +--- + +## app/app.vue + +```vue + + +``` + +--- + +## app/components/AppHeader.vue + +```vue + + + + +``` + +--- + +## app/composables/useAuth.ts + +```ts +interface User { + username: string + burritoConsiderations: number +} + +const users: Map = new Map() + +export function useAuth() { + const user = useState('auth-user', () => { + if (process.client) { + const storedUsername = localStorage.getItem('currentUser') + if (storedUsername) { + const existingUser = users.get(storedUsername) + if (existingUser) { + return existingUser + } + } + } + return null + }) + + const login = async (username: string, password: string): Promise => { + try { + const response = await $fetch<{ success: boolean; user: User }>('/api/auth/login', { + method: 'POST', + body: { username, password }, + }) + + if (response.success) { + let localUser = users.get(username) + if (!localUser) { + localUser = response.user + users.set(username, localUser) + } + + user.value = localUser + if (process.client) { + localStorage.setItem('currentUser', username) + } + + return true + } + return false + } catch (error) { + console.error('Login error:', error) + return false + } + } + + const logout = () => { + user.value = null + if (process.client) { + localStorage.removeItem('currentUser') + } + } + + const incrementBurritoConsiderations = () => { + if (user.value) { + user.value.burritoConsiderations++ + users.set(user.value.username, user.value) + // Trigger reactivity + user.value = { ...user.value } + } + } + + const setUser = (newUser: User) => { + user.value = newUser + users.set(newUser.username, newUser) + } + + return { + user, + login, + logout, + incrementBurritoConsiderations, + setUser, + } +} + +``` + +--- + +## app/middleware/auth.ts + +```ts +export default defineNuxtRouteMiddleware((to, from) => { + const auth = useAuth() + const user = auth.user.value + + // If user is not logged in, redirect to home/login page + if (!user) { + return navigateTo('/') + } +}) + +``` + +--- + +## app/pages/burrito.vue + +```vue + + + + +``` + +--- + +## app/pages/index.vue + +```vue + + + + +``` + +--- + +## app/pages/profile.vue + +```vue + + + + +``` + +--- + +## app/utils/formValidation.ts + +```ts +import { z } from 'zod' + +export const loginSchema = z.object({ + username: z + .string() + .min(1, 'Username is required') + .min(3, 'Username must be at least 3 characters') + .max(50, 'Username must be less than 50 characters'), + password: z + .string() + .min(1, 'Password is required') + .min(3, 'Password must be at least 3 characters'), +}) + +export type LoginFormData = z.infer + +export function validateForm(schema: z.ZodSchema, data: unknown): { + success: boolean + data?: T + errors?: Record +} { + const result = schema.safeParse(data) + + if (result.success) { + return { success: true, data: result.data } + } + + const errors: Record = {} + result.error.errors.forEach((error) => { + const path = error.path.join('.') + errors[path] = error.message + }) + + return { success: false, errors } +} + +``` + +--- + +## nuxt.config.ts + +```ts +import { fileURLToPath } from 'node:url' +import { resolve, dirname } from 'node:path' + +const __filename = fileURLToPath(import.meta.url) +const __dirname = dirname(__filename) + +// https://nuxt.com/docs/api/configuration/nuxt-config +export default defineNuxtConfig({ + compatibilityDate: '2025-07-15', + devtools: { enabled: true }, + css: [resolve(__dirname, 'assets/css/main.css')], + modules: ['@posthog/nuxt'], + runtimeConfig: { + public: { + posthog: { + publicKey: process.env.NUXT_PUBLIC_POSTHOG_PROJECT_TOKEN || '', + host: process.env.NUXT_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com', + }, + }, + }, + posthogConfig: { + publicKey: process.env.NUXT_PUBLIC_POSTHOG_PROJECT_TOKEN || '', // Find it in project settings https://app.posthog.com/settings/project + host: process.env.NUXT_PUBLIC_POSTHOG_HOST || 'https://us.i.posthog.com', // Optional: defaults to https://us.i.posthog.com. Use https://eu.i.posthog.com for EU region + clientConfig: { + capture_exceptions: true, // Enables automatic exception capture on the client side (Vue) + __add_tracing_headers: [ 'localhost', 'yourdomain.com' ], // Add your domain here + }, + serverConfig: { + enableExceptionAutocapture: true, // Enables automatic exception capture on the server side (Nitro) + }, + sourcemaps: { + enabled: true, + envId: process.env.PROJECT_ID || '', // Your project ID from PostHog settings https://app.posthog.com/settings/environment#variables + personalApiKey: process.env.PERSONAL_API_KEY || '', // Your personal API key from PostHog settings https://app.posthog.com/settings/user-api-keys (requires organization:read and error_tracking:write scopes) + project: 'my-application', // Optional: defaults to git repository name + version: '1.0.0', // Optional: defaults to current git commit + }, + }, +}) + + +``` + +--- + +## public/robots.txt + +```txt +User-Agent: * +Disallow: + +``` + +--- + +## server/api/auth/login.post.ts + +```ts +import { useServerPostHog } from '../../utils/posthog' +import { getOrCreateUser, users } from '../../utils/users' + +export default defineEventHandler(async (event) => { + const body = await readBody<{ username: string; password: string }>(event) + const { username, password } = body || {} + + if (!username || !password) { + throw createError({ + statusCode: 400, + message: 'Username and password required', + }) + } + + const user = getOrCreateUser(username) + const isNewUser = !users.has(username) + + const sessionId = getHeader(event, 'x-posthog-session-id') + const distinctId = getHeader(event, 'x-posthog-distinct-id') + + // Capture server-side login event + const posthog = useServerPostHog() + + posthog.capture({ + distinctId: distinctId, + event: 'server_login', + properties: { + $session_id: sessionId, + username: username, + isNewUser: isNewUser, + source: 'api', + }, + }) + + // This handler is short-lived; flush so the enqueued event sends before it returns + await posthog.flush() + + return { + success: true, + user, + } +}) + +``` + +--- + +## server/api/burrito/consider.post.ts + +```ts +import { useServerPostHog } from '../../utils/posthog' +import { users, incrementBurritoConsiderations } from '../../utils/users' +import { defineEventHandler, readBody, createError, getHeader } from 'h3' + +export default defineEventHandler(async (event) => { + const body = await readBody<{ username: string }>(event) + const username = body?.username + + if (!username) { + throw createError({ + statusCode: 400, + message: 'Username required', + }) + } + + if (!users.has(username)) { + throw createError({ + statusCode: 404, + message: 'User not found', + }) + } + + // Increment burrito considerations (fake, in-memory) + const user = incrementBurritoConsiderations(username) + + const sessionId = getHeader(event, 'x-posthog-session-id') + const distinctId = getHeader(event, 'x-posthog-distinct-id') + + // Capture server-side burrito consideration event + const posthog = useServerPostHog() + + posthog.capture({ + distinctId: distinctId, + event: 'burrito_considered', + properties: { + $session_id: sessionId, + username: username, + total_considerations: user.burritoConsiderations, + source: 'api', + }, + }) + + // This handler is short-lived; flush so the enqueued event sends before it returns + await posthog.flush() + + return { + success: true, + user: { ...user }, + } +}) + +``` + +--- + +## server/utils/posthog.ts + +```ts +import { PostHog } from 'posthog-node' + +let client: PostHog | null = null + +export function useServerPostHog(): PostHog { + if (!client) { + const config = useRuntimeConfig() + // The @posthog/nuxt module exposes config at runtimeConfig.public.posthog + const posthogConfig = config.public.posthog + client = new PostHog(posthogConfig.publicKey, { + host: posthogConfig.host, + flushAt: 1, + flushInterval: 0, + }) + } + return client +} + +``` + +--- + +## server/utils/users.ts + +```ts +// Shared in-memory storage for users (fake, no database) +export const users = new Map() + +export function getOrCreateUser(username: string): { username: string; burritoConsiderations: number } { + let user = users.get(username) + + if (!user) { + user = { username, burritoConsiderations: 0 } + users.set(username, user) + } + + return user +} + +export function incrementBurritoConsiderations(username: string): { username: string; burritoConsiderations: number } { + const user = users.get(username) + + if (!user) { + throw new Error('User not found') + } + + user.burritoConsiderations++ + users.set(username, user) + + return { ...user } +} + +``` + +--- + diff --git a/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/identify-users.md b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/identify-users.md new file mode 100644 index 000000000..1417e03a8 --- /dev/null +++ b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/identify-users.md @@ -0,0 +1,272 @@ +# Identify users - Docs + +Linking events to specific users enables you to build a full picture of how they're using your product across different sessions, devices, and platforms. + +This is straightforward to do when [capturing backend events](/docs/product-analytics/capture-events?tab=Node.js.md), as you associate events to a specific user using a `distinct_id`, which is a required argument. + +However, in the frontend of a [web](/docs/libraries/js/features.md#capturing-events) or [mobile app](/docs/libraries/ios.md#capturing-events), a `distinct_id` is not a required argument — PostHog's SDKs will generate an anonymous `distinct_id` for you automatically and you can capture events anonymously, provided you use the appropriate [configuration](/docs/libraries/js/features.md#capturing-anonymous-events). + +To link events to specific users, call `identify`: + +PostHog AI + +### Web + +```javascript +posthog.identify( + 'distinct_id', // Replace 'distinct_id' with your user's unique identifier + { email: 'max@hedgehogmail.com', name: 'Max Hedgehog' } // optional: set additional person properties +); +``` + +### Android + +```kotlin +PostHog.identify( + distinctId = distinctID, // Replace 'distinctID' with your user's unique identifier + // optional: set additional person properties + userProperties = mapOf( + "name" to "Max Hedgehog", + "email" to "max@hedgehogmail.com" + ) +) +``` + +### iOS + +```swift +PostHogSDK.shared.identify("distinct_id", // Replace "distinct_id" with your user's unique identifier + userProperties: ["name": "Max Hedgehog", "email": "max@hedgehogmail.com"]) // optional: set additional person properties +``` + +### React Native + +```jsx +posthog.identify('distinct_id', { // Replace "distinct_id" with your user's unique identifier + email: 'max@hedgehogmail.com', // optional: set additional person properties + name: 'Max Hedgehog' +}) +``` + +### Dart + +```dart +await Posthog().identify( + userId: 'distinct_id', // Replace "distinct_id" with your user's unique identifier + userProperties: { + 'email': 'max@hedgehogmail.com', // optional: set additional person properties + 'name': 'Max Hedgehog', + }, +); +``` + +Events captured after calling `identify` are identified events and this creates a person profile if one doesn't exist already. + +Due to the cost of processing them, anonymous events can be up to 4x cheaper than identified events, so it's recommended you only capture identified events when needed. + +## How identify works + +When a user starts browsing your website or app, PostHog automatically assigns them an **anonymous ID**, which is stored locally. + +Provided you've [configured persistence](/docs/libraries/js/persistence.md) to use cookies or `localStorage`, this enables us to track anonymous users – even across different sessions. + +By calling `identify` with a `distinct_id` of your choice (usually the user's ID in your database, or their email), you link the anonymous ID and distinct ID together. + +Thus, all past and future events made with that anonymous ID are now associated with the distinct ID. + +This enables you to do things like associate events with a user from before they log in for the first time, or associate their events across different devices or platforms. + +Using identify in the backend + +Although you can call `identify` using our backend SDKs, it is used most in frontends. This is because there is no concept of anonymous sessions in the backend SDKs, so calling `identify` only updates person profiles. + +## Best practices when using `identify` + +### 1\. Call `identify` as soon as you're able to + +In your frontend, you should call `identify` as soon as you're able to. + +Typically, this is every time your **app loads** for the first time, and directly after your **users log in**. + +This ensures that events sent during your users' sessions are correctly associated with them. + +You only need to call `identify` once per session, and you should avoid calling it multiple times unnecessarily. + +If you call `identify` multiple times with the same data without reloading the page in between, PostHog will ignore the subsequent calls. + +### 2\. Use unique strings for distinct IDs + +If two users have the same distinct ID, their data is merged and they are considered one user in PostHog. Two common ways this can happen are: + +- Your logic for generating IDs does not generate sufficiently strong IDs and you can end up with a clash where 2 users have the same ID. +- There's a bug, typo, or mistake in your code leading to most or all users being identified with generic IDs like `null`, `true`, or `distinctId`. + +PostHog also has built-in protections to stop the most common distinct ID mistakes. + +### 3\. Reset after logout + +If a user logs out on your frontend, you should call `reset()` to unlink any future events made on that device with that user. + +This is important if your users are sharing a computer, as otherwise all of those users are grouped together into a single user due to shared cookies between sessions. + +**We strongly recommend you call `reset` on logout even if you don't expect users to share a computer.** + +You can do that like so: + +PostHog AI + +### Web + +```javascript +posthog.reset() +``` + +### iOS + +```swift +PostHogSDK.shared.reset() +``` + +### Android + +```kotlin +PostHog.reset() +``` + +### React Native + +```jsx +posthog.reset() +``` + +### Dart + +```dart +await Posthog().reset(); +``` + +If you *also* want to reset the `device_id` so that the device will be considered a new device in future events, you can pass `true` as an argument: + +Web + +PostHog AI + +```javascript +posthog.reset(true) +``` + +### 4\. Person profiles and properties + +You'll notice that one of the parameters in the `identify` method is a `properties` object. + +This enables you to set [person properties](/docs/product-analytics/person-properties.md). + +Whenever possible, we recommend passing in all person properties you have available each time you call identify, as this ensures their person profile on PostHog is up to date. + +Person properties can also be set being adding a `$set` property to a event `capture` call. + +See our [person properties docs](/docs/product-analytics/person-properties.md) for more details on how to work with them and best practices. + +### 5\. Use deep links between platforms + +We recommend you call `identify` [as soon as you're able](#1-call-identify-as-soon-as-youre-able), typically when a user signs up or logs in. + +This doesn't work if one or both platforms are unauthenticated. Some examples of such cases are: + +- Onboarding and signup flows before authentication. +- Unauthenticated web pages redirecting to authenticated mobile apps. +- Authenticated web apps prompting an app download. + +In these cases, you can use a [deep link](https://developer.android.com/training/app-links/deep-linking) on Android and [universal links](https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app) on iOS to identify users. + +1. Use `posthog.get_distinct_id()` to get the current distinct ID. Even if you cannot call identify because the user is unauthenticated, this will return an anonymous distinct ID generated by PostHog. +2. Add the distinct ID to the deep link as query parameters, along with other properties like UTM parameters. +3. When the user is redirected to the app, parse the deep link and handle the following cases: + +- The mobile app is already authenticated. In this case, call [`posthog.alias()`](/docs/libraries/js/features.md#alias) with the distinct ID from the web. This associates the two distinct IDs as a single person. +- The mobile app is unauthenticated. In this case, call [`posthog.identify()`](/docs/libraries/js/features.md#identifying-users) with the distinct ID from the web so pre-login mobile events stay connected to the web session. When the user later logs in on mobile, call `identify()` again with your canonical user ID. + +As long as you associate the distinct IDs with `posthog.identify()` or `posthog.alias()`, you can track events generated across platforms. + +Here's an example implementation for handling deep links from web to mobile: + +PostHog AI + +### iOS + +```swift +import PostHog +class DeepLinkIdentityManager { + static let shared = DeepLinkIdentityManager() + // MARK: - Deep Link Received + func handleDeepLink(_ url: URL, isAuthenticatedOnMobile: Bool) { + guard let webDistinctId = URLComponents(url: url, resolvingAgainstBaseURL: true)? + .queryItems?.first(where: { $0.name == "ph_distinct_id" })?.value else { + return + } + if isAuthenticatedOnMobile { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHogSDK.shared.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHogSDK.shared.identify(webDistinctId) + } + } + // MARK: - Login/Signup + func handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHogSDK.shared.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + func handleLogout() { + PostHogSDK.shared.reset() + } +} +``` + +### Android + +```kotlin +import android.net.Uri +import com.posthog.PostHog +object DeepLinkIdentityManager { + // Deep Link Received + fun handleDeepLink(uri: Uri, isAuthenticatedOnMobile: Boolean) { + val webDistinctId = uri.getQueryParameter("ph_distinct_id") ?: return + if (isAuthenticatedOnMobile) { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHog.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHog.identify(webDistinctId) + } + } + // Login/Signup + fun handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHog.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + fun handleLogout() { + PostHog.reset() + } +} +``` + +## Further reading + +- [Identifying users docs](/docs/product-analytics/identify.md) +- [How person processing works](/docs/how-posthog-works/ingestion-pipeline.md#2-person-processing) +- [An introductory guide to identifying users in PostHog](/tutorials/identifying-users-guide.md) + +### Community questions + +Ask a question + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/nuxt-js.md b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/nuxt-js.md new file mode 100644 index 000000000..7844d457c --- /dev/null +++ b/apps/basic-integration/nuxt/movies-nuxt-4/.claude/skills/integration-nuxt-4/references/nuxt-js.md @@ -0,0 +1,253 @@ +# Nuxt.js - Docs + +PostHog makes it easy to get data about usage of your [Nuxt.js](https://nuxt.com/) app. Integrating PostHog into your app enables analytics about user behavior, custom events capture, session replays, feature flags, and more. + +This guide covers Nuxt v4.x and v3.7+. For these versions, we recommend using `@posthog/nuxt` module for client-side capture. + +The `@posthog/nuxt` module provides: + +- Automatic client-side PostHog initialization +- Auto-imported composables for PostHog and feature flags +- Automatic exception capture for error tracking +- Source map configuration and upload for error tracking + +For server-side event capture beyond error tracking, use the `posthog-node` SDK directly. + +> **Using an older version?** See our docs for [Nuxt 3.0-3.6](/docs/libraries/nuxt-js-3-6.md) or [Nuxt 2.x](/docs/libraries/nuxt-js-2.md). + +## Installation + +Install the PostHog Nuxt module using your package manager: + +PostHog AI + +### npm + +```bash +npm install @posthog/nuxt +``` + +### Yarn + +```bash +yarn add @posthog/nuxt +``` + +### pnpm + +```bash +pnpm add @posthog/nuxt +``` + +### Bun + +```bash +bun add @posthog/nuxt +``` + +## Identifying users + +> **Identifying users is required.** Call `posthog.identify('your-user-id')` after login to link events to a known user. This is what connects frontend event captures, [session replays](/docs/session-replay.md), [LLM traces](/docs/ai-engineering.md), and [error tracking](/docs/error-tracking.md) to the same person — and lets backend events link back too. +> +> See our guide on [identifying users](/docs/getting-started/identify-users.md) for how to set this up. + +## Configuration + +Store your PostHog keys in environment variables rather than hard-coding them. Add them to a `.env` file (and to your hosting provider). You can find these values in [your project settings](https://us.posthog.com/settings/project). + +.env + +PostHog AI + +```shell +NUXT_PUBLIC_POSTHOG_KEY= +NUXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com +``` + +Then reference them when you add the module to your `nuxt.config.ts` file: + +nuxt.config.ts + +PostHog AI + +```typescript +export default defineNuxtConfig({ + modules: ['@posthog/nuxt'], + posthogConfig: { + publicKey: process.env.NUXT_PUBLIC_POSTHOG_KEY, // Find it in project settings https://app.posthog.com/settings/project + host: process.env.NUXT_PUBLIC_POSTHOG_HOST, // Optional: defaults to https://us.i.posthog.com. Use https://eu.i.posthog.com for EU region + clientConfig: { + // Optional: PostHog client configuration options + }, + }, +}) +``` + +**Keep your personal API key out of the client bundle** + +Anything shipped to the browser – the token you pass to `posthog.init()`, anything under Nuxt's `runtimeConfig.public`, or the `@posthog/nuxt` module's `posthogConfig` – ends up in your client-side JavaScript and is visible to anyone who visits your site. This is fine for your **project token** (``), which is designed to be public. + +Your **[personal API key](/docs/api.md#authentication)** is different. It can grant full access to your PostHog account, so it must never reach the browser. If you need it – for example, for [source map uploads](/docs/error-tracking/upload-source-maps/nuxt.md) or [server-side local evaluation](/docs/feature-flags/local-evaluation.md) – read it from a server-only environment variable (or top-level `runtimeConfig`, never `runtimeConfig.public`) and only use it in server code. + +Either way, prefer reading keys from environment variables rather than hard-coding them in `nuxt.config`, so you can keep them out of source control and use different values per environment. + +## Usage on the client side + +The module provides the `usePostHog()` composable which is auto-imported and available in all your Vue components: + +app/pages/index.vue + +PostHog AI + +```html + +``` + +> **Note:** `usePostHog()` returns `undefined` on the server side during SSR, so use optional chaining `?.` when calling methods. + +## Usage on the server side + +The `@posthog/nuxt` module initializes a server-side client for error tracking only. For general event capture in Nitro routes, create your own `posthog-node` SDK client. + +The `@posthog/nuxt` module makes your config available at `runtimeConfig.public.posthog`. + +First, create a server utility to reuse the PostHog client across requests: + +server/utils/posthog.ts + +PostHog AI + +```typescript +import { PostHog } from 'posthog-node' +let client: PostHog | null = null +export function useServerPostHog(): PostHog { + if (!client) { + const config = useRuntimeConfig() + client = new PostHog(config.public.posthog.publicKey, { + host: config.public.posthog.host, + }) + } + return client +} +``` + +Then use it in your server routes: + +server/api/example.ts + +PostHog AI + +```typescript +export default defineEventHandler((event) => { + const posthog = useServerPostHog() + posthog.capture({ + distinctId: 'user_123', + event: 'server_event', + }) + return { success: true } +}) +``` + +Set up a reverse proxy (recommended) + +We recommend [setting up a reverse proxy](/docs/advanced/proxy.md), so that events are less likely to be intercepted by tracking blockers. + +We have our [own managed reverse proxy service](/docs/advanced/proxy/managed-reverse-proxy.md), which is free for all PostHog Cloud users, routes through our infrastructure, and makes setting up your proxy easy. + +If you don't want to use our managed service then there are several other options for creating a reverse proxy, including using [Cloudflare](/docs/advanced/proxy/cloudflare.md), [AWS Cloudfront](/docs/advanced/proxy/cloudfront.md), and [Vercel](/docs/advanced/proxy/vercel.md). + +Grouping products in one project (recommended) + +If you have multiple customer-facing products (e.g. a marketing website + mobile app + web app), it's best to install PostHog on them all and [group them in one project](/docs/settings/projects.md). + +This makes it possible to track users across their entire journey (e.g. from visiting your marketing website to signing up for your product), or how they use your product across multiple platforms. + +Add IPs to Firewall/WAF allowlists (recommended) + +For certain features like [heatmaps](/docs/toolbar/heatmaps.md), your Web Application Firewall (WAF) may be blocking PostHog's requests to your site. Add these IP addresses to your WAF allowlist or rules to let PostHog access your site. + +**EU**: `3.75.65.221`, `18.197.246.42`, `3.120.223.253` + +**US**: `44.205.89.55`, `52.4.194.122`, `44.208.188.173` + +These are public, stable IPs used by PostHog services (e.g., Celery tasks for snapshots). + +## Feature flags + +The module provides auto-imported composables for feature flags. All composables return reactive refs that automatically update when flags are loaded or changed. + +Vue + +PostHog AI + +```html + + +``` + +Vue + +PostHog AI + +```html + + +``` + +Vue + +PostHog AI + +```html + + +``` + +## Error Tracking + +For a detailed error tracking installation guide, including automatic exception capture and source map configuration, see the [Nuxt error tracking installation docs](/docs/error-tracking/installation/nuxt-3-7.md). + +## Troubleshooting + +**TypeScript errors in posthog config:** Remove the `.nuxt` directory and rebuild your project to regenerate config types. + +**PostHog not capturing events:** Ensure you're using optional chaining (`posthog?.capture()`) since `usePostHog()` returns `undefined` during server-side rendering. + +## Next steps + +For any technical questions for how to integrate specific PostHog features into Nuxt (such as analytics, feature flags, A/B testing, surveys, etc.), have a look at our [JavaScript Web](/docs/libraries/js.md) and [Node](/docs/libraries/node.md) SDK docs. + +Alternatively, the following tutorials can help you get started: + +- [How to set up analytics in Nuxt](/tutorials/nuxt-analytics.md) +- [How to set up feature flags in Nuxt](/tutorials/nuxt-feature-flags.md) +- [How to set up A/B tests in Nuxt](/tutorials/nuxtjs-ab-tests.md) +- [How to set up surveys in Nuxt](/tutorials/nuxt-surveys.md) + +### Community questions + +Ask a question + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/nuxt/movies-nuxt-4/.env.example b/apps/basic-integration/nuxt/movies-nuxt-4/.env.example index 108b00b6c..803224d66 100644 --- a/apps/basic-integration/nuxt/movies-nuxt-4/.env.example +++ b/apps/basic-integration/nuxt/movies-nuxt-4/.env.example @@ -1 +1,5 @@ BASE_URL=http://localhost:3000 + +# Required for PostHog analytics +# NUXT_PUBLIC_POSTHOG_KEY +# NUXT_PUBLIC_POSTHOG_HOST diff --git a/apps/basic-integration/nuxt/movies-nuxt-4/components/media/Card.vue b/apps/basic-integration/nuxt/movies-nuxt-4/components/media/Card.vue index 8c0c6e3fa..c82c04ba7 100644 --- a/apps/basic-integration/nuxt/movies-nuxt-4/components/media/Card.vue +++ b/apps/basic-integration/nuxt/movies-nuxt-4/components/media/Card.vue @@ -1,16 +1,27 @@