Skip to content

Conversation

@ItzNotABug
Copy link
Member

@ItzNotABug ItzNotABug commented Jan 1, 2026

What does this PR do?

(Provide a description of what this PR does.)

Test Plan

(Write your test plan here. If you changed any code, please provide us with clear instructions on how you verified your changes work.)

Related PRs and Issues

(If this PR is related to any other PR or resolves any issue or related to any issue link all related PR and issues here.)

Have you read the Contributing Guidelines on issues?

(Write your answer here.)

Summary by CodeRabbit

  • New Features

    • Integrated analytics and session recording capabilities with automatic user identification and preference tracking for session recording activation.
  • Chores

    • Added project dependencies to support analytics functionality.

✏️ Tip: You can customize this high-level summary in your review settings.

@ItzNotABug ItzNotABug self-assigned this Jan 1, 2026
@appwrite
Copy link

appwrite bot commented Jan 1, 2026

Console (appwrite/console)

Project ID: 688b7bf400350cbd60e9

Sites (1)
Site Status Logs Preview QR
 console-stage
688b7cf6003b1842c9dc
Ready Ready View Logs Preview URL QR Code

Tip

Messaging handles push notifications, emails, and SMS through one unified API

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 1, 2026

Walkthrough

This pull request introduces PostHog analytics integration to the application. The changes add PostHog as a new npm dependency, expose API key and host environment variables through the system configuration, create a new PostHog initialization module that manages session recording based on user preferences stored locally, and integrate session recording initialization into the console layout on mount. Additionally, a reactive statement in the root layout is refactored to use an explicit effect block. The integration is designed to be conditional, initializing only when in cloud environments with a valid API key and not in development or test modes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Add: posthog session recordings' directly and accurately summarizes the main change in the pull request, which introduces PostHog session recording functionality.
✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Nitpick comments (5)
.env.example (1)

10-10: Add trailing blank line.

Add a blank line at the end of the file to follow standard conventions.

🔎 Proposed fix
 PUBLIC_POSTHOG_HOST=
+
src/lib/actions/analytics.ts (2)

10-10: Consider removing commented import.

The commented PostHog import suggests incomplete integration. Since a dedicated PostHog module exists at src/lib/actions/posthog.ts, consider either removing this commented code or documenting why it's preserved for future use.


76-78: Consider removing commented PostHog capture call.

The commented posthog.capture() call indicates incomplete integration within the analytics tracking flow. Since PostHog initialization is handled separately in src/routes/(console)/+layout.svelte, either remove this commented block or document the plan for integrating PostHog events into the main analytics pipeline.

src/routes/(console)/+layout.svelte (1)

276-278: Consider adding error handling for session recording initialization.

While the conditional guards are appropriate, consider wrapping the initializeSessionRecording call in a try-catch block to prevent initialization failures from disrupting the console layout mount process.

🔎 Proposed fix
 if ($user && isCloud) {
-    await initializeSessionRecording($user);
+    try {
+        await initializeSessionRecording($user);
+    } catch (error) {
+        console.error('Failed to initialize session recording:', error);
+    }
 }
src/lib/actions/posthog.ts (1)

24-25: Improve initialization guard to check if PostHog is properly initialized.

The check if (!posthog) on line 25 doesn't effectively validate whether PostHog was initialized, since posthog is a direct import and will always be defined as a module object. The initialization on lines 9-22 is conditional (requires browser context, API key, and specific environment).

Consider tracking initialization state explicitly or checking PostHog's internal state (e.g., posthog.__loaded).

