From aea3673df652d69aa2106202059a614564a07a1f Mon Sep 17 00:00:00 2001 From: "wizard-ci-bot[bot]" <254716194+wizard-ci-bot[bot]@users.noreply.github.com> Date: Fri, 3 Jul 2026 01:00:02 +0000 Subject: [PATCH] wizard-ci: vue/movies --- .../skills/integration-vue-3/.posthog-wizard | 0 .../.claude/skills/integration-vue-3/SKILL.md | 50 + .../integration-vue-3/references/1-begin.md | 56 ++ .../integration-vue-3/references/2-edit.md | 36 + .../integration-vue-3/references/3-revise.md | 22 + .../references/4-conclude.md | 57 ++ .../integration-vue-3/references/EXAMPLE.md | 910 ++++++++++++++++++ .../references/identify-users.md | 272 ++++++ .../integration-vue-3/references/vue-js.md | 306 ++++++ apps/basic-integration/vue/movies/.gitignore | 1 + .../vue/movies/package-lock.json | 87 ++ .../basic-integration/vue/movies/package.json | 1 + .../vue/movies/posthog-setup-report.md | 38 + .../movies/src/components/media/MediaCard.vue | 13 +- .../vue/movies/src/composables/useAuth.ts | 10 +- apps/basic-integration/vue/movies/src/main.js | 10 + .../vue/movies/src/views/MediaDetailView.vue | 16 +- .../vue/movies/src/views/SearchView.vue | 8 +- 18 files changed, 1888 insertions(+), 5 deletions(-) create mode 100644 apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/.posthog-wizard create mode 100644 apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/SKILL.md create mode 100644 apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/1-begin.md create mode 100644 apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/2-edit.md create mode 100644 apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/3-revise.md create mode 100644 apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/4-conclude.md create mode 100644 apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/EXAMPLE.md create mode 100644 apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/identify-users.md create mode 100644 apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/vue-js.md create mode 100644 apps/basic-integration/vue/movies/posthog-setup-report.md diff --git a/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/.posthog-wizard b/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/.posthog-wizard new file mode 100644 index 000000000..e69de29bb diff --git a/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/SKILL.md b/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/SKILL.md new file mode 100644 index 000000000..c3eea858b --- /dev/null +++ b/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/SKILL.md @@ -0,0 +1,50 @@ +--- +name: integration-vue-3 +description: PostHog integration for Vue 3 applications +metadata: + author: PostHog + version: dev +--- + +# PostHog integration for Vue 3 + +This skill helps you add PostHog analytics to Vue 3 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` - Vue 3 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/vue-js.md` - Vue.js - docs +- `references/identify-users.md` - Identify users - docs + +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 + +- 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). + +## 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/vue/movies/.claude/skills/integration-vue-3/references/1-begin.md b/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/1-begin.md new file mode 100644 index 000000000..55f0a8326 --- /dev/null +++ b/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/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/vue/movies/.claude/skills/integration-vue-3/references/2-edit.md b/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/2-edit.md new file mode 100644 index 000000000..e5f7ffd16 --- /dev/null +++ b/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/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/vue/movies/.claude/skills/integration-vue-3/references/3-revise.md b/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/3-revise.md new file mode 100644 index 000000000..3b07f5069 --- /dev/null +++ b/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/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/vue/movies/.claude/skills/integration-vue-3/references/4-conclude.md b/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/4-conclude.md new file mode 100644 index 000000000..d876d4353 --- /dev/null +++ b/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/4-conclude.md @@ -0,0 +1,57 @@ +--- +title: PostHog Setup - Conclusion +description: Review and fix any errors in the PostHog integration implementation +--- + +Use the PostHog MCP to create a new dashboard named "Analytics basics (wizard)" based on the events created here. 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. Make sure to use the exact same event names as implemented in the code. Populate it with up to five insights, with special emphasis on things like conversion funnels, churn events, and other business critical insights. + +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. + +Upon completion, remove .posthog-events.json. + +## Status + +Status to report in this phase: + +- Configured dashboard: [insert PostHog dashboard URL] +- Created setup report: [insert full local file path] \ No newline at end of file diff --git a/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/EXAMPLE.md b/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/EXAMPLE.md new file mode 100644 index 000000000..d8697de13 --- /dev/null +++ b/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/EXAMPLE.md @@ -0,0 +1,910 @@ +# PostHog Vue 3 Example Project + +Repository: https://github.com/PostHog/context-mill +Path: example-apps/vue-3 + +--- + +## README.md + +# PostHog Vue 3 + Vite example + +This is a [Vue 3](https://vuejs.org/) + [Vite](https://vitejs.dev/) example demonstrating PostHog integration with product analytics, session replay, and error tracking. + +It uses the `posthog-js` browser SDK directly and shows how to: + +- Initialize PostHog in a Vue 3 SPA +- Identify users after login +- Track custom events from components +- Capture errors via Vue’s global `errorHandler` +- Reset PostHog state on logout + +## Features + +- **Product analytics**: Track login and burrito consideration events +- **Session replay**: Enabled via `posthog-js` configuration +- **Error tracking**: Global Vue error handler sends exceptions to PostHog +- **Simple auth flow**: Demo login + protected routes using Pinia + Vue Router + +## Getting started + +### 1. Install dependencies + +```bash +npm install +# or +pnpm install +``` + +### 2. Configure environment variables + +Create a `.env` file in the project root: + +```bash +VITE_POSTHOG_PROJECT_TOKEN=your_posthog_project_token +VITE_POSTHOG_HOST=https://us.i.posthog.com +``` + +Get your PostHog project token from your project settings in PostHog. + +### 3. Run the development server + +```bash +npm run dev +# or +pnpm dev +``` + +Open `http://localhost:5173` (or whatever Vite prints) in your browser. + +## Project structure + +```text +src/ + main.ts # Vue app entrypoint, PostHog init + global errorHandler + router/ + index.ts # Routes + simple auth guard + stores/ + auth.ts # Pinia auth store (login, logout, user state) + components/ + Header.vue # Navigation + logout, calls posthog.reset() + views/ + Home.vue # Login form, identifies user + captures 'user_logged_in' + Burrito.vue # Burrito consideration demo, captures 'burrito_considered' + Profile.vue # Profile + error tracking demo (if implemented) + App.vue # Root layout +``` + +## Key integration points + +### PostHog initialization (`src/main.ts`) + +`posthog-js` is initialized once when the app boots: + +```ts +import posthog from 'posthog-js' + +posthog.init(import.meta.env.VITE_POSTHOG_PROJECT_TOKEN || '', { + api_host: import.meta.env.VITE_POSTHOG_HOST || 'https://us.i.posthog.com', +}) + +app.config.errorHandler = (err) => { + posthog.captureException(err) +} +``` + +This ensures: + +- The SDK is configured with your project key and host +- The singleton instance is initialized only once and before the app mounts +- Any uncaught Vue errors are sent to PostHog + +### User identification (`src/views/Home.vue`) + +After a successful “login”, the app identifies the user and captures a login event: + +```ts +const success = await authStore.login(username.value, password.value) +if (success) { + posthog.identify(username.value) + posthog.capture('user_logged_in') +} +``` + +Identification happens **only on login**, all further requests will automatically use the same distinct ID. + +### Event tracking (`src/views/Burrito.vue`) + +The burrito page tracks a custom event when a user “considers” the burrito: + +```ts +posthog.capture('burrito_considered', { + total_considerations: updatedUser.burritoConsiderations, + username: updatedUser.username, +}) +``` + +This shows how to attach useful properties to events (e.g. counts, usernames). + +### Logout and session reset (`src/components/Header.vue`) + +On logout, both the local auth state and PostHog state are cleared: + +```ts +authStore.logout() +posthog.reset() +router.push({ name: 'home' }) +``` + +`posthog.reset()` clears the current distinct ID and session so the next login starts a fresh identity. + +## Scripts + +```bash +# Run dev server +npm run dev + +# Type-check, compile, and minify for production +npm run build + +# Lint +npm run lint +``` + +## Learn more + +- [PostHog documentation](https://posthog.com/docs) +- [posthog-js SDK](https://posthog.com/docs/libraries/js) +- [Vue 3 documentation](https://vuejs.org/guide/introduction.html) +- [Vite documentation](https://vitejs.dev/guide/) + +--- + +## .editorconfig + +``` +[*.{js,jsx,mjs,cjs,ts,tsx,mts,cts,vue,css,scss,sass,less,styl}] +charset = utf-8 +indent_size = 2 +indent_style = space +insert_final_newline = true +trim_trailing_whitespace = true +end_of_line = lf +max_line_length = 100 + +``` + +--- + +## .env.example + +```example +VITE_POSTHOG_PROJECT_TOKEN=your_posthog_project_token +VITE_POSTHOG_HOST=https://us.i.posthog.com + +``` + +--- + +## env.d.ts + +```ts +/// + +``` + +--- + +## index.html + +```html + + + + + + + Vite App + + +
+ + + + +``` + +--- + +## src/App.vue + +```vue + + + + + + +``` + +--- + +## src/components/Header.vue + +```vue + + + + + + +``` + +--- + +## src/main.ts + +```ts +import { createApp } from 'vue' +import { createPinia } from 'pinia' + +import App from './App.vue' +import router from './router' +import posthog from "posthog-js"; + +const app = createApp(App); + +posthog.init(import.meta.env.VITE_POSTHOG_PROJECT_TOKEN || '', { + api_host: import.meta.env.VITE_POSTHOG_HOST || 'https://us.i.posthog.com', + defaults: '2026-01-30', +}); + +app.use(createPinia()) +app.use(router) + +app.config.errorHandler = (err, instance, info) => { + // report error to tracking services + posthog.captureException(err) +} + +app.mount('#app') + +``` + +--- + +## src/router/index.ts + +```ts +import { createRouter, createWebHistory } from 'vue-router' +import { useAuthStore } from '@/stores/auth' +import Home from '@/views/Home.vue' +import Burrito from '@/views/Burrito.vue' +import Profile from '@/views/Profile.vue' + +const router = createRouter({ + history: createWebHistory(import.meta.env.BASE_URL), + routes: [ + { + path: '/', + name: 'home', + component: Home + }, + { + path: '/burrito', + name: 'burrito', + component: Burrito, + meta: { requiresAuth: true } + }, + { + path: '/profile', + name: 'profile', + component: Profile, + meta: { requiresAuth: true } + } + ] +}) + +router.beforeEach((to, from, next) => { + const authStore = useAuthStore() + + // Check if user exists and has a valid username + const isValidUser = authStore.user && authStore.user.username + + if (to.meta.requiresAuth && !isValidUser) { + // Clear invalid state + if (authStore.user && !authStore.user.username) { + authStore.logout() + } + next({ name: 'home' }) + } else { + next() + } +}) + +export default router + +``` + +--- + +## src/stores/auth.ts + +```ts +import { defineStore } from 'pinia' +import { ref, computed } from 'vue' + +interface User { + username: string + burritoConsiderations: number +} + +const users = new Map() + +export const useAuthStore = defineStore('auth', () => { + + const getInitialUser = (): User | null => { + if (typeof window === 'undefined') return null + + const storedUsername = localStorage.getItem('currentUser') + if (storedUsername) { + const existingUser = users.get(storedUsername) + if (existingUser && existingUser.username) { + return existingUser + } else { + // Clean up invalid state + localStorage.removeItem('currentUser') + } + } + return null + } + + const user = ref(getInitialUser()) + + const isAuthenticated = computed(() => user.value !== null) + + const login = async (username: string, password: string): Promise => { + // Client-side only fake auth - no server calls + if (!username || !password) { + return false + } + + let localUser = users.get(username) + if (!localUser) { + localUser = { + username, + burritoConsiderations: 0 + } + users.set(username, localUser) + } + + user.value = localUser + localStorage.setItem('currentUser', username) + + return true + } + + const logout = () => { + user.value = null + localStorage.removeItem('currentUser') + } + + const setUser = (newUser: User) => { + user.value = newUser + users.set(newUser.username, newUser) + } + + return { + user, + isAuthenticated, + login, + logout, + setUser + } +}) + +``` + +--- + +## src/views/Burrito.vue + +```vue + + + + + + +``` + +--- + +## src/views/Home.vue + +```vue + + + + + + +``` + +--- + +## src/views/Profile.vue + +```vue + + + + + + +``` + +--- + +## vite.config.ts + +```ts +import { fileURLToPath, URL } from 'node:url' + +import { defineConfig } from 'vite' +import vue from '@vitejs/plugin-vue' +import vueDevTools from 'vite-plugin-vue-devtools' + +// https://vite.dev/config/ +export default defineConfig({ + plugins: [ + vue(), + vueDevTools(), + ], + resolve: { + alias: { + '@': fileURLToPath(new URL('./src', import.meta.url)) + }, + }, +}) + +``` + +--- + diff --git a/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/identify-users.md b/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/identify-users.md new file mode 100644 index 000000000..1417e03a8 --- /dev/null +++ b/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/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/vue/movies/.claude/skills/integration-vue-3/references/vue-js.md b/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/vue-js.md new file mode 100644 index 000000000..e8e4412c9 --- /dev/null +++ b/apps/basic-integration/vue/movies/.claude/skills/integration-vue-3/references/vue-js.md @@ -0,0 +1,306 @@ +# Vue.js - Docs + +PostHog makes it easy to get data about usage of your [Vue.js](https://vuejs.org/) app. Integrating PostHog into your app enables analytics about user behavior, custom events capture, session replays, feature flags, and more. + +This guide walks you through integrating PostHog into your app for both Vue 2 and Vue 3. We'll use the [JavaScript Web SDK](/docs/libraries/js.md) for this. + +For integrating PostHog into a [Nuxt.js](https://nuxt.com/) app, see our [Nuxt guide](/docs/libraries/nuxt-js.md). + +## Prerequisites + +To follow this guide along, you need: + +1. A [PostHog account](https://app.posthog.com/signup) +2. A running Vue.js app + +## Setting up PostHog + +Start by installing `posthog-js` using your package manager: + +PostHog AI + +### npm + +```bash +npm install --save posthog-js +``` + +### Yarn + +```bash +yarn add posthog-js +``` + +### pnpm + +```bash +pnpm add posthog-js +``` + +### Bun + +```bash +bun add posthog-js +``` + +Next, depending on your Vue version, we recommend initializing PostHog using the composition API or as a plugin. + +## Vue 3: Composition API + +We use the Composition API as it provides better accessibility, maintainability, and type safety. + +PostHog initializes as a singleton, so you can initialize it in your `main.ts` file **before** you mount your app. This ensures PostHog is initialized before any other code runs. + +src/main.ts + +PostHog AI + +```typescript +// src/main.ts +import { createApp } from 'vue' +import { createPinia } from 'pinia' +import App from './App.vue' +import router from './router' +import posthog from "posthog-js"; +const app = createApp(App); +posthog.init(import.meta.env.VITE_POSTHOG_PROJECT_TOKEN || '', { + api_host: import.meta.env.VITE_POSTHOG_HOST || 'https://us.i.posthog.com', + defaults: '2026-05-30', +}); +app.use(createPinia()) +app.use(router) +app.config.errorHandler = (err, instance, info) => { + posthog.captureException(err) +} +app.mount('#app') +``` + +Then, you can access PostHog throughout your app just by importing it from `posthog-js`. + +TypeScript + +PostHog AI + +```typescript +// src/App.vue + +``` + +Once done, PostHog will begin [autocapturing](/docs/product-analytics/autocapture.md) events and pageviews (if enabled) and is ready to use throughout your app. + +## Vue 2: Plugins + +Start by creating a `plugins` folder and adding a `posthog.js` file to that folder. In `posthog.js`, initialize PostHog using the `install` method with your project token and host. You can find these in your [project settings](https://us.posthog.com/project/settings). + +JavaScript + +PostHog AI + +```javascript +// src/plugins/posthog.js +import posthog from 'posthog-js' +export default { + install(Vue) { + posthog.init('', { + api_host: 'https://us.i.posthog.com', + defaults: '2026-05-30' + }) + Vue.prototype.$posthog = posthog + } +} +``` + +Next, in `main.js`, import and use the plugin. + +JavaScript + +PostHog AI + +```javascript +// src/main.js +import Vue from 'vue' +import App from './App.vue' +import PosthogPlugin from './plugins/posthog' +Vue.config.productionTip = false +Vue.use(PosthogPlugin) +new Vue({ + render: h => h(App), +}).$mount('#app') +``` + +This makes PostHog available as `this.$posthog` in any Vue component. + +## 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. + +## Capturing custom events, using feature flags, and more + +Once you have PostHog initialized, there is a lot more you can do with it beyond autocapture, pageviews, and pageleaves. You can find the full details in our [JavaScript SDK docs](/docs/libraries/js/features.md), but we'll cover a few examples here. + +## Vue 3: Composition API + +To capture custom events, evaluate feature flags, and use any of the other PostHog features, you can use the `posthog` object returned from the `usePostHog` composable like this: + +JavaScript + +PostHog AI + +```javascript +// src/App.vue + + +``` + +### Feature flags with reactive updates + +When using feature flags on pages that users navigate to directly, the flags may not be loaded when the component first renders. To ensure your UI updates reactively when flags load, create a composable that returns a reactive ref: + +JavaScript + +PostHog AI + +```javascript +// src/composables/usePostHogFeatureFlag.ts +import { ref, type Ref } from 'vue' +import { usePostHog } from './usePostHog' +export function usePostHogFeatureFlag( + feature: string, +): Ref { + const { posthog } = usePostHog() + const flag = ref(posthog.getFeatureFlag(feature)) + posthog.onFeatureFlags(() => { + flag.value = posthog.getFeatureFlag(feature) + }) + return flag +} +``` + +Then use it in your components: + +JavaScript + +PostHog AI + +```javascript +// src/App.vue + + +``` + +This ensures your component will automatically update when feature flags load, even if the page is accessed directly. + +## Vue 2: Plugins + +To capture custom events, evaluate feature flags, and use any of the other PostHog features, you can use the `$posthog` object returned from the plugin like this: + +JavaScript + +PostHog AI + +```javascript +// src/components/AboutPage.vue + + +``` + +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). + +## Next steps + +For any technical questions for how to integrate specific PostHog features into Vue (such as analytics, feature flags, A/B testing, or surveys), have a look at our [JavaScript Web](/docs/libraries/js/features.md) SDK docs. + +Alternatively, the following tutorials can help you get started: + +- [How to set up analytics in Vue](/tutorials/vue-analytics.md) +- [How to set up feature flags in Vue](/tutorials/vue-feature-flags.md) +- [How to set up A/B tests in Vue](/tutorials/vue-ab-tests.md) +- [How to set up surveys in Vue](/tutorials/vue-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/vue/movies/.gitignore b/apps/basic-integration/vue/movies/.gitignore index cd68f1402..eb0c735c9 100644 --- a/apps/basic-integration/vue/movies/.gitignore +++ b/apps/basic-integration/vue/movies/.gitignore @@ -37,3 +37,4 @@ __screenshots__/ # Vite *.timestamp-*-*.mjs +.env diff --git a/apps/basic-integration/vue/movies/package-lock.json b/apps/basic-integration/vue/movies/package-lock.json index 23b2cfda4..24b46874c 100644 --- a/apps/basic-integration/vue/movies/package-lock.json +++ b/apps/basic-integration/vue/movies/package-lock.json @@ -12,6 +12,7 @@ "lru-cache": "^10.2.0", "ohash": "^1.1.3", "pinia": "^3.0.4", + "posthog-js": "^1.396.5", "vue": "^3.5.27", "vue-router": "^5.0.1" }, @@ -1059,6 +1060,21 @@ "dev": true, "license": "MIT" }, + "node_modules/@posthog/core": { + "version": "1.39.6", + "resolved": "https://registry.npmjs.org/@posthog/core/-/core-1.39.6.tgz", + "integrity": "sha512-o6ajIwN5zXoNP0D4H/QPmOyibNTUkSyOR6ya7AG5U2ywXx4awo72L2KnCoiZPQM5x/bXv6jPBdimH8M18Ax0aw==", + "license": "MIT", + "dependencies": { + "@posthog/types": "^1.392.0" + } + }, + "node_modules/@posthog/types": { + "version": "1.392.0", + "resolved": "https://registry.npmjs.org/@posthog/types/-/types-1.392.0.tgz", + "integrity": "sha512-nctNujXL3FC1v99FktaTMSugSD9ZOZekEpahUSafkU2TSvW+XGKNkQZbokuJtiWvPBK208dwMJva8UfBkChqpw==", + "license": "MIT" + }, "node_modules/@rolldown/pluginutils": { "version": "1.0.0-rc.2", "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.0-rc.2.tgz", @@ -1446,6 +1462,13 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/trusted-types": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz", + "integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==", + "license": "MIT", + "optional": true + }, "node_modules/@unocss/astro": { "version": "0.65.4", "resolved": "https://registry.npmjs.org/@unocss/astro/-/astro-0.65.4.tgz", @@ -2483,6 +2506,17 @@ "url": "https://github.com/sponsors/mesqueeb" } }, + "node_modules/core-js": { + "version": "3.49.0", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.49.0.tgz", + "integrity": "sha512-es1U2+YTtzpwkxVLwAFdSpaIMyQaq0PBgm3YD1W3Qpsn1NAmO3KSgZfu+oGSWVu6NvLHoHCV/aYcsE5wiB7ALg==", + "hasInstallScript": true, + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, "node_modules/css-tree": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/css-tree/-/css-tree-3.1.0.tgz", @@ -2585,6 +2619,15 @@ "dev": true, "license": "MIT" }, + "node_modules/dompurify": { + "version": "3.4.11", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.11.tgz", + "integrity": "sha512-zhlUV12GsaRzMsf9q5M254YhA4+VuF0fG+QFqu6aYpoGlKtz+w8//jBcGVYBgQkR5GHjUomejY84AV+/uPbWdw==", + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, "node_modules/duplexer": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/duplexer/-/duplexer-0.1.2.tgz", @@ -2702,6 +2745,12 @@ } } }, + "node_modules/fflate": { + "version": "0.4.8", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.4.8.tgz", + "integrity": "sha512-FJqqoDBR00Mdj9ppamLa/Y7vxm+PRmNWA67N846RvsoYVMKB4q3y/de5PA7gUmRMYK/8CMz2GDZQmCRN1wBcWA==", + "license": "MIT" + }, "node_modules/fill-range": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", @@ -3307,6 +3356,32 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/posthog-js": { + "version": "1.396.5", + "resolved": "https://registry.npmjs.org/posthog-js/-/posthog-js-1.396.5.tgz", + "integrity": "sha512-huW/8R151I08i/tkOaAv3Q/yWVqzhqPj3SxyhpgNLB/xysaNeV1ibp6DHzbRWV5D7FRM48Zg6Icxsm4q0irEtg==", + "license": "(Apache-2.0 AND MIT)", + "dependencies": { + "@posthog/core": "^1.39.5", + "@posthog/types": "^1.392.0", + "core-js": "^3.38.1", + "dompurify": "^3.3.2", + "fflate": "^0.4.8", + "preact": "^10.29.2", + "query-selector-shadow-dom": "^1.0.1", + "web-vitals": "^5.3.0" + } + }, + "node_modules/preact": { + "version": "10.29.3", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.29.3.tgz", + "integrity": "sha512-D9NL1GAnJZhc3RndVs4gDdxEeU9TcHgywMrhhOsnpdlvFjdbx0gAsLUnH6JEhlJH5giL7Tx5biWPUSEXE/HPzw==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } + }, "node_modules/quansync": { "version": "0.2.11", "resolved": "https://registry.npmjs.org/quansync/-/quansync-0.2.11.tgz", @@ -3323,6 +3398,12 @@ ], "license": "MIT" }, + "node_modules/query-selector-shadow-dom": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/query-selector-shadow-dom/-/query-selector-shadow-dom-1.0.1.tgz", + "integrity": "sha512-lT5yCqEBgfoMYpf3F2xQRK7zEr1rhIIZuceDK6+xRkJQ4NMbHTwXqk4NkwDwQMNqXgG9r9fyHnzwNVs6zV5KRw==", + "license": "MIT" + }, "node_modules/readdirp": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", @@ -4570,6 +4651,12 @@ "typescript": ">=5.0.0" } }, + "node_modules/web-vitals": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-5.3.0.tgz", + "integrity": "sha512-q6LWsLatGYZp5VGBIOvbTj6JBV2nOmC8KvWztXBmwJcfFAzhwKwbOxhUH306XY3CcaZDUlSmSuNPBsCn0bFu+g==", + "license": "Apache-2.0" + }, "node_modules/webpack-virtual-modules": { "version": "0.6.2", "resolved": "https://registry.npmjs.org/webpack-virtual-modules/-/webpack-virtual-modules-0.6.2.tgz", diff --git a/apps/basic-integration/vue/movies/package.json b/apps/basic-integration/vue/movies/package.json index 49e32caa3..d58d147b5 100644 --- a/apps/basic-integration/vue/movies/package.json +++ b/apps/basic-integration/vue/movies/package.json @@ -13,6 +13,7 @@ "lru-cache": "^10.2.0", "ohash": "^1.1.3", "pinia": "^3.0.4", + "posthog-js": "^1.396.5", "vue": "^3.5.27", "vue-router": "^5.0.1" }, diff --git a/apps/basic-integration/vue/movies/posthog-setup-report.md b/apps/basic-integration/vue/movies/posthog-setup-report.md new file mode 100644 index 000000000..5f8388832 --- /dev/null +++ b/apps/basic-integration/vue/movies/posthog-setup-report.md @@ -0,0 +1,38 @@ + +# PostHog post-wizard report + +The wizard has completed a deep integration of PostHog into the Vue Movies app. PostHog is initialised in `src/main.js` using environment variables, with a global Vue error handler attached to forward uncaught exceptions. User identity is established on login via `posthog.identify()` and cleared on logout via `posthog.reset()`. Six custom events are now tracked across four components covering the full user journey from authentication through content discovery and engagement. + +| Event | Description | File | +|---|---|---| +| `user_logged_in` | User successfully logs in to the app. | `src/composables/useAuth.ts` | +| `user_logged_out` | User logs out and their session is cleared. | `src/composables/useAuth.ts` | +| `search_performed` | User submits a search query for movies or TV shows. | `src/views/SearchView.vue` | +| `media_detail_viewed` | User views the detail page for a movie or TV show, the top of the engagement funnel. | `src/views/MediaDetailView.vue` | +| `trailer_played` | User clicks to play the trailer for a movie or TV show. | `src/views/MediaDetailView.vue` | +| `media_card_clicked` | User clicks on a media card in a carousel or search results list. | `src/components/media/MediaCard.vue` | + +## 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: + +- [Analytics basics (wizard) — Dashboard](https://us.posthog.com/project/483112/dashboard/1793574) +- [Daily Logins](https://us.posthog.com/project/483112/insights/9yAZWZlU) +- [Searches Performed](https://us.posthog.com/project/483112/insights/NQSSpLbk) +- [Media Detail Views](https://us.posthog.com/project/483112/insights/P8o8xaJP) +- [Media Card Clicks](https://us.posthog.com/project/483112/insights/Zpp3CGNB) +- [Engagement Funnel: Login → Media Viewed → Trailer Played](https://us.posthog.com/project/483112/insights/KbfGyY0a) + +## Verify before merging + +- [ ] 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. +- [ ] Run the test suite — call sites that were rewritten or instrumented may need updated mocks or fixtures. +- [ ] Add `VITE_POSTHOG_PROJECT_TOKEN` and `VITE_POSTHOG_HOST` to `.env.example` and any monorepo/bootstrap scripts so collaborators know what to set. +- [ ] Wire source-map upload (`posthog-cli sourcemap` or your bundler's upload step) into CI so production stack traces de-minify. +- [ ] Confirm the returning-visitor path also calls `identify` — a handler that only identifies on fresh login can leave returning sessions on anonymous distinct IDs. + +### 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. + + diff --git a/apps/basic-integration/vue/movies/src/components/media/MediaCard.vue b/apps/basic-integration/vue/movies/src/components/media/MediaCard.vue index 1da473a92..b3da9a3d6 100644 --- a/apps/basic-integration/vue/movies/src/components/media/MediaCard.vue +++ b/apps/basic-integration/vue/movies/src/components/media/MediaCard.vue @@ -1,18 +1,29 @@