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/SKILL.md b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/SKILL.md new file mode 100644 index 000000000..06813fafd --- /dev/null +++ b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/SKILL.md @@ -0,0 +1,54 @@ +--- +name: integration-angular +description: PostHog integration for Angular applications +metadata: + author: PostHog + version: dev +--- + +# PostHog integration for Angular + +This skill helps you add PostHog analytics to Angular applications. + +## Workflow + +Follow these steps in order to complete the integration: + +1. `references/1-begin.md` - PostHog Setup - Begin ← **Start here** +2. `references/2-edit.md` - PostHog Setup - Edit +3. `references/3-revise.md` - PostHog Setup - Revise +4. `references/4-conclude.md` - PostHog Setup - Conclusion + +## Reference files + +- `references/EXAMPLE.md` - Angular example project code +- `references/1-begin.md` - Start the event tracking setup process by analyzing the project and creating an event tracking plan +- `references/2-edit.md` - Implement PostHog event tracking in the identified files, following best practices and the example project +- `references/3-revise.md` - Review and fix any errors in the PostHog integration implementation +- `references/4-conclude.md` - Review and fix any errors in the PostHog integration implementation +- `references/angular.md` - Angular - docs +- `references/identify-users.md` - Identify users - docs + +The example project shows the target implementation pattern. Consult the documentation for API details. + +## Key principles + +- **Environment variables**: Always use environment variables for PostHog keys. Never hardcode them. +- **Minimal changes**: Add PostHog code alongside existing integrations. Don't replace or restructure existing code. +- **Match the example**: Your implementation should follow the example project's patterns as closely as possible. + +## Framework guidelines + +- Use inject() instead of constructor injection. PostHog service should be injected via inject() in components/services that need it. +- Create a dedicated PosthogService as a singleton root service that wraps the PostHog SDK. +- Always use standalone components over NgModules. +- Configure PostHog credentials in src/environments/environment.ts files, as Angular reads environment variables from these configuration files +- When a reverse proxy is configured, both /static/* AND /array/* must route to the assets origin (us-assets.i.posthog.com or eu-assets.i.posthog.com). + +## Identifying users + +Identify users during login and signup events. Refer to the example code and documentation for the correct identify pattern for this framework. If both frontend and backend code exist, pass the client-side session and distinct ID using `X-POSTHOG-DISTINCT-ID` and `X-POSTHOG-SESSION-ID` headers to maintain correlation. + +## Error tracking + +Add PostHog error tracking to relevant files, particularly around critical user flows and API boundaries. diff --git a/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/1-begin.md b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/1-begin.md new file mode 100644 index 000000000..55f0a8326 --- /dev/null +++ b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/1-begin.md @@ -0,0 +1,56 @@ +--- +title: PostHog Setup - Begin +description: Start the event tracking setup process by analyzing the project and creating an event tracking plan +--- + +We're making an event tracking plan for this project. + +This is the first of several phases — plan the events, implement them, revise and validate changes, then conclude by creating a dashboard and writing a setup report. + +## Task list + +As soon as you've read this description and have a rough sense of the work, make a single **call `TaskCreate` immediately** before reading any reference file or beginning analysis. The user is watching the task pane and shouldn't see it sit empty. + +It's fine if your first list is incomplete or imprecise. Seed it with whatever high-level items you can infer from the overview above, then call `TaskCreate` again (or `TaskUpdate` to refine existing items) every time your understanding sharpens: after a phase reveals work you didn't anticipate, after planning surfaces concrete sub-items, after you hit something new. Use `TaskUpdate` to mark items `in_progress` when you start them and `completed` when you finish. Keeping the list current matters more than getting it right on the first call. + +Keep task titles broad and job-oriented. Describe the purpose or area of work with wording like "Planning event tracking", "Identifying users", "Installing PostHog", "Capturing events", or "Creating dashboards", not the specific files, paths, or symbols involved. Adjust the task names according to the user's project and context. + +Before proceeding, find any existing `posthog.capture()` code. Make note of event name formatting. + +From the project's file list, select between 10 and 15 files that might have interesting business value for event tracking, especially conversion and churn events. Also look for additional files related to login that could be used for identifying users, along with error handling. Read the files. If a file is already well-covered by PostHog events, replace it with another option. Do not spawn subagents. + +Look for opportunities to track client-side events. + +**IMPORTANT: Server-side events are REQUIRED** if the project includes any instrumentable server-side code. If the project has API routes (e.g., `app/api/**/route.ts`) or Server Actions, you MUST include server-side events for critical business operations like: + + - Payment/checkout completion + - Webhook handlers + - Authentication endpoints + +Do not skip server-side events - they capture actions that cannot be tracked client-side. + +Create a new file with a JSON array at the root of the project: .posthog-events.json. It should include one object for each event we want to add with these exact field names: `event_name` (the event name), `event_description` (one sentence), and `file` (the file path the event goes in). The wizard reads this file to surface the plan in the UI. If events already exist, don't duplicate them; supplement them. + +Track actions only, not pageviews. These can be captured automatically. Exceptions can be made for "viewed"-type events that correspond to the top of a conversion funnel. + +As you review files, make an internal note of opportunities to identify users and catch errors. We'll need them for the next step. + +## Status + +Before beginning a phase of the setup, you will send a status message with the exact prefix '[STATUS]', as in: + +[STATUS] Checking project structure. + +Status to report in this phase: + +- Checking project structure +- Verifying PostHog dependencies +- Generating events based on project + +## Abort statuses + +If and only if the instructions have `[ABORT]` states specified, and you clearly match the conditions for an abort, emit the abort message. Do NOT attempt to exit or halt yourself — the wizard's middleware catches `[ABORT]` and terminates the run for you. + +--- + +**Upon completion, continue with:** [2-edit.md](2-edit.md) \ No newline at end of file diff --git a/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/2-edit.md b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/2-edit.md new file mode 100644 index 000000000..e5f7ffd16 --- /dev/null +++ b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/2-edit.md @@ -0,0 +1,36 @@ +--- +title: PostHog Setup - Edit +description: Implement PostHog event tracking in the identified files, following best practices and the example project +--- + +For each of the files and events noted in .posthog-events.json, make edits to capture events using PostHog. Make sure to set up any helper files needed. Carefully examine the included example project code: your implementation should match it as closely as possible. Do not spawn subagents. + +Use environment variables for PostHog keys. Do not hardcode PostHog keys. + +If a file already has existing integration code for other tools or services, don't overwrite or remove that code. Place PostHog code below it. + +For each event, add useful properties, and use your access to the PostHog source code to ensure correctness. You also have access to documentation about creating new events with PostHog. Consider this documentation carefully and follow it closely before adding events. Your integration should be based on documented best practices. Carefully consider how the user project's framework version may impact the correct PostHog integration approach. + +Remember that you can find the source code for any dependency in the node_modules directory. This may be necessary to properly populate property names. There are also example project code files available via the PostHog MCP; use these for reference. + +Where possible, add calls for PostHog's identify() function on the client side upon events like logins and signups. Use the contents of login and signup forms to identify users on submit. If there is server-side code, pass the client-side session and distinct ID to the server-side code to identify the user. On the server side, make sure events have a matching distinct ID where relevant. + +It's essential to do this in both client code and server code, so that user behavior from both domains is easy to correlate. + +You should also add PostHog exception capture error tracking to these files where relevant. + +Remember: Do not alter the fundamental architecture of existing files. Make your additions minimal and targeted. + +Remember the documentation and example project resources you were provided at the beginning. Read them now. + +## Status + +Status to report in this phase: + +- Inserting PostHog capture code +- A status message for each file whose edits you are planning, including a high level summary of changes +- A status message for each file you have edited + +--- + +**Upon completion, continue with:** [3-revise.md](3-revise.md) \ No newline at end of file diff --git a/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/3-revise.md b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/3-revise.md new file mode 100644 index 000000000..3b07f5069 --- /dev/null +++ b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/3-revise.md @@ -0,0 +1,22 @@ +--- +title: PostHog Setup - Revise +description: Review and fix any errors in the PostHog integration implementation +--- + +Check the project for errors. Read the package.json file for any type checking or build scripts that may provide input about what to fix. Remember that you can find the source code for any dependency in the node_modules directory. Do not spawn subagents. + +Ensure that any components created were actually used. + +Once all other tasks are complete, run any linter or prettier-like scripts found in the package.json, but ONLY on the files you have edited or created during this session. Do not run formatting or linting across the entire project's codebase. + +## Status + +Status to report in this phase: + +- Finding and correcting errors +- Report details of any errors you fix +- Linting, building and prettying + +--- + +**Upon completion, continue with:** [4-conclude.md](4-conclude.md) \ No newline at end of file diff --git a/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/4-conclude.md b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/4-conclude.md new file mode 100644 index 000000000..d876d4353 --- /dev/null +++ b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/4-conclude.md @@ -0,0 +1,57 @@ +--- +title: PostHog Setup - Conclusion +description: Review and fix any errors in the PostHog integration implementation +--- + +Use the PostHog MCP to create a new dashboard named "Analytics basics (wizard)" based on the events created here. Keep the `(wizard)` tag with that exact casing so anyone browsing PostHog can see the wizard created this dashboard, and so a quick search for `(wizard)` surfaces every wizard-created artifact in one go. Make sure to use the exact same event names as implemented in the code. Populate it with up to five insights, with special emphasis on things like conversion funnels, churn events, and other business critical insights. + +Once the dashboard exists, emit its URL on its own line in your assistant message using this exact marker: `[DASHBOARD_URL] `. The wizard parses this marker from your visible message and surfaces the link in the success summary. Mentioning the URL only in thinking or in prose without the marker means the link is dropped. + +Search for a file called `.posthog-events.json` and read it for available events. + +Do not spawn subagents. + +Create the file posthog-setup-report.md. It should include a summary of the integration edits, a table with the event names, event descriptions, and files where events were added, a list of links for the dashboard and insights created, and a "Verify before merging" checklist (see below). Follow this format: + + +# PostHog post-wizard report + +The wizard has completed a deep integration of your project. [Detailed summary of changes] + +[table of events/descriptions/files] + +## Next steps + +We've built some insights and a dashboard for you to keep an eye on user behavior, based on the events we just instrumented: + +[links] + +## Verify before merging + +[checklist] + +### Agent skill + +We've left an agent skill folder in your project. You can use this context for further agent development when using Claude Code. This will help ensure the model provides the most up-to-date approaches for integrating PostHog. + + + +For the "Verify before merging" checklist, write GitHub-style checkboxes (`- [ ] ...`) covering what the developer (or their coding agent) still needs to do to take this from "wizard finished" to "merged". Include ONLY the items that actually apply to the integration you just performed — judge each against the code you changed in this run, and drop any that don't fit. Phrase each item as a concrete, checkable action. Candidate items, with the condition for including each: + +- Always: "Run a full production build (the wizard only verified the files it touched) and fix any lint or type errors introduced by the generated code." +- Always: "Run the test suite — call sites that were rewritten or instrumented may need updated mocks or fixtures." +- If you added environment variables: "Add the exact PostHog env var names you added to `.env.example` and any monorepo/bootstrap scripts so collaborators know what to set." +- If this integration ships a minified production browser bundle (most SPA/SSR web frameworks — e.g. Next.js, Nuxt, SvelteKit, Astro, Vite-based apps): "Wire source-map upload (`posthog-cli sourcemap` or your bundler's upload step) into CI so production stack traces de-minify." +- If LLM analytics was set up in this run: "Trigger the LLM call path(s) you instrumented and confirm `$ai_generation` events appear in PostHog AI Observability." +- If the app has user auth and an `identify` call was added: "Confirm the returning-visitor path also calls `identify` — a handler that only identifies on fresh login can leave returning sessions on anonymous distinct IDs." + +Do not invent items beyond what applies. If only the two "Always" items apply, the checklist is just those two. + +Upon completion, remove .posthog-events.json. + +## Status + +Status to report in this phase: + +- Configured dashboard: [insert PostHog dashboard URL] +- Created setup report: [insert full local file path] \ No newline at end of file diff --git a/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/EXAMPLE.md b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/EXAMPLE.md new file mode 100644 index 000000000..8ab4233be --- /dev/null +++ b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/EXAMPLE.md @@ -0,0 +1,944 @@ +# PostHog Angular Example Project + +Repository: https://github.com/PostHog/context-mill +Path: example-apps/angular + +--- + +## README.md + +# PostHog Angular Example + +This is an [Angular](https://angular.dev/) example demonstrating PostHog integration with product analytics, session replay, and error tracking. + +## Features + +- **Product analytics**: Track user events and behaviors +- **Session replay**: Record and replay user sessions +- **Error tracking**: Capture and track errors +- **User authentication**: Demo login system with PostHog user identification +- **SSR-safe**: Uses platform checks for browser-only PostHog calls +- **Reverse proxy**: PostHog ingestion through Angular proxy + +## Getting started + +### 1. Install dependencies + +```bash +pnpm install +``` + +### 2. Configure environment variables + +Create a `.env` file in the root directory: + +```bash +VITE_POSTHOG_PROJECT_TOKEN=your_posthog_project_token +VITE_POSTHOG_HOST=https://us.posthog.com +``` + +Get your PostHog project token from your [PostHog project settings](https://app.posthog.com/project/settings). + +### 3. Run the development server + +```bash +pnpm start +``` + +Open [http://localhost:3000](http://localhost:3000) with your browser to see the app. + +## Project structure + +``` +src/ +├── app/ +│ ├── components/ +│ │ └── header/ # Navigation header with auth state +│ ├── pages/ +│ │ ├── home/ # Home/Login page +│ │ ├── burrito/ # Demo feature page with event tracking +│ │ └── profile/ # User profile with error tracking demo +│ ├── services/ +│ │ ├── posthog.service.ts # PostHog service wrapper (SSR-safe) +│ │ └── auth.service.ts # Auth service with PostHog integration +│ ├── guards/ +│ │ └── auth.guard.ts # Route guard for protected pages +│ ├── app.component.ts # Root component with PostHog init +│ ├── app.routes.ts # Route definitions +│ └── app.config.ts # App configuration +├── environments/ +│ ├── environment.ts # Dev environment config +│ └── environment.production.ts +└── main.ts # App entry point +``` + +## Key integration points + +### PostHog service (services/posthog.service.ts) + +A wrapper service that handles SSR safety and provides access to the PostHog instance: + +```typescript +import { Injectable, inject, PLATFORM_ID } from '@angular/core'; +import { isPlatformBrowser } from '@angular/common'; +import posthog from 'posthog-js'; + +@Injectable({ providedIn: 'root' }) +export class PostHogService { + private readonly platformId = inject(PLATFORM_ID); + + get posthog(): typeof posthog { + if (isPlatformBrowser(this.platformId)) { + return posthog; + } + // Return a no-op proxy for SSR safety + return new Proxy({} as typeof posthog, { + get: () => () => undefined, + }); + } + + init(apiKey: string, options: Partial): void { + if (isPlatformBrowser(this.platformId)) { + posthog.init(apiKey, options); + } + } +} +``` + +### PostHog initialization (app.component.ts) + +PostHog is initialized in the root component's `ngOnInit`: + +```typescript +import { PostHogService } from './services/posthog.service'; +import { environment } from '../environments/environment'; + +export class AppComponent implements OnInit { + private readonly posthogService = inject(PostHogService); + + ngOnInit(): void { + this.posthogService.init(environment.posthogKey, { + api_host: '/ingest', + ui_host: environment.posthogHost || 'https://us.posthog.com', + capture_exceptions: true, + }); + } +} +``` + +### User identification (services/auth.service.ts) + +```typescript +import { PostHogService } from './posthog.service'; + +const posthogService = inject(PostHogService); + +posthogService.posthog.identify(username, { + username, + isNewUser, +}); +``` + +### Event tracking (pages/burrito/burrito.component.ts) + +```typescript +import { PostHogService } from '../../services/posthog.service'; + +const posthogService = inject(PostHogService); + +posthogService.posthog.capture('burrito_considered', { + total_considerations: count, + username: username, +}); +``` + +### Error tracking (pages/profile/profile.component.ts) + +```typescript +posthogService.posthog.captureException(error); +``` + +## Angular-specific details + +This example uses Angular 21 with modern features: + +1. **Standalone components**: No NgModules, all components use `standalone: true` +2. **Signals**: Reactive state management with Angular signals +3. **SSR support**: Uses `isPlatformBrowser()` checks for SSR safety +4. **Dependency injection**: PostHog wrapped in an injectable service +5. **Proxy configuration**: Uses `proxy.conf.json` for PostHog API calls +6. **Environment files**: Generated from `.env` at build time via prebuild script + +## Environment variable handling + +Angular CLI doesn't natively support `.env` files. This project uses a prebuild script: + +1. `scripts/generate-env.js` reads `.env` and generates `environment.generated.ts` +2. The script runs automatically before `pnpm start` and `pnpm build` +3. Environment files import from the generated file + +## Learn more + +- [PostHog Documentation](https://posthog.com/docs) +- [Angular Documentation](https://angular.dev/) +- [PostHog JavaScript Web SDK](https://posthog.com/docs/libraries/js) + +--- + +## .env.example + +```example +NG_APP_POSTHOG_PROJECT_TOKEN= +NG_APP_POSTHOG_HOST=https://us.posthog.com + +``` + +--- + +## src/app/app.component.ts + +```ts +import { + Component, + inject, + OnInit, + PLATFORM_ID, + ChangeDetectionStrategy, +} from '@angular/core'; +import { isPlatformBrowser } from '@angular/common'; +import { RouterOutlet } from '@angular/router'; +import { HeaderComponent } from './components/header/header.component'; +import { PostHogService } from './services/posthog.service'; +import { environment } from '../environments/environment'; + +@Component({ + selector: 'app-root', + imports: [RouterOutlet, HeaderComponent], + template: ` + + + `, + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class AppComponent implements OnInit { + private readonly platformId = inject(PLATFORM_ID); + private readonly posthogService = inject(PostHogService); + + ngOnInit(): void { + if (isPlatformBrowser(this.platformId)) { + this.posthogService.init(environment.posthogKey, { + api_host: '/ingest', + ui_host: environment.posthogHost || 'https://us.posthog.com', + capture_exceptions: true, + }); + } + } +} + +``` + +--- + +## src/app/app.config.server.ts + +```ts +import { mergeApplicationConfig, ApplicationConfig } from '@angular/core'; +import { provideServerRendering, withRoutes } from '@angular/ssr'; +import { appConfig } from './app.config'; +import { serverRoutes } from './app.routes.server'; + +const serverConfig: ApplicationConfig = { + providers: [provideServerRendering(withRoutes(serverRoutes))], +}; + +export const config = mergeApplicationConfig(appConfig, serverConfig); + +``` + +--- + +## src/app/app.config.ts + +```ts +import { ApplicationConfig } from '@angular/core'; +import { provideRouter, withComponentInputBinding } from '@angular/router'; +import { + provideClientHydration, + withEventReplay, +} from '@angular/platform-browser'; +import { provideHttpClient, withFetch } from '@angular/common/http'; +import { routes } from './app.routes'; + +export const appConfig: ApplicationConfig = { + providers: [ + provideRouter(routes, withComponentInputBinding()), + provideHttpClient(withFetch()), + provideClientHydration(withEventReplay()), + ], +}; + +``` + +--- + +## src/app/app.routes.server.ts + +```ts +import { RenderMode, ServerRoute } from '@angular/ssr'; + +export const serverRoutes: ServerRoute[] = [ + { + path: '', + renderMode: RenderMode.Server, + }, + { + path: 'burrito', + renderMode: RenderMode.Client, // Protected route, render client-side + }, + { + path: 'profile', + renderMode: RenderMode.Client, // Protected route, render client-side + }, + { + path: '**', + renderMode: RenderMode.Server, + }, +]; + +``` + +--- + +## src/app/app.routes.ts + +```ts +import { Routes } from '@angular/router'; +import { authGuard } from './guards/auth.guard'; + +export const routes: Routes = [ + { + path: '', + title: 'Burrito Consideration App', + loadComponent: () => + import('./pages/home/home.component').then((m) => m.HomeComponent), + }, + { + path: 'burrito', + title: 'Burrito Consideration - Burrito Consideration App', + loadComponent: () => + import('./pages/burrito/burrito.component').then( + (m) => m.BurritoComponent + ), + canActivate: [authGuard], + }, + { + path: 'profile', + title: 'Profile - Burrito Consideration App', + loadComponent: () => + import('./pages/profile/profile.component').then( + (m) => m.ProfileComponent + ), + canActivate: [authGuard], + }, + { + path: '**', + redirectTo: '', + }, +]; + +``` + +--- + +## src/app/components/header/header.component.ts + +```ts +import { Component, inject, ChangeDetectionStrategy } from '@angular/core'; +import { RouterLink } from '@angular/router'; +import { AuthService } from '../../services/auth.service'; + +@Component({ + selector: 'app-header', + imports: [RouterLink], + template: ` + + + `, + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class HeaderComponent { + readonly auth = inject(AuthService); +} + +``` + +--- + +## src/app/guards/auth.guard.ts + +```ts +import { inject } from '@angular/core'; +import { Router, CanActivateFn } from '@angular/router'; +import { AuthService } from '../services/auth.service'; + +export const authGuard: CanActivateFn = () => { + const auth = inject(AuthService); + const router = inject(Router); + + if (auth.isAuthenticated()) { + return true; + } + + return router.createUrlTree(['/']); +}; + +``` + +--- + +## src/app/pages/burrito/burrito.component.ts + +```ts +import { + Component, + inject, + signal, + ChangeDetectionStrategy, +} from '@angular/core'; +import { Router } from '@angular/router'; +import { AuthService } from '../../services/auth.service'; +import { PostHogService } from '../../services/posthog.service'; + +@Component({ + selector: 'app-burrito', + template: ` +
+
+

