Skip to content

Integrate PostHog#254

Merged
quancao-ea merged 6 commits intomainfrom
integrate-posthog
Mar 12, 2026
Merged

Integrate PostHog#254
quancao-ea merged 6 commits intomainfrom
integrate-posthog

Conversation

@quancao-ea
Copy link
Copy Markdown
Collaborator

@quancao-ea quancao-ea commented Mar 11, 2026

Summary by CodeRabbit

  • New Features
    • Integrated analytics and error tracking to monitor application behavior and performance
    • Added performance metrics for snippet operations including timing data
    • Enhanced exception and error reporting capabilities

Add PostHog provider with auto pageview tracking (via history_change),
user identification on auth state changes, error boundary, and
exception autocapture. Gracefully no-ops when VITE_POSTHOG_KEY is absent.
Track RPC duration, slow queries (>20s), errors, and timeouts
for the get_snippets endpoint. Add proper abort signal handling
to cancel in-flight requests when queries change.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 11, 2026

Walkthrough

This pull request integrates PostHog analytics into the application by adding environment variable configuration, dependencies, and instrumentation. It wraps the app with PostHogProvider, instruments snippet fetching with timing and error tracking, and ties analytics identification to the authenticated user.

Changes

Cohort / File(s) Summary
Configuration & Environment
.env.production.example, src/vite-env.d.ts, Dockerfile, .github/workflows/deploy.yml
Added PostHog configuration keys (VITE_POSTHOG_KEY, VITE_POSTHOG_HOST) across environment setup, type definitions, Docker builds, and deployment workflow.
Dependencies
package.json
Added @posthog/react (^1.8.2) and posthog-js (^1.360.0) dependencies.
PostHog Integration
src/lib/posthog.ts, src/providers/posthog.tsx
Created wrapper functions for conditional analytics dispatch and implemented PostHogProvider with user identification tied to authentication context.
App Provider Integration
src/App.tsx
Wrapped existing provider tree with PostHogProvider to enable analytics across the application.
Snippet API Instrumentation
src/apis/snippet.ts, src/hooks/useSnippets.tsx
Added telemetry around snippet fetching: timing measurements, error tracking, slow query detection (20s threshold), and abort signal support for query cancellation.
Type Updates
src/types/snippet.ts
Removed unused similarity property from IRelatedSnippet interface.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 Hop! The analytics now flow,
PostHog data starts to grow,
Timing tracks each snippet request,
User journeys logged their best,
Telemetry hops down the whole nest! 📊

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ 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 'Integrate PostHog' directly and clearly summarizes the main change: adding PostHog analytics integration throughout the application.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch integrate-posthog

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.

@github-actions
Copy link
Copy Markdown

github-actions Bot commented Mar 11, 2026

✅ Preview Deployment Ready!

URL: https://pr-254-verdad-frontend.fly.dev
Commit: f779b81


Preview auto-updates on push. Destroyed when PR closes.

@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces PostHog, a powerful analytics and telemetry platform, to the application. This integration will provide valuable insights into how users interact with the application, track key performance indicators, and automatically report exceptions. These changes are crucial for understanding user behavior, optimizing performance, and proactively addressing issues, ultimately leading to a more stable and user-friendly experience. Additionally, the snippet fetching mechanism has been refined to include cancellation capabilities and improved error handling.

Highlights

  • Analytics and Telemetry Integration: Integrated PostHog, an analytics and telemetry platform, to monitor application usage patterns, user interactions, and overall system performance data.
  • Enhanced Error Reporting: Added automatic exception tracking and a comprehensive error reporting system to identify critical issues faster and improve application stability.
  • Improved Snippet Data Loading: Enhanced snippet data loading with support for request cancellation and more robust error detection and handling mechanisms for increased reliability.
