-
-
Notifications
You must be signed in to change notification settings - Fork 337
feat: add PostHog support integration #2851
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
feat: add PostHog support integration #2851
Conversation
- 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
Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings. WalkthroughAdds 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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Possibly related PRs
Suggested reviewers
Pre-merge checks and finishing touches❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing touches🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
Tip ✨ Issue Enrichment is now available for GitHub issues!CodeRabbit can now help you manage issues more effectively:
Disable automatic issue enrichmentTo disable automatic issue enrichment, add the following to your issue_enrichment:
auto_enrich:
enabled: falseThanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this 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
⛔ Files ignored due to path filters (1)
frontend/pnpm-lock.yamlis 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.pyreview 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
posthogpackage must be installed, aPosthogContextMiddlewareentry must be added toMIDDLEWARE, andposthog.api_keyandposthog.hostmust be initialized (typically in an AppConfig'sready()method). Verify that these integration components are present in the codebase and that theposthogpackage is listed in backend dependencies.
| "next": "^16.0.8", | ||
| "next-auth": "^4.24.13", | ||
| "next-themes": "^0.4.6", | ||
| "posthog-js": "^1.302.2", |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 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.
frontend/src/wrappers/provider.tsx
Outdated
| // 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, | ||
| }) | ||
| } | ||
| }, []) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.
kasya
left a comment
There was a problem hiding this 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 ☑️
There was a problem hiding this 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, meaningPostHogProviderwill wrap an uninitializedposthoginstance 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
usePosthogProviderinstead ofposthogInitializedfor wrapping withPostHogProvider.
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 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
ENVIRONMENTfrom 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
PostHogProvideronly after the initialization check completes addresses the race condition concern. The code duplication between branches is acceptable given the clarity it provides.
|
Hi @kasya! I've addressed the changes suggested by CodeRabbit. |
|



Proposed change
Resolves #2838
This PR integrates PostHog support into OWASP Nest for production and staging environments only.
Checklist
make check-testlocally; all checks and tests passed.