Burrito consideration zone

+

Take a moment to truly consider the potential of burritos.

+ +
+ + + @if (hasConsidered()) { +

+ Thank you for your consideration! Count: + {{ auth.user()?.burritoConsiderations }} +

+ } +
+ +
+

Consideration stats

+

Total considerations: {{ auth.user()?.burritoConsiderations }}

+
+
+
+ `, + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class BurritoComponent { + readonly auth = inject(AuthService); + private readonly posthogService = inject(PostHogService); + private readonly router = inject(Router); + + hasConsidered = signal(false); + + constructor() { + // Redirect if not authenticated + if (!this.auth.isAuthenticated()) { + this.router.navigate(['/']); + } + } + + handleConsideration(): void { + const user = this.auth.user(); + if (!user) return; + + this.auth.incrementBurritoConsiderations(); + this.hasConsidered.set(true); + setTimeout(() => this.hasConsidered.set(false), 2000); + + this.posthogService.posthog.capture('burrito_considered', { + total_considerations: user.burritoConsiderations + 1, + username: user.username, + }); + } +} + +``` + +--- + +## src/app/pages/home/home.component.ts + +```ts +import { + Component, + inject, + signal, + ChangeDetectionStrategy, +} from '@angular/core'; +import { ReactiveFormsModule, FormBuilder, Validators } from '@angular/forms'; +import { AuthService } from '../../services/auth.service'; + +@Component({ + selector: 'app-home', + imports: [ReactiveFormsModule], + template: ` +
+ @if (auth.user(); as user) { +
+

Welcome back, {{ user.username }}!

+

You are now logged in. Feel free to explore:

+
    +
  • Consider the potential of burritos
  • +
  • View your profile and statistics
  • +
+
+ } @else { +
+

Welcome to Burrito Consideration App

+

Please sign in to begin your burrito journey

+ +
+
+ + +
+ +
+ + +
+ + @if (error()) { + + } + + +
+ +

+ Note: This is a demo app. Use any username and password to sign in. +

+
+ } +
+ `, + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class HomeComponent { + private readonly fb = inject(FormBuilder); + readonly auth = inject(AuthService); + + loginForm = this.fb.nonNullable.group({ + username: ['', Validators.required], + password: ['', Validators.required], + }); + + error = signal(''); + + handleSubmit(): void { + this.error.set(''); + + if (this.loginForm.invalid) { + this.error.set('Please provide both username and password'); + return; + } + + const { username, password } = this.loginForm.getRawValue(); + + const success = this.auth.login(username, password); + if (success) { + this.loginForm.reset(); + } else { + this.error.set('Please provide both username and password'); + } + } +} + +``` + +--- + +## src/app/pages/profile/profile.component.ts + +```ts +import { + Component, + inject, + computed, + ChangeDetectionStrategy, +} from '@angular/core'; +import { Router } from '@angular/router'; +import { AuthService } from '../../services/auth.service'; +import { PostHogService } from '../../services/posthog.service'; + +@Component({ + selector: 'app-profile', + template: ` +
+
+

