Skip to content

feat(posthog): update PostHog integration with environment variables and consent handling#75

Merged
JoachimLK merged 3 commits into
mainfrom
fix/fix-posthog-integration
Mar 9, 2026
Merged

feat(posthog): update PostHog integration with environment variables and consent handling#75
JoachimLK merged 3 commits into
mainfrom
fix/fix-posthog-integration

Conversation

@JoachimLK
Copy link
Copy Markdown
Contributor

@JoachimLK JoachimLK commented Mar 9, 2026

Summary

  • What does this PR change?
  • Why is this needed?

Type of change

  • Bug fix
  • Feature
  • Refactor
  • Docs
  • Chore

Validation

  • I tested locally
  • I added/updated relevant documentation
  • I verified multi-tenant scoping and auth behavior for affected API paths

DCO

  • All commits in this PR are signed off (Signed-off-by) via git commit -s

Summary by CodeRabbit

  • New Features

    • Optional PostHog analytics configuration via environment/build settings.
    • Build-time support for injecting PostHog keys to control inclusion in production bundles.
    • Route proxying added to improve analytics delivery and bypass ad-blockers.
  • Bug Fixes / Improvements

    • Consent flow now records a pageview when a user opts in.
    • Extended URL sanitization to include an additional initial-referrer field.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 9, 2026

Warning

Rate limit exceeded

@JoachimLK has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 14 minutes and 4 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 29718b45-a5e1-4a97-83aa-c5cc821c44a6

📥 Commits

Reviewing files that changed from the base of the PR and between 74ae687 and da4e78d.

📒 Files selected for processing (2)
  • app/composables/useInterviews.ts
  • nuxt.config.ts
📝 Walkthrough

Walkthrough

Adds PostHog analytics configuration and build args, updates Nuxt/PostHog configuration and route proxying, extends client consent composable to emit a manual pageview capture after consent, adjusts a client plugin sanitization set, and switches server-side PostHog config to environment variables.

Changes

