Skip to content

feat(analytics): restructure PostHog config under analytics.posthog + wire env vars#3641

Merged
PierreBrisorgueil merged 1 commit intomasterfrom
posthog-env-wiring
May 10, 2026
Merged

feat(analytics): restructure PostHog config under analytics.posthog + wire env vars#3641
PierreBrisorgueil merged 1 commit intomasterfrom
posthog-env-wiring

Conversation

@PierreBrisorgueil
Copy link
Copy Markdown
Contributor

@PierreBrisorgueil PierreBrisorgueil commented May 10, 2026

Summary

  • Root cause: Wave 1 PR feat(analytics): extend analytics service with posthog-node SDK #3637 left config.posthog.{apiKey,host,appTag} commented out and enabled: false. The Trawl Node manifest sets POSTHOG_* env vars but no code path read them, so config.posthog.apiKey === undefined → service stayed no-op. Prod logs: WARN analytics PostHog not configured.
  • Fix (Wave 3 W3.1): Move config.posthog.*config.analytics.posthog.*, rename apiKeykey, and wire all env reads to DEVKIT_NODE_analytics_posthog_{enabled,key,host,appTag,errorTracking,autoCapture}.
  • Convention alignment: Node now matches Vue's config.analytics.posthog.key path (cf pierreb-devkit/Vue + trawl_vue/.github/workflows/build.yml).

Files changed

  • config/defaults/development.config.js — restructure block, uncomment env reads, drop sentry: remnant
  • lib/services/analytics.jsconfig.posthogconfig.analytics?.posthog, apiKeykey
  • lib/services/errorTracker.js — same path migration + apiKeykey
  • lib/services/express.jsconfig.posthog?.autoCaptureconfig.analytics?.posthog?.autoCapture
  • modules/home/services/home.service.js — readiness check: config.posthog?.apiKeyconfig.analytics?.posthog?.key
  • 7 test files — fixture migration: { posthog: { apiKey:... } }{ analytics: { posthog: { key:... } } }

Downstream impact

After merge: trawl_node picks this up via /update-stack, then infra manifest renames POSTHOG_*DEVKIT_NODE_analytics_posthog_* (Wave W3.3). No downstream project overrides config.posthog at config level — all get values via env vars.

Test plan

  • npm run lint — ESLint: No issues found
  • npm run test:unit — 1358 passed, 0 failed (all analytics/errorTracker/home tests green)
  • npm run test:coverage — 1759 passed, 3 pre-existing failures (MongoDB $sortArray version constraint, unrelated)
  • DeepSeek critical-review — Verdict: OK with nits (0 critical, 0 high introduced; 2 pre-existing in env-var mapper noted as tech-debt)

Summary by CodeRabbit

  • Chores
    • Reorganized analytics configuration structure from top-level to nested namespace
    • Added environment variable support for analytics settings with fallback defaults
    • Updated internal configuration references across services and tests

Review Change Stack

… wire env vars

Move config.posthog.* → config.analytics.posthog.*, rename apiKey → key,
and wire DEVKIT_NODE_analytics_posthog_* env vars so Node prod ingestion
actually reads POSTHOG_* values from the manifest.

Aligns Node convention with Vue (config.analytics.posthog.key) per Wave 3
of PostHog Cloud migration. All consumers and test fixtures updated.

Fixes: prod logs "WARN analytics PostHog not configured" caused by Wave 1
leaving env reads commented out in development.config.js.
Copilot AI review requested due to automatic review settings May 10, 2026 17:17
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 10, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: afe45ab1-0057-458b-9bb7-8f27b6378176

📥 Commits

Reviewing files that changed from the base of the PR and between 131eddf and 0b51b84.

📒 Files selected for processing (12)
  • config/defaults/development.config.js
  • lib/services/analytics.js
  • lib/services/errorTracker.js
  • lib/services/express.js
  • lib/services/tests/analytics.capture.unit.tests.js
  • lib/services/tests/analytics.forRequest.unit.tests.js
  • lib/services/tests/analytics.service.resilience.unit.tests.js
  • lib/services/tests/analytics.service.unit.tests.js
  • lib/services/tests/errorTracker.unit.tests.js
  • modules/home/services/home.service.js
  • modules/home/tests/home.integration.tests.js
  • modules/home/tests/home.service.unit.tests.js