User Profile

+ +
+

Your Information

+

Username: {{ auth.user()?.username }}

+

+ Burrito Considerations: + {{ auth.user()?.burritoConsiderations }} +

+
+ +
+ +
+ +
+

Your Burrito Journey

+

{{ journeyMessage() }}

+
+
+
+ `, + changeDetection: ChangeDetectionStrategy.OnPush, +}) +export class ProfileComponent { + readonly auth = inject(AuthService); + private readonly posthogService = inject(PostHogService); + private readonly router = inject(Router); + + journeyMessage = computed(() => { + const count = this.auth.user()?.burritoConsiderations ?? 0; + + if (count === 0) { + return "You haven't considered any burritos yet. Visit the Burrito Consideration page to start!"; + } else if (count === 1) { + return "You've considered the burrito potential once. Keep going!"; + } else if (count < 5) { + return "You're getting the hang of burrito consideration!"; + } else if (count < 10) { + return "You're becoming a burrito consideration expert!"; + } else { + return 'You are a true burrito consideration master!'; + } + }); + + constructor() { + if (!this.auth.isAuthenticated()) { + this.router.navigate(['/']); + } + } + + triggerTestError(): void { + try { + throw new Error('Test error for PostHog error tracking'); + } catch (err) { + const error = err as Error; + this.posthogService.posthog.captureException(error); + console.error('Captured error:', err); + alert('Error captured and sent to PostHog!'); + } + } +} + +``` + +--- + +## src/app/services/auth.service.ts + +```ts +import { + Injectable, + signal, + computed, + inject, + PLATFORM_ID, +} from '@angular/core'; +import { isPlatformBrowser } from '@angular/common'; +import { PostHogService } from './posthog.service'; + +export interface User { + username: string; + burritoConsiderations: number; +} + +@Injectable({ providedIn: 'root' }) +export class AuthService { + private readonly platformId = inject(PLATFORM_ID); + private readonly posthogService = inject(PostHogService); + + // In-memory user store (matches TanStack behavior) + private readonly users = new Map(); + + // Signals for reactive state + private readonly _user = signal(null); + + // Public computed signals + readonly user = this._user.asReadonly(); + readonly isAuthenticated = computed(() => this._user() !== null); + + constructor() { + // Initialize from localStorage on browser + if (isPlatformBrowser(this.platformId)) { + const storedUsername = localStorage.getItem('currentUser'); + if (storedUsername) { + const existingUser = this.users.get(storedUsername); + if (existingUser) { + this._user.set(existingUser); + } + } + } + } + + login(username: string, password: string): boolean { + if (!username || !password) { + return false; + } + + // Get or create user in local map (no API call) + let user = this.users.get(username); + const isNewUser = !user; + + if (!user) { + user = { username, burritoConsiderations: 0 }; + this.users.set(username, user); + } + + this._user.set(user); + + if (isPlatformBrowser(this.platformId)) { + localStorage.setItem('currentUser', username); + } + + // PostHog identification (client-side only) + this.posthogService.posthog.identify(username, { + username, + isNewUser, + }); + + this.posthogService.posthog.capture('user_logged_in', { + username, + isNewUser, + }); + + return true; + } + + logout(): void { + this.posthogService.posthog.capture('user_logged_out'); + this.posthogService.posthog.reset(); + + this._user.set(null); + + if (isPlatformBrowser(this.platformId)) { + localStorage.removeItem('currentUser'); + } + } + + incrementBurritoConsiderations(): void { + const currentUser = this._user(); + if (currentUser) { + const updated = { + ...currentUser, + burritoConsiderations: currentUser.burritoConsiderations + 1, + }; + this.users.set(currentUser.username, updated); + this._user.set(updated); + } + } +} + +``` + +--- + +## src/app/services/posthog.service.ts + +```ts +import { Injectable, inject, PLATFORM_ID } from '@angular/core'; +import { isPlatformBrowser } from '@angular/common'; +import posthog, { PostHogConfig } from 'posthog-js'; + +@Injectable({ providedIn: 'root' }) +export class PostHogService { + private readonly platformId = inject(PLATFORM_ID); + private initialized = false; + + /** + * The posthog instance. Use this directly to call posthog methods. + * Returns the actual posthog instance on browser, or a no-op proxy on server. + */ + get posthog(): typeof posthog { + if (isPlatformBrowser(this.platformId) && this.initialized) { + return posthog; + } + // Return a no-op proxy for SSR safety + return new Proxy({} as typeof posthog, { + get: () => () => undefined, + }); + } + + init(apiKey: string, options: Partial): void { + if (isPlatformBrowser(this.platformId) && !this.initialized) { + posthog.init(apiKey, options); + this.initialized = true; + } + } +} + +``` + +--- + +## src/env.d.ts + +```ts +// Define the type of the environment variables. +declare interface Env { + readonly NODE_ENV: string; + readonly NG_APP_POSTHOG_PROJECT_TOKEN: string; + readonly NG_APP_POSTHOG_HOST: string; +} + +// Use import.meta.env.YOUR_ENV_VAR in your code. +declare interface ImportMeta { + readonly env: Env; +} + +``` + +--- + +## src/environments/environment.prod.ts + +```ts +export const environment = { + production: true, + posthogKey: import.meta.env['NG_APP_POSTHOG_PROJECT_TOKEN'] || '', + posthogHost: import.meta.env['NG_APP_POSTHOG_HOST'] || 'https://us.posthog.com', +}; + +``` + +--- + +## src/environments/environment.production.ts + +```ts +export const environment = { + production: true, + posthogKey: import.meta.env['NG_APP_POSTHOG_PROJECT_TOKEN'] || '', + posthogHost: import.meta.env['NG_APP_POSTHOG_HOST'] || 'https://us.posthog.com', +}; + +``` + +--- + +## src/environments/environment.ts + +```ts +export const environment = { + production: false, + posthogKey: import.meta.env['NG_APP_POSTHOG_PROJECT_TOKEN'] || '', + posthogHost: import.meta.env['NG_APP_POSTHOG_HOST'] || 'https://us.posthog.com', +}; + +``` + +--- + +## src/index.html + +```html + + + + + Burrito Consideration App + + + + + + + + + + +``` + +--- + +## src/main.server.ts + +```ts +import { bootstrapApplication, BootstrapContext } from '@angular/platform-browser'; +import { AppComponent } from './app/app.component'; +import { config } from './app/app.config.server'; + +const bootstrap = (context: BootstrapContext) => + bootstrapApplication(AppComponent, config, context); + +export default bootstrap; + +``` + +--- + +## src/main.ts + +```ts +import { bootstrapApplication } from '@angular/platform-browser'; +import { appConfig } from './app/app.config'; +import { AppComponent } from './app/app.component'; + +bootstrapApplication(AppComponent, appConfig).catch((err) => + console.error(err) +); + +``` + +--- + 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..8e05e53ee --- /dev/null +++ b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/angular.md @@ -0,0 +1,376 @@ +# 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 +``` + +### 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. +> +> See our guide on [identifying users](/docs/getting-started/identify-users.md) for how to set this up. + +> **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 (e.g., Celery tasks for snapshots). + +## 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/features.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) + +### Community questions + +Ask a question + +### 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..1417e03a8 --- /dev/null +++ b/apps/basic-integration/angular/angular-saas/.claude/skills/integration-angular/references/identify-users.md @@ -0,0 +1,272 @@ +# Identify users - Docs + +Linking events to specific users enables you to build a full picture of how they're using your product across different sessions, devices, and platforms. + +This is straightforward to do when [capturing backend events](/docs/product-analytics/capture-events?tab=Node.js.md), as you associate events to a specific user using a `distinct_id`, which is a required argument. + +However, in the frontend of a [web](/docs/libraries/js/features.md#capturing-events) or [mobile app](/docs/libraries/ios.md#capturing-events), a `distinct_id` is not a required argument — PostHog's SDKs will generate an anonymous `distinct_id` for you automatically and you can capture events anonymously, provided you use the appropriate [configuration](/docs/libraries/js/features.md#capturing-anonymous-events). + +To link events to specific users, call `identify`: + +PostHog AI + +### Web + +```javascript +posthog.identify( + 'distinct_id', // Replace 'distinct_id' with your user's unique identifier + { email: 'max@hedgehogmail.com', name: 'Max Hedgehog' } // optional: set additional person properties +); +``` + +### Android + +```kotlin +PostHog.identify( + distinctId = distinctID, // Replace 'distinctID' with your user's unique identifier + // optional: set additional person properties + userProperties = mapOf( + "name" to "Max Hedgehog", + "email" to "max@hedgehogmail.com" + ) +) +``` + +### iOS + +```swift +PostHogSDK.shared.identify("distinct_id", // Replace "distinct_id" with your user's unique identifier + userProperties: ["name": "Max Hedgehog", "email": "max@hedgehogmail.com"]) // optional: set additional person properties +``` + +### React Native + +```jsx +posthog.identify('distinct_id', { // Replace "distinct_id" with your user's unique identifier + email: 'max@hedgehogmail.com', // optional: set additional person properties + name: 'Max Hedgehog' +}) +``` + +### Dart + +```dart +await Posthog().identify( + userId: 'distinct_id', // Replace "distinct_id" with your user's unique identifier + userProperties: { + 'email': 'max@hedgehogmail.com', // optional: set additional person properties + 'name': 'Max Hedgehog', + }, +); +``` + +Events captured after calling `identify` are identified events and this creates a person profile if one doesn't exist already. + +Due to the cost of processing them, anonymous events can be up to 4x cheaper than identified events, so it's recommended you only capture identified events when needed. + +## How identify works + +When a user starts browsing your website or app, PostHog automatically assigns them an **anonymous ID**, which is stored locally. + +Provided you've [configured persistence](/docs/libraries/js/persistence.md) to use cookies or `localStorage`, this enables us to track anonymous users – even across different sessions. + +By calling `identify` with a `distinct_id` of your choice (usually the user's ID in your database, or their email), you link the anonymous ID and distinct ID together. + +Thus, all past and future events made with that anonymous ID are now associated with the distinct ID. + +This enables you to do things like associate events with a user from before they log in for the first time, or associate their events across different devices or platforms. + +Using identify in the backend + +Although you can call `identify` using our backend SDKs, it is used most in frontends. This is because there is no concept of anonymous sessions in the backend SDKs, so calling `identify` only updates person profiles. + +## Best practices when using `identify` + +### 1\. Call `identify` as soon as you're able to + +In your frontend, you should call `identify` as soon as you're able to. + +Typically, this is every time your **app loads** for the first time, and directly after your **users log in**. + +This ensures that events sent during your users' sessions are correctly associated with them. + +You only need to call `identify` once per session, and you should avoid calling it multiple times unnecessarily. + +If you call `identify` multiple times with the same data without reloading the page in between, PostHog will ignore the subsequent calls. + +### 2\. Use unique strings for distinct IDs + +If two users have the same distinct ID, their data is merged and they are considered one user in PostHog. Two common ways this can happen are: + +- Your logic for generating IDs does not generate sufficiently strong IDs and you can end up with a clash where 2 users have the same ID. +- There's a bug, typo, or mistake in your code leading to most or all users being identified with generic IDs like `null`, `true`, or `distinctId`. + +PostHog also has built-in protections to stop the most common distinct ID mistakes. + +### 3\. Reset after logout + +If a user logs out on your frontend, you should call `reset()` to unlink any future events made on that device with that user. + +This is important if your users are sharing a computer, as otherwise all of those users are grouped together into a single user due to shared cookies between sessions. + +**We strongly recommend you call `reset` on logout even if you don't expect users to share a computer.** + +You can do that like so: + +PostHog AI + +### Web + +```javascript +posthog.reset() +``` + +### iOS + +```swift +PostHogSDK.shared.reset() +``` + +### Android + +```kotlin +PostHog.reset() +``` + +### React Native + +```jsx +posthog.reset() +``` + +### Dart + +```dart +await Posthog().reset(); +``` + +If you *also* want to reset the `device_id` so that the device will be considered a new device in future events, you can pass `true` as an argument: + +Web + +PostHog AI + +```javascript +posthog.reset(true) +``` + +### 4\. Person profiles and properties + +You'll notice that one of the parameters in the `identify` method is a `properties` object. + +This enables you to set [person properties](/docs/product-analytics/person-properties.md). + +Whenever possible, we recommend passing in all person properties you have available each time you call identify, as this ensures their person profile on PostHog is up to date. + +Person properties can also be set being adding a `$set` property to a event `capture` call. + +See our [person properties docs](/docs/product-analytics/person-properties.md) for more details on how to work with them and best practices. + +### 5\. Use deep links between platforms + +We recommend you call `identify` [as soon as you're able](#1-call-identify-as-soon-as-youre-able), typically when a user signs up or logs in. + +This doesn't work if one or both platforms are unauthenticated. Some examples of such cases are: + +- Onboarding and signup flows before authentication. +- Unauthenticated web pages redirecting to authenticated mobile apps. +- Authenticated web apps prompting an app download. + +In these cases, you can use a [deep link](https://developer.android.com/training/app-links/deep-linking) on Android and [universal links](https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app) on iOS to identify users. + +1. Use `posthog.get_distinct_id()` to get the current distinct ID. Even if you cannot call identify because the user is unauthenticated, this will return an anonymous distinct ID generated by PostHog. +2. Add the distinct ID to the deep link as query parameters, along with other properties like UTM parameters. +3. When the user is redirected to the app, parse the deep link and handle the following cases: + +- The mobile app is already authenticated. In this case, call [`posthog.alias()`](/docs/libraries/js/features.md#alias) with the distinct ID from the web. This associates the two distinct IDs as a single person. +- The mobile app is unauthenticated. In this case, call [`posthog.identify()`](/docs/libraries/js/features.md#identifying-users) with the distinct ID from the web so pre-login mobile events stay connected to the web session. When the user later logs in on mobile, call `identify()` again with your canonical user ID. + +As long as you associate the distinct IDs with `posthog.identify()` or `posthog.alias()`, you can track events generated across platforms. + +Here's an example implementation for handling deep links from web to mobile: + +PostHog AI + +### iOS + +```swift +import PostHog +class DeepLinkIdentityManager { + static let shared = DeepLinkIdentityManager() + // MARK: - Deep Link Received + func handleDeepLink(_ url: URL, isAuthenticatedOnMobile: Bool) { + guard let webDistinctId = URLComponents(url: url, resolvingAgainstBaseURL: true)? + .queryItems?.first(where: { $0.name == "ph_distinct_id" })?.value else { + return + } + if isAuthenticatedOnMobile { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHogSDK.shared.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHogSDK.shared.identify(webDistinctId) + } + } + // MARK: - Login/Signup + func handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHogSDK.shared.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + func handleLogout() { + PostHogSDK.shared.reset() + } +} +``` + +### Android + +```kotlin +import android.net.Uri +import com.posthog.PostHog +object DeepLinkIdentityManager { + // Deep Link Received + fun handleDeepLink(uri: Uri, isAuthenticatedOnMobile: Boolean) { + val webDistinctId = uri.getQueryParameter("ph_distinct_id") ?: return + if (isAuthenticatedOnMobile) { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHog.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHog.identify(webDistinctId) + } + } + // Login/Signup + fun handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHog.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + fun handleLogout() { + PostHog.reset() + } +} +``` + +## Further reading + +- [Identifying users docs](/docs/product-analytics/identify.md) +- [How person processing works](/docs/how-posthog-works/ingestion-pipeline.md#2-person-processing) +- [An introductory guide to identifying users in PostHog](/tutorials/identifying-users-guide.md) + +### Community questions + +Ask a question + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/apps/basic-integration/angular/angular-saas/.gitignore b/apps/basic-integration/angular/angular-saas/.gitignore index cc7b14135..cac319af0 100644 --- a/apps/basic-integration/angular/angular-saas/.gitignore +++ b/apps/basic-integration/angular/angular-saas/.gitignore @@ -40,3 +40,4 @@ testem.log # System files .DS_Store Thumbs.db +.env diff --git a/apps/basic-integration/angular/angular-saas/package-lock.json b/apps/basic-integration/angular/angular-saas/package-lock.json index 3034213a2..c12346cbc 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.396.5", "reflect-metadata": "^0.2.0", "rxjs": "^7.8.2", "sanitize.css": "^13.0.0", @@ -3768,6 +3769,21 @@ "url": "https://opencollective.com/popperjs" } }, + "node_modules/@posthog/core": { + "version": "1.39.6", + "resolved": "https://registry.npmjs.org/@posthog/core/-/core-1.39.6.tgz", + "integrity": "sha512-o6ajIwN5zXoNP0D4H/QPmOyibNTUkSyOR6ya7AG5U2ywXx4awo72L2KnCoiZPQM5x/bXv6jPBdimH8M18Ax0aw==", + "license": "MIT", + "dependencies": { + "@posthog/types": "^1.392.0" + } + }, + "node_modules/@posthog/types": { + "version": "1.392.0", + "resolved": "https://registry.npmjs.org/@posthog/types/-/types-1.392.0.tgz", + "integrity": "sha512-nctNujXL3FC1v99FktaTMSugSD9ZOZekEpahUSafkU2TSvW+XGKNkQZbokuJtiWvPBK208dwMJva8UfBkChqpw==", + "license": "MIT" + }, "node_modules/@rolldown/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 +4611,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 +5782,17 @@ "node": ">=6.6.0" } }, + "node_modules/core-js": { + "version": "3.49.0", + "resolved": "https://registry.npmjs.org/core-js/-/core-js-3.49.0.tgz", + "integrity": "sha512-es1U2+YTtzpwkxVLwAFdSpaIMyQaq0PBgm3YD1W3Qpsn1NAmO3KSgZfu+oGSWVu6NvLHoHCV/aYcsE5wiB7ALg==", + "hasInstallScript": true, + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/core-js" + } + }, "node_modules/core-util-is": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", @@ -5995,6 +6029,15 @@ "url": "https://github.com/fb55/domhandler?sponsor=1" } }, + "node_modules/dompurify": { + "version": "3.4.11", + "resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.11.tgz", + "integrity": "sha512-zhlUV12GsaRzMsf9q5M254YhA4+VuF0fG+QFqu6aYpoGlKtz+w8//jBcGVYBgQkR5GHjUomejY84AV+/uPbWdw==", + "license": "(MPL-2.0 OR Apache-2.0)", + "optionalDependencies": { + "@types/trusted-types": "^2.0.7" + } + }, "node_modules/domutils": { "version": "3.2.2", "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz", @@ -6798,6 +6841,12 @@ } } }, + "node_modules/fflate": { + "version": "0.4.8", + "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.4.8.tgz", + "integrity": "sha512-FJqqoDBR00Mdj9ppamLa/Y7vxm+PRmNWA67N846RvsoYVMKB4q3y/de5PA7gUmRMYK/8CMz2GDZQmCRN1wBcWA==", + "license": "MIT" + }, "node_modules/file-entry-cache": { "version": "8.0.0", "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", @@ -10030,6 +10079,32 @@ "dev": true, "license": "MIT" }, + "node_modules/posthog-js": { + "version": "1.396.5", + "resolved": "https://registry.npmjs.org/posthog-js/-/posthog-js-1.396.5.tgz", + "integrity": "sha512-huW/8R151I08i/tkOaAv3Q/yWVqzhqPj3SxyhpgNLB/xysaNeV1ibp6DHzbRWV5D7FRM48Zg6Icxsm4q0irEtg==", + "license": "(Apache-2.0 AND MIT)", + "dependencies": { + "@posthog/core": "^1.39.5", + "@posthog/types": "^1.392.0", + "core-js": "^3.38.1", + "dompurify": "^3.3.2", + "fflate": "^0.4.8", + "preact": "^10.29.2", + "query-selector-shadow-dom": "^1.0.1", + "web-vitals": "^5.3.0" + } + }, + "node_modules/preact": { + "version": "10.29.3", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.29.3.tgz", + "integrity": "sha512-D9NL1GAnJZhc3RndVs4gDdxEeU9TcHgywMrhhOsnpdlvFjdbx0gAsLUnH6JEhlJH5giL7Tx5biWPUSEXE/HPzw==", + "license": "MIT", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } + }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", @@ -10132,6 +10207,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 +11761,12 @@ "license": "MIT", "optional": true }, + "node_modules/web-vitals": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/web-vitals/-/web-vitals-5.3.0.tgz", + "integrity": "sha512-q6LWsLatGYZp5VGBIOvbTj6JBV2nOmC8KvWztXBmwJcfFAzhwKwbOxhUH306XY3CcaZDUlSmSuNPBsCn0bFu+g==", + "license": "Apache-2.0" + }, "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..c1d08b94f 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.396.5", "reflect-metadata": "^0.2.0", "rxjs": "^7.8.2", "sanitize.css": "^13.0.0", diff --git a/apps/basic-integration/angular/angular-saas/posthog-setup-report.md b/apps/basic-integration/angular/angular-saas/posthog-setup-report.md new file mode 100644 index 000000000..7f067d29f --- /dev/null +++ b/apps/basic-integration/angular/angular-saas/posthog-setup-report.md @@ -0,0 +1,42 @@ + +# PostHog post-wizard report + +The wizard has completed a deep integration of PostHog into this Angular 21 SaaS application. A singleton `PostHogService` was created to safely wrap posthog-js, handling SSR/browser platform checks. PostHog is initialized in `AppComponent.ngOnInit()` using environment variables (`NG_APP_POSTHOG_PROJECT_TOKEN` and `NG_APP_POSTHOG_HOST`). Ten events covering the most business-critical user flows — authentication, billing upgrades, project creation, team growth, profile management, and security actions — were instrumented across nine components. Users are identified on login with `posthog.identify()` and the identity is reset on logout with `posthog.reset()`. Exception capture is enabled via `capture_exceptions: true` in the PostHog init config. + +| Event | Description | File | +|---|---|---| +| `user_logged_in` | Fired when a user successfully completes the login form and is authenticated. | `src/app/auth/login/login.component.ts` | +| `user_logged_out` | Fired when a user completes the logout flow and their session is cleared. | `src/app/auth/logout/logout.component.ts` | +| `billing_page_viewed` | Fired when the billing page loads, marking the entry point of the plan upgrade funnel. | `src/app/pages/billing/billing.component.ts` | +| `plan_upgrade_clicked` | Fired when a user clicks the Upgrade button on a billing plan card. | `src/app/pages/billing/billing.component.ts` | +| `project_created` | Fired when a user successfully submits the create project form. | `src/app/shared/components/create-project-modal/create-project-modal.component.ts` | +| `member_added` | Fired when a user successfully adds a new team member. | `src/app/shared/components/add-member-modal/add-member-modal.component.ts` | +| `profile_updated` | Fired when a user saves changes to their profile information. | `src/app/pages/profile/profile.component.ts` | +| `two_factor_authentication_toggled` | Fired when a user enables or disables two-factor authentication. | `src/app/pages/settings/components/security-settings/security-settings.component.ts` | +| `session_revoked` | Fired when a user revokes one or all active sessions from the security settings. | `src/app/pages/settings/components/security-settings/security-settings.component.ts` | +| `user_profile_viewed` | Fired when a user clicks on another team member's entry in the users list. | `src/app/pages/users/list/list.component.ts` | + +## Next steps + +We've built some insights and a dashboard for you to keep an eye on user behavior, based on the events we just instrumented: + +- [Analytics basics (wizard) — Dashboard](https://us.posthog.com/project/483112/dashboard/1793445) +- [Daily Logins](https://us.posthog.com/project/483112/insights/uAdzf4N7) +- [Billing upgrade funnel](https://us.posthog.com/project/483112/insights/bt4sM9gL) +- [Projects created over time](https://us.posthog.com/project/483112/insights/WcKvCDK0) +- [Team members added](https://us.posthog.com/project/483112/insights/6xm09t9v) +- [Security events](https://us.posthog.com/project/483112/insights/MSCzbsMU) + +## Verify before merging + +- [ ] Run a full production build (the wizard only verified the files it touched) and fix any lint or type errors introduced by the generated code. +- [ ] Run the test suite — call sites that were rewritten or instrumented may need updated mocks or fixtures. +- [ ] Add `NG_APP_POSTHOG_PROJECT_TOKEN` and `NG_APP_POSTHOG_HOST` to `.env.example` and any CI/bootstrap scripts so collaborators know what to set. +- [ ] Wire source-map upload (`posthog-cli sourcemap` or your bundler's upload step) into CI so production stack traces de-minify. +- [ ] Confirm the returning-visitor path also calls `identify` — the current implementation only identifies on fresh login, which can leave returning sessions on anonymous distinct IDs. + +### Agent skill + +We've left an agent skill folder in your project. You can use this context for further agent development when using Claude Code. This will help ensure the model provides the most up-to-date approaches for integrating PostHog. + + diff --git a/apps/basic-integration/angular/angular-saas/src/app/@core/services/index.ts b/apps/basic-integration/angular/angular-saas/src/app/@core/services/index.ts index 348fac120..f8a9f9eeb 100644 --- a/apps/basic-integration/angular/angular-saas/src/app/@core/services/index.ts +++ b/apps/basic-integration/angular/angular-saas/src/app/@core/services/index.ts @@ -2,3 +2,4 @@ export * from './misc'; export * from './random-user.service'; +export * from './posthog.service'; 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..1336a74d2 --- /dev/null +++ b/apps/basic-integration/angular/angular-saas/src/app/@core/services/posthog.service.ts @@ -0,0 +1,25 @@ +import { Injectable, inject, PLATFORM_ID } from '@angular/core'; +import { isPlatformBrowser } from '@angular/common'; +import posthog, { PostHogConfig } from 'posthog-js'; + +@Injectable({ providedIn: 'root' }) +export class PostHogService { + private readonly platformId = inject(PLATFORM_ID); + private initialized = false; + + get posthog(): typeof posthog { + if (isPlatformBrowser(this.platformId) && this.initialized) { + return posthog; + } + return new Proxy({} as typeof posthog, { + get: () => () => undefined, + }); + } + + init(apiKey: string, options: Partial): void { + if (isPlatformBrowser(this.platformId) && !this.initialized) { + posthog.init(apiKey, options); + 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..8a9a707a3 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 @@ -1,4 +1,5 @@ -import { Component, OnInit, inject, ChangeDetectionStrategy, DestroyRef } from '@angular/core'; +import { Component, OnInit, inject, ChangeDetectionStrategy, DestroyRef, PLATFORM_ID } from '@angular/core'; +import { isPlatformBrowser } from '@angular/common'; import { NavigationEnd, Router, RouterOutlet } from '@angular/router'; import { I18nService } from '@app/i18n'; import { Title } from '@angular/platform-browser'; @@ -6,7 +7,7 @@ import { TranslateModule, TranslateService } from '@ngx-translate/core'; import { environment } from '@env/environment'; import { filter, merge } from 'rxjs'; import { takeUntilDestroyed } from '@angular/core/rxjs-interop'; -import { AppUpdateService, Logger } from '@core/services'; +import { AppUpdateService, Logger, PostHogService } from '@core/services'; import { SocketIoService } from '@core/socket-io'; @Component({ @@ -24,6 +25,8 @@ export class AppComponent implements OnInit { private readonly socketService = inject(SocketIoService); private readonly updateService = inject(AppUpdateService); private readonly destroyRef = inject(DestroyRef); + private readonly platformId = inject(PLATFORM_ID); + private readonly posthogService = inject(PostHogService); title = 'angular-boilerplate'; @@ -33,6 +36,14 @@ export class AppComponent implements OnInit { Logger.enableProductionMode(); } + if (isPlatformBrowser(this.platformId)) { + this.posthogService.init(environment.posthogKey, { + api_host: environment.posthogHost, + ui_host: 'https://us.posthog.com', + capture_exceptions: true, + }); + } + // Initialize i18nService with default language and supported languages this.i18nService.init(environment.defaultLanguage, environment.supportedLanguages); 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..d3a1505f8 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'; @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; @@ -40,6 +42,13 @@ export class LoginComponent { next: (res) => { if (res) { console.log('Login successful'); + this.posthogService.posthog.identify(username, { + username, + email: res.email, + }); + this.posthogService.posthog.capture('user_logged_in', { + username, + }); 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..d5845f54e 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'; @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,8 @@ export class LogoutComponent implements OnInit { } else { this.authService.logout().subscribe({ next: () => { + this.posthogService.posthog.capture('user_logged_out'); + this.posthogService.posthog.reset(); this.credentialsService.setCredentials(); this.router.navigate(['/login']).then(() => { window.location.reload(); diff --git a/apps/basic-integration/angular/angular-saas/src/app/pages/billing/billing.component.html b/apps/basic-integration/angular/angular-saas/src/app/pages/billing/billing.component.html index bdcf22a23..9706df51b 100644 --- a/apps/basic-integration/angular/angular-saas/src/app/pages/billing/billing.component.html +++ b/apps/basic-integration/angular/angular-saas/src/app/pages/billing/billing.component.html @@ -35,7 +35,7 @@

