diff --git a/apps/basic-integration/sveltekit/CMSaasStarter/.claude/skills/integration-sveltekit/.posthog-wizard b/apps/basic-integration/sveltekit/CMSaasStarter/.claude/skills/integration-sveltekit/.posthog-wizard new file mode 100644 index 000000000..e69de29bb diff --git a/apps/basic-integration/sveltekit/CMSaasStarter/.claude/skills/integration-sveltekit/references/identify-users.md b/apps/basic-integration/sveltekit/CMSaasStarter/.claude/skills/integration-sveltekit/references/identify-users.md new file mode 100644 index 000000000..8647dcb37 --- /dev/null +++ b/apps/basic-integration/sveltekit/CMSaasStarter/.claude/skills/integration-sveltekit/references/identify-users.md @@ -0,0 +1,307 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Identify users - Docs + +Copy page + +# 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/usage.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/usage.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. + +#### Identify users when the web SDK loads + +If your app already knows the signed-in user when you initialize the JavaScript web SDK, the [`loaded` callback](/docs/libraries/js/config.md) is a convenient place to call `identify`. This identifies the user as soon as the SDK has loaded: + +Web + +PostHog AI + +```javascript +posthog.init('', { + api_host: 'https://us.i.posthog.com', + defaults: '2026-05-30', + loaded: (posthog) => { + if (currentUser?.id) { + posthog.identify(currentUser.id, { + email: currentUser.email, + name: currentUser.name, + }) + } + }, +}) +``` + +In this example, `currentUser` represents user data already available from your authentication system. If your app loads the user asynchronously, call `posthog.identify()` as soon as that data becomes available instead. + +### 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. + +**\`$set\` and \`$set\_once\` aren't stored on events** + +These properties only tell PostHog how to update person data during ingestion — they aren't kept on the stored event, so you can't filter, break down, or query events by them. To query the values you set, use [person properties](/docs/product-analytics/person-properties.md) instead. + +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/usage.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/usage.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) + +### Still have questions? + +Ask PostHog AI + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/sveltekit/CMSaasStarter/.claude/skills/integration-sveltekit/references/svelte.md b/apps/basic-integration/sveltekit/CMSaasStarter/.claude/skills/integration-sveltekit/references/svelte.md new file mode 100644 index 000000000..8cda817ae --- /dev/null +++ b/apps/basic-integration/sveltekit/CMSaasStarter/.claude/skills/integration-sveltekit/references/svelte.md @@ -0,0 +1,278 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Svelte - Docs + +Copy page + +# Svelte - Docs + +PostHog makes it easy to get data about traffic and usage of your [Svelte](https://svelte.dev/) app. Integrating PostHog into your site enables analytics about user behavior, custom events capture, session recordings, feature flags, and more. + +This guide walks you through integrating PostHog into your SvelteKit app using the [JavaScript Web](/docs/libraries/js.md) and [Node.js](/docs/libraries/node.md) SDKs. + +## Beta: integration via LLM + +Install PostHog for Svelte in seconds with our wizard by running this prompt with [LLM coding agents](/blog/envoy-wizard-llm-agent.md) like Cursor and Bolt, or by running it in your terminal. + +`npx @posthog/wizard` + +[Learn more](/wizard.md) + +Or, to integrate manually, continue with the rest of this guide. + +## Client-side setup + +Install `posthog-js` using your package manager: + +PostHog AI + +### npm + +```bash +npm install --save posthog-js +``` + +### Yarn + +```bash +yarn add posthog-js +``` + +### pnpm + +```bash +pnpm add posthog-js +``` + +### Bun + +```bash +bun add posthog-js +``` + +> **If your site sets a Content-Security-Policy**, it needs to allow PostHog. This applies to the snippet and to package installs alike: the SDK lazy-loads extra bundles (session replay, surveys) from PostHog's CDN, and sends events to the ingestion host. PostHog serves from subdomains of `posthog.com` that change over time, so allow the wildcard: +> +> PostHog AI +> +> ``` +> script-src 'self' https://*.posthog.com; +> connect-src 'self' https://*.posthog.com; +> worker-src 'self' blob: data:; +> ``` +> +> `script-src` covers the snippet and the lazy-loaded bundles, `connect-src` covers event ingestion and feature flags, and `worker-src` covers session replay. The [toolbar needs a few more](/docs/advanced/content-security-policy.md), or use a [reverse proxy](/docs/advanced/proxy.md) so everything is first-party. Failing to do so causes silent failures where `capture` and `identify` calls never send, so the integration looks complete while zero events arrive. Remember `connect-src` falls back to `default-src`, so `default-src 'self'` blocks event delivery even when the script itself is bundled. + +Then, if you haven't created a root [layout](https://kit.svelte.dev/docs/routing#layout) already, create a new file called `+layout.js` in your `src/routes` folder In this file, check the environment is the browser, and initialize PostHog if so. You can get both your API key and instance address in your [project settings](https://us.posthog.com/project/settings). + +routes/+layout.js + +PostHog AI + +```javascript +import posthog from 'posthog-js' +import { browser } from '$app/environment'; +export const load = async () => { + if (browser) { + posthog.init('', { + api_host: 'https://us.i.posthog.com', + defaults: '2026-05-30', + }) + } + return +}; +``` + +## 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. +> +> Use a stable ID from your auth system when possible, not an email or display name. Send those as person properties instead. If your app has no other stable key, email works as a fallback if they are unique. Never a shared literal like `"anonymous"` or `"user"`, which pools many people onto one person and corrupts their data. When no ID is available at all, skip the identify and retain the anonymous distinct ID that's automatically assigned. +> +> Call `posthog.reset()` on logout, so the next person to use the browser doesn't inherit the last one's identity. +> +> See our guide on [identifying users](/docs/getting-started/identify-users.md) for how to set this up. + +If your app calls your own backend, `tracing_headers` adds `X-POSTHOG-DISTINCT-ID` and `X-POSTHOG-SESSION-ID` to matching `fetch` and `XMLHttpRequest` requests. This lets server-side SDKs link backend events, errors, and LLM traces back to frontend sessions and replays. Use hostnames only, without protocols or paths. + +JavaScript + +PostHog AI + +```javascript +posthog.init('', { + api_host: 'https://us.i.posthog.com', + // Optional: send PostHog session/user context to your backend + tracing_headers: ['api.example.com'], +}) +``` + +This works in local development too, but match on the hostname alone: use `'localhost'`, not `'localhost:3000'`. Ports are never part of a hostname, so a value with one in it never matches anything. `localhost` and `127.0.0.1` are also different hostnames — use whichever your app actually calls. + +Tracing headers help you attribute events across front and backend consistently. When this isn't available, use your server-side stable IDs to deduce the matching `distinctId`, and pass it in when capturing the event. + +> ❗️ If you intend on using session replays with a server-side rendered Svelte app ensure that your [asset URLs are configured to be relative](/docs/session-replay/troubleshooting.md#ensure-assets-are-imported-from-the-base-URL-in-Svelte). + +Set up a reverse proxy (recommended) + +We recommend [setting up a reverse proxy](/docs/advanced/proxy.md), so that events are less likely to be intercepted by tracking blockers. + +We have our [own managed reverse proxy service](/docs/advanced/proxy/managed-reverse-proxy.md), which is free for all PostHog Cloud users, routes through our infrastructure, and makes setting up your proxy easy. + +If you don't want to use our managed service then there are several other options for creating a reverse proxy, including using [Cloudflare](/docs/advanced/proxy/cloudflare.md), [AWS Cloudfront](/docs/advanced/proxy/cloudfront.md), and [Vercel](/docs/advanced/proxy/vercel.md). + +Grouping products in one project (recommended) + +If you have multiple customer-facing products (e.g. a marketing website + mobile app + web app), it's best to install PostHog on them all and [group them in one project](/docs/settings/projects.md). + +This makes it possible to track users across their entire journey (e.g. from visiting your marketing website to signing up for your product), or how they use your product across multiple platforms. + +Add IPs to Firewall/WAF allowlists (recommended) + +For certain features like [heatmaps](/docs/toolbar/heatmaps.md), your Web Application Firewall (WAF) may be blocking PostHog's requests to your site. Add these IP addresses to your WAF allowlist or rules to let PostHog access your site. + +**EU**: `3.75.65.221`, `18.197.246.42`, `3.120.223.253` + +**US**: `44.205.89.55`, `52.4.194.122`, `44.208.188.173` + +These are public, stable IPs used by PostHog services. + +PostHog captures heatmap screenshots using [Browserless](https://www.browserless.io), which has its own IP addresses. Browserless [publishes the current list here](https://docs.browserless.io/baas/troubleshooting/whitelisting-ips). + +An allowlist does not help when your app has a private address. For apps on an internal network, see [internal and intranet applications](/docs/session-replay/troubleshooting.md#internal-and-intranet-applications). + +## Server-side setup + +Install `posthog-node` using your package manager: + +PostHog AI + +### npm + +```bash +npm install posthog-node --save +``` + +### Yarn + +```bash +yarn add posthog-node +``` + +### pnpm + +```bash +pnpm add posthog-node +``` + +### Bun + +```bash +bun add posthog-node +``` + +Then, initialize the PostHog Node client where you'd like to use it on the server side. For example, in a [load function](https://kit.svelte.dev/docs/load#page-data): + +routes/+page.server.js + +PostHog AI + +```javascript +import { PostHog } from 'posthog-node'; +export async function load() { + const posthog = new PostHog('', { host: 'https://us.i.posthog.com' }); + posthog.capture({ + distinctId: 'distinct_id_of_the_user', + event: 'event_name', + }) + await posthog.shutdown() +} +``` + +> **Note:** Make sure to always call `posthog.shutdown()` after capturing events from the server-side. PostHog queues events into larger batches, and this call forces all batched events to be flushed immediately. + +## Feature flags + +To use client-side feature flags, import PostHog into your Svelte component and check if the feature is enabled (while ensuring the code only runs in the browser). + +routes/+page.svelte + +PostHog AI + +```javascript + +{#if coolFeature} +

