From 297579fe4fa348b98ba9ede36c354945b55efb14 Mon Sep 17 00:00:00 2001 From: "wizard-ci-bot[bot]" <254716194+wizard-ci-bot[bot]@users.noreply.github.com> Date: Mon, 6 Jul 2026 22:05:59 +0000 Subject: [PATCH] wizard-ci: javascript-web/saas-dashboard --- .../.posthog-wizard | 0 .../integration-javascript_web/SKILL.md | 63 + .../references/1-begin.md | 56 + .../references/2-edit.md | 36 + .../references/3-revise.md | 22 + .../references/4-conclude.md | 57 + .../references/identify-users.md | 272 ++ .../references/js.md | 367 +++ .../references/posthog-js.md | 2290 +++++++++++++++++ .../saas-dashboard/package-lock.json | 90 +- .../saas-dashboard/package.json | 3 +- .../saas-dashboard/posthog-setup-report.md | 41 + .../saas-dashboard/src/components/shell.js | 3 + .../javascript-web/saas-dashboard/src/main.js | 14 + .../saas-dashboard/src/pages/login.js | 6 +- .../src/pages/project-detail.js | 20 +- .../saas-dashboard/src/pages/projects.js | 4 + .../saas-dashboard/src/pages/settings.js | 5 + 18 files changed, 3342 insertions(+), 7 deletions(-) create mode 100644 apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/.posthog-wizard create mode 100644 apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/SKILL.md create mode 100644 apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/1-begin.md create mode 100644 apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/2-edit.md create mode 100644 apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/3-revise.md create mode 100644 apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/4-conclude.md create mode 100644 apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/identify-users.md create mode 100644 apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/js.md create mode 100644 apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/posthog-js.md create mode 100644 apps/basic-integration/javascript-web/saas-dashboard/posthog-setup-report.md diff --git a/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/.posthog-wizard b/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/.posthog-wizard new file mode 100644 index 000000000..e69de29bb diff --git a/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/SKILL.md b/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/SKILL.md new file mode 100644 index 000000000..ecec96a69 --- /dev/null +++ b/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/SKILL.md @@ -0,0 +1,63 @@ +--- +name: integration-javascript_web +description: >- + PostHog integration for client-side web JavaScript applications using + posthog-js +metadata: + author: PostHog + version: dev +--- + +# PostHog integration for JavaScript Web + +This skill helps you add PostHog analytics to JavaScript Web 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/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/js.md` - JavaScript web - docs +- `references/posthog-js.md` - PostHog JavaScript web SDK +- `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). +- 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). Do NOT disable autocapture unless the user explicitly requests it. +- 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 +- Remember that source code is available in the node_modules directory +- Check package.json for type checking or build scripts to validate changes + +## 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/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/1-begin.md b/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/1-begin.md new file mode 100644 index 000000000..55f0a8326 --- /dev/null +++ b/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/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/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/2-edit.md b/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/2-edit.md new file mode 100644 index 000000000..e5f7ffd16 --- /dev/null +++ b/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/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/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/3-revise.md b/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/3-revise.md new file mode 100644 index 000000000..3b07f5069 --- /dev/null +++ b/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/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/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/4-conclude.md b/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/4-conclude.md new file mode 100644 index 000000000..d876d4353 --- /dev/null +++ b/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/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/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/identify-users.md b/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/identify-users.md new file mode 100644 index 000000000..1417e03a8 --- /dev/null +++ b/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/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/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/js.md b/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/js.md new file mode 100644 index 000000000..a7fb42ab0 --- /dev/null +++ b/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/js.md @@ -0,0 +1,367 @@ +# JavaScript web - Docs + +> **Note:** This doc refers to our [posthog-js](https://github.com/PostHog/posthog-js) library for use on the browser. For server-side JavaScript, see our [Node SDK](/docs/libraries/node.md). + +## Installation + +### Option 1: Add the JavaScript snippet to your HTML Recommended + +HTML + +PostHog AI + +```html + +``` + +Keeping the SDK version up to date + +Be careful to avoid things which can cause the SDK version to be cached and fail to update. See: [Ways SDK versions fall behind](/docs/health-checks/keeping-sdks-current.md#ways-sdk-versions-fall-behind) + +Using TypeScript with the script tag? + +If you're using TypeScript and want type safety for `window.posthog`, install the `@posthog/types` package: + +Terminal + +PostHog AI + +```bash +npm install @posthog/types +``` + +Then create a type declaration file: + +typescript + +PostHog AI + +```typescript +// posthog.d.ts +import type { PostHog } from '@posthog/types' +declare global { + interface Window { + posthog?: PostHog + } +} +export {} +``` + +See the [TypeScript types documentation](/docs/libraries/js/types.md) for more details. + +### Option 2: Install via 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 +``` + +And then include it with your project token and host (which you can find in [your project settings](https://us.posthog.com/settings/project)): + +Web + +PostHog AI + +```javascript +import posthog from 'posthog-js' +posthog.init('', { + api_host: 'https://us.i.posthog.com', + defaults: '2026-05-30' +}) +``` + +See our framework specific docs for [Next.js](/docs/libraries/next-js.md), [React](/docs/libraries/react.md), [Vue](/docs/libraries/vue-js.md), [Angular](/docs/libraries/angular.md), [Astro](/docs/libraries/astro.md), [Remix](/docs/libraries/remix.md), and [Svelte](/docs/libraries/svelte.md) for more installation details. + +Update early, update often + +We ship weirdly fast, especially for our JavaScript web SDK. If you choose the npm package instead of the HTML snippet, be sure to update it frequently: + +To actually *update* the package, you need to update the version constraint in your `package.json` file and then reinstall, or run `update` instead of `install`: + +PostHog AI + +### npm + +```bash +npm update posthog-js +``` + +### pnpm + +```bash +pnpm update posthog-js +``` + +### Yarn + +```bash +yarn upgrade posthog-js +``` + +Bundle all required extensions (advanced) + +By default, the JavaScript Web library only loads the core functionality. It lazy-loads extensions such as surveys or the session replay 'recorder' when needed. + +This can cause issues if: + +- You have a Content Security Policy (CSP) that blocks inline scripts. +- You want to optimize your bundle at build time to ensure all dependencies are ready immediately. +- Your app is running in environments like the Chrome Extension store or [Electron](/tutorials/electron-analytics.md) that reject or block remote code loading. + +To solve these issues, we have multiple import options available below. + +**Note:** With any of the `no-external` options, the toolbar will be unavailable as this is only possible as a runtime dependency loaded directly from `us.posthog.com`. + +Web + +PostHog AI + +```javascript +// No external code loading possible (this disables all extensions such as Replay, Surveys, Exceptions etc.) +import posthog from 'posthog-js/dist/module.no-external' +// No external code loading possible but all external dependencies pre-bundled +import posthog from 'posthog-js/dist/module.full.no-external' +// All external dependencies pre-bundled and with the ability to load external scripts (primarily useful is you use JS snippets) +import posthog from 'posthog-js/dist/module.full' +// Finally you can also import specific extra dependencies +import "posthog-js/dist/posthog-recorder" +import "posthog-js/dist/surveys" +import "posthog-js/dist/exception-autocapture" +import "posthog-js/dist/tracing-headers" +import "posthog-js/dist/web-vitals" +import posthog from 'posthog-js/dist/module.no-external' +// All other posthog commands are the same as usual +posthog.init('', { api_host: 'https://us.i.posthog.com', defaults: '2026-05-30' }) +``` + +**Note:** You should ensure if using this option that you always import `posthog-js` from the same module, otherwise multiple bundles could get included. At this time `@posthog/react` does not work with any module import other than the default. + +Tree shaking with the slim bundle (advanced) + +If you only need a subset of PostHog features, you can use the **slim bundle** to reduce your bundle size. It gives you the core functionality (event capture, identify, group analytics) and lets you explicitly opt in to additional features via extension bundles. This is currently experimental, but offers the biggest reduction in bundle size. + +Web + +PostHog AI + +```javascript +import posthog from 'posthog-js/dist/module.slim' +import { + SessionReplayExtensions, + AnalyticsExtensions, +} from 'posthog-js/dist/extension-bundles' +posthog.init('', { + api_host: 'https://us.i.posthog.com', + defaults: '2026-05-30', + __extensionClasses: { + ...SessionReplayExtensions, + ...AnalyticsExtensions, + } +}) +``` + +**Note:** Always import `posthog-js` from the same module path (`posthog-js/dist/module.slim`) throughout your app, otherwise multiple bundles could get included. + +#### Available extension bundles + +| Bundle | What's included | +| --- | --- | +| FeatureFlagsExtensions | [Feature Flags](/docs/feature-flags.md) | +| SessionReplayExtensions | [Session Replay](/docs/session-replay.md) | +| AnalyticsExtensions | [Autocapture](/docs/product-analytics/autocapture.md), pageview tracking, [heatmaps](/docs/toolbar/heatmaps.md), dead click detection, [web vitals](/docs/web-analytics/web-vitals.md) | +| ErrorTrackingExtensions | [Error Tracking](/docs/error-tracking.md) | +| SurveysExtensions | [Surveys](/docs/surveys.md) | +| ExperimentsExtensions | [Experiments](/docs/experiments.md) | +| SiteAppsExtensions | [JS snippets](/docs/js-snippets.md) | +| TracingExtensions | Distributed tracing header injection | +| ToolbarExtensions | [Toolbar](/docs/toolbar.md) | +| LogsExtensions | [Log capture](/docs/logs.md) | +| ConversationsExtensions | Conversations | +| AllExtensions | Everything (equivalent to the default posthog-js bundle) | + +**Note:** Each extension bundle includes its own dependencies. You don't need to worry about adding them separately. + +Don't want to send test data while developing? + +If you don't want to send test data while you're developing, you can do the following: + +Web + +PostHog AI + +```javascript +if (!window.location.host.includes('127.0.0.1') && !window.location.host.includes('localhost')) { + posthog.init('', { api_host: 'https://us.i.posthog.com', defaults: '2026-05-30' }) +} +``` + +What is the \`defaults\` option? + +The `defaults` is a date, such as `2026-05-30`, for a configuration snapshot used as defaults to initialize PostHog. This default is overridden when you explicitly set a value for any of the options. + +## 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. + +Once you've installed PostHog, see our [features doc](/docs/libraries/js/features.md) for more information about what you can do with it. You can also install the [PostHog VS Code extension](/docs/vscode-extension.md) to see live analytics, flag status, and session replay links inline in your code. + +### Track across marketing website & app + +We recommend putting PostHog both on your homepage and your application if applicable. That means you'll be able to follow a user from the moment they come onto your website, all the way through signup and actually using your product. + +> PostHog automatically sets a cross-domain cookie, so if your website is `yourapp.com` and your app is on `app.yourapp.com` users will be followed when they go from one to the other. See our tutorial on [cross-website tracking](/tutorials/cross-domain-tracking.md) if you need to track users across different domains. + +### Replay triggers + +You can configure "replay triggers" in your [project settings](https://app.posthog.com/project/settings). You can configure triggers to enable or pause session recording when the user visit a page that matches the URL(s) you configure. + +You are also able to setup "event triggers". Session recording will be started immediately before PostHog queues any of these events to be sent to the backend. + +## Opt out of data capture + +You can completely opt-out users from data capture. To do this, there are two options: + +1. Opt users out by default by setting `opt_out_capturing_by_default` to `true` in your [PostHog config](/docs/libraries/js/config.md). + +Web + +PostHog AI + +```javascript +posthog.init('', { + opt_out_capturing_by_default: true, +}); +``` + +2. Opt users out on a per-person basis by calling `posthog.opt_out_capturing()`. + +Similarly, you can opt users in: + +Web + +PostHog AI + +```javascript +posthog.opt_in_capturing() +``` + +To check if a user is opted out: + +Web + +PostHog AI + +```javascript +posthog.has_opted_out_capturing() +``` + +## Running more than one instance of PostHog at the same time + +While not a first-class citizen, PostHog allows you to run more than one instance of PostHog at the same time if you, for example, want to track different events in different posthog instances/projects. + +`posthog.init` accepts a third parameter that can be used to create named instances. + +TypeScript + +PostHog AI + +```typescript +posthog.init('', {}, 'project1') +posthog.init('', {}, 'project2') +``` + +You can then call these different instances by accessing it on the global `posthog` object + +TypeScript + +PostHog AI + +```typescript +posthog.project1.capture('some_event') +posthog.project2.capture('other_event') +``` + +> **Note:** You'll probably want to disable autocapture (and some other events) to avoid them from being sent to both instances. Check all of our [config options](/docs/libraries/js/config.md) to better understand that. + +## Development + +For instructions on how to run `posthog-js` locally and setup your development environment, please checkout the README on the [posthog-js](https://github.com/PostHog/posthog-js#README) repository. + +### Community questions + +Ask a question + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/posthog-js.md b/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/posthog-js.md new file mode 100644 index 000000000..34d271a82 --- /dev/null +++ b/apps/basic-integration/javascript-web/saas-dashboard/.claude/skills/integration-javascript_web/references/posthog-js.md @@ -0,0 +1,2290 @@ +# PostHog JavaScript Web SDK + +**SDK Version:** + +Posthog-js allows you to automatically capture usage and send events to PostHog. + +## Categories + +- Initialization +- Identification +- Capture +- Error tracking +- Surveys +- Logs +- LLM analytics +- Privacy +- Session replay +- Feature flags +- Toolbar +- Lifecycle + +## PostHog + +This is the SDK reference for the PostHog JavaScript Web SDK. You can learn more about example usage in the [JavaScript Web SDK documentation](/docs/libraries/js). You can also follow [framework specific guides](/docs/frameworks) to integrate PostHog into your project. +This SDK is designed for browser environments. Use the PostHog [Node.js SDK](/docs/libraries/node) for server-side usage. + +### Other methods + +#### PostHog() + +**Release Tag:** public + +Creates an uninitialized PostHog instance. + +**Notes:** + +Most browser applications should use the default exported singleton and call `posthog.init()`. Construct a new instance only when you need to manage a separate SDK instance manually. + +### Returns + +- `any` + +### Examples + +```ts +const instance = new PostHog() +instance.init('', { api_host: 'https://us.i.posthog.com' }) +``` + +--- + +#### clearIdentity() + +**Release Tag:** public + +Clear HMAC-based identity verification, reverting to anonymous mode. + +### Returns + +- `void` + +### Examples + +```ts +posthog.clearIdentity() +``` + +--- + +#### get_explicit_consent_status() + +**Release Tag:** public + +Returns the explicit consent status of the user. + +**Notes:** + +This can be used to check if the user has explicitly opted in or out of data capturing, or neither. This does not take the default config options into account, only whether the user has made an explicit choice, so this can be used to determine whether to show an initial cookie banner or not. + +### Returns + +**Union of:** +- `'granted'` +- `'denied'` +- `'pending'` + +### Examples + +```ts +const consentStatus = posthog.get_explicit_consent_status() +if (consentStatus === "granted") { + // user has explicitly opted in +} else if (consentStatus === "denied") { + // user has explicitly opted out +} else if (consentStatus === "pending"){ + // user has not made a choice, show consent banner +} +``` + +--- + +#### get_session_id() + +**Release Tag:** public + +Returns the current session_id. + +**Notes:** + +This should only be used for informative purposes. Any actual internal use case for the session_id should be handled by the sessionManager. + +### Returns + +- `string` + +### Examples + +```ts +// Generated example for get_session_id +posthog.get_session_id(); +``` + +--- + +#### getAllFeatureFlags() + +**Release Tag:** public + +Returns all currently cached feature flags as `FeatureFlagResult`s. This is a synchronous read of the flags from the last load (no network request); call `reloadFeatureFlags()` first to refresh. Unlike `getFeatureFlag()`, it does not send a `$feature_flag_called` event. + +### Returns + +- `FeatureFlagResult[]` + +### Examples + +```ts +// Generated example for getAllFeatureFlags +posthog.getAllFeatureFlags(); +``` + +--- + +#### push() + +**Release Tag:** public + +push() keeps the standard async-array-push behavior around after the lib is loaded. This is only useful for external integrations that do not wish to rely on our convenience methods (created in the snippet). + +### Parameters + +- **`item`** (`SnippetArrayItem`) - A `[function_name, ...args]` array to be executed. + +### Returns + +- `void` + +### Examples + +```ts +posthog.push(['register', { a: 'b' }]); +``` + +--- + +#### setIdentity() + +**Release Tag:** public + +Set HMAC-based identity verification. + +**Notes:** + +When set, products like conversations use server-verified identity (distinct_id + HMAC hash) instead of anonymous session identifiers. The hash should be computed server-side as HMAC-SHA256 of the distinct_id using the project's API secret. + +### Parameters + +- **`distinctId`** (`string`) - The verified user distinct_id +- **`hash`** (`string`) - HMAC-SHA256 of distinctId using the project API secret + +### Returns + +- `void` + +### Examples + +```ts +posthog.setIdentity('user_123', 'a1b2c3d4e5f6...') +``` + +--- + +### Error tracking methods + +#### addExceptionStep() + +**Release Tag:** public + +Add a breadcrumb-like step that will be attached to the next captured exception. + +### Parameters + +- **`message`** (`string`) - The step message. +- **`properties?`** (`Properties`) - Additional context for this step. + +### Returns + +- `void` + +### Examples + +```ts +posthog.addExceptionStep('Checkout button clicked', { + checkout_id: 'ch_123', +}) +``` + +--- + +#### captureException() + +**Release Tag:** public + +Capture a caught exception manually + +### Parameters + +- **`error`** (`unknown`) - The error or exception-like value to capture. +- **`additionalProperties?`** (`Properties`) - Any additional properties to add to the error event. + +### Returns + +**Union of:** +- `CaptureResult` +- `undefined` + +### Examples + +#### Capture a caught exception + +```ts +// Capture a caught exception +try { + // something that might throw +} catch (error) { + posthog.captureException(error) +} +``` + +#### With additional properties + +```ts +// With additional properties +posthog.captureException(error, { + customProperty: 'value', + anotherProperty: ['I', 'can be a list'], + ... +}) +``` + +--- + +#### startExceptionAutocapture() + +**Release Tag:** public + +turns exception autocapture on, and updates the config option `capture_exceptions` to the provided config (or `true`) + +### Parameters + +- **`config?`** (`ExceptionAutoCaptureConfig`) - optional configuration option to control the exception autocapture behavior + +### Returns + +- `void` + +### Examples + +#### Start with default exception autocapture rules. No-op if already enabled + +```ts +// Start with default exception autocapture rules. No-op if already enabled +posthog.startExceptionAutocapture() +``` + +#### Start and override controls + +```ts +// Start and override controls +posthog.startExceptionAutocapture({ + // you don't have to send all of these (unincluded values will use the default) + capture_unhandled_errors: true || false, + capture_unhandled_rejections: true || false, + capture_console_errors: true || false +}) +``` + +--- + +#### stopExceptionAutocapture() + +**Release Tag:** public + +turns exception autocapture off by updating the config option `capture_exceptions` to `false` + +### Returns + +- `void` + +### Examples + +```ts +// Stop capturing exceptions automatically +posthog.stopExceptionAutocapture() +``` + +--- + +### Identification methods + +#### alias() + +**Release Tag:** public + +Creates an alias linking two distinct user identifiers. Learn more about [identifying users](/docs/product-analytics/identify) + +**Notes:** + +PostHog will use this to link two distinct_ids going forward (not retroactively). Call this when a user signs up to connect their anonymous session with their account. + +### Parameters + +- **`alias`** (`string`) - A unique identifier that you want to use for this user in the future. +- **`original?`** (`string`) - The current identifier being used for this user. + +### Returns + +**Union of:** +- `CaptureResult` +- `void` +- `number` + +### Examples + +#### link anonymous user to account on signup + +```ts +// link anonymous user to account on signup +posthog.alias('user_12345') +``` + +#### explicit alias with original ID + +```ts +// explicit alias with original ID +posthog.alias('user_12345', 'anonymous_abc123') +``` + +--- + +#### createPersonProfile() + +**Release Tag:** public + +Creates a person profile for the current user, if they don't already have one and config.person_profiles is set to 'identified_only'. Produces a warning and does not create a profile if config.person_profiles is set to 'never'. Learn more about [person profiles](/docs/product-analytics/identify) + +### Returns + +- `void` + +### Examples + +```ts +posthog.createPersonProfile() +``` + +--- + +#### get_distinct_id() + +**Release Tag:** public + +Returns the current distinct ID for the user. + +**Notes:** + +This is either the auto-generated ID or the ID set via `identify()`. The distinct ID is used to associate events with users in PostHog. + +### Returns + +- `string` + +### Examples + +#### get the current user ID + +```ts +// get the current user ID +const userId = posthog.get_distinct_id() +console.log('Current user:', userId) +``` + +#### use in loaded callback + +```ts +// use in loaded callback +posthog.init('token', { + loaded: (posthog) => { + const id = posthog.get_distinct_id() + // use the ID + } +}) +``` + +--- + +#### get_property() + +**Release Tag:** public + +Returns the value of a super property. Returns undefined if the property doesn't exist. + +**Notes:** + +get_property() can only be called after the PostHog library has finished loading. init() has a loaded function available to handle this automatically. + +### Parameters + +- **`property_name`** (`string`) - The name of the super property you want to retrieve + +### Returns + +**Union of:** +- `Property` +- `undefined` + +### Examples + +```ts +// grab value for '$user_id' after the posthog library has loaded +posthog.init('', { + loaded: function(posthog) { + user_id = posthog.get_property('$user_id'); + } +}); +``` + +--- + +#### getGroups() + +**Release Tag:** public + +Returns the current groups. + +### Returns + +- `Record` + +### Examples + +```ts +// Generated example for getGroups +posthog.getGroups(); +``` + +--- + +#### getSessionProperty() + +**Release Tag:** public + +Returns the value of the session super property named property_name. If no such property is set, getSessionProperty() will return the undefined value. + +**Notes:** + +This is based on browser-level `sessionStorage`, NOT the PostHog session. getSessionProperty() can only be called after the PostHog library has finished loading. init() has a loaded function available to handle this automatically. + +### Parameters + +- **`property_name`** (`string`) - The name of the session super property you want to retrieve + +### Returns + +**Union of:** +- `Property` +- `undefined` + +### Examples + +```ts +// grab value for 'user_id' after the posthog library has loaded +posthog.init('YOUR PROJECT TOKEN', { + loaded: function(posthog) { + user_id = posthog.getSessionProperty('user_id'); + } +}); +``` + +--- + +#### group() + +**Release Tag:** public + +Associates the user with a group for group-based analytics. Learn more about [groups](/docs/product-analytics/group-analytics) + +**Notes:** + +Groups allow you to analyze users collectively (e.g., by organization, team, or account). This sets the group association for all subsequent events and reloads feature flags. + +### Parameters + +- **`groupType`** (`string`) - Group type (example: 'organization') +- **`groupKey`** (`string`) - Group key (example: 'org::5') +- **`groupPropertiesToSet?`** (`Properties`) - Optional properties to set for group + +### Returns + +- `void` + +### Examples + +#### associate user with an organization + +```ts +// associate user with an organization +posthog.group('organization', 'org_12345', { + name: 'Acme Corp', + plan: 'enterprise' +}) +``` + +#### associate with multiple group types + +```ts +// associate with multiple group types +posthog.group('organization', 'org_12345') +posthog.group('team', 'team_67890') +``` + +--- + +#### identify() + +**Release Tag:** public + +Associates a user with a unique identifier instead of an auto-generated ID. Learn more about [identifying users](/docs/product-analytics/identify) + +**Notes:** + +By default, PostHog assigns each user a randomly generated `distinct_id`. Use this method to replace that ID with your own unique identifier (like a user ID from your database). + +### Parameters + +- **`new_distinct_id?`** (`string`) - A string that uniquely identifies a user. If not provided, the distinct_id currently in the persistent store (cookie or localStorage) will be used. +- **`userPropertiesToSet?`** (`Properties`) - Optional: An associative array of properties to store about the user. Note: For feature flag evaluations, if the same key is present in the userPropertiesToSetOnce, it will be overwritten by the value in userPropertiesToSet. +- **`userPropertiesToSetOnce?`** (`Properties`) - Optional: An associative array of properties to store about the user. If property is previously set, this does not override that value. + +### Returns + +- `void` + +### Examples + +#### basic identification + +```ts +// basic identification +posthog.identify('user_12345') +``` + +#### identify with user properties + +```ts +// identify with user properties +posthog.identify('user_12345', { + email: 'user@example.com', + plan: 'premium' +}) +``` + +#### identify with set and set_once properties + +```ts +// identify with set and set_once properties +posthog.identify('user_12345', + { last_login: new Date() }, // updates every time + { signup_date: new Date() } // sets only once +) +``` + +--- + +#### onSessionId() + +**Release Tag:** public + +Register an event listener that runs whenever the session id or window id change. If there is already a session id, the listener is called immediately in addition to being called on future changes. +Can be used, for example, to sync the PostHog session id with a backend session. + +### Parameters + +- **`callback`** (`SessionIdChangedCallback`) - The callback function will be called once a session id is present or when it or the window id are updated. + +### Returns + +- `() => void` + +### Examples + +```ts +posthog.onSessionId(function(sessionId, windowId) { // do something }) +``` + +--- + +#### reset() + +**Release Tag:** public + +Resets all user data and starts a fresh session. +⚠️ **Warning**: Only call this when a user logs out. Calling at the wrong time can cause split sessions. +This clears: - Session ID and super properties - User identification (sets new random distinct_id) - Cached data and consent settings + +### Parameters + +- **`reset_device_id?`** (`boolean`) - Whether to generate a new device ID as well as a new distinct ID. + +### Returns + +- `void` + +### Examples + +#### reset on user logout + +```ts +// reset on user logout +function logout() { + posthog.reset() + // redirect to login page +} +``` + +#### reset and generate new device ID + +```ts +// reset and generate new device ID +posthog.reset(true) // also resets device_id +``` + +--- + +#### resetGroups() + +**Release Tag:** public + +Resets only the group properties of the user currently logged in. Learn more about [groups](/docs/product-analytics/group-analytics) + +### Returns + +- `void` + +### Examples + +```ts +posthog.resetGroups() +``` + +--- + +#### setInternalOrTestUser() + +**Release Tag:** public + +Marks the current user as a test user by setting the `$internal_or_test_user` person property to `true`. This also enables person processing for the current user. +This is useful for using in a cohort your internal/test filters for your posthog org. + +### Returns + +- `void` + +### Examples + +```ts +// Manually mark as test user +posthog.setInternalOrTestUser() + +// Or use internal_or_test_user_hostname config for automatic detection +posthog.init('token', { internal_or_test_user_hostname: 'localhost' }) +``` + +--- + +#### setPersonProperties() + +**Release Tag:** public + +Sets properties on the person profile associated with the current `distinct_id`. Learn more about [identifying users](/docs/product-analytics/identify) + +**Notes:** + +Updates user properties that are stored with the person profile in PostHog. If `person_profiles` is set to `identified_only` and no profile exists, this will create one. + +### Parameters + +- **`userPropertiesToSet?`** (`Properties`) - Optional: An associative array of properties to store about the user. Note: For feature flag evaluations, if the same key is present in the userPropertiesToSetOnce, it will be overwritten by the value in userPropertiesToSet. +- **`userPropertiesToSetOnce?`** (`Properties`) - Optional: An associative array of properties to store about the user. If property is previously set, this does not override that value. + +### Returns + +- `void` + +### Examples + +#### set user properties + +```ts +// set user properties +posthog.setPersonProperties({ + email: 'user@example.com', + plan: 'premium' +}) +``` + +#### set properties + +```ts +// set properties +posthog.setPersonProperties( + { name: 'Max Hedgehog' }, // $set properties + { initial_url: '/blog' } // $set_once properties +) +``` + +--- + +#### unsetPersonProperties() + +**Release Tag:** public + +Removes properties from the person profile associated with the current `distinct_id`. Learn more about [identifying users](/docs/product-analytics/identify) + +**Notes:** + +Deletes the given person properties from the person profile in PostHog. This is the counterpart to — instead of hand-passing `$unset` inside a `capture()` call, you can remove properties with a dedicated method. If `person_profiles` is set to `never`, this call is ignored. + +### Parameters + +- **`propertyNames`** (`string | string[]`) - The name (or names) of the person properties to remove. + +### Returns + +- `void` + +### Examples + +#### remove a single property + +```ts +// remove a single property +posthog.unsetPersonProperties('plan') +``` + +#### remove multiple properties + +```ts +// remove multiple properties +posthog.unsetPersonProperties(['plan', 'email']) +``` + +--- + +### Surveys methods + +#### cancelPendingSurvey() + +**Release Tag:** public + +Cancels a pending survey that is waiting to be displayed (e.g., due to a popup delay). + +### Parameters + +- **`surveyId`** (`string`) - The survey ID whose pending display should be cancelled. + +### Returns + +- `void` + +### Examples + +```ts +// Generated example for cancelPendingSurvey +posthog.cancelPendingSurvey(); +``` + +--- + +#### canRenderSurvey() + +**Release Tag:** deprecated + +Checks the feature flags associated with this Survey to see if the survey can be rendered. This method is deprecated because it's synchronous and won't return the correct result if surveys are not loaded. Use `canRenderSurveyAsync` instead. + +### Parameters + +- **`surveyId`** (`string`) - The ID of the survey to check. + +### Returns + +**Union of:** +- `SurveyRenderReason` +- `null` + +### Examples + +```ts +// Generated example for canRenderSurvey +posthog.canRenderSurvey(); +``` + +--- + +#### canRenderSurveyAsync() + +**Release Tag:** public + +Checks the feature flags associated with this Survey to see if the survey can be rendered. + +### Parameters + +- **`surveyId`** (`string`) - The ID of the survey to check. +- **`forceReload?`** (`boolean`) - If true, the survey will be reloaded from the server, Default: false + +### Returns + +- `Promise` + +### Examples + +```ts +posthog.canRenderSurveyAsync(surveyId).then((result) => { + if (result.visible) { + // Survey can be rendered + console.log('Survey can be rendered') + } else { + // Survey cannot be rendered + console.log('Survey cannot be rendered:', result.disabledReason) + } +}) +``` + +--- + +#### displaySurvey() + +**Release Tag:** public + +Display a survey programmatically as either a popover or inline element. + +### Parameters + +- **`surveyId`** (`string`) - The survey ID to display. +- **`options?`** (`DisplaySurveyOptions`) - Display configuration. Defaults to a popover that respects dashboard conditions and delays. + +### Returns + +- `void` + +### Examples + +#### Display as popover (respects all conditions defined in the dashboard) + +```ts +// Display as popover (respects all conditions defined in the dashboard) +posthog.displaySurvey('survey-id-123') +``` + +#### Display inline in a specific element + +```ts +// Display inline in a specific element +posthog.displaySurvey('survey-id-123', { + displayType: DisplaySurveyType.Inline, + ignoreConditions: false, + ignoreDelay: false, + selector: '#survey-container' +}) +``` + +#### Force display ignoring conditions and delays + +```ts +// Force display ignoring conditions and delays +posthog.displaySurvey('survey-id-123', { + displayType: DisplaySurveyType.Popover, + ignoreConditions: true, + ignoreDelay: true +}) +``` + +--- + +#### getActiveMatchingSurveys() + +**Release Tag:** public + +Get surveys that should be enabled for the current user. See [fetching surveys documentation](/docs/surveys/implementing-custom-surveys#fetching-surveys-manually) for more details. + +### Parameters + +- **`callback`** (`SurveyCallback`) - The callback function will be called when the surveys are loaded or updated. +- **`forceReload?`** (`boolean`) - Whether to force a reload of the surveys. + +### Returns + +- `void` + +### Examples + +```ts +posthog.getActiveMatchingSurveys((surveys) => { + // do something +}) +``` + +--- + +#### getSurveys() + +**Release Tag:** public + +Get list of all surveys. + +### Parameters + +- **`callback`** (`SurveyCallback`) - Function that receives the array of surveys. +- **`forceReload?`** (`boolean`) - Optional boolean to force an API call for updated surveys. + +### Returns + +- `void` + +### Examples + +```ts +function callback(surveys, context) { + // do something +} + +posthog.getSurveys(callback, false) +``` + +--- + +#### onSurveysLoaded() + +**Release Tag:** public + +Register an event listener that runs when surveys are loaded. +Callback parameters: - surveys: Survey[]: An array containing all survey objects fetched from PostHog using the getSurveys method - context: isLoaded: boolean, error?: string : An object indicating if the surveys were loaded successfully + +### Parameters + +- **`callback`** (`SurveyCallback`) - The callback function will be called when surveys are loaded or updated. + +### Returns + +- `() => void` + +### Examples + +```ts +posthog.onSurveysLoaded((surveys, context) => { // do something }) +``` + +--- + +#### renderSurvey() + +**Release Tag:** deprecated + +Although we recommend using popover surveys and display conditions, if you want to show surveys programmatically without setting up all the extra logic needed for API surveys, you can render surveys programmatically with the renderSurvey method. +This takes a survey ID and an HTML selector to render an unstyled survey. + +### Parameters + +- **`surveyId`** (`string`) - The ID of the survey to render. +- **`selector`** (`string`) - The selector of the HTML element to render the survey on. + +### Returns + +- `void` + +### Examples + +```ts +posthog.renderSurvey(coolSurveyID, '#survey-container') +``` + +--- + +### Capture methods + +#### capture() + +**Release Tag:** public + +Captures an event with optional properties and configuration. + +**Notes:** + +You can capture arbitrary object-like values as events. [Learn about capture best practices](/docs/product-analytics/capture-events) + +### Parameters + +- **`event_name`** (`EventName`) - The name of the event (e.g., 'Sign Up', 'Button Click', 'Purchase') +- **`properties?`** (`Properties | null`) - Properties to include with the event describing the user or event details +- **`options?`** (`CaptureOptions`) - Optional configuration for the capture request + +### Returns + +**Union of:** +- `CaptureResult` +- `undefined` + +### Examples + +```ts +// basic event capture +posthog.capture('cta-button-clicked', { + button_name: 'Get Started', + page: 'homepage' +}) +``` + +--- + +#### on() + +**Release Tag:** public + +Exposes a set of events that PostHog will emit. e.g. `eventCaptured` is emitted immediately before trying to send an event +Unlike `onFeatureFlags` and `onSessionId` these are not called when the listener is registered, the first callback will be the next event _after_ registering a listener +Available events: - `eventCaptured`: Emitted immediately before trying to send an event - `featureFlagsReloading`: Emitted when feature flags are being reloaded (e.g. after `identify()`, `group()`, or `reloadFeatureFlags()`) + +### Parameters + +- **`event`** (`'eventCaptured' | 'featureFlagsReloading'`) - The event to listen for. +- **`cb`** (`(...args: any[]) => void`) - The callback function to call when the event is emitted. + +### Returns + +- `() => void` + +### Examples + +#### + +```ts +posthog.on('eventCaptured', (event) => { + console.log(event) +}) +``` + +#### Track when feature flags are reloading to show a loading state + +```ts +// Track when feature flags are reloading to show a loading state +posthog.on('featureFlagsReloading', () => { + console.log('Feature flags are being reloaded...') +}) +``` + +--- + +#### register_for_session() + +**Release Tag:** public + +Registers super properties for the current session only. + +**Notes:** + +Session super properties are automatically added to all events during the current browser session. Unlike regular super properties, these are cleared when the session ends and are stored in sessionStorage. + +### Parameters + +- **`properties`** (`Properties`) - An associative array of properties to store about the user + +### Returns + +- `void` + +### Examples + +#### register session-specific properties + +```ts +// register session-specific properties +posthog.register_for_session({ + current_page_type: 'checkout', + ab_test_variant: 'control' +}) +``` + +#### register properties for user flow tracking + +```ts +// register properties for user flow tracking +posthog.register_for_session({ + selected_plan: 'pro', + completed_steps: 3, + flow_id: 'signup_flow_v2' +}) +``` + +--- + +#### register_once() + +**Release Tag:** public + +Registers super properties only if they haven't been set before. + +**Notes:** + +Unlike `register()`, this method will not overwrite existing super properties. Use this for properties that should only be set once, like signup date or initial referrer. + +### Parameters + +- **`properties`** (`Properties`) - An associative array of properties to store about the user +- **`default_value?`** (`Property`) - Value to override if already set in super properties (ex: 'False') Default: 'None' +- **`days?`** (`number`) - How many days since the users last visit to store the super properties + +### Returns + +- `void` + +### Examples + +#### register once-only properties + +```ts +// register once-only properties +posthog.register_once({ + first_login_date: new Date().toISOString(), + initial_referrer: document.referrer +}) +``` + +#### override existing value if it matches default + +```ts +// override existing value if it matches default +posthog.register_once( + { user_type: 'premium' }, + 'unknown' // overwrite if current value is 'unknown' +) +``` + +--- + +#### register() + +**Release Tag:** public + +Registers super properties that are included with all events. + +**Notes:** + +Super properties are stored in persistence and automatically added to every event you capture. These values will overwrite any existing super properties with the same keys. + +### Parameters + +- **`properties`** (`Properties`) - properties to store about the user +- **`days?`** (`number`) - How many days since the user's last visit to store the super properties + +### Returns + +- `void` + +### Examples + +#### register a single property + +```ts +// register a single property +posthog.register({ plan: 'premium' }) +``` + +#### register multiple properties + +```ts +// register multiple properties +posthog.register({ + email: 'user@example.com', + account_type: 'business', + signup_date: '2023-01-15' +}) +``` + +#### register with custom expiration + +```ts +// register with custom expiration +posthog.register({ campaign: 'summer_sale' }, 7) // expires in 7 days +``` + +--- + +#### unregister_for_session() + +**Release Tag:** public + +Removes a session super property from the current session. + +**Notes:** + +This will stop the property from being automatically included in future events for this session. The property is removed from sessionStorage. + +### Parameters + +- **`property`** (`string`) - The name of the session super property to remove + +### Returns + +- `void` + +### Examples + +```ts +// remove a session property +posthog.unregister_for_session('current_flow') +``` + +--- + +#### unregister() + +**Release Tag:** public + +Removes a super property from persistent storage. + +**Notes:** + +This will stop the property from being automatically included in future events. The property will be permanently removed from the user's profile. + +### Parameters + +- **`property`** (`string`) - The name of the super property to remove + +### Returns + +- `void` + +### Examples + +```ts +// remove a super property +posthog.unregister('plan_type') +``` + +--- + +### Logs methods + +#### captureLog() + +**Release Tag:** public + +Capture a log entry and send it to the PostHog logs endpoint. + +### Parameters + +- **`options`** (`CaptureLogOptions`) - The log entry options + +### Returns + +- `void` + +### Examples + +```ts +posthog.captureLog({ + body: 'checkout completed', + level: 'info', + attributes: { order_id: 'ord_789', amount_cents: 4999 }, +}) +``` + +--- + +### LLM analytics methods + +#### captureTraceFeedback() + +**Release Tag:** public + +Capture written user feedback for a LLM trace. Numeric values are converted to strings. + +### Parameters + +- **`traceId`** (`string | number`) - The trace ID to capture feedback for. +- **`userFeedback`** (`string`) - The feedback to capture. + +### Returns + +- `void` + +### Examples + +```ts +// Generated example for captureTraceFeedback +posthog.captureTraceFeedback(); +``` + +--- + +#### captureTraceMetric() + +**Release Tag:** public + +Capture a metric for a LLM trace. Numeric values are converted to strings. + +### Parameters + +- **`traceId`** (`string | number`) - The trace ID to capture the metric for. +- **`metricName`** (`string`) - The name of the metric to capture. +- **`metricValue`** (`string | number | boolean`) - The value of the metric to capture. + +### Returns + +- `void` + +### Examples + +```ts +// Generated example for captureTraceMetric +posthog.captureTraceMetric(); +``` + +--- + +### Privacy methods + +#### clear_opt_in_out_capturing() + +**Release Tag:** public + +Clear the user's opt in/out status of data capturing and cookies/localstorage for this PostHog instance + +### Returns + +- `void` + +### Examples + +```ts +// Generated example for clear_opt_in_out_capturing +posthog.clear_opt_in_out_capturing(); +``` + +--- + +#### has_opted_in_capturing() + +**Release Tag:** public + +Checks if the user has opted into data capturing. + +**Notes:** + +Returns the current consent status for event tracking and data persistence. + +### Returns + +- `boolean` + +### Examples + +```ts +if (posthog.has_opted_in_capturing()) { + // show analytics features +} +``` + +--- + +#### has_opted_out_capturing() + +**Release Tag:** public + +Checks if the user has opted out of data capturing. + +**Notes:** + +Returns the current consent status for event tracking and data persistence. + +### Returns + +- `boolean` + +### Examples + +```ts +if (posthog.has_opted_out_capturing()) { + // disable analytics features +} +``` + +--- + +#### is_capturing() + +**Release Tag:** public + +Checks whether the PostHog library is currently capturing events. +Usually this means that the user has not opted out of capturing, but the exact behaviour can be controlled by some config options. +Additionally, if the cookieless_mode is set to `'on_reject'`, we will capture events in cookieless mode if the user has opted out or been defaulted to opt-out. + +### Returns + +- `boolean` + +### Examples + +```ts +// Generated example for is_capturing +posthog.is_capturing(); +``` + +--- + +#### opt_in_capturing() + +**Release Tag:** public + +Opts the user into data capturing and persistence. + +**Notes:** + +Enables event tracking and data persistence (cookies/localStorage) for this PostHog instance. By default, captures an `$opt_in` event unless disabled. + +### Parameters + +- **`options?`** (`{ + captureEventName?: EventName | null | false; /** event name to be used for capturing the opt-in action */ + captureProperties?: Properties; /** set of properties to be captured along with the opt-in action */ + }`) - A dictionary of opt-in options. + +### Returns + +- `void` + +### Examples + +#### simple opt-in + +```ts +// simple opt-in +posthog.opt_in_capturing() +``` + +#### opt-in with custom event and properties + +```ts +// opt-in with custom event and properties +posthog.opt_in_capturing({ + captureEventName: 'Privacy Accepted', + captureProperties: { source: 'banner' } +}) +``` + +#### opt-in without capturing event + +```ts +// opt-in without capturing event +posthog.opt_in_capturing({ + captureEventName: false +}) +``` + +--- + +#### opt_out_capturing() + +**Release Tag:** public + +Opts the user out of data capturing and persistence. + +**Notes:** + +Disables event tracking and data persistence (cookies/localStorage) for this PostHog instance. If `opt_out_persistence_by_default` is true, SDK persistence will also be disabled. + +### Returns + +- `void` + +### Examples + +```ts +// opt user out (e.g., on privacy settings page) +posthog.opt_out_capturing() +``` + +--- + +### Initialization methods + +#### debug() + +**Release Tag:** public + +Enables or disables debug mode for detailed logging. + +**Notes:** + +Debug mode logs all PostHog calls to the browser console for troubleshooting. Can also be enabled by adding `?__posthog_debug=true` to the URL. + +### Parameters + +- **`debug?`** (`boolean`) - If true, will enable debug mode. + +### Returns + +- `void` + +### Examples + +#### enable debug mode + +```ts +// enable debug mode +posthog.debug(true) +``` + +#### disable debug mode + +```ts +// disable debug mode +posthog.debug(false) +``` + +--- + +#### getPageViewId() + +**Release Tag:** public + +Returns the current page view ID. + +### Returns + +**Union of:** +- `string` +- `undefined` + +### Examples + +```ts +// Generated example for getPageViewId +posthog.getPageViewId(); +``` + +--- + +#### init() + +**Release Tag:** public + +Initializes a new instance of the PostHog capturing object. + +**Notes:** + +All new instances are added to the main posthog object as sub properties (such as `posthog.library_name`) and also returned by this function. [Learn more about configuration options](https://posthog.com/docs/libraries/js/config) + +### Parameters + +- **`token`** (`string`) - Your PostHog API token +- **`config?`** (`OnlyValidKeys, Partial>`) - A dictionary of config options to override +- **`name?`** (`string`) - The name for the new posthog instance that you want created + +### Returns + +- `PostHog` + +### Examples + +#### basic initialization + +```ts +// basic initialization +posthog.init('', { + api_host: '' +}) +``` + +#### multiple instances + +```ts +// multiple instances +posthog.init('', {}, 'project1') +posthog.init('', {}, 'project2') +``` + +--- + +#### set_config() + +**Release Tag:** public + +Updates the configuration of the PostHog instance. + +### Parameters + +- **`config`** (`Partial`) - A dictionary of new configuration values to update + +### Returns + +- `void` + +### Examples + +```ts +// Generated example for set_config +posthog.set_config(); +``` + +--- + +### Session replay methods + +#### get_session_replay_url() + +**Release Tag:** public + +Returns the Replay url for the current session. + +### Parameters + +- **`options?`** (`{ + withTimestamp?: boolean; + timestampLookBack?: number; + }`) - Options for the URL. + +### Returns + +- `string` + +### Examples + +#### basic usage + +```ts +// basic usage +posthog.get_session_replay_url() +``` + +#### timestamp + +```ts +// timestamp +posthog.get_session_replay_url({ withTimestamp: true }) +``` + +#### timestamp and lookback + +```ts +// timestamp and lookback +posthog.get_session_replay_url({ + withTimestamp: true, + timestampLookBack: 30 // look back 30 seconds +}) +``` + +--- + +#### sessionRecordingStarted() + +**Release Tag:** public + +returns a boolean indicating whether session recording is currently running + +### Returns + +- `boolean` + +### Examples + +```ts +// Stop session recording if it's running +if (posthog.sessionRecordingStarted()) { + posthog.stopSessionRecording() +} +``` + +--- + +#### startSessionRecording() + +**Release Tag:** public + +turns session recording on, and updates the config option `disable_session_recording` to false + +### Parameters + +- **`override?`** (`{ + sampling?: boolean; + linked_flag?: boolean; + url_trigger?: true; + event_trigger?: true; + } | true`) - optional boolean to override the default sampling behavior - ensures the next session recording to start will not be skipped by sampling or linked_flag config. `true` is shorthand for sampling: true, linked_flag: true + +### Returns + +- `void` + +### Examples + +#### Start and ignore controls + +```ts +// Start and ignore controls +posthog.startSessionRecording(true) +``` + +#### Start and override controls + +```ts +// Start and override controls +posthog.startSessionRecording({ + // you don't have to send all of these + sampling: true || false, + linked_flag: true || false, + url_trigger: true || false, + event_trigger: true || false +}) +``` + +--- + +#### stopSessionRecording() + +**Release Tag:** public + +turns session recording off, and updates the config option disable_session_recording to true + +### Returns + +- `void` + +### Examples + +```ts +// Stop session recording +posthog.stopSessionRecording() +``` + +--- + +### Feature flags methods + +#### getEarlyAccessFeatures() + +**Release Tag:** public + +Get the list of early access features. To check enrollment status, use `isFeatureEnabled`. [Learn more in the docs](/docs/feature-flags/early-access-feature-management#option-2-custom-implementation) + +### Parameters + +- **`callback`** (`EarlyAccessFeatureCallback`) - The callback function will be called when the early access features are loaded. +- **`force_reload?`** (`boolean`) - Whether to force a reload of the early access features. +- **`stages?`** (`EarlyAccessFeatureStage[]`) - The stages of the early access features to load. + +### Returns + +- `void` + +### Examples + +```ts +const posthog = usePostHog() +const activeFlags = useActiveFeatureFlags() + +const [activeBetas, setActiveBetas] = useState([]) +const [inactiveBetas, setInactiveBetas] = useState([]) +const [comingSoonFeatures, setComingSoonFeatures] = useState([]) + +useEffect(() => { + posthog.getEarlyAccessFeatures((features) => { + // Filter features by stage + const betaFeatures = features.filter(feature => feature.stage === 'beta') + const conceptFeatures = features.filter(feature => feature.stage === 'concept') + + setComingSoonFeatures(conceptFeatures) + + if (!activeFlags || activeFlags.length === 0) { + setInactiveBetas(betaFeatures) + return + } + + const activeBetas = betaFeatures.filter( + beta => activeFlags.includes(beta.flagKey) + ); + const inactiveBetas = betaFeatures.filter( + beta => !activeFlags.includes(beta.flagKey) + ); + setActiveBetas(activeBetas) + setInactiveBetas(inactiveBetas) + }, true, ['concept', 'beta']) +}, [activeFlags]) +``` + +--- + +#### getFeatureFlag() + +**Release Tag:** public + +Gets the value of a feature flag for the current user. + +**Notes:** + +Returns the feature flag value which can be a boolean, string, or undefined. Supports multivariate flags that can return custom string values. + +### Parameters + +- **`key`** (`string`) - Key of the feature flag. +- **`options?`** (`FeatureFlagOptions`) - Optional lookup settings. If `{ send_event: false }`, we won't send a `$feature_flag_called` event to PostHog. If `{ fresh: true }`, we won't return cached values from localStorage - only values loaded from the server. + +### Returns + +**Union of:** +- `boolean` +- `string` +- `undefined` + +### Examples + +#### check boolean flag + +```ts +// check boolean flag +if (posthog.getFeatureFlag('new-feature')) { + // show new feature +} +``` + +#### check multivariate flag + +```ts +// check multivariate flag +const variant = posthog.getFeatureFlag('button-color') +if (variant === 'red') { + // show red button +} +``` + +--- + +#### getFeatureFlagPayload() + +**Release Tag:** deprecated + +Get feature flag payload value matching key for user (supports multivariate flags). + +### Parameters + +- **`key`** (`string`) - Key of the feature flag. + +### Returns + +- `JsonType` + +### Examples + +```ts +const betaFeature = posthog.getFeatureFlagResult('beta-feature') +if (betaFeature?.variant === 'some-value') { + const someValue = betaFeature?.payload + // do something +} +``` + +--- + +#### getFeatureFlagResult() + +**Release Tag:** public + +Get a feature flag evaluation result including both the flag value and payload. +By default, this method emits the `$feature_flag_called` event. + +### Parameters + +- **`key`** (`string`) - Key of the feature flag. +- **`options?`** (`FeatureFlagOptions`) - Options for the feature flag lookup. + +### Returns + +**Union of:** +- `FeatureFlagResult` +- `undefined` + +### Examples + +#### + +```ts +const result = posthog.getFeatureFlagResult('my-flag') +if (result?.enabled) { + console.log('Flag is enabled with payload:', result.payload) +} +``` + +#### multivariate flag + +```ts +// multivariate flag +const result = posthog.getFeatureFlagResult('button-color') +if (result?.variant === 'red') { + showRedButton(result.payload) +} +``` + +--- + +#### isFeatureEnabled() + +**Release Tag:** public + +Checks if a feature flag is enabled for the current user. + +**Notes:** + +Returns true if the flag is enabled, false if disabled, or undefined if not found. This is a convenience method that treats any truthy value as enabled. + +### Parameters + +- **`key`** (`string`) - Key of the feature flag. +- **`options?`** (`FeatureFlagOptions`) - Optional lookup settings. If `{ send_event: false }`, we won't send a `$feature_flag_called` event to PostHog. If `{ fresh: true }`, we won't return cached values from localStorage - only values loaded from the server. + +### Returns + +**Union of:** +- `boolean` +- `undefined` + +### Examples + +#### simple feature flag check + +```ts +// simple feature flag check +if (posthog.isFeatureEnabled('new-checkout')) { + showNewCheckout() +} +``` + +#### disable event tracking + +```ts +// disable event tracking +if (posthog.isFeatureEnabled('feature', { send_event: false })) { + // flag checked without sending $feature_flag_called event +} +``` + +--- + +#### onFeatureFlags() + +**Release Tag:** public + +Register an event listener that runs when feature flags become available or when they change. If there are flags, the listener is called immediately in addition to being called on future changes. Note that this is not called only when we fetch feature flags from the server, but also when they change in the browser. + +### Parameters + +- **`callback`** (`FeatureFlagsCallback`) - The callback function will be called once the feature flags are ready or when they are updated. It'll return a list of feature flags enabled for the user, the variants, and also a context object indicating whether we succeeded to fetch the flags or not. + +### Returns + +- `() => void` + +### Examples + +```ts +posthog.onFeatureFlags(function(featureFlags, featureFlagsVariants, { errorsLoading }) { + // do something +}) +``` + +--- + +#### reloadFeatureFlags() + +**Release Tag:** public + +Feature flag values are cached. If something has changed with your user and you'd like to refetch their flag values, call this method. + +### Returns + +- `void` + +### Examples + +```ts +posthog.reloadFeatureFlags() +``` + +--- + +#### resetGroupPropertiesForFlags() + +**Release Tag:** public + +Resets the group properties for feature flags. + +### Parameters + +- **`group_type?`** (`string`) - Optional group type to reset. If omitted, all group properties are reset. + +### Returns + +- `void` + +### Examples + +```ts +posthog.resetGroupPropertiesForFlags() +``` + +--- + +#### resetPersonPropertiesForFlags() + +**Release Tag:** public + +Resets the person properties for feature flags. + +### Parameters + +- **`reloadFeatureFlags?`** (`boolean`) - Whether to reload feature flags. + +### Returns + +- `void` + +### Examples + +#### + +```ts +posthog.resetPersonPropertiesForFlags() +``` + +#### Reset properties without reloading + +```ts +// Reset properties without reloading +posthog.resetPersonPropertiesForFlags(false) +``` + +--- + +#### setGroupPropertiesForFlags() + +**Release Tag:** public + +Set override group properties for feature flags. This is used when dealing with new groups / where you don't want to wait for ingestion to update properties. Takes in an object, the key of which is the group type. + +### Parameters + +- **`properties`** (`{ + [type: string]: Properties; + }`) - The properties to override, the key of which is the group type. +- **`reloadFeatureFlags?`** (`boolean`) - Whether to reload feature flags. + +### Returns + +- `void` + +### Examples + +#### Set properties with reload + +```ts +// Set properties with reload +posthog.setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } }) +``` + +#### Set properties without reload + +```ts +// Set properties without reload +posthog.setGroupPropertiesForFlags({'organization': { name: 'CYZ', employees: '11' } }, false) +``` + +--- + +#### setPersonPropertiesForFlags() + +**Release Tag:** public + +Sometimes, you might want to evaluate feature flags using properties that haven't been ingested yet, or were set incorrectly earlier. You can do so by setting properties the flag depends on with these calls: + +### Parameters + +- **`properties`** (`Properties`) - The properties to override. +- **`reloadFeatureFlags?`** (`boolean`) - Whether to reload feature flags. + +### Returns + +- `void` + +### Examples + +#### Set properties + +```ts +// Set properties +posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}) +``` + +#### Set properties without reloading + +```ts +// Set properties without reloading +posthog.setPersonPropertiesForFlags({'property1': 'value', property2: 'value2'}, false) +``` + +--- + +#### updateEarlyAccessFeatureEnrollment() + +**Release Tag:** public + +Opt the user in or out of an early access feature. [Learn more in the docs](/docs/feature-flags/early-access-feature-management#option-2-custom-implementation) + +### Parameters + +- **`key`** (`string`) - The key of the feature flag to update. +- **`isEnrolled`** (`boolean`) - Whether the user is enrolled in the feature. +- **`stage?`** (`string`) - The stage of the feature flag to update. + +### Returns + +- `void` + +### Examples + +```ts +const toggleBeta = (betaKey) => { + if (activeBetas.some( + beta => beta.flagKey === betaKey + )) { + posthog.updateEarlyAccessFeatureEnrollment( + betaKey, + false + ) + setActiveBetas( + prevActiveBetas => prevActiveBetas.filter( + item => item.flagKey !== betaKey + ) + ); + return + } + + posthog.updateEarlyAccessFeatureEnrollment( + betaKey, + true + ) + setInactiveBetas( + prevInactiveBetas => prevInactiveBetas.filter( + item => item.flagKey !== betaKey + ) + ); +} + +const registerInterest = (featureKey) => { + posthog.updateEarlyAccessFeatureEnrollment( + featureKey, + true + ) + // Update UI to show user has registered +} +``` + +--- + +#### updateFlags() + +**Release Tag:** public + +Manually update feature flag values without making a network request. +This is useful when you have feature flag values from an external source (e.g., server-side evaluation, edge middleware) and want to inject them into the client SDK. + +### Parameters + +- **`flags`** (`Record`) - An object mapping flag keys to their values (boolean or string variant) +- **`payloads?`** (`Record`) - Optional object mapping flag keys to their JSON payloads +- **`options?`** (`{ + merge?: boolean; + }`) - Optional settings. Use `{ merge: true }` to merge with existing flags instead of replacing. + +### Returns + +- `void` + +### Examples + +```ts +// Replace all flags with server-evaluated values +posthog.updateFlags({ + 'my-flag': true, + 'my-experiment': 'variant-a' +}) + +// Merge with existing flags (update only specified flags) +posthog.updateFlags( + { 'my-flag': true }, + undefined, + { merge: true } +) + +// With payloads +posthog.updateFlags( + { 'my-flag': true }, + { 'my-flag': { some: 'data' } } +) +``` + +--- + +### Toolbar methods + +#### loadToolbar() + +**Release Tag:** public + +returns a boolean indicating whether the [toolbar](/docs/toolbar) loaded + +### Parameters + +- **`params`** (`ToolbarParams`) - Toolbar parameters. + +### Returns + +- `boolean` + +### Examples + +```ts +// Generated example for loadToolbar +posthog.loadToolbar(); +``` + +--- + +### Lifecycle methods + +#### shutdown() + +**Release Tag:** public + +Flushes any queued events and resolves once teardown is complete. + +**Notes:** + +This exists primarily for parity with the server-side [Node.js SDK](/docs/libraries/node), whose `shutdown()` you call once before a process exits. In the browser there is no process to exit — the SDK already flushes pending events on `pagehide`/`unload` — so this method is mostly a graceful no-op that best-effort flushes the request queues and always resolves. +It is safe to call in isomorphic teardown code (for example a Nuxt/Next module that calls `shutdown()` on both the server and the client) so the same symmetric cleanup works in either environment without throwing. + +### Parameters + +- **`_shutdownTimeoutMs?`** (`number`) - Accepted for call-site parity with the Node.js SDK. The browser flush is synchronous, so this is ignored. + +### Returns + +- `Promise` + +### Examples + +```ts +// symmetric teardown that runs on both server and client +await posthog.shutdown() +``` + +--- \ No newline at end of file diff --git a/apps/basic-integration/javascript-web/saas-dashboard/package-lock.json b/apps/basic-integration/javascript-web/saas-dashboard/package-lock.json index 05bcd0830..81b0dc1cf 100644 --- a/apps/basic-integration/javascript-web/saas-dashboard/package-lock.json +++ b/apps/basic-integration/javascript-web/saas-dashboard/package-lock.json @@ -8,7 +8,8 @@ "name": "trackflow", "version": "1.0.0", "dependencies": { - "chart.js": "^4.4.0" + "chart.js": "^4.4.0", + "posthog-js": "^1.398.0" }, "devDependencies": { "vite": "^6.0.0" @@ -462,6 +463,21 @@ "integrity": "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w==", "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.1", + "resolved": "https://registry.npmjs.org/@posthog/types/-/types-1.392.1.tgz", + "integrity": "sha512-Qg6Gl7/1vlr8+gPtBi5gwnLgAgiyFoKOVmTvTtDcvya9cpTwZfna7rQmkGQ4B63CunUYNNbOlqcwiUwUDyTK6w==", + "license": "MIT" + }, "node_modules/@rollup/rollup-android-arm-eabi": { "version": "4.57.1", "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.57.1.tgz", @@ -819,6 +835,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/chart.js": { "version": "4.5.1", "resolved": "https://registry.npmjs.org/chart.js/-/chart.js-4.5.1.tgz", @@ -831,6 +854,26 @@ "pnpm": ">=8" } }, + "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/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/esbuild": { "version": "0.25.12", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz", @@ -891,6 +934,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/fsevents": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", @@ -938,7 +987,6 @@ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -975,6 +1023,38 @@ "node": "^10 || ^12 || >=14" } }, + "node_modules/posthog-js": { + "version": "1.398.0", + "resolved": "https://registry.npmjs.org/posthog-js/-/posthog-js-1.398.0.tgz", + "integrity": "sha512-1+1FPmP6sw1NxtFz5YI1MqwpvRrGGJIedvczk8rJ7YD0Ez3pjolQ21krc+iKrpkvuoNjORZATGOYpUtaL5yWjQ==", + "license": "(Apache-2.0 AND MIT)", + "dependencies": { + "@posthog/core": "^1.39.6", + "@posthog/types": "^1.392.1", + "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.4", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.29.4.tgz", + "integrity": "sha512-GMpwh9+NJ8tSmqwIaVyFRQkiKfBEzQ+k7r7tle4W+kaJ+7wJiB9hFz9BixAomMtenPPSBfM4bZhXozGxhf0uFQ==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } + }, + "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/rollup": { "version": "4.57.1", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.57.1.tgz", @@ -1121,6 +1201,12 @@ "optional": true } } + }, + "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" } } } diff --git a/apps/basic-integration/javascript-web/saas-dashboard/package.json b/apps/basic-integration/javascript-web/saas-dashboard/package.json index c11a7b4b6..c0feed558 100644 --- a/apps/basic-integration/javascript-web/saas-dashboard/package.json +++ b/apps/basic-integration/javascript-web/saas-dashboard/package.json @@ -9,7 +9,8 @@ "preview": "vite preview" }, "dependencies": { - "chart.js": "^4.4.0" + "chart.js": "^4.4.0", + "posthog-js": "^1.398.0" }, "devDependencies": { "vite": "^6.0.0" diff --git a/apps/basic-integration/javascript-web/saas-dashboard/posthog-setup-report.md b/apps/basic-integration/javascript-web/saas-dashboard/posthog-setup-report.md new file mode 100644 index 000000000..3c7615a36 --- /dev/null +++ b/apps/basic-integration/javascript-web/saas-dashboard/posthog-setup-report.md @@ -0,0 +1,41 @@ +# PostHog post-wizard report + +The wizard has completed a full PostHog integration for **TrackFlow**, a SaaS project-management dashboard built with Vite + vanilla JavaScript. `posthog-js` was installed and initialized in `src/main.js` using `VITE_POSTHOG_KEY` and `VITE_POSTHOG_HOST` environment variables. PostHog identifies the current user on every page load (via the `loaded` callback) and re-identifies on login, so returning sessions are always linked to a known person. `posthog.reset()` is called on logout to start a fresh anonymous session. Exception capture was added to the login flow and project/task operations. Twelve custom events were instrumented across five files covering the full user lifecycle: authentication, project management, task operations, and settings. + +| Event | Description | File | +|---|---|---| +| `user_signed_in` | Fired when a user successfully signs in to TrackFlow. | `src/pages/login.js` | +| `user_signed_out` | Fired when a user signs out from the app shell. | `src/components/shell.js` | +| `project_created` | Fired when a user creates a new project. | `src/pages/projects.js` | +| `project_deleted` | Fired when a user deletes an existing project. | `src/pages/projects.js` | +| `project_viewed` | Fired when a user views a project detail page, representing the top of the project engagement funnel. | `src/pages/project-detail.js` | +| `task_created` | Fired when a user adds a new task to a project. | `src/pages/project-detail.js` | +| `task_completed` | Fired when a task is moved to the 'done' status. | `src/pages/project-detail.js` | +| `task_status_changed` | Fired when a task is moved to a non-done status (todo or in_progress). | `src/pages/project-detail.js` | +| `task_assigned` | Fired when a task is assigned to a team member. | `src/pages/project-detail.js` | +| `task_deleted` | Fired when a task is deleted from a project. | `src/pages/project-detail.js` | +| `settings_updated` | Fired when a user changes their preferences in the settings page. | `src/pages/settings.js` | +| `data_reset` | Fired when a user resets all application data from the Danger Zone. | `src/pages/settings.js` | + +## 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/1807666) +- [Daily Active Users (wizard)](https://us.posthog.com/project/483112/insights/D4U2iGJo) +- [Project Engagement Funnel (wizard)](https://us.posthog.com/project/483112/insights/XoJzzyrA) +- [Task Activity Over Time (wizard)](https://us.posthog.com/project/483112/insights/zNhgLvGt) +- [Project Lifecycle (wizard)](https://us.posthog.com/project/483112/insights/O9crTSVV) +- [Churn Signals (wizard)](https://us.posthog.com/project/483112/insights/N0431rDT) + +## 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 the exact PostHog env var names (`VITE_POSTHOG_KEY`, `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/javascript-web/saas-dashboard/src/components/shell.js b/apps/basic-integration/javascript-web/saas-dashboard/src/components/shell.js index 7b7502aa9..ebe911e27 100644 --- a/apps/basic-integration/javascript-web/saas-dashboard/src/components/shell.js +++ b/apps/basic-integration/javascript-web/saas-dashboard/src/components/shell.js @@ -1,6 +1,7 @@ import { api } from '../api.js'; import { router } from '../router.js'; import { store } from '../store.js'; +import { posthog } from '../main.js'; /** * Renders the app shell: sidebar + header + content area. @@ -53,7 +54,9 @@ export function renderShell(activeSection) { `; document.getElementById('logout-btn').addEventListener('click', async () => { + posthog.capture('user_signed_out'); await api.logout(); + posthog.reset(); router.navigate('/login'); }); } diff --git a/apps/basic-integration/javascript-web/saas-dashboard/src/main.js b/apps/basic-integration/javascript-web/saas-dashboard/src/main.js index 1036566af..d5f0d5e0e 100644 --- a/apps/basic-integration/javascript-web/saas-dashboard/src/main.js +++ b/apps/basic-integration/javascript-web/saas-dashboard/src/main.js @@ -1,3 +1,4 @@ +import posthog from 'posthog-js'; import { router } from './router.js'; import { store } from './store.js'; import { renderLogin } from './pages/login.js'; @@ -7,6 +8,19 @@ import { renderProjectDetail } from './pages/project-detail.js'; import { renderSettings } from './pages/settings.js'; import { renderActivity } from './pages/activity.js'; +posthog.init(import.meta.env.VITE_POSTHOG_KEY, { + api_host: import.meta.env.VITE_POSTHOG_HOST, + defaults: '2026-05-30', + loaded(ph) { + const user = store.state.currentUser; + if (user) { + ph.identify(user.id, { name: user.name, email: user.email, role: user.role }); + } + }, +}); + +export { posthog }; + /** * Auth guard — redirects to login if no user is logged in. */ diff --git a/apps/basic-integration/javascript-web/saas-dashboard/src/pages/login.js b/apps/basic-integration/javascript-web/saas-dashboard/src/pages/login.js index ad700ace8..0dbda3637 100644 --- a/apps/basic-integration/javascript-web/saas-dashboard/src/pages/login.js +++ b/apps/basic-integration/javascript-web/saas-dashboard/src/pages/login.js @@ -1,5 +1,6 @@ import { api } from '../api.js'; import { router } from '../router.js'; +import { posthog } from '../main.js'; export function renderLogin() { const app = document.getElementById('app'); @@ -39,9 +40,12 @@ export function renderLogin() { btn.textContent = 'Signing in...'; try { - await api.login(email); + const user = await api.login(email); + posthog.identify(user.id, { name: user.name, email: user.email, role: user.role }); + posthog.capture('user_signed_in', { role: user.role }); router.navigate('/dashboard'); } catch (err) { + posthog.captureException(err, { context: 'login' }); errorEl.textContent = err.message; errorEl.hidden = false; btn.disabled = false; diff --git a/apps/basic-integration/javascript-web/saas-dashboard/src/pages/project-detail.js b/apps/basic-integration/javascript-web/saas-dashboard/src/pages/project-detail.js index 506deabf2..3f846cf01 100644 --- a/apps/basic-integration/javascript-web/saas-dashboard/src/pages/project-detail.js +++ b/apps/basic-integration/javascript-web/saas-dashboard/src/pages/project-detail.js @@ -2,6 +2,7 @@ import { api } from '../api.js'; import { store } from '../store.js'; import { renderShell } from '../components/shell.js'; import { showModal } from '../components/modal.js'; +import { posthog } from '../main.js'; const STATUS_OPTIONS = ['todo', 'in_progress', 'done']; const PRIORITY_OPTIONS = ['low', 'medium', 'high']; @@ -16,8 +17,10 @@ export async function renderProjectDetail({ id }) { const project = await api.getProject(id); const members = await api.getTeamMembers(); + posthog.capture('project_viewed', { project_id: project.id, project_name: project.name, task_count: project.tasks.length }); render(project, members); } catch (err) { + posthog.captureException(err, { context: 'project_detail', project_id: id }); content.innerHTML = `
${err.message}
`; } } @@ -104,11 +107,13 @@ function render(project, members) { const priority = modalEl.querySelector('#task-priority').value; try { - await api.addTask(project.id, title, priority); + const task = await api.addTask(project.id, title, priority); + posthog.capture('task_created', { project_id: project.id, task_id: task.id, priority }); document.getElementById('modal-overlay')?.remove(); const updated = await api.getProject(project.id); render(updated, members); } catch (err) { + posthog.captureException(err, { context: 'add_task', project_id: project.id }); alert(err.message); } }); @@ -118,7 +123,13 @@ function render(project, members) { // Move task status content.querySelectorAll('.move-task').forEach((btn) => { btn.addEventListener('click', async () => { - await api.updateTaskStatus(project.id, btn.dataset.taskId, btn.dataset.status); + const newStatus = btn.dataset.status; + await api.updateTaskStatus(project.id, btn.dataset.taskId, newStatus); + if (newStatus === 'done') { + posthog.capture('task_completed', { project_id: project.id, task_id: btn.dataset.taskId }); + } else { + posthog.capture('task_status_changed', { project_id: project.id, task_id: btn.dataset.taskId, status: newStatus }); + } const updated = await api.getProject(project.id); render(updated, members); }); @@ -135,7 +146,9 @@ function render(project, members) { `, (modalEl) => { modalEl.querySelectorAll('.assign-option').forEach((opt) => { opt.addEventListener('click', async () => { - await api.assignTask(project.id, btn.dataset.taskId, opt.dataset.assignee || null); + const assigneeId = opt.dataset.assignee || null; + await api.assignTask(project.id, btn.dataset.taskId, assigneeId); + posthog.capture('task_assigned', { project_id: project.id, task_id: btn.dataset.taskId, assigned: assigneeId !== null }); document.getElementById('modal-overlay')?.remove(); const updated = await api.getProject(project.id); render(updated, members); @@ -149,6 +162,7 @@ function render(project, members) { content.querySelectorAll('.delete-task').forEach((btn) => { btn.addEventListener('click', async () => { await api.deleteTask(project.id, btn.dataset.taskId); + posthog.capture('task_deleted', { project_id: project.id, task_id: btn.dataset.taskId }); const updated = await api.getProject(project.id); render(updated, members); }); diff --git a/apps/basic-integration/javascript-web/saas-dashboard/src/pages/projects.js b/apps/basic-integration/javascript-web/saas-dashboard/src/pages/projects.js index 5a56d3aba..1ffcfd075 100644 --- a/apps/basic-integration/javascript-web/saas-dashboard/src/pages/projects.js +++ b/apps/basic-integration/javascript-web/saas-dashboard/src/pages/projects.js @@ -2,6 +2,7 @@ import { api } from '../api.js'; import { router } from '../router.js'; import { renderShell } from '../components/shell.js'; import { showModal } from '../components/modal.js'; +import { posthog } from '../main.js'; export async function renderProjects() { renderShell('projects'); @@ -75,8 +76,10 @@ export async function renderProjects() { try { const project = await api.createProject(name, desc); + posthog.capture('project_created', { project_id: project.id, project_name: project.name }); router.navigate(`/projects/${project.id}`); } catch (err) { + posthog.captureException(err, { context: 'create_project' }); alert(err.message); } }); @@ -90,6 +93,7 @@ export async function renderProjects() { const id = btn.dataset.id; if (confirm('Delete this project and all its tasks?')) { await api.deleteProject(id); + posthog.capture('project_deleted', { project_id: id }); renderProjects(); } }); diff --git a/apps/basic-integration/javascript-web/saas-dashboard/src/pages/settings.js b/apps/basic-integration/javascript-web/saas-dashboard/src/pages/settings.js index 16bb76dab..409b3af23 100644 --- a/apps/basic-integration/javascript-web/saas-dashboard/src/pages/settings.js +++ b/apps/basic-integration/javascript-web/saas-dashboard/src/pages/settings.js @@ -1,6 +1,7 @@ import { api } from '../api.js'; import { store } from '../store.js'; import { renderShell } from '../components/shell.js'; +import { posthog } from '../main.js'; export async function renderSettings() { renderShell('settings'); @@ -83,21 +84,25 @@ export async function renderSettings() { // Theme document.getElementById('theme-select').addEventListener('change', async (e) => { await api.updateSettings({ theme: e.target.value }); + posthog.capture('settings_updated', { setting: 'theme', value: e.target.value }); document.body.dataset.theme = e.target.value; }); // Notifications document.getElementById('email-notif').addEventListener('change', async (e) => { await api.updateSettings({ emailNotifications: e.target.checked }); + posthog.capture('settings_updated', { setting: 'email_notifications', value: e.target.checked }); }); document.getElementById('weekly-digest').addEventListener('change', async (e) => { await api.updateSettings({ weeklyDigest: e.target.checked }); + posthog.capture('settings_updated', { setting: 'weekly_digest', value: e.target.checked }); }); // Reset document.getElementById('reset-data-btn').addEventListener('click', () => { if (confirm('Reset all data to defaults? This cannot be undone.')) { + posthog.capture('data_reset'); store.reset(); store.login(user.email); renderSettings();