{{ plan.name }}

} - diff --git a/apps/basic-integration/angular/angular-saas/src/app/pages/billing/billing.component.ts b/apps/basic-integration/angular/angular-saas/src/app/pages/billing/billing.component.ts index ec7c6db49..b45b8f189 100644 --- a/apps/basic-integration/angular/angular-saas/src/app/pages/billing/billing.component.ts +++ b/apps/basic-integration/angular/angular-saas/src/app/pages/billing/billing.component.ts @@ -1,5 +1,6 @@ -import { Component, signal, computed, ChangeDetectionStrategy } from '@angular/core'; +import { Component, signal, computed, ChangeDetectionStrategy, OnInit, inject } from '@angular/core'; import { TitleCasePipe } from '@angular/common'; +import { PostHogService } from '@core/services'; interface Plan { id: string; @@ -24,7 +25,8 @@ interface Invoice { styleUrl: './billing.component.scss', changeDetection: ChangeDetectionStrategy.OnPush, }) -export class BillingComponent { +export class BillingComponent implements OnInit { + private readonly posthogService = inject(PostHogService); readonly currentPlan = signal('starter'); readonly plans: Plan[] = [ @@ -62,4 +64,21 @@ export class BillingComponent { ]; readonly currentPlanDetails = computed(() => this.plans.find((p) => p.id === this.currentPlan())); + + ngOnInit() { + this.posthogService.posthog.capture('billing_page_viewed', { + current_plan: this.currentPlan(), + }); + } + + selectPlan(plan: Plan) { + if (plan.id === this.currentPlan()) return; + this.posthogService.posthog.capture('plan_upgrade_clicked', { + plan_id: plan.id, + plan_name: plan.name, + plan_price: plan.price, + current_plan: this.currentPlan(), + }); + this.currentPlan.set(plan.id); + } } diff --git a/apps/basic-integration/angular/angular-saas/src/app/pages/profile/profile.component.ts b/apps/basic-integration/angular/angular-saas/src/app/pages/profile/profile.component.ts index 3e84d2fab..709d58cc8 100644 --- a/apps/basic-integration/angular/angular-saas/src/app/pages/profile/profile.component.ts +++ b/apps/basic-integration/angular/angular-saas/src/app/pages/profile/profile.component.ts @@ -2,6 +2,7 @@ import { Component, OnInit, inject, signal, computed, ChangeDetectionStrategy } import { ReactiveFormsModule, FormBuilder, FormGroup, Validators } from '@angular/forms'; import { CredentialsService } from '@app/auth/services/credentials.service'; import { HotToastService } from '@ngxpert/hot-toast'; +import { PostHogService } from '@core/services'; @Component({ selector: 'app-profile', @@ -14,6 +15,7 @@ export class ProfileComponent implements OnInit { private readonly fb = inject(FormBuilder); private readonly toast = inject(HotToastService); readonly credentialsService = inject(CredentialsService); + private readonly posthogService = inject(PostHogService); readonly isEditing = signal(false); @@ -61,6 +63,7 @@ export class ProfileComponent implements OnInit { onSave() { if (this.profileForm.valid) { + this.posthogService.posthog.capture('profile_updated'); this.toast.success('Profile updated successfully'); this.isEditing.set(false); } else { 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..fb6e45c4f 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'; 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,16 +302,26 @@ export class SecuritySettingsComponent { toggleTfa() { this.tfaEnabled.update((v) => !v); + this.posthogService.posthog.capture('two_factor_authentication_toggled', { + enabled: this.tfaEnabled(), + }); this.toast.success(this.tfaEnabled() ? '2FA enabled' : '2FA disabled'); } revokeSession(session: Session) { this.sessions.update((current) => current.filter((s) => s.id !== session.id)); + this.posthogService.posthog.capture('session_revoked', { + device: session.device, + revoke_all: false, + }); this.toast.success('Session revoked'); } revokeAllSessions() { this.sessions.update((current) => current.filter((s) => s.current)); + this.posthogService.posthog.capture('session_revoked', { + revoke_all: true, + }); this.toast.success('All other sessions revoked'); } } diff --git a/apps/basic-integration/angular/angular-saas/src/app/pages/users/list/list.component.ts b/apps/basic-integration/angular/angular-saas/src/app/pages/users/list/list.component.ts index 8eb5445a3..5c6b862a0 100644 --- a/apps/basic-integration/angular/angular-saas/src/app/pages/users/list/list.component.ts +++ b/apps/basic-integration/angular/angular-saas/src/app/pages/users/list/list.component.ts @@ -2,6 +2,7 @@ import { Component, inject, OnInit, ChangeDetectionStrategy, signal } from '@ang import { UseRandomUser } from '@core/usecases'; import { RandomUserEntity } from '@core/entities'; import { HotToastService } from '@ngxpert/hot-toast'; +import { PostHogService } from '@core/services'; @Component({ selector: 'app-list', @@ -15,6 +16,7 @@ export class ListComponent implements OnInit { private readonly useRandomUser = new UseRandomUser(); private readonly toast = inject(HotToastService); + private readonly posthogService = inject(PostHogService); ngOnInit() { this.useRandomUser.getAllUsers().subscribe({ @@ -28,7 +30,8 @@ export class ListComponent implements OnInit { }); } - userClicked() { + userClicked(user?: RandomUserEntity) { + this.posthogService.posthog.capture('user_profile_viewed'); this.toast.show('User clicked'); } } 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..29d127457 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'; 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(); @@ -198,6 +200,10 @@ export class AddMemberModalComponent { avatar: current.avatar, }); + this.posthogService.posthog.capture('member_added', { + member_role: current.role, + }); + this.toast.success(`${current.name} added to the team!`); this.resetForm(); this.created.emit(); 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..94927b94b 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'; @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(); @@ -139,6 +141,11 @@ export class CreateProjectModalComponent { this.dataService.addProject({ name, description, status }); + this.posthogService.posthog.capture('project_created', { + project_name: name, + project_status: status, + }); + this.toast.success(`Project "${name}" created!`); this.projectForm.reset({ name: '', description: '', status: 'active' }); this.created.emit(); diff --git a/apps/basic-integration/angular/angular-saas/src/env.d.ts b/apps/basic-integration/angular/angular-saas/src/env.d.ts new file mode 100644 index 000000000..c66a047a0 --- /dev/null +++ b/apps/basic-integration/angular/angular-saas/src/env.d.ts @@ -0,0 +1,9 @@ +declare interface Env { + readonly NODE_ENV: string; + readonly NG_APP_POSTHOG_PROJECT_TOKEN: string; + readonly NG_APP_POSTHOG_HOST: string; +} + +declare interface ImportMeta { + readonly env: Env; +} 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..8ee694364 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: import.meta.env['NG_APP_POSTHOG_PROJECT_TOKEN'] || '', + posthogHost: import.meta.env['NG_APP_POSTHOG_HOST'] || 'https://us.posthog.com', }; 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..028d5d008 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: import.meta.env['NG_APP_POSTHOG_PROJECT_TOKEN'] || '', + posthogHost: import.meta.env['NG_APP_POSTHOG_HOST'] || 'https://us.posthog.com', };