Skip to content

claim db worker: update posthog and env vars#79

Merged
aidankmcalister merged 2 commits intomainfrom
claim-db-worker/update-posthog-and-env-vars
Mar 2, 2026
Merged

claim db worker: update posthog and env vars#79
aidankmcalister merged 2 commits intomainfrom
claim-db-worker/update-posthog-and-env-vars

Conversation

@aidankmcalister
Copy link
Member

@aidankmcalister aidankmcalister commented Feb 27, 2026

This PR goes hand in hand with a message I have sent to @ankur-arch around updating the secrets in cloudflare. That must be done prior to merging

Summary by CodeRabbit

Release Notes

  • New Features

    • Added tracking for campaign source and medium parameters
    • Improved page view tracking with enhanced data collection
  • Improvements

    • Enhanced analytics collection system infrastructure
    • Refined request context handling for analytics events
  • Tests

    • Updated test environment configuration

@coderabbitai
Copy link

coderabbitai bot commented Feb 27, 2026

Walkthrough

Refactors analytics infrastructure by replacing direct PostHog API calls with centralized sendAnalyticsEvent functions across server and client implementations. Updates environment variables from POSTHOG_API_HOST to POSTHOG_PROXY_HOST and replaces PostHogProvider with PageViewTracker component for page tracking.

Changes

Cohort / File(s) Summary
Environment Configuration
lib/env.ts, claim-db-worker/__tests__/callback-api.test.ts
Updated environment variable keys: POSTHOG_API_HOST removed and replaced with POSTHOG_PROXY_HOST; POSTHOG_API_KEY now optional. Test mock updated to reflect new key naming.
Server-side Analytics Layer
lib/analytics.ts, app/api/analytics/route.ts
Introduced centralized sendAnalyticsEvent with NextRequest support, distinct_id derivation, environment validation, and event prefix enforcement. Analytics route now validates events starting with "create_db:" and routes requests through the new function.
Client-side Analytics Layer
lib/analytics-client.ts, components/PageViewTracker.tsx
Added client-side sendAnalyticsEvent with localStorage-based distinct ID persistence. PageViewTracker component replaces PostHog direct integration with server-side analytics routing; includes pathname and search string in payload.
API Route Integration
app/api/auth/callback/route.ts, app/api/claim/route.ts
Replaced local sendServerAnalyticsEvent helper with centralized sendAnalyticsEvent. Enhanced claim route with utm_source and utm_medium query parameters passed to analytics payload.
Provider Replacement
components/PostHogProvider.tsx
Removed PostHog initialization, PHProvider, and global window exposure. Now renders PageViewTracker alongside children for unified analytics tracking.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • DC-5180-analytics #55: Both PRs modify the analytics infrastructure by replacing direct PostHog calls with a centralized sendAnalyticsEvent function and updating environment variable configuration (POSTHOG_API_HOST to POSTHOG_PROXY_HOST).
🚥 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 accurately reflects the main changes: migrating from PostHog API host to a proxy-based approach and updating related environment variables across the codebase.

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


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

@github-actions
Copy link

Preview CLIs & Workers are live!

Test the CLIs locally under tag pr79-claim-db-worker-update-posthog-and-env-vars-22497633465:

npx create-db@pr79
npx create-pg@pr79
npx create-postgres@pr79

Worker URLs
• Create-DB Worker: https://create-db-temp.prisma.io
• Claim-DB Worker: https://create-db.prisma.io

These will live as long as this PR exists under tag pr79-claim-db-worker-update-posthog-and-env-vars-22497633465.

@cloudflare-workers-and-pages
Copy link

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
claim-db-worker 831a53a Commit Preview URL

Branch Preview URL
Feb 27 2026, 05:58 PM

Copy link

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
claim-db-worker/__tests__/callback-api.test.ts (1)

108-114: ⚠️ Potential issue | 🟠 Major

Test assertion does not match the new analytics endpoint.