Changelog
  • .env.production.example
    • Added environment variables for PostHog API key and host.
  • package-lock.json
    • Added new dependencies for PostHog React and JavaScript client libraries, along with their transitive dependencies including OpenTelemetry, Protobuf.js, core-js, dompurify, fflate, long, preact, query-selector-shadow-dom, and web-vitals.
    • Updated the version of the 'cross-spawn' dependency.
    • Adjusted type definition configurations for '@types/node' and 'undici-types'.
  • package.json
    • Added '@posthog/react' and 'posthog-js' to the project's dependencies.
  • src/App.tsx
    • Imported the new 'PostHogProvider' component.
    • Wrapped the main application content with 'PostHogProvider' to enable analytics across the app.
  • src/apis/snippet.ts
    • Imported the 'posthog' client for analytics capture.
    • Defined a 'SLOW_THRESHOLD_MS' constant to identify slow snippet fetching operations.
    • Modified the 'fetchSnippets' function to accept an 'abortSignal' for request cancellation.
    • Implemented PostHog capture for both successful and erroneous snippet fetching operations, including performance metrics and error details.
    • Added logic to differentiate between aborted requests and timeouts for more precise error tracking.
  • src/hooks/useSnippets.tsx
    • Updated the 'useInfiniteQuery' hook to pass the 'signal' from the query function context as 'abortSignal' to the 'fetchSnippets' API call, enabling request cancellation.
  • src/providers/posthog.tsx
    • Created a new provider file for PostHog integration.
    • Initialized the PostHog client with API key and configuration options from environment variables.
    • Implemented a 'PostHogTracking' component that identifies users with PostHog based on their authentication status.
    • Provided a conditional 'PostHogProvider' that only initializes PostHog if the API key is configured.
  • src/types/snippet.ts
    • Removed the 'similarity' property from the 'IRelatedSnippet' interface.
  • src/vite-env.d.ts
    • Declared 'VITE_POSTHOG_KEY' and 'VITE_POSTHOG_HOST' in the 'ImportMetaEnv' interface for type safety.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@vercel
Copy link
Copy Markdown

vercel Bot commented Mar 11, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
verdad-frontend Error Error Mar 12, 2026 7:57am

Copy link
Copy Markdown