🔎 Suggested approach
+let isPostHogInitialized = false;
+
 if (browser && VARS.POSTHOG_API_KEY && !ENV.DEV && !ENV.TEST) {
     posthog.init(VARS.POSTHOG_API_KEY, {
         api_host: VARS.POSTHOG_HOST,
         person_profiles: 'identified_only',
         capture_pageview: true,
         capture_pageleave: true,
         session_recording: {
             recordCrossOriginIframes: false,
             /*maskTextSelector: '.ph-no-capture'*/
         },
         autocapture: true,
         disable_session_recording: !ENV.PROD
     });
+    isPostHogInitialized = true;
 }
 
 export async function initializeSessionRecording(user: Models.User<Models.Preferences>): Promise<void> {
-    if (!posthog) return;
+    if (!isPostHogInitialized) return;
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 936666d and 0de66d5.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (7)
  • .env.example
  • package.json
  • src/lib/actions/analytics.ts
  • src/lib/actions/posthog.ts
  • src/lib/system.ts
  • src/routes/(console)/+layout.svelte
  • src/routes/+layout.svelte
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{ts,tsx,js,jsx,svelte,json}

📄 CodeRabbit inference engine (AGENTS.md)

Use 4 spaces for indentation, single quotes, 100 character line width, and no trailing commas per Prettier configuration

Files:

  • package.json
  • src/lib/actions/analytics.ts
  • src/lib/actions/posthog.ts
  • src/lib/system.ts
  • src/routes/+layout.svelte
  • src/routes/(console)/+layout.svelte
**/*.{ts,tsx,js,jsx,svelte}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx,js,jsx,svelte}: Import reusable modules from the src/lib directory using the $lib alias
Use minimal comments in code; reserve comments for TODOs or complex logic explanations
Use $lib, $routes, and $themes aliases instead of relative paths for module imports

Files:

  • src/lib/actions/analytics.ts
  • src/lib/actions/posthog.ts
  • src/lib/system.ts
  • src/routes/+layout.svelte
  • src/routes/(console)/+layout.svelte
**/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

**/*.ts: Define types inline or in .d.ts files, avoid creating separate .types.ts files
Use TypeScript in non-strict mode; any type is tolerated in this project

Files:

  • src/lib/actions/analytics.ts
  • src/lib/actions/posthog.ts
  • src/lib/system.ts
src/routes/**/*.svelte

📄 CodeRabbit inference engine (AGENTS.md)

Use SvelteKit file conventions: +page.svelte for components, +page.ts for data loaders, +layout.svelte for wrappers, +error.svelte for error handling, and dynamic route params in square brackets like [param]

Files:

  • src/routes/+layout.svelte
  • src/routes/(console)/+layout.svelte
**/*.svelte

📄 CodeRabbit inference engine (AGENTS.md)

Use Svelte 5 + SvelteKit 2 syntax with TypeScript for component development

Files:

  • src/routes/+layout.svelte
  • src/routes/(console)/+layout.svelte
src/routes/**

📄 CodeRabbit inference engine (AGENTS.md)

Configure dynamic routes using SvelteKit convention with [param] syntax in route directory names

Files:

  • src/routes/+layout.svelte
  • src/routes/(console)/+layout.svelte
🧠 Learnings (4)
📚 Learning: 2025-11-25T03:15:27.539Z
Learnt from: CR
Repo: appwrite/console PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-11-25T03:15:27.539Z
Learning: Configure environment variables by copying .env.example to .env and setting PUBLIC_APPWRITE_ENDPOINT and PUBLIC_CONSOLE_MODE

Applied to files:

  • src/lib/system.ts
  • .env.example
📚 Learning: 2025-11-25T03:15:27.539Z
Learnt from: CR
Repo: appwrite/console PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-11-25T03:15:27.539Z
Learning: Applies to src/routes/**/*.svelte : Use SvelteKit file conventions: +page.svelte for components, +page.ts for data loaders, +layout.svelte for wrappers, +error.svelte for error handling, and dynamic route params in square brackets like [param]

Applied to files:

  • src/routes/+layout.svelte
  • src/routes/(console)/+layout.svelte
📚 Learning: 2025-11-25T03:15:27.539Z
Learnt from: CR
Repo: appwrite/console PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-11-25T03:15:27.539Z
Learning: Applies to **/*.svelte : Use Svelte 5 + SvelteKit 2 syntax with TypeScript for component development

Applied to files:

  • src/routes/+layout.svelte
📚 Learning: 2025-10-13T05:16:07.656Z
Learnt from: ItzNotABug
Repo: appwrite/console PR: 2413
File: src/routes/(console)/project-[region]-[project]/databases/database-[database]/header.svelte:54-58
Timestamp: 2025-10-13T05:16:07.656Z
Learning: In SvelteKit apps, shared layout components (like headers) that use `$derived(page.data.*)` should use optional chaining when accessing properties that may not be present on all routes. During page transitions, reactive statements can briefly evaluate with different page.data structures, so optional chaining prevents runtime errors when navigating between routes with different data shapes (e.g., between `/databases` and `/databases/database-[database]`).

Applied to files:

  • src/routes/+layout.svelte
🧬 Code graph analysis (2)
src/lib/actions/posthog.ts (2)
src/lib/system.ts (2)
  • VARS (9-18)
  • ENV (20-25)
src/lib/stores/preferences.ts (1)
  • preferences (319-319)
src/lib/system.ts (1)
build.js (1)
  • env (7-7)
🪛 dotenv-linter (4.0.0)
.env.example

[warning] 8-8: [UnorderedKey] The PUBLIC_CONSOLE_MOCK_AI_SUGGESTIONS key should go before the PUBLIC_CONSOLE_MODE key

(UnorderedKey)


[warning] 9-9: [UnorderedKey] The PUBLIC_POSTHOG_API_KEY key should go before the PUBLIC_STRIPE_KEY key

(UnorderedKey)


[warning] 10-10: [EndingBlankLine] No blank line at the end of the file

(EndingBlankLine)


[warning] 10-10: [UnorderedKey] The PUBLIC_POSTHOG_HOST key should go before the PUBLIC_STRIPE_KEY key

(UnorderedKey)

🪛 GitHub Actions: Tests
src/lib/actions/posthog.ts

[error] 1-1: Prettier formatting check failed for src/lib/actions/posthog.ts. Run 'prettier --write' to fix code style issues.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: e2e
🔇 Additional comments (5)
.env.example (1)

9-10: LGTM! Environment variables added for PostHog integration.

The PostHog configuration variables are properly added with the PUBLIC_ prefix, making them available client-side as required by the integration in src/routes/(console)/+layout.svelte.

src/lib/system.ts (1)

16-17: LGTM! PostHog configuration properly integrated.

The PostHog environment variables are correctly added to the VARS object, following the same pattern as other optional configuration values in the system.

package.json (1)

46-46: Package version [email protected] is valid and secure.

Version ^1.312.0 exists on npm with no known security vulnerabilities. The November 2025 supply-chain compromise (Shai-Hulud) affected version 1.297.3, not 1.312.0. Older XSS vulnerabilities were fixed in v1.57.2 and earlier. Safe to merge.

src/routes/+layout.svelte (1)

113-140: LGTM! Clean migration to Svelte 5 $effect syntax.

The refactor correctly migrates from the legacy reactive statement ($:) to the explicit $effect API introduced in Svelte 5. The theme switching and DOM update logic remains unchanged.

src/lib/actions/posthog.ts (1)

29-37: No action required—the session recording logic is intentional.

The function correctly records only the first session per user. This is a deliberate design choice approved by @ItzNotABug (per commit 0de66d5), balancing analytics needs with privacy by capturing initial session identification without recording all subsequent sessions. The POSTHOG_PREFS_KEY flag prevents re-recording on repeat visits, and session recording is already disabled outside production environments.

Likely an incorrect or invalid review comment.

Comment on lines +1 to +40
import posthog from 'posthog-js';
import { browser } from '$app/environment';
import { VARS, ENV } from '$lib/system';
import type { Models } from '@appwrite.io/console';
import { preferences } from '$lib/stores/preferences';

const POSTHOG_PREFS_KEY = 'posthog_session_recorded';

if (browser && VARS.POSTHOG_API_KEY && !ENV.DEV && !ENV.TEST) {
posthog.init(VARS.POSTHOG_API_KEY, {
api_host: VARS.POSTHOG_HOST,
person_profiles: 'identified_only',
capture_pageview: true,
capture_pageleave: true,
session_recording: {
recordCrossOriginIframes: false,
/*maskTextSelector: '.ph-no-capture'*/
},
autocapture: true,
disable_session_recording: !ENV.PROD
});
}