Walkthrough

This PR refactors the PostHog analytics configuration structure throughout the codebase, moving it from a top-level config.posthog object to config.analytics.posthog and renaming the API key field from apiKey to key. All dependent services, readiness checks, and tests are updated to reflect the new configuration contract.

Changes

PostHog Configuration Structure Refactoring

Layer / File(s) Summary
Configuration Contract
config/defaults/development.config.js
Development config now defines analytics.posthog with environment-driven values for enabled, key, host, appTag, errorTracking, and autoCapture, replacing the top-level posthog object.
Analytics Service Implementation
lib/services/analytics.js
Service init reads from config.analytics.posthog with key (instead of apiKey), resolves and stores appTag at initialization, and updates documentation to reflect the new config path for context injection.
Dependent Service Updates
lib/services/errorTracker.js, lib/services/express.js
Error tracker and Express service updated to check config.analytics.posthog for PostHog credentials, error tracking enablement, and auto-capture configuration.
Readiness Checks
modules/home/services/home.service.js
Home service status checks updated to source PostHog and error tracking configuration from config.analytics.posthog instead of top-level config.posthog.
Analytics Service Tests
lib/services/tests/analytics.*.unit.tests.js
Unit tests for analytics service, capture, and feature flags updated to mock config.analytics.posthog with key field; all existing behavioral assertions (no-ops, property injection, context merging, idempotency) remain unchanged under the new config structure.
Error Tracker Tests
lib/services/tests/errorTracker.unit.tests.js
Tests updated to mock config.analytics.posthog.key; new coverage added for errorTracking=false and missing errorTracking scenarios to verify capture is correctly gated.
Home Service Tests
modules/home/tests/home.*.tests.js
Integration and unit tests updated to mock config.analytics.posthog instead of config.posthog; readiness check assertions reflect new config path and field names.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • pierreb-devkit/Node#3361: Modifies lib/services/analytics.js to make track/identify/groupIdentify error-resilient, complementing this PR's config structure changes.
  • pierreb-devkit/Node#3305: Registers Express auto-capture middleware that is controlled by the config.analytics.posthog.autoCapture flag updated in this PR.
  • pierreb-devkit/Node#3308: Adds comprehensive analytics service and middleware tests that exercise the same initialization and config reading patterns modified here.

Suggested labels

Refactor

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(analytics): restructure PostHog config under analytics.posthog + wire env vars' clearly and concisely summarizes the main change: moving PostHog configuration to a new namespace and connecting it to environment variables.
Description check ✅ Passed The pull request description provides comprehensive context including root cause, the fix applied, file-by-file changes, downstream impact, and test validation results. It follows the template structure with Summary, Files changed, Downstream impact, and Test plan sections.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch posthog-env-wiring

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.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 10, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 89.14%. Comparing base (131eddf) to head (0b51b84).

Additional details and impacted files
@@           Coverage Diff           @@
##           master    #3641   +/-   ##
=======================================
  Coverage   89.14%   89.14%           
=======================================
  Files         135      135           
  Lines        4641     4641           
  Branches     1433     1433           
=======================================
  Hits         4137     4137           
  Misses        392      392           
  Partials      112      112           
Flag Coverage Δ
integration 59.14% <88.88%> (ø)
unit 64.14% <88.88%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.


Continue to review full report in Codecov by Sentry.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 131eddf...0b51b84. Read the comment docs.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR migrates PostHog configuration from config.posthog.* to config.analytics.posthog.* (including apiKey → key) and wires the new config shape throughout the runtime services and test fixtures so analytics/error-tracking can be enabled via DEVKIT_NODE_analytics_posthog_* env vars.

Changes:

  • Restructured config defaults to analytics.posthog and added env var reads for enabled/key/host/appTag/errorTracking/autoCapture.
  • Updated analytics + error-tracking + Express wiring to read from config.analytics.posthog and use key.
  • Migrated Home readiness checks and updated unit/integration tests to the new config shape.

Reviewed changes

Copilot reviewed 12 out of 12 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
config/defaults/development.config.js Adds analytics.posthog defaults and reads DEVKIT_NODE_analytics_posthog_* env vars.
lib/services/analytics.js Switches config reads to config.analytics.posthog and uses key for client init.
lib/services/errorTracker.js Migrates error-tracker gating to config.analytics.posthog + key.
lib/services/express.js Mounts auto-capture middleware based on config.analytics.posthog.autoCapture.
modules/home/services/home.service.js Updates readiness checks to the new analytics.posthog.key path.
modules/home/tests/home.integration.tests.js Updates readiness integration setup to set config.analytics.posthog.key.
modules/home/tests/home.service.unit.tests.js Updates readiness unit test fixtures and assertions to analytics.posthog.key.
lib/services/tests/analytics.service.unit.tests.js Migrates analytics service unit test fixtures to analytics.posthog.key.
lib/services/tests/analytics.service.resilience.unit.tests.js Migrates resilience test fixture to analytics.posthog.key.
lib/services/tests/analytics.forRequest.unit.tests.js Migrates request-aware helper tests to analytics.posthog.key.
lib/services/tests/analytics.capture.unit.tests.js Migrates capture/init tests to analytics.posthog.key.
lib/services/tests/errorTracker.unit.tests.js Migrates error-tracker tests to analytics.posthog.key.

Comment on lines 165 to 167
// analytics — PostHog
const posthogConfigured = isSet(config.posthog?.apiKey);
const posthogConfigured = isSet(config.analytics?.posthog?.key);
checks.push({
Comment on lines 173 to +178
// errorTracking — PostHog
const errorTrackingEnabled = posthogConfigured && config.posthog?.errorTracking === true;
const errorTrackingEnabled = posthogConfigured && config.analytics?.posthog?.errorTracking === true;
checks.push({
category: 'errorTracking',
status: errorTrackingEnabled ? 'ok' : 'warning',
message: errorTrackingEnabled ? 'PostHog $exception capture enabled' : 'PostHog Error Tracking not enabled (set posthog.errorTracking=true)',
message: errorTrackingEnabled ? 'PostHog $exception capture enabled' : 'PostHog Error Tracking not enabled (set analytics.posthog.errorTracking=true)',
Comment on lines 8 to 24
@@ -19,8 +19,8 @@ import analyticsService from './analytics.js';
* @returns {void}
*/
const captureException = (err, ctx = {}) => {
const posthogConfig = config?.posthog ?? {};
if (posthogConfig.apiKey && posthogConfig.errorTracking === true) {
const posthogConfig = config?.analytics?.posthog ?? {};
if (posthogConfig.key && posthogConfig.errorTracking === true) {
analyticsService.captureException(err, ctx);
Comment thread lib/services/analytics.js
const { enabled, apiKey, host, flushAt, flushInterval, appTag } = config.posthog ?? {};
if (!enabled || !apiKey) return;
const { enabled, key, host, flushAt, flushInterval, appTag } = config.analytics?.posthog ?? {};
if (!enabled || !key) return;
Comment thread lib/services/express.js
Comment on lines +295 to 300
// auto-capture middleware is opt-in: only mounted when analytics.posthog.autoCapture === true.
try {
await AnalyticsService.init();
if (config.posthog?.autoCapture === true) {
if (config.analytics?.posthog?.autoCapture === true) {
app.use(analyticsMiddleware);
}
expect(row.status).toBe('warning');
});

test('warning when posthog is not configured at all', async () => {
@PierreBrisorgueil PierreBrisorgueil merged commit 2f5ebd9 into master May 10, 2026
11 checks passed
@PierreBrisorgueil PierreBrisorgueil deleted the posthog-env-wiring branch May 10, 2026 17:29
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