@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: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/apis/snippet.ts`:
- Around line 52-59: The telemetry code currently spreads getSnippetsOptions
(which contains p_search_term and p_filter) into analytics causing raw user
input to be sent; update places that spread getSnippetsOptions (the telemetry
payload usage around where telemetry/event tracking is called) to instead build
a sanitized payload that omits p_search_term and p_filter and includes only
non-sensitive derived fields (e.g. has_search: Boolean(searchTerm),
filters_count: Object.keys(actualFilters || {}).length or similar, language,
orderBy, page, page_size). Replace the direct spread of getSnippetsOptions with
this explicit sanitized object wherever getSnippetsOptions was used for
telemetry (preserving the original getSnippetsOptions for API calls).

In `@src/providers/posthog.tsx`:
- Around line 24-33: The current useEffect calls posthog.reset() whenever userId
is falsy, which resets distinct IDs on initial mount and fragments anonymous
activity; change the effect to only call posthog.reset() when the user
transitions from authenticated to unauthenticated (a real logout). Implement a
previous-userId check (e.g., a useRef prevUserId) inside the useEffect that
compares prevUserId to userId and only calls posthog.reset() if prevUserId was
truthy and userId is now falsy; continue to call posthog.identify(userId, {
email: userEmail }) when userId becomes truthy, and update prevUserId after
handling. Ensure the effect still depends on posthog, userId, and userEmail.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 0dce0365-a48e-46f5-88ae-b4630528b8c9

📥 Commits

Reviewing files that changed from the base of the PR and between 1c0be49 and e313dc3.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (8)
  • .env.production.example
  • package.json
  • src/App.tsx
  • src/apis/snippet.ts
  • src/hooks/useSnippets.tsx
  • src/providers/posthog.tsx
  • src/types/snippet.ts
  • src/vite-env.d.ts
💤 Files with no reviewable changes (1)
  • src/types/snippet.ts

Comment thread src/apis/snippet.ts
Comment on lines +52 to +59
const getSnippetsOptions = {
page: pageParam,
page_size: pageSize,
p_language: language,
p_filter: actualFilters,
p_order_by: orderBy,
p_search_term: searchTerm
})
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Don't send raw search input and filters to PostHog.

Lines 73-77 and 83-89 spread getSnippetsOptions into telemetry, which includes p_search_term and p_filter. That exports raw user queries/filter state to analytics and creates very high-cardinality events. Whitelist derived, non-sensitive fields instead.

Safer payload shape
   const getSnippetsOptions = {
     page: pageParam,
     page_size: pageSize,
     p_language: language,
     p_filter: actualFilters,
     p_order_by: orderBy,
     p_search_term: searchTerm
   }
+  const analyticsProps = {
+    page: pageParam,
+    page_size: pageSize,
+    p_language: language,
+    p_order_by: orderBy,
+    has_search_term: searchTerm.trim().length > 0,
+    filter_count: Object.keys(actualFilters ?? {}).length
+  }
@@
       const isTimeout = /timeout|canceling statement/i.test(error.message)
       posthog.captureException(error, {
-        ...getSnippetsOptions,
+        ...analyticsProps,
         duration_ms: durationMs,
         is_timeout: isTimeout
       })
@@
   posthog.capture('get_snippets_rpc', {
-    ...getSnippetsOptions,
+    ...analyticsProps,
     duration_ms: durationMs,
     status: durationMs > SLOW_THRESHOLD_MS ? 'warning' : 'success',
     total_pages: data.total_pages,
     total_snippets: data.num_of_snippets
   })

Also applies to: 73-89

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/apis/snippet.ts` around lines 52 - 59, The telemetry code currently
spreads getSnippetsOptions (which contains p_search_term and p_filter) into
analytics causing raw user input to be sent; update places that spread
getSnippetsOptions (the telemetry payload usage around where telemetry/event
tracking is called) to instead build a sanitized payload that omits
p_search_term and p_filter and includes only non-sensitive derived fields (e.g.
has_search: Boolean(searchTerm), filters_count: Object.keys(actualFilters ||
{}).length or similar, language, orderBy, page, page_size). Replace the direct
spread of getSnippetsOptions with this explicit sanitized object wherever
getSnippetsOptions was used for telemetry (preserving the original
getSnippetsOptions for API calls).

Comment thread src/providers/posthog.tsx
Comment on lines +24 to +33
useEffect(() => {
if (!userId) {
posthog.reset()
return
}

posthog.identify(userId, {
email: userEmail
})
}, [posthog, userId, userEmail])
Copy link
Copy Markdown

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:

#!/bin/bash
set -euo pipefail

rg -n -C3 'useState|onAuthStateChange|getSession|setUser|signOut|logout' src/providers/auth.tsx
sed -n '1,260p' src/providers/auth.tsx

Repository: PublicDataWorks/verdad-frontend

Length of output: 6470


Avoid resetting PostHog on every anonymous render.

Lines 25–27 reset PostHog whenever userId is falsy, including on initial mount before session restoration completes. This rotates the distinct ID before authentication finishes, causing anonymous activity to fragment instead of merging cleanly into the later identified user. Reset only when transitioning from a logged-in state to logged-out (i.e., a real logout), not on initial mount or anonymous states.