The pipeline failure indicates this test expects posthog.com in the fetch URL, but the implementation now sends analytics to POSTHOG_PROXY_HOST (mocked as https://proxyhog.prisma-data.net on line 12). The assertion needs to match the proxy host.

🐛 Proposed fix
       expect(mockFetch).toHaveBeenCalledWith(
-        expect.stringContaining("posthog.com"),
+        expect.stringContaining("proxyhog.prisma-data.net"),
         expect.objectContaining({
           method: "POST",
           body: expect.stringContaining("create_db:claim_successful"),
         })
       );
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@claim-db-worker/__tests__/callback-api.test.ts` around lines 108 - 114, The
test assertion in callback-api.test.ts is still expecting "posthog.com" (see
expect.stringContaining("posthog.com")) but the code now sends analytics to the
POSTHOG_PROXY_HOST (mocked as "https://proxyhog.prisma-data.net"); update the
expect.toHaveBeenCalledWith call to check for the proxy host string (e.g.
expect.stringContaining(process.env.POSTHOG_PROXY_HOST or the mocked
"https://proxyhog.prisma-data.net")) and keep the existing objectContaining
assertions (method/body) intact so mockFetch is asserted against the correct
analytics endpoint.
🧹 Nitpick comments (2)
claim-db-worker/components/PostHogProvider.tsx (1)

5-12: Consider renaming the component for clarity.

The component no longer provides a PostHog context; it simply renders PageViewTracker alongside children. The name PostHogProvider is now misleading. Consider renaming to something like AnalyticsWrapper or AnalyticsProvider in a follow-up to better reflect its current purpose.

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

In `@claim-db-worker/components/PostHogProvider.tsx` around lines 5 - 12, The
component PostHogProvider no longer provides a PostHog context and the name is
misleading; rename the exported component PostHogProvider to a clearer name
(e.g., AnalyticsWrapper or AnalyticsProvider) and update all references/usages
accordingly so that the function Component PostHogProvider (which renders
PageViewTracker and children) is renamed and exported under the new name, and
any imports/usages across the codebase that reference PostHogProvider are
updated to the new identifier.
claim-db-worker/app/api/analytics/route.ts (1)

48-50: Consider distinguishing JSON parse errors from analytics failures.

The catch block handles both JSON parsing errors (client error) and potential analytics failures. Currently, both return a 500 status, but invalid JSON from the client would more accurately be a 400 Bad Request.

🔧 Optional: More precise error handling
-  try {
-    const body = (await request.json()) as {
+  let body: { event?: string; properties?: Record<string, unknown> };
+  try {
+    body = await request.json();
+  } catch {
+    return NextResponse.json(
+      { error: "Invalid JSON body" },
+      { status: 400 }
+    );
+  }
+
+  try {
+    const body = body as {
       event?: string;
       properties?: Record<string, unknown>;
     };

Alternatively, a simpler approach keeping the current structure:

   } catch (error) {
-    console.error("Failed to send PostHog event:", error);
-    return NextResponse.json({ error: "Analytics failed" }, { status: 500 });
+    if (error instanceof SyntaxError) {
+      return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
+    }
+    console.error("Failed to send PostHog event:", error);
+    return NextResponse.json({ error: "Analytics failed" }, { status: 500 });
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@claim-db-worker/app/api/analytics/route.ts` around lines 48 - 50, The catch
block in the route handler currently treats JSON parse errors and analytics
failures the same; update the catch to detect client-side JSON parse errors
(e.g., error.name === 'SyntaxError' or error instanceof SyntaxError) and return
NextResponse.json({ error: "Invalid JSON" }, { status: 400 }) for those,
otherwise keep logging (console.error("Failed to send PostHog event:", error))
and return the 500 response; adjust the existing catch in route.ts around the
PostHog/send logic and use NextResponse.json for both branches.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@claim-db-worker/__tests__/callback-api.test.ts`:
- Around line 108-114: The test assertion in callback-api.test.ts is still
expecting "posthog.com" (see expect.stringContaining("posthog.com")) but the
code now sends analytics to the POSTHOG_PROXY_HOST (mocked as
"https://proxyhog.prisma-data.net"); update the expect.toHaveBeenCalledWith call
to check for the proxy host string (e.g.
expect.stringContaining(process.env.POSTHOG_PROXY_HOST or the mocked
"https://proxyhog.prisma-data.net")) and keep the existing objectContaining
assertions (method/body) intact so mockFetch is asserted against the correct
analytics endpoint.

---

Nitpick comments:
In `@claim-db-worker/app/api/analytics/route.ts`:
- Around line 48-50: The catch block in the route handler currently treats JSON
parse errors and analytics failures the same; update the catch to detect
client-side JSON parse errors (e.g., error.name === 'SyntaxError' or error
instanceof SyntaxError) and return NextResponse.json({ error: "Invalid JSON" },
{ status: 400 }) for those, otherwise keep logging (console.error("Failed to
send PostHog event:", error)) and return the 500 response; adjust the existing
catch in route.ts around the PostHog/send logic and use NextResponse.json for
both branches.

In `@claim-db-worker/components/PostHogProvider.tsx`:
- Around line 5-12: The component PostHogProvider no longer provides a PostHog
context and the name is misleading; rename the exported component
PostHogProvider to a clearer name (e.g., AnalyticsWrapper or AnalyticsProvider)
and update all references/usages accordingly so that the function Component
PostHogProvider (which renders PageViewTracker and children) is renamed and
exported under the new name, and any imports/usages across the codebase that
reference PostHogProvider are updated to the new identifier.

ℹ️ Review info

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8221f62 and 831a53a.

📒 Files selected for processing (9)
  • claim-db-worker/__tests__/callback-api.test.ts
  • claim-db-worker/app/api/analytics/route.ts
  • claim-db-worker/app/api/auth/callback/route.ts
  • claim-db-worker/app/api/claim/route.ts
  • claim-db-worker/components/PageViewTracker.tsx
  • claim-db-worker/components/PostHogProvider.tsx
  • claim-db-worker/lib/analytics-client.ts
  • claim-db-worker/lib/analytics.ts
  • claim-db-worker/lib/env.ts

@aidankmcalister aidankmcalister merged commit 39b32da into main Mar 2, 2026
5 of 6 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