Welcome to the cool feature!

+{/if} +``` + +To use server-side feature flags, import PostHog into your SvelteKit `load` function and check if the feature is enabled. + +routes/+page.server.js + +PostHog AI + +```javascript +import { PostHog } from 'posthog-node'; +const client = new PostHog( + '', + { host: 'https://us.i.posthog.com' } +); +export async function load() { + const distinctId = 'distinct_id_of_the_user'; + const megaFeature = await client.isFeatureEnabled( + 'mega-feature', + distinctId + ); + return { + megaFeature + }; +} +``` + +See our [JavaScript Web](/docs/libraries/js/usage.md#feature-flags) and [Node](/docs/libraries/node.md#feature-flags) docs for more details. + +## Configuring session replay for server-side rendered apps + +By default, [Svelte uses relative asset paths](https://kit.svelte.dev/docs/configuration) during server-side rending. This causes issues with PostHog's ability to record sessions. + +To fix this, set the config to not use relative paths in `svelte.config.js`: + +JavaScript + +PostHog AI + +```javascript +kit: { + paths: { + relative: false, + }, + }, +``` + +## Next steps + +For any technical questions for how to integrate specific PostHog features into Svelte (such as analytics, feature flags, A/B testing, surveys, etc.), have a look at our [JavaScript Web](/docs/libraries/js/usage.md) and [Node](/docs/libraries/node.md) SDK docs. + +Alternatively, the following tutorials can help you get started: + +- [How to set up Svelte analytics, feature flags, and more](/tutorials/svelte-analytics.md) +- [How to set up A/B tests in Svelte](/tutorials/svelte-ab-tests.md) +- [How to set up surveys in Svelte](/tutorials/svelte-surveys.md) + +### Still have questions? + +Ask PostHog AI + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/sveltekit/CMSaasStarter/.env.example b/apps/basic-integration/sveltekit/CMSaasStarter/.env.example index 04e92240a..fd0e79cc3 100644 --- a/apps/basic-integration/sveltekit/CMSaasStarter/.env.example +++ b/apps/basic-integration/sveltekit/CMSaasStarter/.env.example @@ -6,6 +6,10 @@ PRIVATE_SUPABASE_SERVICE_ROLE='REPLACE_ME' # Stripe settings PRIVATE_STRIPE_API_KEY='REPLACE_ME' +# PostHog analytics settings +PUBLIC_POSTHOG_PROJECT_TOKEN='your_posthog_project_token_here' +PUBLIC_POSTHOG_HOST='https://us.i.posthog.com' + # Optional - settings for email # Email address admin messages will be sent to diff --git a/apps/basic-integration/sveltekit/CMSaasStarter/package-lock.json b/apps/basic-integration/sveltekit/CMSaasStarter/package-lock.json index 04d318971..f3c995d92 100644 --- a/apps/basic-integration/sveltekit/CMSaasStarter/package-lock.json +++ b/apps/basic-integration/sveltekit/CMSaasStarter/package-lock.json @@ -13,6 +13,7 @@ "@supabase/ssr": "^0.5.2", "@supabase/supabase-js": "^2.45.2", "handlebars": "^4.7.8", + "posthog-js": "^1.419.0", "resend": "^3.5.0", "stripe": "^13.3.0" }, @@ -800,6 +801,31 @@ "dev": true, "license": "MIT" }, + "node_modules/@posthog/browser-common": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/@posthog/browser-common/-/browser-common-0.5.2.tgz", + "integrity": "sha512-8GvfEshFdeKIccuy3kpp6mDBxawQtRamMYRCwzy1r1ixLKQVLAGs3afhOf6r75yp59ZQBi5mtXQgUJ2Jz8eHuw==", + "license": "MIT", + "dependencies": { + "@posthog/core": "^1.48.11", + "@posthog/types": "^1.405.3" + } + }, + "node_modules/@posthog/core": { + "version": "1.48.11", + "resolved": "https://registry.npmjs.org/@posthog/core/-/core-1.48.11.tgz", + "integrity": "sha512-fvKbxGaUM8RuCDB1jdhSqAHYjk42INfJDWT1KVezn74sCrfnr1YaUafxzmcS+87D5FzbA2tu7IT0GQRV2WkkRg==", + "license": "MIT", + "dependencies": { + "@posthog/types": "^1.405.3" + } + }, + "node_modules/@posthog/types": { + "version": "1.406.0", + "resolved": "https://registry.npmjs.org/@posthog/types/-/types-1.406.0.tgz", + "integrity": "sha512-JR00vHgZjqWA+d+HwOdGJ/dsWFcQwnnsNiq9SC9HsQK8woefW1jrhiz0top26oxn/y5MsgfKpxtrQYeG2QocIQ==", + "license": "MIT" + }, "node_modules/@react-email/render": { "version": "0.0.16", "resolved": "https://registry.npmjs.org/@react-email/render/-/render-0.0.16.tgz", @@ -1214,7 +1240,6 @@ "resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.90.1.tgz", "integrity": "sha512-U8KaKGLUgTIFHtwEW1dgw1gK7XrdpvvYo7nzzqPx721GqPe8WZbAiLh/hmyKLGBYQ/mmQNr20vU9tWSDZpii3w==", "license": "MIT", - "peer": true, "dependencies": { "@supabase/auth-js": "2.90.1", "@supabase/functions-js": "2.90.1", @@ -1255,7 +1280,6 @@ "integrity": "sha512-dCYqelr2RVnWUuxc+Dk/dB/SjV/8JBndp1UovCyCZdIQezd8TRwFLNZctYkzgHxRJtaNvseCSRsuuHPeUgIN/A==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@standard-schema/spec": "^1.0.0", "@sveltejs/acorn-typescript": "^1.0.5", @@ -1299,7 +1323,6 @@ "integrity": "sha512-MCFS6CrQDu1yGwspm4qtli0e63vaPCehf6V7pIMP15AsWgMKrqDGCPFF/0kn4SP0ii4aySu4Pa62+fIRGFMjgw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@sveltejs/vite-plugin-svelte-inspector": "^4.0.1", "debug": "^4.4.0", @@ -1682,6 +1705,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/@types/ws": { "version": "8.18.1", "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", @@ -1733,7 +1763,6 @@ "integrity": "sha512-tbsV1jPne5CkFQCgPBcDOt30ItF7aJoZL997JSF7MhGQqOeT3svWRYxiqlfA5RUdlHN6Fi+EI9bxqbdyAUZjYQ==", "dev": true, "license": "BSD-2-Clause", - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "6.21.0", "@typescript-eslint/types": "6.21.0", @@ -2024,7 +2053,6 @@ "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.14.1.tgz", "integrity": "sha512-OvQ/2pUDKmgfCg++xsTX1wGxfTaszcHVcTctW4UJB4hibJx2HXxxO5UmVgyjMa+ZDsiaf5wWLXYpRWMmBI0QHg==", "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -2515,6 +2543,20 @@ "node": ">= 0.6" } }, + "node_modules/core-js": { + "version": "3.50.0", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.50.0.tgz", + "integrity": "sha512-BRWgOLKkFeCgRudR6zrs8p9XJZcE14grzKMMssoYrk6krtuEZ7MTKPIY5RzOnqsEKIR9kst7wNzphttraT+Yqw==", + "hasInstallScript": true, + "license": "MIT", + "engines": { + "node": "*" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -2798,6 +2840,15 @@ "url": "https://github.com/fb55/domhandler?sponsor=1" } }, + "node_modules/dompurify": { + "version": "3.4.14", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.14.tgz", + "integrity": "sha512-dVoH9z+MY+C9IilgGCk3YfFqjLi3fChm2OiKJMzh6axrJ5qwxqWaZamgmHrpv22CN/KdbZJuGEGgfQoL00LTdg==", + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, "node_modules/domutils": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.1.0.tgz", @@ -3011,7 +3062,6 @@ "deprecated": "This version is no longer supported. Please see https://eslint.org/version-support for other options.", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", @@ -3378,6 +3428,12 @@ "reusify": "^1.0.4" } }, + "node_modules/fflate": { + "version": "0.4.9", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.4.9.tgz", + "integrity": "sha512-zdxgIEddhfsyCaWpJ2SdXEP8ZMrKJ6+5jl4OupODcywU0IhRk6gdXuVGcPICyfx2H97hVK7xmJtRLPjkxAX8Vw==", + "license": "MIT" + }, "node_modules/file-entry-cache": { "version": "6.0.1", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-6.0.1.tgz", @@ -4042,7 +4098,8 @@ "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/js-yaml": { "version": "4.1.1", @@ -4500,6 +4557,7 @@ "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", "license": "MIT", + "peer": true, "dependencies": { "js-tokens": "^3.0.0 || ^4.0.0" }, @@ -4938,7 +4996,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "nanoid": "^3.3.8", "picocolors": "^1.1.1", @@ -5046,6 +5103,42 @@ "node": ">=4" } }, + "node_modules/posthog-js": { + "version": "1.419.0", + "resolved": "https://registry.npmjs.org/posthog-js/-/posthog-js-1.419.0.tgz", + "integrity": "sha512-twFNo9cO2W6zwBc2u690GIpsZ9c11nG2lhLFW3PjFEO1Mlxgmkh6aEdON2/D/VSvCnx1geYt6r8yiSo2yzG6Fg==", + "license": "(Apache-2.0 AND MIT)", + "dependencies": { + "@posthog/browser-common": "^0.5.2", + "@posthog/core": "^1.48.11", + "@posthog/types": "^1.406.0", + "core-js": "^3.49.0", + "dompurify": "^3.4.13", + "fflate": "^0.4.8", + "preact": "^10.29.3", + "query-selector-shadow-dom": "^1.0.1", + "web-vitals": "^5.3.0", + "web-vitals-soft-navs": "npm:web-vitals@6.0.0" + } + }, + "node_modules/preact": { + "version": "10.29.8", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.29.8.tgz", + "integrity": "sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + }, + "peerDependencies": { + "preact-render-to-string": ">=5" + }, + "peerDependenciesMeta": { + "preact-render-to-string": { + "optional": true + } + } + }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", @@ -5062,7 +5155,6 @@ "integrity": "sha512-e9MewbtFo+Fevyuxn/4rrcDAaq0IYxPGLvObpQjiZBMAzB9IGmzlnG9RZy3FFas+eBMu2vA0CszMeduow5dIuQ==", "dev": true, "license": "MIT", - "peer": true, "bin": { "prettier": "bin/prettier.cjs" }, @@ -5128,6 +5220,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "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/querystringify": { "version": "2.2.0", "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", @@ -5433,6 +5531,7 @@ "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz", "integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==", "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0" } @@ -5810,7 +5909,6 @@ "resolved": "https://registry.npmjs.org/svelte/-/svelte-5.14.0.tgz", "integrity": "sha512-xHrS9dd2Ci9GJd2sReNFqJztoe515wB4OzsPw4A8L2M6lddLFkREkWDJnM5DAND30Zyvjwc1icQVzH0F+Sdx5A==", "license": "MIT", - "peer": true, "dependencies": { "@ampproject/remapping": "^2.3.0", "@jridgewell/sourcemap-codec": "^1.5.0", @@ -5945,8 +6043,7 @@ "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.0.9.tgz", "integrity": "sha512-12laZu+fv1ONDRoNR9ipTOpUD7RN9essRVkX36sjxuRUInpN7hIiHN4lBd/SIFjbISvnXzp8h/hXzmU8SQQYhw==", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/tapable": { "version": "2.2.1", @@ -6017,7 +6114,6 @@ "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -6145,7 +6241,6 @@ "integrity": "sha512-i5t66RHxDvVN40HfDd1PsEThGNnlMCMT3jMUuoh9/0TaqWevNontacunWyN02LA9/fIbEWlcHZcgTKb9QoaLfg==", "dev": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -6227,7 +6322,6 @@ "integrity": "sha512-+Oxm7q9hDoLMyJOYfUYBuHQo+dkAloi33apOPP56pzj+vsdJDzr+j1NISE5pyaAuKL4A3UD34qd0lx5+kfKp2g==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "esbuild": "^0.25.0", "fdir": "^6.4.4", @@ -6341,7 +6435,6 @@ "integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -6451,6 +6544,19 @@ "node": ">=18" } }, + "node_modules/web-vitals": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-5.3.0.tgz", + "integrity": "sha512-q6LWsLatGYZp5VGBIOvbTj6JBV2nOmC8KvWztXBmwJcfFAzhwKwbOxhUH306XY3CcaZDUlSmSuNPBsCn0bFu+g==", + "license": "Apache-2.0" + }, + "node_modules/web-vitals-soft-navs": { + "name": "web-vitals", + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-6.0.0.tgz", + "integrity": "sha512-Guaibvy/+uNtL6Bsu4jmMJGzuSl91oeRH5iO9pPRbYftnFUr3yqT1TUNX/OE4o9HexuEMU3Kb/Wg7iKhlffZUA==", + "license": "Apache-2.0" + }, "node_modules/webidl-conversions": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz", diff --git a/apps/basic-integration/sveltekit/CMSaasStarter/package.json b/apps/basic-integration/sveltekit/CMSaasStarter/package.json index be50d6ac6..7b092e690 100644 --- a/apps/basic-integration/sveltekit/CMSaasStarter/package.json +++ b/apps/basic-integration/sveltekit/CMSaasStarter/package.json @@ -51,6 +51,7 @@ "@supabase/ssr": "^0.5.2", "@supabase/supabase-js": "^2.45.2", "handlebars": "^4.7.8", + "posthog-js": "^1.419.0", "resend": "^3.5.0", "stripe": "^13.3.0" }, diff --git a/apps/basic-integration/sveltekit/CMSaasStarter/src/hooks.client.ts b/apps/basic-integration/sveltekit/CMSaasStarter/src/hooks.client.ts new file mode 100644 index 000000000..247900603 --- /dev/null +++ b/apps/basic-integration/sveltekit/CMSaasStarter/src/hooks.client.ts @@ -0,0 +1,41 @@ +import { PUBLIC_POSTHOG_HOST, PUBLIC_POSTHOG_PROJECT_TOKEN } from "$env/static/public" +import type { HandleClientError } from "@sveltejs/kit" +import posthog from "posthog-js" + +let posthogInitialized = false + +export async function init() { + if (!PUBLIC_POSTHOG_PROJECT_TOKEN) { + if (import.meta.env.DEV) { + throw new Error( + "PUBLIC_POSTHOG_PROJECT_TOKEN variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once PUBLIC_POSTHOG_PROJECT_TOKEN is configured", + ) + } + + return + } + + if (!PUBLIC_POSTHOG_HOST) { + if (import.meta.env.DEV) { + throw new Error( + "PUBLIC_POSTHOG_HOST variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once PUBLIC_POSTHOG_HOST is configured", + ) + } + + return + } + + posthog.init(PUBLIC_POSTHOG_PROJECT_TOKEN, { + api_host: PUBLIC_POSTHOG_HOST, + capture_exceptions: true, + }) + posthogInitialized = true +} + +export const handleError: HandleClientError = ({ error, status, message }) => { + if (posthogInitialized) { + posthog.captureException(error) + } + + return { message, status } +} diff --git a/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/change_email_subscription/+page.svelte b/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/change_email_subscription/+page.svelte index d5905920a..f5e8f0339 100644 --- a/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/change_email_subscription/+page.svelte +++ b/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/change_email_subscription/+page.svelte @@ -22,5 +22,6 @@ ? "You have been re-subscribed to emails" : "You have been unsubscribed from emails"} formTarget="/account/api?/toggleEmailSubscription" + analyticsEvent="email_subscription_changed" fields={[]} /> diff --git a/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/change_password/+page.svelte b/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/change_password/+page.svelte index 5337bb4e9..9e9b4de5b 100644 --- a/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/change_password/+page.svelte +++ b/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/change_password/+page.svelte @@ -2,6 +2,7 @@ import { page } from "$app/stores" import { getContext } from "svelte" import type { Writable } from "svelte/store" + import posthog from "posthog-js" import SettingsModule from "../settings_module.svelte" let adminSection: Writable = getContext("adminSection") @@ -36,6 +37,9 @@ }) .then((d) => { sentEmail = d.error ? false : true + if (!d.error) { + posthog.capture("password_reset_requested") + } sendBtnDisabled = false sendBtnText = "Send Forgot Password Email" }) @@ -57,6 +61,7 @@ successTitle="Password Changed" successBody="On next sign in, use your new password." formTarget="/account/api?/updatePassword" + analyticsEvent="password_changed" fields={[ { id: "newPassword1", diff --git a/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/delete_account/+page.svelte b/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/delete_account/+page.svelte index 0a7751f4e..773a24591 100644 --- a/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/delete_account/+page.svelte +++ b/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/delete_account/+page.svelte @@ -26,6 +26,7 @@ successTitle="Account queued for deletion" successBody="Your account will be deleted shortly." formTarget="/account/api?/deleteAccount" + analyticsEvent="account_deletion_requested" fields={[ { id: "currentPassword", diff --git a/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/edit_profile/+page.svelte b/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/edit_profile/+page.svelte index e6099d3c1..50899f20b 100644 --- a/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/edit_profile/+page.svelte +++ b/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/edit_profile/+page.svelte @@ -22,6 +22,7 @@ title="Edit Profile" successTitle="Saved Profile" formTarget="/account/api?/updateProfile" + analyticsEvent="profile_updated" fields={[ { id: "fullName", diff --git a/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/settings_module.svelte b/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/settings_module.svelte index 6b115cada..ecde48923 100644 --- a/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/settings_module.svelte +++ b/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/(menu)/settings/settings_module.svelte @@ -2,6 +2,7 @@ import { enhance, applyAction } from "$app/forms" import { page } from "$app/stores" import type { SubmitFunction } from "@sveltejs/kit" + import posthog from "posthog-js" const fieldError = (liveForm: FormAccountUpdateResult, name: string) => { let errors = liveForm?.errorFields ?? [] @@ -34,6 +35,7 @@ editButtonTitle?: string | null editLink?: string | null saveButtonTitle?: string + analyticsEvent?: string } let { @@ -48,15 +50,23 @@ editButtonTitle = null, editLink = null, saveButtonTitle = "Save", + analyticsEvent, }: Props = $props() const handleSubmit: SubmitFunction = () => { loading = true return async ({ update, result }) => { + if (result.type === "redirect" && analyticsEvent) { + posthog.capture(analyticsEvent) + } + await update({ reset: false }) await applyAction(result) loading = false if (result.type === "success") { + if (analyticsEvent) { + posthog.capture(analyticsEvent) + } showSuccess = true } } diff --git a/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/+layout.svelte b/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/+layout.svelte index 1a9259171..a816517f9 100644 --- a/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/+layout.svelte +++ b/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/+layout.svelte @@ -1,5 +1,6 @@ diff --git a/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/create_profile/+page.svelte b/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/create_profile/+page.svelte index 0a9270666..9d4baed32 100644 --- a/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/create_profile/+page.svelte +++ b/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(admin)/account/create_profile/+page.svelte @@ -1,5 +1,6 @@ diff --git a/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(marketing)/contact_us/+page.svelte b/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(marketing)/contact_us/+page.svelte index 489d5019e..c4e320408 100644 --- a/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(marketing)/contact_us/+page.svelte +++ b/apps/basic-integration/sveltekit/CMSaasStarter/src/routes/(marketing)/contact_us/+page.svelte @@ -1,5 +1,6 @@