Suggested direction
-import { useEffect } from 'react'
+import { useEffect, useRef } from 'react'
@@
 function PostHogTracking({ children }: PostHogProviderProps) {
   const posthog = usePostHog()
   const { user } = useAuth()
   const userId = user?.id
   const userEmail = user?.email
+  const previousUserId = useRef<string | undefined>(undefined)

   useEffect(() => {
     if (!userId) {
-      posthog.reset()
+      if (previousUserId.current) {
+        posthog.reset()
+        previousUserId.current = undefined
+      }
       return
     }

+    previousUserId.current = userId
     posthog.identify(userId, {
       email: userEmail
     })
   }, [posthog, userId, userEmail])
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/providers/posthog.tsx` around lines 24 - 33, The current useEffect calls
posthog.reset() whenever userId is falsy, which resets distinct IDs on initial
mount and fragments anonymous activity; change the effect to only call
posthog.reset() when the user transitions from authenticated to unauthenticated
(a real logout). Implement a previous-userId check (e.g., a useRef prevUserId)
inside the useEffect that compares prevUserId to userId and only calls
posthog.reset() if prevUserId was truthy and userId is now falsy; continue to
call posthog.identify(userId, { email: userEmail }) when userId becomes truthy,
and update prevUserId after handling. Ensure the effect still depends on
posthog, userId, and userEmail.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request integrates PostHog for analytics and error tracking. The implementation is well-structured, introducing a PostHogProvider and instrumenting the fetchSnippets API call for performance monitoring and error reporting. The changes also correctly add support for request cancellation using AbortSignal. I've left a few comments on making the error handling logic more robust and cleaning up the PostHog configuration.

@PublicDataWorks PublicDataWorks deleted a comment from gemini-code-assist Bot Mar 12, 2026
@PublicDataWorks PublicDataWorks deleted a comment from gemini-code-assist Bot Mar 12, 2026
@PublicDataWorks PublicDataWorks deleted a comment from gemini-code-assist Bot Mar 12, 2026
Include VITE_POSTHOG_KEY and VITE_POSTHOG_HOST as build arguments
to support PostHog analytics integration during the Docker build
process.
Copy link
Copy Markdown

@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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@Dockerfile`:
- Around line 11-12: The Dockerfile now declares ARG VITE_POSTHOG_KEY and ARG
VITE_POSTHOG_HOST but the Fly deployment workflows don't pass them through;
update the Fly deploy steps (the flyctl build/deploy commands in your CI
workflows) to include --build-arg VITE_POSTHOG_KEY=${{ secrets.VITE_POSTHOG_KEY
}} and --build-arg VITE_POSTHOG_HOST=${{ secrets.VITE_POSTHOG_HOST }} (or the
appropriate env/secret variables used in the repo) so the build-time args are
populated and the PostHog integration is compiled with real values.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: b765a4ec-cddd-4573-8b70-4a5503fc2e43

📥 Commits

Reviewing files that changed from the base of the PR and between e313dc3 and 0c002cc.

📒 Files selected for processing (1)
  • Dockerfile

Comment thread Dockerfile
Add VITE_POSTHOG_KEY and VITE_POSTHOG_HOST build arguments to both
the production deployment and PR preview workflows to ensure PostHog
analytics configuration is properly passed during Docker builds.
Copy link
Copy Markdown

@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: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In @.github/workflows/fly-pr-preview.yml:
- Around line 100-102: The workflow is injecting production PostHog credentials
into PR previews (VITE_POSTHOG_KEY and VITE_POSTHOG_HOST) which will send
reviewer traffic/PII to production; remove those two --build-arg lines from the
fly-pr-preview workflow (or set them to empty) so previews do not receive the
production key, and add a defensive guard in src/providers/posthog.tsx (e.g.,
check a new env like VITE_ENABLE_POSTHOG or require NODE_ENV==='production'
before calling the PostHog init/identify code) so PostHog only initializes when
an explicit preview project or production flag is present.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: afe6b324-b62a-4c63-babf-10528699cd5b

📥 Commits

Reviewing files that changed from the base of the PR and between 0c002cc and 71fb31e.

📒 Files selected for processing (2)
  • .github/workflows/deploy.yml
  • .github/workflows/fly-pr-preview.yml

Comment thread .github/workflows/fly-pr-preview.yml Outdated
Add a thin wrapper (src/lib/posthog.ts) that no-ops capture and
captureException when VITE_POSTHOG_KEY is not set, preventing calls
to an uninitialized posthog-js singleton.
PostHog environment variables are not needed for PR preview
deployments. Removing unnecessary build arguments to simplify
the workflow configuration.
Copy link
Copy Markdown

@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: 2

♻️ Duplicate comments (1)
src/apis/snippet.ts (1)

52-59: ⚠️ Potential issue | 🟠 Major

Whitelist analytics props instead of spreading RPC params.

getSnippetsOptions still contains p_search_term and p_filter, and both telemetry paths spread it straight into PostHog. That sends raw user input/high-cardinality filter state to analytics; build a sanitized analyticsProps object and use that for both calls.

Also applies to: 73-89

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/apis/snippet.ts` around lines 52 - 59, getSnippetsOptions currently
includes raw user inputs (p_search_term, p_filter) which are being spread into
analytics; create a sanitized analyticsProps object that whitelists only safe
fields (e.g., page, page_size, p_language, p_order_by, plus
low-cardinality/sanitized filter tokens) and omit p_search_term and any
high-cardinality filter values, then use analyticsProps for PostHog/event
tracking instead of spreading getSnippetsOptions or RPC params; update both the
getSnippetsOptions construction and the places referenced around lines 73-89 to
send analyticsProps to PostHog while keeping getSnippetsOptions intact for the
RPC call.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/apis/snippet.ts`:
- Around line 67-78: The current error handling logs every error before checking
for aborts; move the console.error call inside the non-aborted branch so
cancelled requests aren't logged as errors. Specifically, evaluate isAborted
using the existing /AbortError/i test on error.message, then only call
console.error and captureException when !isAborted (use the same
getSnippetsOptions and durationMs context and preserve the is_timeout check).
Ensure you still guard usage of error.message if it can be undefined before
running the regex.

In `@src/lib/posthog.ts`:
- Around line 5-16: The wrappers capture and captureException currently mix bare
"return" with "return posthog..." which violates consistent-return; make them
explicit side-effect-only by removing returned values: change both functions to
have a void return type, and when isEnabled is true call posthog.capture(...)
and posthog.captureException(...) as standalone statements (no returned value)
while keeping the early "if (!isEnabled) return" guard; reference the functions
capture, captureException and the delegated
posthog.capture/posthog.captureException and the isEnabled flag when applying
the change.

---

Duplicate comments:
In `@src/apis/snippet.ts`:
- Around line 52-59: getSnippetsOptions currently includes raw user inputs
(p_search_term, p_filter) which are being spread into analytics; create a
sanitized analyticsProps object that whitelists only safe fields (e.g., page,
page_size, p_language, p_order_by, plus low-cardinality/sanitized filter tokens)
and omit p_search_term and any high-cardinality filter values, then use
analyticsProps for PostHog/event tracking instead of spreading
getSnippetsOptions or RPC params; update both the getSnippetsOptions
construction and the places referenced around lines 73-89 to send analyticsProps
to PostHog while keeping getSnippetsOptions intact for the RPC call.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8663efac-b0ba-4630-8a6d-c4853e45f7b4

📥 Commits

Reviewing files that changed from the base of the PR and between 71fb31e and f779b81.

📒 Files selected for processing (2)
  • src/apis/snippet.ts
  • src/lib/posthog.ts

Comment thread src/lib/posthog.ts
Comment on lines +5 to +16
export function capture(
...args: Parameters<typeof posthog.capture>
): ReturnType<typeof posthog.capture> | undefined {
if (!isEnabled) return
return posthog.capture(...args)
}

export function captureException(
...args: Parameters<typeof posthog.captureException>
): ReturnType<typeof posthog.captureException> | undefined {
if (!isEnabled) return
return posthog.captureException(...args)
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# First, let's check if the file exists and read the relevant section
cat -n src/lib/posthog.ts

Repository: PublicDataWorks/verdad-frontend

Length of output: 686


🏁 Script executed:

# Check the callers mentioned in src/apis/snippet.ts
cat -n src/apis/snippet.ts | sed -n '70,95p'

Repository: PublicDataWorks/verdad-frontend

Length of output: 954


🏁 Script executed:

# Search for all usages of the capture and captureException functions
rg -n "capture\(" src/ --type ts --type tsx -B 2 -A 2

Repository: PublicDataWorks/verdad-frontend

Length of output: 102


🏁 Script executed:

# Also check for captureException usages
rg -n "captureException\(" src/ --type ts --type tsx -B 2 -A 2

Repository: PublicDataWorks/verdad-frontend

Length of output: 102


🏁 Script executed:

# Search for all capture( and captureException( usages
rg -n "capture\(" src/ -B 2 -A 2

Repository: PublicDataWorks/verdad-frontend

Length of output: 715


🏁 Script executed:

# Check for any linting configuration
fd -e "eslintrc*" -e "eslint.config.*" -e ".prettierrc*"

Repository: PublicDataWorks/verdad-frontend

Length of output: 57


🏁 Script executed:

# Also check package.json for linting rules
cat package.json | grep -A 20 '"eslint\|"lint'

Repository: PublicDataWorks/verdad-frontend

Length of output: 1899


🏁 Script executed:

# Search for captureException usages more thoroughly
rg -n "captureException" src/

Repository: PublicDataWorks/verdad-frontend

Length of output: 490


🏁 Script executed:

# Check if there's an eslintrc config file
find . -maxdepth 3 -name ".eslintrc*" -o -name "eslint.config.*"

Repository: PublicDataWorks/verdad-frontend

Length of output: 115


🏁 Script executed:

# Look for the actual linting rules configuration
cat .eslintrc.cjs 2>/dev/null || cat .eslintrc.json 2>/dev/null || cat .eslintrc.js 2>/dev/null || echo "No eslintrc found in root"

Repository: PublicDataWorks/verdad-frontend

Length of output: 5618


🏁 Script executed:

# Double-check if these functions are imported/exported elsewhere
rg -n "from.*posthog|import.*capture" src/ | grep -v node_modules

Repository: PublicDataWorks/verdad-frontend

Length of output: 483


Make these wrappers explicitly side-effect-only.

Both functions mix bare return with return posthog..., triggering the consistent-return linting rule. The only callers in src/apis/snippet.ts (lines 73 and 83) treat both helpers as fire-and-forget, so returning the delegated value serves no purpose.

Suggested fix
 export function capture(
   ...args: Parameters<typeof posthog.capture>
-): ReturnType<typeof posthog.capture> | undefined {
+): void {
   if (!isEnabled) return
-  return posthog.capture(...args)
+  posthog.capture(...args)
 }
 
 export function captureException(
   ...args: Parameters<typeof posthog.captureException>
-): ReturnType<typeof posthog.captureException> | undefined {
+): void {
   if (!isEnabled) return
-  return posthog.captureException(...args)
+  posthog.captureException(...args)
 }
📝 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 function capture(
...args: Parameters<typeof posthog.capture>
): ReturnType<typeof posthog.capture> | undefined {
if (!isEnabled) return
return posthog.capture(...args)
}
export function captureException(
...args: Parameters<typeof posthog.captureException>
): ReturnType<typeof posthog.captureException> | undefined {
if (!isEnabled) return
return posthog.captureException(...args)
export function capture(
...args: Parameters<typeof posthog.capture>
): void {
if (!isEnabled) return
posthog.capture(...args)
}
export function captureException(
...args: Parameters<typeof posthog.captureException>
): void {
if (!isEnabled) return
posthog.captureException(...args)
}
🧰 Tools
🪛 ESLint

[error] 9-9: Function 'capture' expected no return value.

(consistent-return)


[error] 16-16: Function 'captureException' expected no return value.

(consistent-return)

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/lib/posthog.ts` around lines 5 - 16, The wrappers capture and
captureException currently mix bare "return" with "return posthog..." which
violates consistent-return; make them explicit side-effect-only by removing
returned values: change both functions to have a void return type, and when
isEnabled is true call posthog.capture(...) and posthog.captureException(...) as
standalone statements (no returned value) while keeping the early "if
(!isEnabled) return" guard; reference the functions capture, captureException
and the delegated posthog.capture/posthog.captureException and the isEnabled
flag when applying the change.

@PublicDataWorks PublicDataWorks deleted a comment from coderabbitai Bot Mar 12, 2026
@quancao-ea quancao-ea merged commit 4e5bbaf into main Mar 12, 2026
4 of 5 checks passed
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.

1 participant