From ce81f0c3b545f873e2bd96dac2fc8dd627f1f979 Mon Sep 17 00:00:00 2001 From: "wizard-ci-bot[bot]" <254716194+wizard-ci-bot[bot]@users.noreply.github.com> Date: Wed, 9 Sep 2026 22:12:36 +0000 Subject: [PATCH] wizard-ci: angular/angular-saas --- .../integration-angular/.posthog-wizard | 0 .../integration-angular/references/angular.md | 420 ++++++++++++++++++ .../references/identify-users.md | 307 +++++++++++++ .../angular/angular-saas/.env.example | 2 + .../angular/angular-saas/package-lock.json | 129 ++++++ .../angular/angular-saas/package.json | 1 + .../services/posthog-error-handler.service.ts | 17 + .../src/app/@core/services/posthog.service.ts | 42 ++ .../angular-saas/src/app/app.component.ts | 2 + .../angular-saas/src/app/app.config.ts | 7 +- .../src/app/auth/login/login.component.ts | 3 + .../src/app/auth/logout/logout.component.ts | 3 + .../app/auth/services/credentials.service.ts | 34 +- .../notification-settings.component.ts | 3 + .../preferences-settings.component.ts | 3 + .../security-settings.component.ts | 5 + .../add-member-modal.component.ts | 3 + .../create-project-modal.component.ts | 3 + .../src/environments/environment.prod.ts | 2 + .../src/environments/environment.ts | 2 + 20 files changed, 986 insertions(+), 2 deletions(-) create mode 100644 apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/.posthog-wizard create mode 100644 apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/angular.md create mode 100644 apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/identify-users.md create mode 100644 apps/basic-integration/angular/angular-saas/.env.example create mode 100644 apps/basic-integration/angular/angular-saas/src/app/@core/services/posthog-error-handler.service.ts create mode 100644 apps/basic-integration/angular/angular-saas/src/app/@core/services/posthog.service.ts diff --git a/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/.posthog-wizard b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/.posthog-wizard new file mode 100644 index 000000000..e69de29bb diff --git a/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/angular.md b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/angular.md new file mode 100644 index 000000000..569d7dba5 --- /dev/null +++ b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/angular.md @@ -0,0 +1,420 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Angular - Docs + +Copy page + +# Angular - Docs + +PostHog makes it easy to get data about traffic and usage of your [Angular](https://angular.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 Angular app using the [JavaScript Web SDK](/docs/libraries/js.md). + +## Installation + +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. + +### Initialize the PostHog client + +Generate environment files for your project with `ng g environments`. Configure the following environment variables: + +- `posthogKey`: Your project token from your [project settings](https://app.posthog.com/settings/project#variables). +- `posthogHost`: Your project's client API host. Usually `https://us.i.posthog.com` for US-based projects and `https://eu.i.posthog.com` for EU-based projects. + +## Angular v17+ + +For Angular v17 and above, you can set up PostHog as a singleton service. To do this, start by creating and injecting a `PosthogService` instance. + +Create a service by running `ng g service services/posthog`. The service should look like this: + +posthog.service.ts + +PostHog AI + +```typescript +// src/app/services/posthog.service.ts +import { Injectable, NgZone } from "@angular/core"; +import posthog from "posthog-js"; +import { environment } from "../../environments/environment"; +@Injectable({ providedIn: "root" }) +export class PosthogService { + constructor( + private ngZone: NgZone, + ) { + this.initPostHog(); + } + private initPostHog() { + this.ngZone.runOutsideAngular(() => { + posthog.init(environment.posthogKey, { + api_host: environment.posthogHost, + defaults: '2026-05-30', + }); + }); + } +} +``` + +The service is initialized [outside of the Angular zone](https://angular.dev/api/core/NgZone#runOutsideAngular) to reduce change detection cycles. This is important to avoid performance issues with session recording. + +Then, inject the service in your app's root component `app.component.ts`. This will make sure PostHog is initialized before any other component is rendered. + +app.component.ts + +PostHog AI + +```typescript +// src/app/app.component.ts +import { Component } from "@angular/core"; +import { RouterOutlet } from "@angular/router"; +import { PosthogService } from "./services/posthog.service"; +@Component({ + selector: "app-root", + styleUrls: ["./app.component.scss"], + template: ` + `, + imports: [RouterOutlet], +}) +export class AppComponent { + title = "angular-app"; + constructor(posthogService: PosthogService) {} +} +``` + +## Angular v16 and below + +In your `src/main.ts`, initialize PostHog using your project token and instance address. You can find both in your [project settings](https://us.posthog.com/project/settings). + +main.ts + +PostHog AI + +```typescript +// src/main.ts +import { bootstrapApplication } from '@angular/platform-browser'; +import { appConfig } from './app/app.config'; +import { AppComponent } from './app/app.component'; +import { environment } from "./environments/environment"; +import posthog from 'posthog-js' +posthog.init(environment.posthogKey, { + api_host: environment.posthogHost, + defaults: '2026-05-30' +}) +bootstrapApplication(AppComponent, appConfig) + .catch((err) => console.error(err)); +``` + +## 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. + +> **Note:** If you're using Typescript, you might have some trouble getting your types to compile because we depend on `rrweb` but don't ship all of their types. To accommodate that, you'll need to add `@rrweb/types@2.0.0-alpha.17` and `rrweb-snapshot@2.0.0-alpha.17` as a dependency if you want your Angular compiler to typecheck correctly. +> +> Given the nature of this library, you might need to completely clear your `.npm` cache to get this to work as expected. Make sure your clear your CI's cache as well. +> +> In the rare case the versions above get out-of-date, you can check our [JavaScript SDK's `package.json`](https://github.com/PostHog/posthog-js/blob/main/package.json) to understand what's the exact version you need to depend on. + +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). + +## Tracking pageviews + +PostHog automatically tracks your pageviews by hooking up to the browser's `navigator` API as long as you initialize PostHog with the `defaults` config option set after `2026-01-30`. + +## Capture custom events + +To [capture custom events](/docs/product-analytics/capture-events.md), import `posthog` and call `posthog.capture()`. Below is an example of how to do this in a component: + +app.component.ts + +PostHog AI + +```typescript +import { Component } from '@angular/core'; +import posthog from 'posthog-js' +@Component({ + // existing component code +}) +export class AppComponent { + handleClick() { + posthog.capture( + 'home_button_clicked', + ) + } +} +``` + +## Session replay + +Session replay uses change detection to record the DOM. This can clash with Angular's change detection. + +The recorder tool attempts to detect when an Angular zone is present and avoid the clash but might not always succeed. + +- If you followed the installation instructions for Angular v17 and above, you don't need to do anything. +- If you followed the installation instructions for Angular v16 and below and you see performance impact from recording in an Angular project, ensure that you use [`ngZone.runOutsideAngular`](https://angular.io/api/core/NgZone#runoutsideangular). + +posthog.service.ts + +PostHog AI + +```typescript +import { Injectable } from '@angular/core'; +import posthog from 'posthog-js' +@Injectable({ providedIn: 'root' }) +export class PostHogSessionRecordingService { + constructor(private ngZone: NgZone) {} +initPostHog() { + this.ngZone.runOutsideAngular(() => { + posthog.init( + /* your config */ + ) + }) + } +} +``` + +## Angular with SSR + +To use PostHog with Angular server-side rendering (SSR), you need to: + +1. Update the PostHog web JS client to only initialize on the client-side. +2. Initialize PostHog Node on the server-side. + +### 1\. Update the PostHog web JS client + +Update your `posthog.service.ts` to restrict the initialization of the PostHog web JS client to the client-side. The web SDK uses methods that are not available on the server side, so we need to check if we're on the client side before initializing PostHog. + +posthog.service.ts + +PostHog AI + +```typescript +import { PLATFORM_ID } from "@angular/core"; +@Injectable({ providedIn: "root" }) +export class PosthogService { + constructor( + private ngZone: NgZone, + @Inject(PLATFORM_ID) private platformId: Object + ) { + // Only initialize PostHog in browser environment + if (isPlatformBrowser(this.platformId)) { + this.initPostHog(); //+ + } + } + private initPostHog() { + this.ngZone.runOutsideAngular(() => { + posthog.init(environment.posthogKey, { +``` + +### 2\. Add server-side initialization + +Angular SSR uses a `server.ts` file to handle requests. We can add any server-side initialization code to this file. + +First, install the `posthog-node` package to run on the server side. + +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, add the following code to the `server.ts` file: + +server.ts + +PostHog AI + +```typescript +// src/server.ts +import { environment } from './environments/environment'; +import { PostHog } from 'posthog-node' +/** + * Extract distinct ID from PostHog cookie + */ +function getDistinctIdFromCookie(cookieHeader: string | undefined): string | null { + if (!cookieHeader) return null; + const cookieMatch = cookieHeader.match(`ph_${environment.posthogKey}_posthog=([^;]+)`); + if (cookieMatch) { + try { + const parsed = JSON.parse(decodeURIComponent(cookieMatch[1])); + return parsed?.distinct_id || null; + } catch (error) { + console.error('Error parsing PostHog cookie:', error); + return null; + } + } + return null; +} +/** + * Handle all other requests by rendering the Angular application. + */ +app.get('**', async (req, res, next) => { + const { protocol, originalUrl, baseUrl, headers } = req; + const distinctId = getDistinctIdFromCookie(headers.cookie); + let isFeatureEnabled = false; + const client = new PostHog( + environment.posthogKey, + { host: environment.posthogHost } + ); + if (distinctId) { + client.capture({ + distinctId: distinctId, + event: 'test_ssr_event', + properties: { + message: 'Hello from Angular SSR!' + } + }) + isFeatureEnabled = await client.isFeatureEnabled( + 'your_feature_flag_key', distinctId) || false; + } + commonEngine + .render({ + bootstrap, + documentFilePath: indexHtml, + url: `${protocol}://${headers.host}${originalUrl}`, + publicPath: browserDistFolder, + providers: [ + { provide: APP_BASE_HREF, useValue: baseUrl }, + { provide: 'FEATURE_FLAG_ENABLED', useValue: isFeatureEnabled } + ], + }) + .then((html) => res.send(html)) + .catch((err) => next(err)); + await client.shutdown() +}); +``` + +This code does the following: + +- Extracts the distinct ID from the cookie header. This is set by the web JS client. +- Captures an event on the server side. +- Evaluates a feature flag on the server side. This can be passed as a provider to the Angular application. +- Calls `shutdown` on the PostHog Node client to ensure all events are flushed. + +**Using PostHog in server-side code** + +Angular SSR does not allow Node.js code to be bundled into client-side components. Even though resolvers and other server-side code can be written along with client-side components, you cannot use PostHog Node in those components. + +## Next steps + +For any technical questions for how to integrate specific PostHog features into Angular (such as feature flags, A/B testing, surveys, etc.), have a look at our [JavaScript Web SDK docs](/docs/libraries/js/usage.md). + +Alternatively, the following tutorials can help you get started: + +- [How to set up Angular analytics, feature flags, and more](/tutorials/angular-analytics.md) +- [How to set up A/B tests in Angular](/tutorials/angular-ab-tests.md) +- [How to set up surveys in Angular](/tutorials/angular-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/angular/angular-saas/.claude/skills/integration-angular/references/identify-users.md b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/identify-users.md new file mode 100644 index 000000000..8647dcb37 --- /dev/null +++ b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/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/angular/angular-saas/.env.example b/apps/basic-integration/angular/angular-saas/.env.example new file mode 100644 index 000000000..a38b8b2a6 --- /dev/null +++ b/apps/basic-integration/angular/angular-saas/.env.example @@ -0,0 +1,2 @@ +NG_APP_POSTHOG_PROJECT_TOKEN= +NG_APP_POSTHOG_HOST= diff --git a/apps/basic-integration/angular/angular-saas/package-lock.json b/apps/basic-integration/angular/angular-saas/package-lock.json index 3034213a2..f47579521 100644 --- a/apps/basic-integration/angular/angular-saas/package-lock.json +++ b/apps/basic-integration/angular/angular-saas/package-lock.json @@ -26,6 +26,7 @@ "bootstrap": "^5.3.0", "class-transformer": "^0.5.1", "package.json": "^2.0.1", + "posthog-js": "^1.429.0", "reflect-metadata": "^0.2.0", "rxjs": "^7.8.2", "sanitize.css": "^13.0.0", @@ -3768,6 +3769,31 @@ "url": "https://opencollective.com/popperjs" } }, + "node_modules/@posthog/browser-common": { + "version": "0.8.2", + "resolved": "https://registry.npmjs.org/@posthog/browser-common/-/browser-common-0.8.2.tgz", + "integrity": "sha512-8g7+ijrx8bfWmpDjmP07e0ZmdRnJoFqZ6PCcMQvfBTUrr422GRXvQWpQn7yD028zIJHIIn/rUTipKgUC5UkWpw==", + "license": "MIT", + "dependencies": { + "@posthog/core": "^1.51.0", + "@posthog/types": "^1.409.1" + } + }, + "node_modules/@posthog/core": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/@posthog/core/-/core-1.52.0.tgz", + "integrity": "sha512-pvbdeRRpizktmo8MXZQxjAI4aFfNajwkzxbm72wKV9n2wWcnQWa4m+AqTI2zmmCSsYk7F666rRUdvYqZLjjhWg==", + "license": "MIT", + "dependencies": { + "@posthog/types": "^1.409.4" + } + }, + "node_modules/@posthog/types": { + "version": "1.410.0", + "resolved": "https://registry.npmjs.org/@posthog/types/-/types-1.410.0.tgz", + "integrity": "sha512-741sltt/h+l0eYH+Nkow96qKfDmRxwKacfjF93Z+kMySjzL0a87ptmpklZxGkbjBp/DJH/CSowGrolYWK/1ToA==", + "license": "MIT" + }, "node_modules/@rolldown/binding-android-arm64": { "version": "1.0.0-beta.58", "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.0-beta.58.tgz", @@ -4595,6 +4621,13 @@ "undici-types": "~7.16.0" } }, + "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/@typescript-eslint/eslint-plugin": { "version": "8.54.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.54.0.tgz", @@ -5759,6 +5792,20 @@ "node": ">=6.6.0" } }, + "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/core-util-is": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", @@ -5995,6 +6042,15 @@ "url": "https://github.com/fb55/domhandler?sponsor=1" } }, + "node_modules/dompurify": { + "version": "3.4.15", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.15.tgz", + "integrity": "sha512-EUBjM+B+lkDE41iE82DDSCfkoPGfXx8IxFxPMjNzm/Uk4xDet77rTN9wqlxlVg71kK7XGuUMv6wUxJUwwv+Xyw==", + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, "node_modules/domutils": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", @@ -6798,6 +6854,12 @@ } } }, + "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": "8.0.0", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", @@ -10030,6 +10092,54 @@ "dev": true, "license": "MIT" }, + "node_modules/posthog-js": { + "version": "1.429.0", + "resolved": "https://registry.npmjs.org/posthog-js/-/posthog-js-1.429.0.tgz", + "integrity": "sha512-a6OTvuAqfq4vE8Y9GKcoYdvxmIcVISDMNzICju6d9tXS8AQW0/Bwm/F0EICrHLC8CDnVHDe1EWO6p3uyNTpi+g==", + "license": "(Apache-2.0 AND MIT)", + "dependencies": { + "@posthog/browser-common": "^0.8.2", + "@posthog/core": "^1.52.0", + "@posthog/types": "^1.410.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": "^6.2.1", + "web-vitals-soft-navs": "npm:web-vitals@6.2.1" + }, + "peerDependencies": { + "@types/react": ">=16.8.0", + "react": ">=16.8.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "react": { + "optional": true + } + } + }, + "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", @@ -10132,6 +10242,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/r-json": { "version": "1.3.1", "resolved": "https://registry.npmjs.org/r-json/-/r-json-1.3.1.tgz", @@ -11680,6 +11796,19 @@ "license": "MIT", "optional": true }, + "node_modules/web-vitals": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-6.2.1.tgz", + "integrity": "sha512-rLcLXA2sx6+9dE88NHFubwTtGxpK4yYBLj6qHPdFoCaLr0cXGb4efOqtKLlm4loGA4OEKHIQKMKzZkKyOh5ctw==", + "license": "Apache-2.0" + }, + "node_modules/web-vitals-soft-navs": { + "name": "web-vitals", + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-6.2.1.tgz", + "integrity": "sha512-rLcLXA2sx6+9dE88NHFubwTtGxpK4yYBLj6qHPdFoCaLr0cXGb4efOqtKLlm4loGA4OEKHIQKMKzZkKyOh5ctw==", + "license": "Apache-2.0" + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", diff --git a/apps/basic-integration/angular/angular-saas/package.json b/apps/basic-integration/angular/angular-saas/package.json index f5499e313..611c90402 100644 --- a/apps/basic-integration/angular/angular-saas/package.json +++ b/apps/basic-integration/angular/angular-saas/package.json @@ -29,6 +29,7 @@ "bootstrap": "^5.3.0", "class-transformer": "^0.5.1", "package.json": "^2.0.1", + "posthog-js": "^1.429.0", "reflect-metadata": "^0.2.0", "rxjs": "^7.8.2", "sanitize.css": "^13.0.0", diff --git a/apps/basic-integration/angular/angular-saas/src/app/@core/services/posthog-error-handler.service.ts b/apps/basic-integration/angular/angular-saas/src/app/@core/services/posthog-error-handler.service.ts new file mode 100644 index 000000000..ded20316a --- /dev/null +++ b/apps/basic-integration/angular/angular-saas/src/app/@core/services/posthog-error-handler.service.ts @@ -0,0 +1,17 @@ +import { ErrorHandler, Injectable, inject } from '@angular/core'; + +import { PosthogService } from './posthog.service'; + +@Injectable({ + providedIn: 'root', +}) +export class PosthogErrorHandler implements ErrorHandler { + private readonly posthogService = inject(PosthogService); + + handleError(error: unknown): void { + const exception = error instanceof Error ? error : new Error(String(error)); + + this.posthogService.client?.captureException(exception); + console.error(error); + } +} diff --git a/apps/basic-integration/angular/angular-saas/src/app/@core/services/posthog.service.ts b/apps/basic-integration/angular/angular-saas/src/app/@core/services/posthog.service.ts new file mode 100644 index 000000000..b788c0d37 --- /dev/null +++ b/apps/basic-integration/angular/angular-saas/src/app/@core/services/posthog.service.ts @@ -0,0 +1,42 @@ +import { Injectable, NgZone, inject } from '@angular/core'; +import posthog from 'posthog-js'; + +import { environment } from '@env/environment'; + +@Injectable({ + providedIn: 'root', +}) +export class PosthogService { + private readonly ngZone = inject(NgZone); + private initialized = false; + + constructor() { + this.init(); + } + + get client(): typeof posthog | undefined { + return this.initialized ? posthog : undefined; + } + + private init(): void { + const { posthogKey, posthogHost } = environment; + + if (!posthogKey || !posthogHost) { + if (!environment.production) { + const missingVariable = posthogKey ? 'NG_APP_POSTHOG_HOST' : 'NG_APP_POSTHOG_PROJECT_TOKEN'; + throw new Error( + `${missingVariable} variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once ${missingVariable} is configured`, + ); + } + return; + } + + this.ngZone.runOutsideAngular(() => { + posthog.init(posthogKey, { + api_host: posthogHost, + defaults: '2026-05-30', + }); + this.initialized = true; + }); + } +} diff --git a/apps/basic-integration/angular/angular-saas/src/app/app.component.ts b/apps/basic-integration/angular/angular-saas/src/app/app.component.ts index 28502f976..9d9583ee6 100644 --- a/apps/basic-integration/angular/angular-saas/src/app/app.component.ts +++ b/apps/basic-integration/angular/angular-saas/src/app/app.component.ts @@ -7,6 +7,7 @@ import { environment } from '@env/environment'; import { filter, merge } from 'rxjs'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { AppUpdateService, Logger } from '@core/services'; +import { PosthogService } from '@core/services/posthog.service'; import { SocketIoService } from '@core/socket-io'; @Component({ @@ -23,6 +24,7 @@ export class AppComponent implements OnInit { private readonly i18nService = inject(I18nService); private readonly socketService = inject(SocketIoService); private readonly updateService = inject(AppUpdateService); + private readonly posthogService = inject(PosthogService); private readonly destroyRef = inject(DestroyRef); title = 'angular-boilerplate'; diff --git a/apps/basic-integration/angular/angular-saas/src/app/app.config.ts b/apps/basic-integration/angular/angular-saas/src/app/app.config.ts index 65552a4de..43ecc7d80 100644 --- a/apps/basic-integration/angular/angular-saas/src/app/app.config.ts +++ b/apps/basic-integration/angular/angular-saas/src/app/app.config.ts @@ -1,4 +1,4 @@ -import { ApplicationConfig, enableProdMode, importProvidersFrom, provideZonelessChangeDetection } from '@angular/core'; +import { ApplicationConfig, ErrorHandler, enableProdMode, importProvidersFrom, provideZonelessChangeDetection } from '@angular/core'; import { PreloadAllModules, provideRouter, RouteReuseStrategy, withEnabledBlockingInitialNavigation, withInMemoryScrolling, withPreloading, withRouterConfig } from '@angular/router'; import { HTTP_INTERCEPTORS, provideHttpClient, withInterceptorsFromDi } from '@angular/common/http'; import { provideServiceWorker } from '@angular/service-worker'; @@ -9,6 +9,7 @@ import { routes } from './app.routes'; import { environment } from '@env/environment'; import { ApiPrefixInterceptor, ErrorHandlerInterceptor } from '@core/interceptors'; import { RouteReusableStrategy } from '@core/helpers'; +import { PosthogErrorHandler } from '@core/services/posthog-error-handler.service'; import { provideSocketIo } from '@core/socket-io'; if (environment.production) { @@ -18,6 +19,10 @@ if (environment.production) { export const appConfig: ApplicationConfig = { providers: [ provideZonelessChangeDetection(), + { + provide: ErrorHandler, + useExisting: PosthogErrorHandler, + }, importProvidersFrom(TranslateModule.forRoot()), diff --git a/apps/basic-integration/angular/angular-saas/src/app/auth/login/login.component.ts b/apps/basic-integration/angular/angular-saas/src/app/auth/login/login.component.ts index 2a8833ec5..978969dbe 100644 --- a/apps/basic-integration/angular/angular-saas/src/app/auth/login/login.component.ts +++ b/apps/basic-integration/angular/angular-saas/src/app/auth/login/login.component.ts @@ -4,6 +4,7 @@ import { ActivatedRoute, Router } from '@angular/router'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; import { environment } from '@env/environment'; import { AuthenticationService } from '@app/auth/services/authentication.service'; +import { PosthogService } from '@core/services/posthog.service'; @Component({ selector: 'app-login', @@ -18,6 +19,7 @@ export class LoginComponent { private readonly authService = inject(AuthenticationService); private readonly fb = inject(FormBuilder); private readonly destroyRef = inject(DestroyRef); + private readonly posthogService = inject(PosthogService); version: string | null = environment.version; @@ -39,6 +41,7 @@ export class LoginComponent { .subscribe({ next: (res) => { if (res) { + this.posthogService.client?.capture('login_succeeded'); console.log('Login successful'); this.router.navigate([this.route.snapshot.queryParams['redirect'] || '/dashboard'], { replaceUrl: true }).then(() => { console.log('Navigated to dashboard'); diff --git a/apps/basic-integration/angular/angular-saas/src/app/auth/logout/logout.component.ts b/apps/basic-integration/angular/angular-saas/src/app/auth/logout/logout.component.ts index 744105910..c5994f412 100644 --- a/apps/basic-integration/angular/angular-saas/src/app/auth/logout/logout.component.ts +++ b/apps/basic-integration/angular/angular-saas/src/app/auth/logout/logout.component.ts @@ -2,6 +2,7 @@ import { Component, OnInit, ChangeDetectionStrategy, inject } from '@angular/cor import { Router } from '@angular/router'; import { AuthenticationService } from '@app/auth/services/authentication.service'; import { CredentialsService } from '@app/auth/services/credentials.service'; +import { PosthogService } from '@core/services/posthog.service'; @Component({ selector: 'app-logout', @@ -13,6 +14,7 @@ export class LogoutComponent implements OnInit { private readonly authService = inject(AuthenticationService); private readonly router = inject(Router); private readonly credentialsService = inject(CredentialsService); + private readonly posthogService = inject(PosthogService); ngOnInit() { if (!this.credentialsService.isAuthenticated()) { @@ -23,6 +25,7 @@ export class LogoutComponent implements OnInit { } else { this.authService.logout().subscribe({ next: () => { + this.posthogService.client?.capture('logout_completed'); this.credentialsService.setCredentials(); this.router.navigate(['/login']).then(() => { window.location.reload(); diff --git a/apps/basic-integration/angular/angular-saas/src/app/auth/services/credentials.service.ts b/apps/basic-integration/angular/angular-saas/src/app/auth/services/credentials.service.ts index b1cd019d0..cfd924dc9 100644 --- a/apps/basic-integration/angular/angular-saas/src/app/auth/services/credentials.service.ts +++ b/apps/basic-integration/angular/angular-saas/src/app/auth/services/credentials.service.ts @@ -1,5 +1,6 @@ -import { computed, Injectable, signal } from '@angular/core'; +import { computed, Injectable, inject, signal } from '@angular/core'; import { Credentials } from '@core/entities'; +import { PosthogService } from '@core/services/posthog.service'; const credentialsKey = 'credentials'; @@ -11,12 +12,18 @@ const credentialsKey = 'credentials'; providedIn: 'root', }) export class CredentialsService { + private readonly posthogService = inject(PosthogService); + /** The user credentials signal */ readonly credentials = signal(this.loadCredentials()); /** Computed signal for checking authentication status */ readonly isAuthenticated = computed(() => !!this.credentials()); + constructor() { + this.identify(this.credentials()); + } + private loadCredentials(): Credentials | null { const savedCredentials = sessionStorage.getItem(credentialsKey) || localStorage.getItem(credentialsKey); return savedCredentials ? JSON.parse(savedCredentials) : null; @@ -30,6 +37,19 @@ export class CredentialsService { * @param remember True to remember credentials across sessions. */ setCredentials(credentials?: Credentials, remember = true) { + const previousCredentials = this.credentials(); + + if (!credentials) { + if (previousCredentials) { + this.posthogService.client?.reset(); + } + } else { + if (previousCredentials && previousCredentials.id !== credentials.id) { + this.posthogService.client?.reset(); + } + this.identify(credentials); + } + this.credentials.set(credentials || null); if (credentials) { @@ -40,4 +60,16 @@ export class CredentialsService { localStorage.removeItem(credentialsKey); } } + + private identify(credentials: Credentials | null): void { + if (!credentials?.id) { + return; + } + + this.posthogService.client?.identify(credentials.id, { + email: credentials.email, + name: credentials.fullName.trim(), + role: credentials.roles[0], + }); + } } diff --git a/apps/basic-integration/angular/angular-saas/src/app/pages/settings/components/notification-settings/notification-settings.component.ts b/apps/basic-integration/angular/angular-saas/src/app/pages/settings/components/notification-settings/notification-settings.component.ts index e5c70e2fa..79b8e7bd3 100644 --- a/apps/basic-integration/angular/angular-saas/src/app/pages/settings/components/notification-settings/notification-settings.component.ts +++ b/apps/basic-integration/angular/angular-saas/src/app/pages/settings/components/notification-settings/notification-settings.component.ts @@ -1,6 +1,7 @@ import { Component, inject, ChangeDetectionStrategy, signal } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HotToastService } from '@ngxpert/hot-toast'; +import { PosthogService } from '@core/services/posthog.service'; interface NotificationSettings { productUpdates: boolean; @@ -210,6 +211,7 @@ interface NotificationSettings { }) export class NotificationSettingsComponent { private readonly toast = inject(HotToastService); + private readonly posthogService = inject(PosthogService); readonly notifications = signal({ productUpdates: true, @@ -225,6 +227,7 @@ export class NotificationSettingsComponent { } saveNotifications() { + this.posthogService.client?.capture('notification_preferences_saved'); this.toast.success('Notification preferences saved'); } } diff --git a/apps/basic-integration/angular/angular-saas/src/app/pages/settings/components/preferences-settings/preferences-settings.component.ts b/apps/basic-integration/angular/angular-saas/src/app/pages/settings/components/preferences-settings/preferences-settings.component.ts index 756f8ddb9..5db018fc3 100644 --- a/apps/basic-integration/angular/angular-saas/src/app/pages/settings/components/preferences-settings/preferences-settings.component.ts +++ b/apps/basic-integration/angular/angular-saas/src/app/pages/settings/components/preferences-settings/preferences-settings.component.ts @@ -2,6 +2,7 @@ import { Component, inject, ChangeDetectionStrategy, signal } from '@angular/cor import { FormsModule } from '@angular/forms'; import { ThemeService } from '@app/shell/services/theme.service'; import { HotToastService } from '@ngxpert/hot-toast'; +import { PosthogService } from '@core/services/posthog.service'; interface Preferences { isDarkMode: boolean; @@ -214,6 +215,7 @@ interface Preferences { export class PreferencesSettingsComponent { private readonly themeService = inject(ThemeService); private readonly toast = inject(HotToastService); + private readonly posthogService = inject(PosthogService); readonly preferences = signal({ isDarkMode: false, @@ -244,6 +246,7 @@ export class PreferencesSettingsComponent { } savePreferences() { + this.posthogService.client?.capture('preferences_saved'); this.toast.success('Preferences saved'); } } diff --git a/apps/basic-integration/angular/angular-saas/src/app/pages/settings/components/security-settings/security-settings.component.ts b/apps/basic-integration/angular/angular-saas/src/app/pages/settings/components/security-settings/security-settings.component.ts index f2d13848b..85c16766c 100644 --- a/apps/basic-integration/angular/angular-saas/src/app/pages/settings/components/security-settings/security-settings.component.ts +++ b/apps/basic-integration/angular/angular-saas/src/app/pages/settings/components/security-settings/security-settings.component.ts @@ -1,5 +1,6 @@ import { Component, inject, ChangeDetectionStrategy, signal } from '@angular/core'; import { HotToastService } from '@ngxpert/hot-toast'; +import { PosthogService } from '@core/services/posthog.service'; interface Session { id: number; @@ -282,6 +283,7 @@ interface LoginEntry { }) export class SecuritySettingsComponent { private readonly toast = inject(HotToastService); + private readonly posthogService = inject(PosthogService); readonly tfaEnabled = signal(false); @@ -300,6 +302,9 @@ export class SecuritySettingsComponent { toggleTfa() { this.tfaEnabled.update((v) => !v); + this.posthogService.client?.capture('two_factor_authentication_toggled', { + enabled: this.tfaEnabled(), + }); this.toast.success(this.tfaEnabled() ? '2FA enabled' : '2FA disabled'); } diff --git a/apps/basic-integration/angular/angular-saas/src/app/shared/components/add-member-modal/add-member-modal.component.ts b/apps/basic-integration/angular/angular-saas/src/app/shared/components/add-member-modal/add-member-modal.component.ts index 6183ed634..dc0ccfc51 100644 --- a/apps/basic-integration/angular/angular-saas/src/app/shared/components/add-member-modal/add-member-modal.component.ts +++ b/apps/basic-integration/angular/angular-saas/src/app/shared/components/add-member-modal/add-member-modal.component.ts @@ -3,6 +3,7 @@ import { FormsModule } from '@angular/forms'; import { ModalComponent } from '../modal/modal.component'; import { DataService } from '@app/@core/services/data.service'; import { HotToastService } from '@ngxpert/hot-toast'; +import { PosthogService } from '@core/services/posthog.service'; interface MemberForm { name: string; @@ -159,6 +160,7 @@ interface MemberForm { export class AddMemberModalComponent { private readonly dataService = inject(DataService); private readonly toast = inject(HotToastService); + private readonly posthogService = inject(PosthogService); isOpen = input(false); close = output(); @@ -197,6 +199,7 @@ export class AddMemberModalComponent { role: current.role, avatar: current.avatar, }); + this.posthogService.client?.capture('team_member_added', { role: current.role }); this.toast.success(`${current.name} added to the team!`); this.resetForm(); diff --git a/apps/basic-integration/angular/angular-saas/src/app/shared/components/create-project-modal/create-project-modal.component.ts b/apps/basic-integration/angular/angular-saas/src/app/shared/components/create-project-modal/create-project-modal.component.ts index d4df06b19..edb034a61 100644 --- a/apps/basic-integration/angular/angular-saas/src/app/shared/components/create-project-modal/create-project-modal.component.ts +++ b/apps/basic-integration/angular/angular-saas/src/app/shared/components/create-project-modal/create-project-modal.component.ts @@ -3,6 +3,7 @@ import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms'; import { ModalComponent } from '../modal/modal.component'; import { DataService } from '@app/@core/services/data.service'; import { HotToastService } from '@ngxpert/hot-toast'; +import { PosthogService } from '@core/services/posthog.service'; @Component({ selector: 'app-create-project-modal', @@ -121,6 +122,7 @@ export class CreateProjectModalComponent { private readonly dataService = inject(DataService); private readonly toast = inject(HotToastService); private readonly fb = inject(FormBuilder); + private readonly posthogService = inject(PosthogService); isOpen = input(false); close = output(); @@ -138,6 +140,7 @@ export class CreateProjectModalComponent { const { name, description, status } = this.projectForm.getRawValue(); this.dataService.addProject({ name, description, status }); + this.posthogService.client?.capture('project_created', { status }); this.toast.success(`Project "${name}" created!`); this.projectForm.reset({ name: '', description: '', status: 'active' }); diff --git a/apps/basic-integration/angular/angular-saas/src/environments/environment.prod.ts b/apps/basic-integration/angular/angular-saas/src/environments/environment.prod.ts index 10f9ff7e0..f1b5f8a8c 100644 --- a/apps/basic-integration/angular/angular-saas/src/environments/environment.prod.ts +++ b/apps/basic-integration/angular/angular-saas/src/environments/environment.prod.ts @@ -6,4 +6,6 @@ export const environment = { defaultLanguage: 'de-DE', supportedLanguages: ['de-DE', 'en-US', 'es-ES', 'fr-FR', 'it-IT'], buildYear: 2024, + posthogKey: env['NG_APP_POSTHOG_PROJECT_TOKEN'], + posthogHost: env['NG_APP_POSTHOG_HOST'], }; diff --git a/apps/basic-integration/angular/angular-saas/src/environments/environment.ts b/apps/basic-integration/angular/angular-saas/src/environments/environment.ts index 6704e0e03..be7496a11 100644 --- a/apps/basic-integration/angular/angular-saas/src/environments/environment.ts +++ b/apps/basic-integration/angular/angular-saas/src/environments/environment.ts @@ -6,4 +6,6 @@ export const environment = { defaultLanguage: 'en-US', supportedLanguages: ['en-US'], buildYear: 2024, + posthogKey: env['NG_APP_POSTHOG_PROJECT_TOKEN'], + posthogHost: env['NG_APP_POSTHOG_HOST'], };