Cohort / File(s) Summary
Environment & Build
\.env.example, Dockerfile
Added POSTHOG_PUBLIC_KEY and POSTHOG_HOST examples; Dockerfile now accepts ARG POSTHOG_PUBLIC_KEY and ARG POSTHOG_HOST and exposes them as ENV for build-time injection.
Client Analytics & Consent
app/composables/useAnalyticsConsent.ts, app/plugins/posthog-identity.client.ts
Composable extended to call posthog.capture('$pageview', ...) after consent; posthog accessor type gains capture. Removed parallel: true from the plugin and added '$initial_referrer' to sensitive URL properties.
Nuxt / Routing
nuxt.config.ts
Removed explicit public runtime config for PostHog in favor of @posthog/nuxt-managed posthogConfig; added client proxy fields (api_host, ui_host) and route rules to proxy /ingest/** and /ingest/static/**.
Server-side PostHog
server/utils/posthog.ts
Switched PostHog server initialization to read POSTHOG_PUBLIC_KEY and POSTHOG_HOST from environment variables (keeps same defaults and behavior).
Package / Manifest
package.json
(Referenced) PostHog-related dependency adjustments noted in manifest.

Sequence Diagram(s)

mermaid
sequenceDiagram
participant User
participant NuxtApp as Nuxt App (client)
participant PostHogSDK as PostHog SDK
participant Proxy as /ingest Proxy (server)
participant PostHogCloud as PostHog

User->>NuxtApp: grant analytics consent
NuxtApp->>PostHogSDK: enable capturing (opt_in_capturing)
NuxtApp->>PostHogSDK: capture("$pageview", { $current_url })
PostHogSDK->>Proxy: POST /ingest (api_host)
Proxy->>PostHogCloud: forward to PostHog ingestion endpoint

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I hopped in code where keys were new,

PostHog whispers, proxy routes flew,
Consent given, a pageview spun,
Quietly tracked beneath the sun,
Thump-thump—analytics, a tiny hop of fun 🥕📈

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description contains only an empty template with unchecked boxes and no actual content filled in. All required sections (Summary, Type of change, Validation, DCO) lack meaningful information. Fill in the Summary section explaining what changed and why, select the appropriate Type of change checkbox, and confirm testing and DCO compliance with checked boxes.
Docstring Coverage ⚠️ Warning Docstring coverage is 25.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and accurately summarizes the main changes: updating PostHog integration with environment variables and consent handling, which aligns with the changeset.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/fix-posthog-integration

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.

@railway-app railway-app Bot temporarily deployed to applirank / reqcore-pr-75 March 9, 2026 20:16 Destroyed
@railway-app
Copy link
Copy Markdown

railway-app Bot commented Mar 9, 2026

🚅 Deployed to the reqcore-pr-75 environment in applirank

Service Status Web Updated (UTC)
applirank ✅ Success (View Logs) Mar 9, 2026 at 8:34 pm

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

🧹 Nitpick comments (1)
app/composables/useAnalyticsConsent.ts (1)

18-19: Consider extracting the PostHog type for readability.

The inline type cast is verbose. Extracting it improves readability:

♻️ Suggested refactor
+type PostHogClient = {
+  opt_in_capturing: () => void
+  opt_out_capturing: () => void
+  capture: (event: string, properties?: Record<string, unknown>) => void
+}
+
 export function useAnalyticsConsent() {
-  const posthog = (useNuxtApp() as Record<string, unknown>).$posthog as ((() => { opt_in_capturing: () => void, opt_out_capturing: () => void, capture: (event: string, properties?: Record<string, unknown>) => void }) | undefined)
+  const posthog = (useNuxtApp() as Record<string, unknown>).$posthog as (() => PostHogClient) | undefined
   const ph = posthog?.()
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@app/composables/useAnalyticsConsent.ts` around lines 18 - 19, Extract the
inline PostHog type into a named type or interface (e.g., PostHogClient) and use
that alias instead of the verbose cast in useAnalyticsConsent.ts; replace the
current cast on posthog with the new PostHogClient type and keep the posthog
variable and ph assignment logic unchanged (referencing the posthog and ph
identifiers) so the code is more readable and the shape of the PostHog API is
centralized.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@nuxt.config.ts`:
- Around line 206-208: The proxy entries in nuxt.config.ts mapping '/ingest/**'
and '/ingest/static/**' are hardcoded to EU endpoints (eu.i.posthog.com /
eu-assets.i.posthog.com) which will conflict when POSTHOG_HOST is set to a US
host; update the proxy configuration to derive targets from the POSTHOG_HOST
environment variable (or add a new POSTHOG_PROXY_HOST config) and use that value
for the '/ingest/**' and '/ingest/static/**' proxy targets, falling back to the
existing EU endpoints if the env var is not set; alternatively add a comment in
nuxt.config.ts documenting the limitation and instructing users to set the new
env var if they use the US data center so the mapping for '/ingest/**' and
'/ingest/static/**' points to the correct host.
- Around line 124-125: server/utils/posthog.ts is reading removed runtimeConfig
keys (config.public.posthog?.publicKey and config.public.posthog?.host) causing
server init to fail; fix by either restoring those keys into
runtimeConfig.public in nuxt.config.ts (ensure runtimeConfig.public.posthog = {
publicKey: process.env.POSTHOG_PUBLIC_KEY, host: process.env.POSTHOG_HOST } so
server code can read them) or, preferably, change server/utils/posthog.ts to
read directly from environment variables (use process.env.POSTHOG_PUBLIC_KEY and
process.env.POSTHOG_HOST, with optional fallback to config.public.posthog) when
initializing PostHog so server-side initialization does not rely on the
client-only `@posthog/nuxt` module.

---

Nitpick comments:
In `@app/composables/useAnalyticsConsent.ts`:
- Around line 18-19: Extract the inline PostHog type into a named type or
interface (e.g., PostHogClient) and use that alias instead of the verbose cast
in useAnalyticsConsent.ts; replace the current cast on posthog with the new
PostHogClient type and keep the posthog variable and ph assignment logic
unchanged (referencing the posthog and ph identifiers) so the code is more
readable and the shape of the PostHog API is centralized.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 5d91b1cb-586e-4ae8-b17c-2a85cb183b74

📥 Commits

Reviewing files that changed from the base of the PR and between 8bd4bd5 and 4c11f99.

📒 Files selected for processing (5)
  • .env.example
  • Dockerfile
  • app/composables/useAnalyticsConsent.ts
  • app/plugins/posthog-identity.client.ts
  • nuxt.config.ts
💤 Files with no reviewable changes (1)
  • app/plugins/posthog-identity.client.ts

Comment thread nuxt.config.ts
Comment thread nuxt.config.ts
Comment on lines +206 to +208
// ── PostHog reverse proxy — bypasses ad blockers by routing through reqcore.com ──
'/ingest/static/**': { proxy: 'https://eu-assets.i.posthog.com/static/**' },
'/ingest/**': { proxy: 'https://eu.i.posthog.com/**' },
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

Hardcoded EU proxy endpoints may conflict with US data center configuration.

The proxy routes are hardcoded to EU endpoints (eu.i.posthog.com, eu-assets.i.posthog.com), but POSTHOG_HOST can be set to the US data center (us.i.posthog.com). If a user configures US hosting, the proxy will still route to EU servers.

Consider documenting this limitation or making the proxy targets configurable if US support is needed.

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

In `@nuxt.config.ts` around lines 206 - 208, The proxy entries in nuxt.config.ts
mapping '/ingest/**' and '/ingest/static/**' are hardcoded to EU endpoints
(eu.i.posthog.com / eu-assets.i.posthog.com) which will conflict when
POSTHOG_HOST is set to a US host; update the proxy configuration to derive
targets from the POSTHOG_HOST environment variable (or add a new
POSTHOG_PROXY_HOST config) and use that value for the '/ingest/**' and
'/ingest/static/**' proxy targets, falling back to the existing EU endpoints if
the env var is not set; alternatively add a comment in nuxt.config.ts
documenting the limitation and instructing users to set the new env var if they
use the US data center so the mapping for '/ingest/**' and '/ingest/static/**'
points to the correct host.

The PR removed runtimeConfig.public.posthog from nuxt.config.ts since
@posthog/nuxt manages it via posthogConfig. However server/utils/posthog.ts
still referenced config.public.posthog?.publicKey/host which TypeScript
no longer recognises (TS2339).

Switch to process.env.POSTHOG_PUBLIC_KEY / POSTHOG_HOST directly — this is
server-only code running in Nitro, which has full access to process.env,
and avoids the redundant runtimeConfig round-trip.
@railway-app railway-app Bot temporarily deployed to applirank / reqcore-pr-75 March 9, 2026 20:22 Destroyed
… structure

fix(posthog): update proxy targets for PostHog integration with environment variable notes
@railway-app railway-app Bot temporarily deployed to applirank / reqcore-pr-75 March 9, 2026 20:30 Destroyed
@JoachimLK JoachimLK merged commit 4b745ec into main Mar 9, 2026
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