export async function initializeSessionRecording(user: Models.User<Models.Preferences>): Promise<void> {
if (!posthog) return;

const hasRecordedFirstSession = preferences.getKey(POSTHOG_PREFS_KEY, false);

if (!hasRecordedFirstSession) {
posthog.identify(user.$id, {
account_created: user.$createdAt
});
posthog.startSessionRecording();
await preferences.setKey(POSTHOG_PREFS_KEY, true);
} else {
posthog.stopSessionRecording();
}
}

export { posthog };
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Fix Prettier formatting violations before merging.

The pipeline indicates a Prettier formatting check failure. Run prettier --write src/lib/actions/posthog.ts to resolve.

🧰 Tools
🪛 GitHub Actions: Tests

[error] 1-1: Prettier formatting check failed for src/lib/actions/posthog.ts. Run 'prettier --write' to fix code style issues.

🤖 Prompt for AI Agents
In src/lib/actions/posthog.ts around lines 1 to 40, the file fails Prettier
formatting; run Prettier to reformat the file (e.g., prettier --write
src/lib/actions/posthog.ts) or apply your project's configured formatter
settings/IDE formatting to fix whitespace, quoting, and trailing-comma rules,
then re-run the linter/CI and commit the formatted file.

Comment on lines +9 to +22
if (browser && VARS.POSTHOG_API_KEY && !ENV.DEV && !ENV.TEST) {
posthog.init(VARS.POSTHOG_API_KEY, {
api_host: VARS.POSTHOG_HOST,
person_profiles: 'identified_only',
capture_pageview: true,
capture_pageleave: true,
session_recording: {
recordCrossOriginIframes: false,
/*maskTextSelector: '.ph-no-capture'*/
},
autocapture: true,
disable_session_recording: !ENV.PROD
});
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

cat -n src/lib/actions/posthog.ts

Repository: appwrite/console

Length of output: 1618


🏁 Script executed:

# Search for ENV variable definitions
rg -t ts "ENV\s*[:=]\s*\{" --context 10

Repository: appwrite/console

Length of output: 1319


🏁 Script executed:

# Look for environment config files
fd -t js -t ts "env" | grep -E "(config|env)" | head -20

Repository: appwrite/console

Length of output: 229


🌐 Web query:

PostHog session recording configuration production preview environments best practices

💡 Result:

Here are concise best practices for configuring PostHog session recordings across production / preview (staging/dev) environments:

  1. Use separate PostHog projects per environment (prod vs staging/dev/preview). This prevents test noise and billing surprises. Use env vars to load the correct API key per environment. [3]

  2. Don’t record everything by default. Enable recordings only where useful via URL triggers, event triggers or feature flags (e.g., signup/checkout flows). URL triggers replace the older authorized-domains setting. Use sampling and minimum-duration to reduce volume. (start/stop APIs let you programmatically control recordings). [2][4]

  3. Disable or restrict recordings in preview builds:

    • Default to disable_session_recording: true in non-prod builds and call posthog.startSessionRecording() only when needed in tests.
    • Or keep recording off and selectively enable for targeted flows with triggers/feature flags. [2][4]
  4. Protect PII and sensitive UI:

    • Mask inputs/text by default (maskAllInputs / maskTextSelector) and selectively unmask only required elements.
    • Use ph-no-capture on elements that must never be recorded.
    • Use before_send to strip sensitive data from events. [1][5]
  5. Use sampling, minimum-duration (strictMinimumDuration) and billing limits:

    • Configure a sample rate and a minimum continuous duration so short/bounce sessions aren’t ingested.
    • Set recording/billing caps to avoid unexpected overages. [2]
  6. Consent, compliance and persistence:

    • Gate recordings behind consent where required (EU/UK) via your CMP/cookie banner or application logic.
    • Consider persistence settings (localStorage vs cookie) to avoid cookie-driven loops with CMPs. [1][2][5]
  7. Dev/test ergonomics and reliability:

    • Keep posthog-js up to date (recordings features/fixes roll out often).
    • Watch CSP, CORS and ad-blocker interactions (recorder.js may be blocked). Use a reverse-proxy if blockers are an issue. [4]
  8. Operational tips:

    • Logically name projects (prod/staging/dev/preview).
    • Use feature flags or environment-only config to flip recording behavior without code changes.
    • Monitor recording consumption and iterate (most teams watch a small fraction of replays; focus capture on high-value flows). [3][1]

Sources:

  • PostHog privacy & replay masking docs. [1]
  • How to control which sessions you record (session recording triggers, start/stop, sampling, strictMinimumDuration). [2]
  • PostHog tutorial: multiple environments / use separate projects. [3]
  • Session replay troubleshooting (URL triggers, CSP, blockers, SDK version notes). [4]
  • Controlling data collection / autocapture and masking guidance. [5]

If you want, I can produce a short example posthog.init snippet showing a recommended prod vs preview config (masking + disabled recordings in preview).


Clarify disable_session_recording configuration and handle PREVIEW environments properly.

Line 20 sets disable_session_recording: !ENV.PROD, but the outer condition on line 9 already ensures !ENV.DEV. Since ENV.PROD = !dev, this configuration is redundant—when the outer condition passes, ENV.PROD is true, making disable_session_recording always false.

Additionally, the outer condition initializes PostHog for both production and preview environments without distinction. Per PostHog best practices, session recording should be disabled by default in preview deployments and enabled only in production. Consider adding ENV.PREVIEW to the initialization condition check or adjusting the config to properly handle environment-specific behavior.

Line 17 contains commented code for maskTextSelector. Remove it or uncomment with proper configuration for sensitive data masking, which PostHog recommends as default behavior across all environments.

🤖 Prompt for AI Agents
In src/lib/actions/posthog.ts around lines 9 to 22, the PostHog init is enabling
session recording for preview environments and using a redundant
disable_session_recording: !ENV.PROD; change the initialization guard to only
run in production (e.g., require ENV.PROD true, not just !ENV.DEV) or explicitly
exclude ENV.PREVIEW (add && !ENV.PREVIEW), and set disable_session_recording to
true for non-production/preview (e.g., disable_session_recording: !ENV.PROD ||
ENV.PREVIEW) so the flag is accurate regardless of the outer condition; also
remove the commented maskTextSelector line or replace it with a proper default
maskTextSelector (e.g., set a configurable mask selector) so sensitive data
masking is consistently applied.

Comment on lines +24 to +38
export async function initializeSessionRecording(user: Models.User<Models.Preferences>): Promise<void> {
if (!posthog) return;

const hasRecordedFirstSession = preferences.getKey(POSTHOG_PREFS_KEY, false);

if (!hasRecordedFirstSession) {
posthog.identify(user.$id, {
account_created: user.$createdAt
});
posthog.startSessionRecording();
await preferences.setKey(POSTHOG_PREFS_KEY, true);
} else {
posthog.stopSessionRecording();
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Add error handling and consider privacy/consent requirements.

The initializeSessionRecording function lacks error handling. If posthog.identify(), posthog.startSessionRecording(), or preferences.setKey() fail, the state could become inconsistent (e.g., preference flag set but recording not actually started).

Additionally, session recording captures user behavior and personal data (user ID, account creation date). Ensure compliance with privacy regulations (GDPR, CCPA) by implementing:

  • User consent mechanism before starting session recording
  • Clear privacy policy disclosure
  • Opt-out capability
🔎 Example error handling
 export async function initializeSessionRecording(user: Models.User<Models.Preferences>): Promise<void> {
     if (!posthog) return;
 
     const hasRecordedFirstSession = preferences.getKey(POSTHOG_PREFS_KEY, false);
 
     if (!hasRecordedFirstSession) {
-        posthog.identify(user.$id, {
-            account_created: user.$createdAt
-        });
-        posthog.startSessionRecording();
-        await preferences.setKey(POSTHOG_PREFS_KEY, true);
+        try {
+            posthog.identify(user.$id, {
+                account_created: user.$createdAt
+            });
+            posthog.startSessionRecording();
+            await preferences.setKey(POSTHOG_PREFS_KEY, true);
+        } catch (error) {
+            console.error('Failed to initialize PostHog session recording:', error);
+        }
     } else {
         posthog.stopSessionRecording();
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
export async function initializeSessionRecording(user: Models.User<Models.Preferences>): Promise<void> {
if (!posthog) return;
const hasRecordedFirstSession = preferences.getKey(POSTHOG_PREFS_KEY, false);
if (!hasRecordedFirstSession) {
posthog.identify(user.$id, {
account_created: user.$createdAt
});
posthog.startSessionRecording();
await preferences.setKey(POSTHOG_PREFS_KEY, true);
} else {
posthog.stopSessionRecording();
}
}
export async function initializeSessionRecording(user: Models.User<Models.Preferences>): Promise<void> {
if (!posthog) return;
const hasRecordedFirstSession = preferences.getKey(POSTHOG_PREFS_KEY, false);
if (!hasRecordedFirstSession) {
try {
posthog.identify(user.$id, {
account_created: user.$createdAt
});
posthog.startSessionRecording();
await preferences.setKey(POSTHOG_PREFS_KEY, true);
} catch (error) {
console.error('Failed to initialize PostHog session recording:', error);
}
} else {
posthog.stopSessionRecording();
}
}

Comment on lines +43 to +44
import { user } from '$lib/stores/user';
import { initializeSessionRecording } from '$lib/actions/posthog';
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

find src -name "posthog.ts" -o -name "posthog.js" -o -name "posthog.tsx" -o -name "posthog.jsx"

Repository: appwrite/console

Length of output: 86


🏁 Script executed:

cat -n src/lib/actions/posthog.ts

Repository: appwrite/console

Length of output: 1618


🏁 Script executed:

sed -n '270,285p' src/routes/\(console\)/+layout.svelte

Repository: appwrite/console

Length of output: 629


Add error handling and explicit user consent check to PostHog initialization.

The initializeSessionRecording function lacks error handling around PostHog operations and preferences updates. Additionally, it should verify explicit user consent before starting session recording. Ensure:

  • Wrap posthog.identify(), posthog.startSessionRecording(), and await preferences.setKey() in a try-catch block
  • Add an explicit check for user opt-in preferences before calling posthog.startSessionRecording() on line 33
  • Log or handle initialization failures gracefully without breaking the session

The POSTHOG_API_KEY check (line 9) and environment guards are correctly implemented.

🤖 Prompt for AI Agents
In src/routes/(console)/+layout.svelte around lines 43–44, add robust error
handling and an explicit opt-in check when initializing PostHog: wrap calls to
posthog.identify(), posthog.startSessionRecording(), and await
preferences.setKey(...) in a try-catch so failures are caught and logged/handled
without throwing; before calling posthog.startSessionRecording() add an explicit
check that the user has opted in (e.g., a preferences flag or user consent
value) and only start session recording when true; in the catch block log the
error and ensure initialization continues gracefully (do not rethrow) so the
session is not broken.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants