Skip to content

Conversation

@swastikiscoding
Copy link

@swastikiscoding swastikiscoding commented Dec 10, 2025

Proposed change

Resolves #2838

This PR integrates PostHog support into OWASP Nest for production and staging environments only.

  • Added PostHog environment variables for frontend and backend
  • Initialized PostHog in AppInitializer for production and staging environments
  • Updated Django production and staging settings to include PostHog host and API key
  • Updated CONTRIBUTING.md file to include updated PostHog environment variables

Checklist

  • I've read and followed the contributing guidelines.
  • I've run make check-test locally; all checks and tests passed.

- Added PostHog environment variables for frontend and backend
- Initialized PostHog in AppInitializer only in production and staging environments
- Updated Django production and staging settings to support PostHog host and API key
- Enhanced configuration and improved related code formatting
@github-actions github-actions bot added docs Improvements or additions to documentation backend frontend labels Dec 10, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 10, 2025

Summary by CodeRabbit

  • New Features

    • Added PostHog analytics integration, enabled at runtime for production/staging via environment variables.
  • Documentation

    • Added setup guidance, examples, and usage notes for the new PostHog environment variables.
  • Chores

    • Added PostHog client dependency to the frontend.
    • Updated example environment templates with PostHog entries.
    • Adjusted frontend dependency versions.

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

Walkthrough

Adds PostHog analytics support: docs and example env vars, Django production/staging settings for PostHog, a frontend dependency, and conditional PostHog provider initialization wrapping the app.

Changes

Cohort / File(s) Summary
Documentation & Examples
CONTRIBUTING.md, backend/.env.example, frontend/.env.example
Added PostHog environment variable documentation and example entries: DJANGO_POSTHOG_API_KEY, DJANGO_POSTHOG_HOST, NEXT_PUBLIC_POSTHOG_KEY, NEXT_PUBLIC_POSTHOG_HOST.
Backend Settings
backend/settings/production.py, backend/settings/staging.py
Added POSTHOG_API_KEY = values.SecretValue(environ_name="DJANGO_POSTHOG_API_KEY") and POSTHOG_HOST = values.Value(default="https://us.i.posthog.com", environ_name="DJANGO_POSTHOG_HOST") to Production and Staging settings.
Frontend Integration
frontend/package.json, frontend/src/wrappers/provider.tsx
Added posthog-js dependency and initialized PostHog in provider.tsx with ENV gating; conditionally wraps ApolloProvider with PostHogProvider when initialized.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

  • Inspect frontend initialization gating (ENV checks, useEffect/useState) and hydration handling.
  • Verify provider nesting and that telemetry is enabled only in intended environments.
  • Confirm package.json change aligns with lockfile and build process.
  • Ensure environment variable names/defaults match docs, .env examples, and Django settings.

Possibly related PRs

Suggested reviewers

  • kasya
  • arkid15r

Pre-merge checks and finishing touches

❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Out of Scope Changes check ⚠️ Warning The PR contains one minor out-of-scope change: the react dependency was downgraded from ^19.2.3 to ^19.2.1, which is unrelated to PostHog integration objectives. Revert the react dependency change to ^19.2.3 unless there is a specific reason for the downgrade related to PostHog compatibility that should be documented.
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat: add PostHog support integration' clearly and specifically describes the main change of adding PostHog integration to the codebase.
Description check ✅ Passed The PR description is directly related to the changeset, providing context about PostHog integration for production and staging environments with a reference to the resolved issue #2838.
Linked Issues check ✅ Passed The PR successfully implements the objective from issue #2838 to add PostHog support for production and staging environments only, with proper environment-based gating in the code.
✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e494fee and 5fc40d6.

⛔ Files ignored due to path filters (1)
  • frontend/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (1)
  • frontend/package.json (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/package.json

Tip

✨ Issue Enrichment is now available for GitHub issues!

CodeRabbit can now help you manage issues more effectively:

  • Duplicate Detection — Identify similar or duplicate issues
  • Related Issues & PRs — Find relevant issues and PR's from your repository
  • Suggested Assignees — Find the best person to work on the issue
  • Implementation Planning — Generate detailed coding plans for engineers and agents
Disable automatic issue enrichment

To disable automatic issue enrichment, add the following to your .coderabbit.yaml:

issue_enrichment:
  auto_enrich:
    enabled: false

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: 3

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 66533c3 and 6a2eaf1.

⛔ Files ignored due to path filters (1)
  • frontend/pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (7)
  • CONTRIBUTING.md (2 hunks)
  • backend/.env.example (1 hunks)
  • backend/settings/production.py (1 hunks)
  • backend/settings/staging.py (1 hunks)
  • frontend/.env.example (1 hunks)
  • frontend/package.json (1 hunks)
  • frontend/src/wrappers/provider.tsx (3 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-07-13T11:34:31.823Z
Learnt from: Rajgupta36
Repo: OWASP/Nest PR: 1717
File: frontend/src/app/mentorship/programs/page.tsx:14-14
Timestamp: 2025-07-13T11:34:31.823Z
Learning: In the Next.js frontend mentorship application, there are two distinct types for authentication-related data: ExtendedSession for useSession hook (containing accessToken and user.login properties) and UserRolesData for useUserRoles hook (containing currentUserRoles.roles array). The correct access pattern for GitHub username is `(session as ExtendedSession)?.user?.login`.

Applied to files:

  • frontend/src/wrappers/provider.tsx
🧬 Code graph analysis (1)
frontend/src/wrappers/provider.tsx (1)
frontend/src/server/apolloClient.ts (1)
  • apolloClient (36-37)
🪛 dotenv-linter (4.0.0)
frontend/.env.example

[warning] 9-9: [UnorderedKey] The NEXT_PUBLIC_POSTHOG_HOST key should go before the NEXT_PUBLIC_POSTHOG_KEY key

(UnorderedKey)

🔇 Additional comments (6)
backend/.env.example (1)

14-15: LGTM! Environment variables follow existing conventions.

The PostHog environment variables are properly formatted and follow the established pattern for backend configuration.

frontend/.env.example (1)

8-9: LGTM! PostHog environment variables added correctly.

The PostHog configuration variables follow the existing pattern. Note: The static analysis tool flagged key ordering, but this file doesn't follow strict alphabetical ordering throughout, so maintaining the current position is acceptable.

CONTRIBUTING.md (2)

87-97: LGTM! Clear documentation for frontend PostHog variables.

The documentation follows the established format and provides clear guidance on usage and purpose.


187-197: LGTM! Clear documentation for backend PostHog variables.

The documentation is consistent with the frontend variables and follows the established format.

backend/settings/production.py (1)

58-62: PostHog configuration added correctly, but verify backend integration.

The configuration is identical to staging and follows the established pattern. However, as with staging, no actual PostHog client initialization or usage code is shown in the provided diff.

The verification script from backend/settings/staging.py review also applies here to confirm backend PostHog integration exists.

backend/settings/staging.py (1)

55-59: PostHog configuration declared, but backend integration is incomplete.

The API key and host settings follow the correct pattern using environment variables. However, PostHog requires additional setup to function: the posthog package must be installed, a PosthogContextMiddleware entry must be added to MIDDLEWARE, and posthog.api_key and posthog.host must be initialized (typically in an AppConfig's ready() method). Verify that these integration components are present in the codebase and that the posthog package is listed in backend dependencies.

"next": "^16.0.8",
"next-auth": "^4.24.13",
"next-themes": "^0.4.6",
"posthog-js": "^1.302.2",
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 | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check posthog-js package information from npm registry
curl -s https://registry.npmjs.org/posthog-js | jq -r '{
  latest: .["dist-tags"].latest,
  versions: (.versions | keys | .[-10:])
}'

Repository: OWASP/Nest

Length of output: 164


🏁 Script executed:

#!/bin/bash
# Check if version 1.302.2 specifically exists
curl -s https://registry.npmjs.org/posthog-js/1.302.2 | jq -r '.version // "not_found"'

Repository: OWASP/Nest

Length of output: 164


🌐 Web query:

posthog-js 1.302.2 security vulnerabilities CVE

💡 Result:

Short answer: There are no known CVEs that affect posthog-js v1.302.2.

Details:

  • CVE-2023-32325 (XSS) affected versions prior to 1.57.2 and was patched in 1.57.2 — not applicable to 1.302.2. [1][2]
  • A November 2025 npm supply‑chain incident (GitLab advisory GMS-2025-554 / “Shai‑Hulud 2.0”) flagged malicious code in certain published posthog-js releases (report cites an affected release 1.297.3); you should verify installed package integrity, clear caches, rotate credentials if exposed, and prefer the latest clean release. This advisory is about malicious published packages rather than a CVE tied to 1.302.2 itself. [3]

If you want, I can: (a) check the exact npm tarball checksum for 1.302.2, (b) list any advisories affecting nearby versions, or (c) provide remediation steps.


🌐 Web query:

posthog-js npm security advisories latest version

💡 Result:

Summary (as of Dec 10, 2025):

  • Latest published package metadata shows posthog-js latest stable release ≈ 1.302.2. [4]
  • Known security advisories:
    • Supply-chain malware (Shai‑Hulud 2.0) affected posthog-js version 1.297.3 (Nov 24, 2025); compromised versions were deprecated/unpublished and PostHog published clean replacements. [2][1]
    • CVE-2023-32325 (XSS) — affects all versions before 1.57.2; fixed in 1.57.2. [3]

Sources:
[1] GitLab advisories index for npm/posthog-js.
[2] GitLab advisory: posthog-js contains malware after npm account takeover (GMS-2025-554).
[3] OSV / CVE-2023-32325 (PostHog-js XSS).
[4] Snyk package page for posthog-js (latest-version metadata).


Verify posthog-js package integrity due to recent supply-chain incident.

Version 1.302.2 is the current stable release and has no known direct CVEs. However, a November 2025 supply-chain malware incident (Shai-Hulud 2.0) compromised posthog-js 1.297.3; while 1.302.2 appears to be a patched release, verify package integrity by comparing checksums against the official npm registry and consider clearing node_modules cache and rotating any exposed credentials if the package was installed before the incident was resolved.

🤖 Prompt for AI Agents
In frontend/package.json at line 60, the pinned dependency "posthog-js":
"^1.302.2" needs integrity verification due to a past supply-chain compromise;
fetch the published integrity/checksum for 1.302.2 from the official npm
registry (or use npm view [email protected] dist.integrity) and compare it to
your installed package, then remove node_modules and your lockfile, run a fresh
install (npm ci or npm install) to regenerate a clean lockfile, update
package-lock.json/sha sums in source control if they differ, run npm audit and
verify no vulnerable versions are installed, and if the package was installed
before the incident was resolved, clear any npm cache (npm cache clean --force)
and rotate any credentials or tokens that may have been exposed.

Comment on lines 20 to 31
// Initialize PostHog
useEffect(() => {
const isProduction = process.env.NEXT_PUBLIC_ENVIRONMENT === 'production'
const isStaging = process.env.NEXT_PUBLIC_ENVIRONMENT === 'staging'

if (isProduction || isStaging) {
posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
// eslint-disable-next-line @typescript-eslint/naming-convention
api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
})
}
}, [])
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

Add validation for PostHog environment variables.

The code initializes PostHog without verifying that NEXT_PUBLIC_POSTHOG_KEY and NEXT_PUBLIC_POSTHOG_HOST are defined. If these variables are missing in production/staging, posthog.init will be called with undefined, potentially causing runtime errors or silent failures.

Apply this diff to add validation:

   // Initialize PostHog
   useEffect(() => {
     const isProduction = process.env.NEXT_PUBLIC_ENVIRONMENT === 'production'
     const isStaging = process.env.NEXT_PUBLIC_ENVIRONMENT === 'staging'
+    const posthogKey = process.env.NEXT_PUBLIC_POSTHOG_KEY
+    const posthogHost = process.env.NEXT_PUBLIC_POSTHOG_HOST
 
-    if (isProduction || isStaging) {
-      posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY, {
+    if ((isProduction || isStaging) && posthogKey && posthogHost) {
+      posthog.init(posthogKey, {
         // eslint-disable-next-line @typescript-eslint/naming-convention
-        api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST,
+        api_host: posthogHost,
       })
+    } else if ((isProduction || isStaging) && (!posthogKey || !posthogHost)) {
+      console.error('PostHog configuration missing: NEXT_PUBLIC_POSTHOG_KEY or NEXT_PUBLIC_POSTHOG_HOST not set')
     }
   }, [])
🤖 Prompt for AI Agents
In frontend/src/wrappers/provider.tsx around lines 20 to 31, the PostHog
initialization runs in production/staging without validating that
NEXT_PUBLIC_POSTHOG_KEY and NEXT_PUBLIC_POSTHOG_HOST are present; add explicit
checks that both env vars are non-empty before calling posthog.init, and if
either is missing log an error/warning and skip initialization (do not call
posthog.init with undefined). Ensure the validation uses the runtime
NEXT_PUBLIC_* values (not build-time typings), and provide a clear log message
indicating which variable is missing so the app fails safe in
production/staging.

Copy link
Collaborator

@kasya kasya left a comment

Choose a reason for hiding this comment

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

@swastikiscoding hi! Please address CodeRabbit's comments before we review ☑️

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: 0

🧹 Nitpick comments (1)
frontend/src/wrappers/provider.tsx (1)

24-40: State logic wraps PostHogProvider around uninitialized client in non-production environments.

setPosthogInitialized(true) is called unconditionally, meaning PostHogProvider will wrap an uninitialized posthog instance in development/test environments or when keys are missing. While posthog-js may handle this gracefully, it's semantically incorrect and adds unnecessary provider overhead.

Consider tracking whether PostHog was actually initialized:

 export function Providers({ children }: { children: React.ReactNode }) {
-  const [posthogInitialized, setPosthogInitialized] = useState(false)
+  const [posthogInitialized, setPosthogInitialized] = useState(false)
+  const [usePosthogProvider, setUsePosthogProvider] = useState(false)

   useEffect(() => {
     const isProduction = ENVIRONMENT === 'production'
     const isStaging = ENVIRONMENT === 'staging'
     const posthogKey = process.env.NEXT_PUBLIC_POSTHOG_KEY
     const posthogHost = process.env.NEXT_PUBLIC_POSTHOG_HOST

     if ((isProduction || isStaging) && posthogKey && posthogHost) {
       posthog.init(posthogKey, {
         // eslint-disable-next-line @typescript-eslint/naming-convention
         api_host: posthogHost,
       })
+      setUsePosthogProvider(true)
+    } else if (isProduction || isStaging) {
+      console.warn('PostHog keys missing in production/staging environment')
     }

     setPosthogInitialized(true)
   }, [])

Then update the conditional render to use usePosthogProvider instead of posthogInitialized for wrapping with PostHogProvider.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6a2eaf1 and 9ed4977.

📒 Files selected for processing (1)
  • frontend/src/wrappers/provider.tsx (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-07-13T11:34:31.823Z
Learnt from: Rajgupta36
Repo: OWASP/Nest PR: 1717
File: frontend/src/app/mentorship/programs/page.tsx:14-14
Timestamp: 2025-07-13T11:34:31.823Z
Learning: In the Next.js frontend mentorship application, there are two distinct types for authentication-related data: ExtendedSession for useSession hook (containing accessToken and user.login properties) and UserRolesData for useUserRoles hook (containing currentUserRoles.roles array). The correct access pattern for GitHub username is `(session as ExtendedSession)?.user?.login`.

Applied to files:

  • frontend/src/wrappers/provider.tsx
🧬 Code graph analysis (1)
frontend/src/wrappers/provider.tsx (2)
frontend/src/utils/env.client.ts (1)
  • ENVIRONMENT (3-3)
frontend/src/server/apolloClient.ts (1)
  • apolloClient (36-37)
🔇 Additional comments (2)
frontend/src/wrappers/provider.tsx (2)

7-11: LGTM!

Imports are well-organized. Using ENVIRONMENT from the centralized client env helper is the right approach for consistency.


48-60: Conditional rendering structure correctly prevents race condition.

The approach of conditionally wrapping with PostHogProvider only after the initialization check completes addresses the race condition concern. The code duplication between branches is acceptable given the clarity it provides.

@swastikiscoding
Copy link
Author

Hi @kasya! I've addressed the changes suggested by CodeRabbit.

@sonarqubecloud
Copy link

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

Labels

backend docs Improvements or additions to documentation frontend

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add PostHog support

2 participants