From ba42a2e71ff81ae7c8d3fd0e14e1918fe9192214 Mon Sep 17 00:00:00 2001 From: abhitrueprogrammer Date: Wed, 26 Aug 2026 12:39:25 +0530 Subject: [PATCH 1/6] init posthog (w/o) self driving --- .../.posthog-wizard | 0 .../integration-nextjs-app-router/SKILL.md | 81 ++ .../references/1-begin.md | 56 ++ .../references/2-edit.md | 36 + .../references/3-revise.md | 22 + .../references/4-conclude.md | 143 ++++ .../references/COMMANDMENTS.md | 35 + .../references/EXAMPLE.md | 712 ++++++++++++++++++ .../references/identify-users.md | 307 ++++++++ .../references/next-js.md | 453 +++++++++++ next.config.js | 18 + package.json | 2 + pnpm-lock.yaml | 195 +++-- src/app/api/request/route.ts | 21 +- src/app/api/upload/route.ts | 16 + src/app/layout.tsx | 33 +- src/app/request/page.tsx | 7 + src/app/upload/page.tsx | 10 + src/components/CatalogueContent.tsx | 5 + src/components/Footer.tsx | 3 + src/components/PostHogProvider.tsx | 28 + src/components/ReportTagModal.tsx | 8 +- src/components/ShareButton.tsx | 2 + src/components/newPdfViewer.tsx | 5 + src/context/filterContext.tsx | 7 + src/lib/posthog-server.ts | 23 + 26 files changed, 2165 insertions(+), 63 deletions(-) create mode 100644 .claude/skills/integration-nextjs-app-router/.posthog-wizard create mode 100644 .claude/skills/integration-nextjs-app-router/SKILL.md create mode 100644 .claude/skills/integration-nextjs-app-router/references/1-begin.md create mode 100644 .claude/skills/integration-nextjs-app-router/references/2-edit.md create mode 100644 .claude/skills/integration-nextjs-app-router/references/3-revise.md create mode 100644 .claude/skills/integration-nextjs-app-router/references/4-conclude.md create mode 100644 .claude/skills/integration-nextjs-app-router/references/COMMANDMENTS.md create mode 100644 .claude/skills/integration-nextjs-app-router/references/EXAMPLE.md create mode 100644 .claude/skills/integration-nextjs-app-router/references/identify-users.md create mode 100644 .claude/skills/integration-nextjs-app-router/references/next-js.md create mode 100644 src/components/PostHogProvider.tsx create mode 100644 src/lib/posthog-server.ts diff --git a/.claude/skills/integration-nextjs-app-router/.posthog-wizard b/.claude/skills/integration-nextjs-app-router/.posthog-wizard new file mode 100644 index 00000000..e69de29b diff --git a/.claude/skills/integration-nextjs-app-router/SKILL.md b/.claude/skills/integration-nextjs-app-router/SKILL.md new file mode 100644 index 00000000..6eec3de8 --- /dev/null +++ b/.claude/skills/integration-nextjs-app-router/SKILL.md @@ -0,0 +1,81 @@ +--- +name: integration-nextjs-app-router +description: PostHog integration for Next.js App Router applications +metadata: + author: PostHog + version: 1.49.0 +--- + +# PostHog integration for Next.js App Router + +This skill helps you add PostHog analytics to Next.js App Router applications. + +## Workflow + +Follow these steps in order to complete the integration: + +1. `references/1-begin.md` - PostHog Setup - Begin ← **Start here** +2. `references/2-edit.md` - PostHog Setup - Edit +3. `references/3-revise.md` - PostHog Setup - Revise +4. `references/4-conclude.md` - PostHog Setup - Conclusion + +## Reference files + +- `references/EXAMPLE.md` - Next.js App Router example project code +- `references/1-begin.md` - Start the event tracking setup process by analyzing the project and creating an event tracking plan +- `references/2-edit.md` - Implement PostHog event tracking in the identified files, following best practices and the example project +- `references/3-revise.md` - Review and fix any errors in the PostHog integration implementation +- `references/4-conclude.md` - Review and fix any errors in the PostHog integration implementation +- `references/next-js.md` - Next.js - docs +- `references/identify-users.md` - Identify users - docs +- `references/COMMANDMENTS.md` - Framework-specific rules the integration must follow + +The example project shows the target implementation pattern. Consult the documentation for API details. + +## Key principles + +- **Environment variables**: Always use environment variables for PostHog keys. Never hardcode them. +- **Minimal changes**: Add PostHog code alongside existing integrations. Don't replace or restructure existing code. +- **Match the example**: Your implementation should follow the example project's patterns as closely as possible. + +## Framework guidelines + +- A missing PostHog configuration must never break the app — read keys optionally (never a required setting), guard init and capture behind their presence, and keep build and boot working with no PostHog environment set — but never silently: in development or debug builds fail loudly, using the language's idiomatic error, with the message " variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once is configured" (substituting the actual variable name); production stays a no-op +- For Next.js 15.3+, initialize PostHog in instrumentation-client.ts for the simplest setup +- For feature flags, use useFeatureFlagEnabled() or useFeatureFlagPayload() hooks - they handle loading states and external sync automatically +- Add analytics capture in event handlers where user actions occur, NOT in useEffect reacting to state changes +- Do NOT use useEffect for data transformation - calculate derived values during render instead +- Do NOT use useEffect to respond to user events - put that logic in the event handler itself +- Do NOT use useEffect to chain state updates - calculate all related updates together in the event handler +- Do NOT use useEffect to notify parent components - call the parent callback alongside setState in the event handler +- To reset component state when a prop changes, pass the prop as the component's key instead of using useEffect +- useEffect is ONLY for synchronizing with external systems (non-React widgets, browser APIs, network subscriptions) +- Remember that source code is available in the node_modules directory +- Check package.json for type checking or build scripts to validate changes +- When identity comes from framework-bridged state (Inertia or SSR shared props, a serialized session), confirm the backend actually shares that field — add the share server-side if missing — before identifying from it +- When a reverse proxy is configured, both /static/* AND /array/* must route to the assets origin (us-assets.i.posthog.com or eu-assets.i.posthog.com). +- posthog-js is the JavaScript SDK package name +- posthog.init() MUST be called before any other PostHog methods (capture, identify, etc.) +- posthog-js is browser-only — do NOT import it in Node.js or server-side contexts (use posthog-node instead) +- Autocapture is ON by default with posthog-js (tracks clicks, form submissions, pageviews). Keep autocapture enabled unless the user explicitly asks to turn it off. +- NEVER send PII in posthog.capture() event properties — no emails, full names, phone numbers, physical addresses, IP addresses, or user-generated content +- PII belongs in posthog.identify() person properties (email, name, role), NOT in capture() event properties +- Call posthog.identify(userId, { email, name, role }) on login AND on page refresh if the user is already logged in +- Call posthog.reset() on logout — the transition out of an identified session, never an initially anonymous page load (that discards the anonymous id and its history) — and before identify() when switching directly between accounts +- For SPAs without a framework router, capture pageviews with posthog.capture($pageview) or use the capture_pageview history_change option in init for History API routing +- When verifying with an automated browser (Playwright, Puppeteer, Selenium), posthog-js's bot filter silently drops every capture while flags and asset loads still succeed. Override navigator.webdriver, the user agent, AND navigator.userAgentData before concluding events do not send. Diagnose with ?__posthog_debug=true ("likely bot" in the console). +- posthog-node is the Node.js server-side SDK package name; posthog-js is browser-only, so use posthog-node on the server instead +- Include enableExceptionAutocapture: true in the PostHog constructor options +- Add posthog.capture() calls in route handlers for meaningful user actions – every route that creates, updates, or deletes data should track an event with contextual properties +- Add posthog.captureException(err, distinctId) in the application's error handler (e.g., Express error middleware, Fastify setErrorHandler, Koa app.on('error')) +- The SDK batches events and flushes asynchronously. await flush() or await shutdown() before letting that process exit. If unsure, set flushAt 1 and flushInterval 0. +- `posthog.capture()` enqueues synchronously and returns; the batched HTTP send happens afterwards. Treat every per-request handler as short-lived even when the framework feels like a server: Next.js / Nuxt / SvelteKit / Remix route handlers, serverless and edge functions, and Lambda are torn down per invocation before the send runs. Create the client with flushAt 1 and flushInterval 0, then await the send before returning. Always use `await posthog.flush()` for a shared/singleton client, `await posthog.shutdown()` for a per-request client. Never skip the awaited flush or risk the enqueued event being silently dropped. +- Reverse proxy is NOT needed for server-side Node.js – only client-side JavaScript needs a proxy to avoid ad blockers + +## Identifying users + +Identify users during login and signup events. Refer to the example code and documentation for the correct identify pattern for this framework. If both frontend and backend code exist, pass the client-side session and distinct ID using `X-POSTHOG-DISTINCT-ID` and `X-POSTHOG-SESSION-ID` headers to maintain correlation. + +## Error tracking + +Add PostHog error tracking to relevant files, particularly around critical user flows and API boundaries. diff --git a/.claude/skills/integration-nextjs-app-router/references/1-begin.md b/.claude/skills/integration-nextjs-app-router/references/1-begin.md new file mode 100644 index 00000000..55f0a832 --- /dev/null +++ b/.claude/skills/integration-nextjs-app-router/references/1-begin.md @@ -0,0 +1,56 @@ +--- +title: PostHog Setup - Begin +description: Start the event tracking setup process by analyzing the project and creating an event tracking plan +--- + +We're making an event tracking plan for this project. + +This is the first of several phases — plan the events, implement them, revise and validate changes, then conclude by creating a dashboard and writing a setup report. + +## Task list + +As soon as you've read this description and have a rough sense of the work, make a single **call `TaskCreate` immediately** before reading any reference file or beginning analysis. The user is watching the task pane and shouldn't see it sit empty. + +It's fine if your first list is incomplete or imprecise. Seed it with whatever high-level items you can infer from the overview above, then call `TaskCreate` again (or `TaskUpdate` to refine existing items) every time your understanding sharpens: after a phase reveals work you didn't anticipate, after planning surfaces concrete sub-items, after you hit something new. Use `TaskUpdate` to mark items `in_progress` when you start them and `completed` when you finish. Keeping the list current matters more than getting it right on the first call. + +Keep task titles broad and job-oriented. Describe the purpose or area of work with wording like "Planning event tracking", "Identifying users", "Installing PostHog", "Capturing events", or "Creating dashboards", not the specific files, paths, or symbols involved. Adjust the task names according to the user's project and context. + +Before proceeding, find any existing `posthog.capture()` code. Make note of event name formatting. + +From the project's file list, select between 10 and 15 files that might have interesting business value for event tracking, especially conversion and churn events. Also look for additional files related to login that could be used for identifying users, along with error handling. Read the files. If a file is already well-covered by PostHog events, replace it with another option. Do not spawn subagents. + +Look for opportunities to track client-side events. + +**IMPORTANT: Server-side events are REQUIRED** if the project includes any instrumentable server-side code. If the project has API routes (e.g., `app/api/**/route.ts`) or Server Actions, you MUST include server-side events for critical business operations like: + + - Payment/checkout completion + - Webhook handlers + - Authentication endpoints + +Do not skip server-side events - they capture actions that cannot be tracked client-side. + +Create a new file with a JSON array at the root of the project: .posthog-events.json. It should include one object for each event we want to add with these exact field names: `event_name` (the event name), `event_description` (one sentence), and `file` (the file path the event goes in). The wizard reads this file to surface the plan in the UI. If events already exist, don't duplicate them; supplement them. + +Track actions only, not pageviews. These can be captured automatically. Exceptions can be made for "viewed"-type events that correspond to the top of a conversion funnel. + +As you review files, make an internal note of opportunities to identify users and catch errors. We'll need them for the next step. + +## Status + +Before beginning a phase of the setup, you will send a status message with the exact prefix '[STATUS]', as in: + +[STATUS] Checking project structure. + +Status to report in this phase: + +- Checking project structure +- Verifying PostHog dependencies +- Generating events based on project + +## Abort statuses + +If and only if the instructions have `[ABORT]` states specified, and you clearly match the conditions for an abort, emit the abort message. Do NOT attempt to exit or halt yourself — the wizard's middleware catches `[ABORT]` and terminates the run for you. + +--- + +**Upon completion, continue with:** [2-edit.md](2-edit.md) \ No newline at end of file diff --git a/.claude/skills/integration-nextjs-app-router/references/2-edit.md b/.claude/skills/integration-nextjs-app-router/references/2-edit.md new file mode 100644 index 00000000..e5f7ffd1 --- /dev/null +++ b/.claude/skills/integration-nextjs-app-router/references/2-edit.md @@ -0,0 +1,36 @@ +--- +title: PostHog Setup - Edit +description: Implement PostHog event tracking in the identified files, following best practices and the example project +--- + +For each of the files and events noted in .posthog-events.json, make edits to capture events using PostHog. Make sure to set up any helper files needed. Carefully examine the included example project code: your implementation should match it as closely as possible. Do not spawn subagents. + +Use environment variables for PostHog keys. Do not hardcode PostHog keys. + +If a file already has existing integration code for other tools or services, don't overwrite or remove that code. Place PostHog code below it. + +For each event, add useful properties, and use your access to the PostHog source code to ensure correctness. You also have access to documentation about creating new events with PostHog. Consider this documentation carefully and follow it closely before adding events. Your integration should be based on documented best practices. Carefully consider how the user project's framework version may impact the correct PostHog integration approach. + +Remember that you can find the source code for any dependency in the node_modules directory. This may be necessary to properly populate property names. There are also example project code files available via the PostHog MCP; use these for reference. + +Where possible, add calls for PostHog's identify() function on the client side upon events like logins and signups. Use the contents of login and signup forms to identify users on submit. If there is server-side code, pass the client-side session and distinct ID to the server-side code to identify the user. On the server side, make sure events have a matching distinct ID where relevant. + +It's essential to do this in both client code and server code, so that user behavior from both domains is easy to correlate. + +You should also add PostHog exception capture error tracking to these files where relevant. + +Remember: Do not alter the fundamental architecture of existing files. Make your additions minimal and targeted. + +Remember the documentation and example project resources you were provided at the beginning. Read them now. + +## Status + +Status to report in this phase: + +- Inserting PostHog capture code +- A status message for each file whose edits you are planning, including a high level summary of changes +- A status message for each file you have edited + +--- + +**Upon completion, continue with:** [3-revise.md](3-revise.md) \ No newline at end of file diff --git a/.claude/skills/integration-nextjs-app-router/references/3-revise.md b/.claude/skills/integration-nextjs-app-router/references/3-revise.md new file mode 100644 index 00000000..3b07f506 --- /dev/null +++ b/.claude/skills/integration-nextjs-app-router/references/3-revise.md @@ -0,0 +1,22 @@ +--- +title: PostHog Setup - Revise +description: Review and fix any errors in the PostHog integration implementation +--- + +Check the project for errors. Read the package.json file for any type checking or build scripts that may provide input about what to fix. Remember that you can find the source code for any dependency in the node_modules directory. Do not spawn subagents. + +Ensure that any components created were actually used. + +Once all other tasks are complete, run any linter or prettier-like scripts found in the package.json, but ONLY on the files you have edited or created during this session. Do not run formatting or linting across the entire project's codebase. + +## Status + +Status to report in this phase: + +- Finding and correcting errors +- Report details of any errors you fix +- Linting, building and prettying + +--- + +**Upon completion, continue with:** [4-conclude.md](4-conclude.md) \ No newline at end of file diff --git a/.claude/skills/integration-nextjs-app-router/references/4-conclude.md b/.claude/skills/integration-nextjs-app-router/references/4-conclude.md new file mode 100644 index 00000000..200933a9 --- /dev/null +++ b/.claude/skills/integration-nextjs-app-router/references/4-conclude.md @@ -0,0 +1,143 @@ +--- +title: PostHog Setup - Conclusion +description: Review and fix any errors in the PostHog integration implementation +--- + +Create a live PostHog dashboard named "Analytics basics (wizard)" from the events you just instrumented, then populate it with up to five insights — lead with the business-critical views: conversion funnels, churn events, and other key signals. Use the exact same event names as implemented in the code. Keep the `(wizard)` tag with that exact casing so anyone browsing PostHog can see the wizard created this dashboard, and so a quick search for `(wizard)` surfaces every wizard-created artifact in one go. + +Always create the dashboard and insights based on the intended captures, regardless of whether those events have been observed yet. An insight is a definition over event names, not a snapshot of current data: it is expected to render empty until the first events arrive, and it fills in on its own once they do. "No data ingested yet", "the events aren't in the schema", or "the query would return nothing today" are never reasons to skip or defer insights — a dashboard handed off without them is an incomplete integration, not a cautious one. + +## How to call PostHog MCP tools + +The PostHog MCP server exposes a single `exec` tool. Every PostHog operation is driven by a CLI-style command string passed in its `command` parameter — the tool may be namespaced by the host (`mcp__posthog__exec`, `mcp__posthog-wizard__exec`), but the command grammar is the same. Tool names and schemas are not predictable, so discover and inspect before you call. + +**Grammar** — run in this order: + +```text +exec({ "command": "search " }) # find tools by name/title/description; `tools` lists them all +exec({ "command": "info " }) # REQUIRED before every call — description + input schema +exec({ "command": "schema " }) # drill into a field the schema flags with a `hint` +exec({ "command": "call " }) # run the tool +``` + +Running `info ` before `call ` is mandatory, the same way you read a file before editing it. `info` returns the full schema for simple tools; for large ones it summarizes and attaches `hint` entries pointing at fields to drill into with `schema`. Dot-notation descends objects (`query.source`), array items (`series.0.properties`), and unions. Never guess the structure of a field that carries a hint — drill first. + +Every PostHog tool goes through `exec` this way — there is no separate named tool to call directly. The inner tool names and JSON payloads below are what you pass to `call`. + +**Errors** carry a suggestion and similar tool names — read it before retrying. If a name isn't found it may have been renamed; run `search ` or `tools` again to find the current one. + +Create the parent dashboard first with `dashboard-create`, capture its returned `id`, then attach every insight to it via `dashboards: []`: + +```json +{ + "name": "Analytics basics (wizard)", + "description": "Key views for the events instrumented by the PostHog wizard.", + "tags": ["wizard"] +} +``` + +When calling `insight-create`, use these known-good query shapes — they are verified against the MCP schema, and the common variations around them are rejected: + +A trends insight with a breakdown (breakdowns go in `breakdownFilter.breakdowns`, an array — there is NO top-level `breakdown` field on `TrendsQuery`): + +```json +{ + "name": "Signups by plan (wizard)", + "dashboards": [], + "query": { + "kind": "InsightVizNode", + "source": { + "kind": "TrendsQuery", + "series": [{ "kind": "EventsNode", "event": "user_signed_up", "math": "total" }], + "interval": "day", + "dateRange": { "date_from": "-30d" }, + "breakdownFilter": { "breakdowns": [{ "type": "event", "property": "plan" }] }, + "trendsFilter": { "display": "ActionsBar" } + } + } +} +``` + +A conversion funnel (the window fields are camelCase and live INSIDE `funnelsFilter` — not at the top level of `FunnelsQuery`, and not snake_case): + +```json +{ + "name": "Signup funnel (wizard)", + "dashboards": [], + "query": { + "kind": "InsightVizNode", + "source": { + "kind": "FunnelsQuery", + "series": [ + { "kind": "EventsNode", "event": "page_viewed" }, + { "kind": "EventsNode", "event": "user_signed_up" } + ], + "dateRange": { "date_from": "-30d" }, + "funnelsFilter": { + "funnelVizType": "steps", + "funnelOrderType": "ordered", + "funnelWindowInterval": 14, + "funnelWindowIntervalUnit": "day" + } + } + } +} +``` + +Valid `trendsFilter.display` values are `ActionsLineGraph`, `ActionsBar`, `ActionsAreaGraph`, `ActionsPie`, `ActionsStackedBar`, `BoldNumber`, and `ActionsTable` — names like `ActionsBarChart` or `ActionsBarGraph` are rejected. If an insight call is rejected anyway, fix the payload against these examples rather than retrying variations. + +Once the dashboard exists, emit its URL on its own line in your assistant message using this exact marker: `[DASHBOARD_URL] `. The wizard parses this marker from your visible message and surfaces the link in the success summary. Mentioning the URL only in thinking or in prose without the marker means the link is dropped. + +Search for a file called `.posthog-events.json` and read it for available events. + +Do not spawn subagents. + +Compose the setup report as markdown — do NOT write it to a file in the project. It should include a summary of the integration edits, a table with the event names, event descriptions, and files where events were added, a list of links for the dashboard and insights created, and a "Verify before merging" checklist (see below). Follow this format: + + +# PostHog post-wizard report + +The wizard has completed a deep integration of your project. [Detailed summary of changes] + +[table of events/descriptions/files] + +## Next steps + +We've built some insights and a dashboard for you to keep an eye on user behavior, based on the events we just instrumented: + +[links] + +## Verify before merging + +[checklist] + +### Agent skill + +We've left an agent skill folder in your project. You can use this context for further agent development when using Claude Code. This will help ensure the model provides the most up-to-date approaches for integrating PostHog. + + + +For the "Verify before merging" checklist, write GitHub-style checkboxes (`- [ ] ...`) covering what the developer (or their coding agent) still needs to do to take this from "wizard finished" to "merged". Include ONLY the items that actually apply to the integration you just performed — judge each against the code you changed in this run, and drop any that don't fit. Phrase each item as a concrete, checkable action. Candidate items, with the condition for including each: + +- Always: "Run a full production build (the wizard only verified the files it touched) and fix any lint or type errors introduced by the generated code." +- Always: "Run the test suite — call sites that were rewritten or instrumented may need updated mocks or fixtures." +- If you added environment variables: "Add the exact PostHog env var names you added to `.env.example` and any monorepo/bootstrap scripts so collaborators know what to set." +- If this integration ships a minified production browser bundle (most SPA/SSR web frameworks — e.g. Next.js, Nuxt, SvelteKit, Astro, Vite-based apps): "Wire source-map upload (`posthog-cli sourcemap` or your bundler's upload step) into CI so production stack traces de-minify." +- If LLM analytics was set up in this run: "Trigger the LLM call path(s) you instrumented and confirm `$ai_generation` events appear in PostHog AI Observability." +- If the app has user auth and an `identify` call was added: "Confirm the returning-visitor path also calls `identify` — a handler that only identifies on fresh login can leave returning sessions on anonymous distinct IDs." + +Do not invent items beyond what applies. If only the two "Always" items apply, the checklist is just those two. + +Then publish the report to the wizard session with a single `publish_handoff` call, passing the complete report markdown as `content`. This call is how the report reaches the user — do not write it to a file instead. + +Then mirror the report into a shareable PostHog notebook so the user has an in-app copy to link and comment on. Call `notebooks-create-markdown` with a `title` (e.g. `PostHog setup (wizard) – `) and the report verbatim as `markdown` — the title becomes the notebook's leading heading, so start the markdown at the first section below it. Take the `short_id` from the response, build the notebook URL as `/project//notebooks/`, and emit it on its own line so the wizard can surface it: `[NOTEBOOK_URL]` followed by that URL. + +Upon completion, update `.posthog-events.json` so it matches the events you actually implemented, then remove it with your file tools. If removal is blocked or fails in your environment, leave the file in place and move on — the wizard host cleans it up after the run. Do not retry the removal or reach for shell commands to force it. + +## Status + +Status to report in this phase: + +- Configured dashboard: [insert PostHog dashboard URL] +- Published setup report to the wizard session +- Created notebook: [insert PostHog notebook URL] \ No newline at end of file diff --git a/.claude/skills/integration-nextjs-app-router/references/COMMANDMENTS.md b/.claude/skills/integration-nextjs-app-router/references/COMMANDMENTS.md new file mode 100644 index 00000000..9cc1e933 --- /dev/null +++ b/.claude/skills/integration-nextjs-app-router/references/COMMANDMENTS.md @@ -0,0 +1,35 @@ +# Framework rules + +Follow these when integrating PostHog into this framework. + +- A missing PostHog configuration must never break the app — read keys optionally (never a required setting), guard init and capture behind their presence, and keep build and boot working with no PostHog environment set — but never silently: in development or debug builds fail loudly, using the language's idiomatic error, with the message " variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once is configured" (substituting the actual variable name); production stays a no-op +- For Next.js 15.3+, initialize PostHog in instrumentation-client.ts for the simplest setup +- For feature flags, use useFeatureFlagEnabled() or useFeatureFlagPayload() hooks - they handle loading states and external sync automatically +- Add analytics capture in event handlers where user actions occur, NOT in useEffect reacting to state changes +- Do NOT use useEffect for data transformation - calculate derived values during render instead +- Do NOT use useEffect to respond to user events - put that logic in the event handler itself +- Do NOT use useEffect to chain state updates - calculate all related updates together in the event handler +- Do NOT use useEffect to notify parent components - call the parent callback alongside setState in the event handler +- To reset component state when a prop changes, pass the prop as the component's key instead of using useEffect +- useEffect is ONLY for synchronizing with external systems (non-React widgets, browser APIs, network subscriptions) +- Remember that source code is available in the node_modules directory +- Check package.json for type checking or build scripts to validate changes +- When identity comes from framework-bridged state (Inertia or SSR shared props, a serialized session), confirm the backend actually shares that field — add the share server-side if missing — before identifying from it +- When a reverse proxy is configured, both /static/* AND /array/* must route to the assets origin (us-assets.i.posthog.com or eu-assets.i.posthog.com). +- posthog-js is the JavaScript SDK package name +- posthog.init() MUST be called before any other PostHog methods (capture, identify, etc.) +- posthog-js is browser-only — do NOT import it in Node.js or server-side contexts (use posthog-node instead) +- Autocapture is ON by default with posthog-js (tracks clicks, form submissions, pageviews). Keep autocapture enabled unless the user explicitly asks to turn it off. +- NEVER send PII in posthog.capture() event properties — no emails, full names, phone numbers, physical addresses, IP addresses, or user-generated content +- PII belongs in posthog.identify() person properties (email, name, role), NOT in capture() event properties +- Call posthog.identify(userId, { email, name, role }) on login AND on page refresh if the user is already logged in +- Call posthog.reset() on logout — the transition out of an identified session, never an initially anonymous page load (that discards the anonymous id and its history) — and before identify() when switching directly between accounts +- For SPAs without a framework router, capture pageviews with posthog.capture($pageview) or use the capture_pageview history_change option in init for History API routing +- When verifying with an automated browser (Playwright, Puppeteer, Selenium), posthog-js's bot filter silently drops every capture while flags and asset loads still succeed. Override navigator.webdriver, the user agent, AND navigator.userAgentData before concluding events do not send. Diagnose with ?__posthog_debug=true ("likely bot" in the console). +- posthog-node is the Node.js server-side SDK package name; posthog-js is browser-only, so use posthog-node on the server instead +- Include enableExceptionAutocapture: true in the PostHog constructor options +- Add posthog.capture() calls in route handlers for meaningful user actions – every route that creates, updates, or deletes data should track an event with contextual properties +- Add posthog.captureException(err, distinctId) in the application's error handler (e.g., Express error middleware, Fastify setErrorHandler, Koa app.on('error')) +- The SDK batches events and flushes asynchronously. await flush() or await shutdown() before letting that process exit. If unsure, set flushAt 1 and flushInterval 0. +- `posthog.capture()` enqueues synchronously and returns; the batched HTTP send happens afterwards. Treat every per-request handler as short-lived even when the framework feels like a server: Next.js / Nuxt / SvelteKit / Remix route handlers, serverless and edge functions, and Lambda are torn down per invocation before the send runs. Create the client with flushAt 1 and flushInterval 0, then await the send before returning. Always use `await posthog.flush()` for a shared/singleton client, `await posthog.shutdown()` for a per-request client. Never skip the awaited flush or risk the enqueued event being silently dropped. +- Reverse proxy is NOT needed for server-side Node.js – only client-side JavaScript needs a proxy to avoid ad blockers diff --git a/.claude/skills/integration-nextjs-app-router/references/EXAMPLE.md b/.claude/skills/integration-nextjs-app-router/references/EXAMPLE.md new file mode 100644 index 00000000..1f6c0fd5 --- /dev/null +++ b/.claude/skills/integration-nextjs-app-router/references/EXAMPLE.md @@ -0,0 +1,712 @@ +# PostHog Next.js App Router Example Project + +Repository: https://github.com/PostHog/context-mill +Path: example-apps/next-app-router + +--- + +## README.md + +# PostHog Next.js app router example + +This is a [Next.js](https://nextjs.org) App Router example demonstrating PostHog integration with product analytics, session replay, feature flags, and error tracking. + +## Features + +- **Product analytics**: Track user events and behaviors +- **Session replay**: Record and replay user sessions +- **Error tracking**: Capture and track errors +- **User authentication**: Demo login system with PostHog user identification +- **Server-side & Client-side tracking**: Examples of both tracking methods +- **Reverse proxy**: PostHog ingestion through Next.js rewrites + +## Getting started + +### 1. Install dependencies + +```bash +npm install +# or +pnpm install +``` + +### 2. Configure environment variables + +Create a `.env.local` file in the root directory: + +```bash +NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN=your_posthog_project_token +NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com +``` + +Get your PostHog project token from your [PostHog project settings](https://app.posthog.com/project/settings). + +### 3. Run the development server + +```bash +npm run dev +# or +pnpm dev +``` + +Open [http://localhost:3000](http://localhost:3000) with your browser to see the app. + +## Project structure + +``` +src/ +├── app/ +│ ├── api/ +│ │ └── auth/ +│ │ └── login/ +│ │ └── route.ts # Login API with server-side tracking +│ ├── burrito/ +│ │ └── page.tsx # Demo feature page with event tracking +│ ├── profile/ +│ │ └── page.tsx # User profile with error tracking demo +│ ├── layout.tsx # Root layout with providers +│ ├── page.tsx # Home/Login page +│ └── globals.css # Global styles +├── components/ +│ └── Header.tsx # Navigation header with auth state +├── contexts/ +│ └── AuthContext.tsx # Authentication context with PostHog integration +└── lib/ + └── posthog-server.ts # Server-side PostHog client + +instrumentation-client.ts # Client-side PostHog initialization +``` + +## Key integration points + +### Client-side initialization (instrumentation-client.ts) + +```typescript +import posthog from "posthog-js" + +posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, { + api_host: "/ingest", + ui_host: "https://us.posthog.com", + defaults: '2026-01-30', + capture_exceptions: true, + debug: process.env.NODE_ENV === "development", +}); +``` + +### User identification (AuthContext.tsx) + +```typescript +posthog.identify(username, { + username: username, +}); +``` + +### Event tracking (burrito/page.tsx) + +```typescript +posthog.capture('burrito_considered', { + total_considerations: count, + username: username, +}); +``` + +### Error tracking (profile/page.tsx) + +```typescript +posthog.captureException(error); +``` + +### Server-side tracking (app/api/auth/login/route.ts) + +```typescript +const posthog = getPostHogClient(); +posthog.capture({ + distinctId: username, + event: 'server_login', + properties: { ... } +}); +``` + +## App router differences from pages router + +This example uses Next.js App Router instead of Pages Router. Key differences: + +1. **File-based routing**: Pages in `src/app/` instead of `src/pages/` +2. **layout.tsx**: Root layout component wraps all pages +3. **API Routes**: Located in `src/app/api/` with `route.ts` files +4. **'use client'**: Client components need explicit directive +5. **useRouter**: From `next/navigation` instead of `next/router` +6. **Metadata**: Exported from layout/page instead of Head component +7. **Server Components**: Components are server-side by default + +## Learn more + +- [PostHog Documentation](https://posthog.com/docs) +- [Next.js App Router Documentation](https://nextjs.org/docs/app) +- [PostHog Next.js Integration Guide](https://posthog.com/docs/libraries/next-js) + +## Deploy on Vercel + +The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new). + +Check out the [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. + +--- + +## .env.example + +```example +# PostHog Configuration +# Get your PostHog project token from: https://app.posthog.com/project/settings +NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN=your_posthog_project_token_here +# NEXT_PUBLIC_POSTHOG_HOST=https://eu.i.posthog.com +NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com +``` + +--- + +## instrumentation-client.ts + +```ts +import posthog from "posthog-js" + +posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, { + api_host: "/ingest", + ui_host: "https://us.posthog.com", + // Include the defaults option as required by PostHog + defaults: '2026-01-30', + // Enables capturing unhandled exceptions via Error Tracking + capture_exceptions: true, + // Turn on debug in development mode + debug: process.env.NODE_ENV === "development", +}); + +//IMPORTANT: Never combine this approach with other client-side PostHog initialization approaches, especially components like a PostHogProvider. instrumentation-client.ts is the correct solution for initializating client-side PostHog in Next.js 15.3+ apps. +``` + +--- + +## next.config.ts + +```ts +import type { NextConfig } from "next"; + +const nextConfig: NextConfig = { + /* config options here */ + async rewrites() { + return [ + { + source: "/ingest/static/:path*", + destination: "https://us-assets.i.posthog.com/static/:path*", + }, + { + source: "/ingest/array/:path*", + destination: "https://us-assets.i.posthog.com/array/:path*", + }, + { + source: "/ingest/:path*", + destination: "https://us.i.posthog.com/:path*", + }, + ]; + }, + // This is required to support PostHog trailing slash API requests + skipTrailingSlashRedirect: true, +}; + +export default nextConfig; + +``` + +--- + +## src/app/api/auth/login/route.ts + +```ts +import { NextResponse } from 'next/server'; +import { getPostHogClient } from '@/lib/posthog-server'; + +const users = new Map(); + +export async function POST(request: Request) { + const { username, password } = await request.json(); + + if (!username || !password) { + return NextResponse.json({ error: 'Username and password required' }, { status: 400 }); + } + + let user = users.get(username); + const isNewUser = !user; + + if (!user) { + user = { username, burritoConsiderations: 0 }; + users.set(username, user); + } + + // Capture server-side login event + const posthog = getPostHogClient(); + posthog.capture({ + distinctId: username, + event: 'server_login', + properties: { + isNewUser: isNewUser, + source: 'api' + } + }); + + // Identify user on server side + posthog.identify({ + distinctId: username, + properties: { + username: username, + createdAt: isNewUser ? new Date().toISOString() : undefined + } + }); + + // This handler is short-lived; flush so the enqueued events send before it returns + await posthog.flush(); + + return NextResponse.json({ success: true, user }); +} +``` + +--- + +## src/app/burrito/page.tsx + +```tsx +'use client'; + +import { useState } from 'react'; +import { useAuth } from '@/contexts/AuthContext'; +import { useRouter } from 'next/navigation'; +import posthog from 'posthog-js'; + +export default function BurritoPage() { + const { user, incrementBurritoConsiderations } = useAuth(); + const router = useRouter(); + const [hasConsidered, setHasConsidered] = useState(false); + + // Redirect to home if not logged in + if (!user) { + router.push('/'); + return null; + } + + const handleConsideration = () => { + incrementBurritoConsiderations(); + setHasConsidered(true); + setTimeout(() => setHasConsidered(false), 2000); + + // Capture burrito consideration event + posthog.capture('burrito_considered', { + total_considerations: user.burritoConsiderations + 1, + username: user.username, + }); + }; + + return ( +
+

Burrito consideration zone

+

Take a moment to truly consider the potential of burritos.

+ +
+ + + {hasConsidered && ( +

+ Thank you for your consideration! Count: {user.burritoConsiderations} +

+ )} +
+ +
+

Consideration stats

+

Total considerations: {user.burritoConsiderations}

+
+
+ ); +} +``` + +--- + +## src/app/layout.tsx + +```tsx +import type { Metadata } from "next"; +import "./globals.css"; +import { AuthProvider } from "@/contexts/AuthContext"; +import Header from "@/components/Header"; + +export const metadata: Metadata = { + title: "Burrito Consideration App", + description: "Consider the potential of burritos", +}; + +export default function RootLayout({ + children, +}: Readonly<{ + children: React.ReactNode; +}>) { + return ( + + + +
+
{children}
+ + + + ); +} + +``` + +--- + +## src/app/page.tsx + +```tsx +'use client'; + +import { useState } from 'react'; +import { useAuth } from '@/contexts/AuthContext'; + +export default function Home() { + const { user, login } = useAuth(); + const [username, setUsername] = useState(''); + const [password, setPassword] = useState(''); + const [error, setError] = useState(''); + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + setError(''); + + try { + const success = await login(username, password); + if (success) { + setUsername(''); + setPassword(''); + } else { + setError('Please provide both username and password'); + } + } catch (err) { + console.error('Login failed:', err); + setError('An error occurred during login'); + } + }; + + if (user) { + return ( +
+

Welcome back, {user.username}!

+

You are logged in. Feel free to explore:

+
    +
  • Consider the potential of burritos
  • +
  • View your profile and statistics
  • +
+
+ ); + } + + return ( +
+

Welcome to Burrito Consideration App

+

Please sign in to begin your burrito journey

+ +
+
+ + setUsername(e.target.value)} + placeholder="Enter any username" + /> +
+ +
+ + setPassword(e.target.value)} + placeholder="Enter any password" + /> +
+ + {error &&

{error}

} + + +
+ +

+ Note: This is a demo app. Use any username and password to sign in. +

+
+ ); +} +``` + +--- + +## src/app/profile/page.tsx + +```tsx +'use client'; + +import { useAuth } from '@/contexts/AuthContext'; +import { useRouter } from 'next/navigation'; +import posthog from 'posthog-js'; + +export default function ProfilePage() { + const { user } = useAuth(); + const router = useRouter(); + + // Redirect to home if not logged in + if (!user) { + router.push('/'); + return null; + } + + const triggerTestError = () => { + try { + throw new Error('Test error for PostHog error tracking'); + } catch (err) { + posthog.captureException(err); + console.error('Captured error:', err); + alert('Error captured and sent to PostHog!'); + } + }; + + return ( +
+

User Profile

+ +
+

Your Information

+

Username: {user.username}

+

Burrito Considerations: {user.burritoConsiderations}

+
+ +
+ +
+ +
+

Your Burrito Journey

+ {user.burritoConsiderations === 0 ? ( +

You haven't considered any burritos yet. Visit the Burrito Consideration page to start!

+ ) : user.burritoConsiderations === 1 ? ( +

You've considered the burrito potential once. Keep going!

+ ) : user.burritoConsiderations < 5 ? ( +

You're getting the hang of burrito consideration!

+ ) : user.burritoConsiderations < 10 ? ( +

You're becoming a burrito consideration expert!

+ ) : ( +

You are a true burrito consideration master! 🌯

+ )} +
+
+ ); +} +``` + +--- + +## src/components/Header.tsx + +```tsx +'use client'; + +import Link from 'next/link'; +import { useAuth } from '@/contexts/AuthContext'; + +export default function Header() { + const { user, logout } = useAuth(); + + return ( +
+
+ +
+ {user ? ( + <> + Welcome, {user.username}! + + + ) : ( + Not logged in + )} +
+
+
+ ); +} +``` + +--- + +## src/contexts/AuthContext.tsx + +```tsx +'use client'; + +import { createContext, useContext, useState, ReactNode } from 'react'; +import posthog from 'posthog-js'; + +interface User { + username: string; + burritoConsiderations: number; +} + +interface AuthContextType { + user: User | null; + login: (username: string, password: string) => Promise; + logout: () => void; + incrementBurritoConsiderations: () => void; +} + +const AuthContext = createContext(undefined); + +const users: Map = new Map(); + +export function AuthProvider({ children }: { children: ReactNode }) { + // Use lazy initializer to read from localStorage only once on mount + const [user, setUser] = useState(() => { + if (typeof window === 'undefined') return null; + + const storedUsername = localStorage.getItem('currentUser'); + if (storedUsername) { + const existingUser = users.get(storedUsername); + if (existingUser) { + return existingUser; + } + } + return null; + }); + + const login = async (username: string, password: string): Promise => { + try { + const response = await fetch('/api/auth/login', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username, password }), + }); + + if (response.ok) { + const { user: userData } = await response.json(); + + let localUser = users.get(username); + if (!localUser) { + localUser = userData as User; + users.set(username, localUser); + } + + setUser(localUser); + localStorage.setItem('currentUser', username); + + // Identify user in PostHog using username as distinct ID + posthog.identify(username, { + username: username, + }); + + // Capture login event + posthog.capture('user_logged_in', { + username: username, + }); + + return true; + } + return false; + } catch (error) { + console.error('Login error:', error); + return false; + } + }; + + const logout = () => { + // Capture logout event before resetting + posthog.capture('user_logged_out'); + posthog.reset(); + + setUser(null); + localStorage.removeItem('currentUser'); + }; + + const incrementBurritoConsiderations = () => { + if (user) { + user.burritoConsiderations++; + users.set(user.username, user); + setUser({ ...user }); + } + }; + + return ( + + {children} + + ); +} + +export function useAuth() { + const context = useContext(AuthContext); + if (context === undefined) { + throw new Error('useAuth must be used within an AuthProvider'); + } + return context; +} +``` + +--- + +## src/lib/posthog-server.ts + +```ts +import { PostHog } from 'posthog-node'; + +let posthogClient: PostHog | null = null; + +export function getPostHogClient() { + if (!posthogClient) { + posthogClient = new PostHog( + process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, + { + host: process.env.NEXT_PUBLIC_POSTHOG_HOST, + flushAt: 1, + flushInterval: 0 + } + ); + posthogClient.debug(true); + } + return posthogClient; +} + +export async function shutdownPostHog() { + if (posthogClient) { + await posthogClient.shutdown(); + } +} +``` + +--- + diff --git a/.claude/skills/integration-nextjs-app-router/references/identify-users.md b/.claude/skills/integration-nextjs-app-router/references/identify-users.md new file mode 100644 index 00000000..8647dcb3 --- /dev/null +++ b/.claude/skills/integration-nextjs-app-router/references/identify-users.md @@ -0,0 +1,307 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Identify users - Docs + +Copy page + +# Identify users - Docs + +Linking events to specific users enables you to build a full picture of how they're using your product across different sessions, devices, and platforms. + +This is straightforward to do when [capturing backend events](/docs/product-analytics/capture-events?tab=Node.js.md), as you associate events to a specific user using a `distinct_id`, which is a required argument. + +However, in the frontend of a [web](/docs/libraries/js/usage.md#capturing-events) or [mobile app](/docs/libraries/ios.md#capturing-events), a `distinct_id` is not a required argument — PostHog's SDKs will generate an anonymous `distinct_id` for you automatically and you can capture events anonymously, provided you use the appropriate [configuration](/docs/libraries/js/usage.md#capturing-anonymous-events). + +To link events to specific users, call `identify`: + +PostHog AI + +### Web + +```javascript +posthog.identify( + 'distinct_id', // Replace 'distinct_id' with your user's unique identifier + { email: 'max@hedgehogmail.com', name: 'Max Hedgehog' } // optional: set additional person properties +); +``` + +### Android + +```kotlin +PostHog.identify( + distinctId = distinctID, // Replace 'distinctID' with your user's unique identifier + // optional: set additional person properties + userProperties = mapOf( + "name" to "Max Hedgehog", + "email" to "max@hedgehogmail.com" + ) +) +``` + +### iOS + +```swift +PostHogSDK.shared.identify("distinct_id", // Replace "distinct_id" with your user's unique identifier + userProperties: ["name": "Max Hedgehog", "email": "max@hedgehogmail.com"]) // optional: set additional person properties +``` + +### React Native + +```jsx +posthog.identify('distinct_id', { // Replace "distinct_id" with your user's unique identifier + email: 'max@hedgehogmail.com', // optional: set additional person properties + name: 'Max Hedgehog' +}) +``` + +### Dart + +```dart +await Posthog().identify( + userId: 'distinct_id', // Replace "distinct_id" with your user's unique identifier + userProperties: { + 'email': 'max@hedgehogmail.com', // optional: set additional person properties + 'name': 'Max Hedgehog', + }, +); +``` + +Events captured after calling `identify` are identified events and this creates a person profile if one doesn't exist already. + +Due to the cost of processing them, anonymous events can be up to 4x cheaper than identified events, so it's recommended you only capture identified events when needed. + +## How identify works + +When a user starts browsing your website or app, PostHog automatically assigns them an **anonymous ID**, which is stored locally. + +Provided you've [configured persistence](/docs/libraries/js/persistence.md) to use cookies or `localStorage`, this enables us to track anonymous users – even across different sessions. + +By calling `identify` with a `distinct_id` of your choice (usually the user's ID in your database, or their email), you link the anonymous ID and distinct ID together. + +Thus, all past and future events made with that anonymous ID are now associated with the distinct ID. + +This enables you to do things like associate events with a user from before they log in for the first time, or associate their events across different devices or platforms. + +Using identify in the backend + +Although you can call `identify` using our backend SDKs, it is used most in frontends. This is because there is no concept of anonymous sessions in the backend SDKs, so calling `identify` only updates person profiles. + +## Best practices when using `identify` + +### 1\. Call `identify` as soon as you're able to + +In your frontend, you should call `identify` as soon as you're able to. + +Typically, this is every time your **app loads** for the first time, and directly after your **users log in**. + +This ensures that events sent during your users' sessions are correctly associated with them. + +You only need to call `identify` once per session, and you should avoid calling it multiple times unnecessarily. + +If you call `identify` multiple times with the same data without reloading the page in between, PostHog will ignore the subsequent calls. + +#### Identify users when the web SDK loads + +If your app already knows the signed-in user when you initialize the JavaScript web SDK, the [`loaded` callback](/docs/libraries/js/config.md) is a convenient place to call `identify`. This identifies the user as soon as the SDK has loaded: + +Web + +PostHog AI + +```javascript +posthog.init('', { + api_host: 'https://us.i.posthog.com', + defaults: '2026-05-30', + loaded: (posthog) => { + if (currentUser?.id) { + posthog.identify(currentUser.id, { + email: currentUser.email, + name: currentUser.name, + }) + } + }, +}) +``` + +In this example, `currentUser` represents user data already available from your authentication system. If your app loads the user asynchronously, call `posthog.identify()` as soon as that data becomes available instead. + +### 2\. Use unique strings for distinct IDs + +If two users have the same distinct ID, their data is merged and they are considered one user in PostHog. Two common ways this can happen are: + +- Your logic for generating IDs does not generate sufficiently strong IDs and you can end up with a clash where 2 users have the same ID. +- There's a bug, typo, or mistake in your code leading to most or all users being identified with generic IDs like `null`, `true`, or `distinctId`. + +PostHog also has built-in protections to stop the most common distinct ID mistakes. + +### 3\. Reset after logout + +If a user logs out on your frontend, you should call `reset()` to unlink any future events made on that device with that user. + +This is important if your users are sharing a computer, as otherwise all of those users are grouped together into a single user due to shared cookies between sessions. + +**We strongly recommend you call `reset` on logout even if you don't expect users to share a computer.** + +You can do that like so: + +PostHog AI + +### Web + +```javascript +posthog.reset() +``` + +### iOS + +```swift +PostHogSDK.shared.reset() +``` + +### Android + +```kotlin +PostHog.reset() +``` + +### React Native + +```jsx +posthog.reset() +``` + +### Dart + +```dart +await Posthog().reset(); +``` + +If you *also* want to reset the `device_id` so that the device will be considered a new device in future events, you can pass `true` as an argument: + +Web + +PostHog AI + +```javascript +posthog.reset(true) +``` + +### 4\. Person profiles and properties + +You'll notice that one of the parameters in the `identify` method is a `properties` object. + +This enables you to set [person properties](/docs/product-analytics/person-properties.md). + +Whenever possible, we recommend passing in all person properties you have available each time you call identify, as this ensures their person profile on PostHog is up to date. + +Person properties can also be set being adding a `$set` property to a event `capture` call. + +**\`$set\` and \`$set\_once\` aren't stored on events** + +These properties only tell PostHog how to update person data during ingestion — they aren't kept on the stored event, so you can't filter, break down, or query events by them. To query the values you set, use [person properties](/docs/product-analytics/person-properties.md) instead. + +See our [person properties docs](/docs/product-analytics/person-properties.md) for more details on how to work with them and best practices. + +### 5\. Use deep links between platforms + +We recommend you call `identify` [as soon as you're able](#1-call-identify-as-soon-as-youre-able), typically when a user signs up or logs in. + +This doesn't work if one or both platforms are unauthenticated. Some examples of such cases are: + +- Onboarding and signup flows before authentication. +- Unauthenticated web pages redirecting to authenticated mobile apps. +- Authenticated web apps prompting an app download. + +In these cases, you can use a [deep link](https://developer.android.com/training/app-links/deep-linking) on Android and [universal links](https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app) on iOS to identify users. + +1. Use `posthog.get_distinct_id()` to get the current distinct ID. Even if you cannot call identify because the user is unauthenticated, this will return an anonymous distinct ID generated by PostHog. +2. Add the distinct ID to the deep link as query parameters, along with other properties like UTM parameters. +3. When the user is redirected to the app, parse the deep link and handle the following cases: + +- The mobile app is already authenticated. In this case, call [`posthog.alias()`](/docs/libraries/js/usage.md#alias) with the distinct ID from the web. This associates the two distinct IDs as a single person. +- The mobile app is unauthenticated. In this case, call [`posthog.identify()`](/docs/libraries/js/usage.md#identifying-users) with the distinct ID from the web so pre-login mobile events stay connected to the web session. When the user later logs in on mobile, call `identify()` again with your canonical user ID. + +As long as you associate the distinct IDs with `posthog.identify()` or `posthog.alias()`, you can track events generated across platforms. + +Here's an example implementation for handling deep links from web to mobile: + +PostHog AI + +### iOS + +```swift +import PostHog +class DeepLinkIdentityManager { + static let shared = DeepLinkIdentityManager() + // MARK: - Deep Link Received + func handleDeepLink(_ url: URL, isAuthenticatedOnMobile: Bool) { + guard let webDistinctId = URLComponents(url: url, resolvingAgainstBaseURL: true)? + .queryItems?.first(where: { $0.name == "ph_distinct_id" })?.value else { + return + } + if isAuthenticatedOnMobile { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHogSDK.shared.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHogSDK.shared.identify(webDistinctId) + } + } + // MARK: - Login/Signup + func handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHogSDK.shared.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + func handleLogout() { + PostHogSDK.shared.reset() + } +} +``` + +### Android + +```kotlin +import android.net.Uri +import com.posthog.PostHog +object DeepLinkIdentityManager { + // Deep Link Received + fun handleDeepLink(uri: Uri, isAuthenticatedOnMobile: Boolean) { + val webDistinctId = uri.getQueryParameter("ph_distinct_id") ?: return + if (isAuthenticatedOnMobile) { + // The mobile app already knows the current user. + // Alias the incoming web distinct ID to that user. + PostHog.alias(webDistinctId) + } else { + // Reuse the web distinct ID until login on mobile. + PostHog.identify(webDistinctId) + } + } + // Login/Signup + fun handleLogin(canonicalUserId: String) { + // Switch from the web distinct ID (or a mobile anon ID) + // to your canonical user ID. + PostHog.identify(canonicalUserId) + // Set user properties, track signup event, etc. + } + fun handleLogout() { + PostHog.reset() + } +} +``` + +## Further reading + +- [Identifying users docs](/docs/product-analytics/identify.md) +- [How person processing works](/docs/how-posthog-works/ingestion-pipeline.md#2-person-processing) +- [An introductory guide to identifying users in PostHog](/tutorials/identifying-users-guide.md) + +### Still have questions? + +Ask PostHog AI + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/.claude/skills/integration-nextjs-app-router/references/next-js.md b/.claude/skills/integration-nextjs-app-router/references/next-js.md new file mode 100644 index 00000000..13c9c804 --- /dev/null +++ b/.claude/skills/integration-nextjs-app-router/references/next-js.md @@ -0,0 +1,453 @@ +> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt + +# Next.js - Docs + +Copy page + +# Next.js - Docs + +PostHog makes it easy to get data about traffic and usage of your [Next.js](https://nextjs.org/) app. Integrating PostHog into your site enables analytics about user behavior, custom events capture, session recordings, feature flags, and more. + +This guide walks you through integrating PostHog into your Next.js app using the [React](/docs/libraries/react.md) and the [Node.js](/docs/libraries/node.md) SDKs. + +> You can see a working example of this integration in our [Next.js demo app](https://github.com/PostHog/posthog-js/tree/main/playground/nextjs). + +Next.js has both client and server-side rendering, as well as pages and app routers. We'll cover all of these options in this guide. + +> **Try `@posthog/next` (pre-release):** A simplified Next.js integration with synchronized client/server identity, server-side flag bootstrapping, and a built-in API proxy. [Read the setup guide →](/docs/libraries/next-js/posthog-next.md) + +## Prerequisites + +To follow this guide along, you need: + +1. A PostHog instance (either [Cloud](https://app.posthog.com/signup) or [self-hosted](/docs/self-host.md)) +2. A Next.js application + +## Beta: integration via LLM + +Install PostHog for Next.js in seconds with our wizard by running this prompt with [LLM coding agents](/blog/envoy-wizard-llm-agent.md) like Cursor and Bolt, or by running it in your terminal. + +`npx @posthog/wizard` + +[Learn more](/wizard.md) + +Or, to integrate manually, continue with the rest of this guide. + +## Client-side setup + +Install `posthog-js` using your package manager: + +PostHog AI + +### npm + +```bash +npm install --save posthog-js +``` + +### Yarn + +```bash +yarn add posthog-js +``` + +### pnpm + +```bash +pnpm add posthog-js +``` + +### Bun + +```bash +bun add posthog-js +``` + +> **If your site sets a Content-Security-Policy**, it needs to allow PostHog. This applies to the snippet and to package installs alike: the SDK lazy-loads extra bundles (session replay, surveys) from PostHog's CDN, and sends events to the ingestion host. PostHog serves from subdomains of `posthog.com` that change over time, so allow the wildcard: +> +> PostHog AI +> +> ``` +> script-src 'self' https://*.posthog.com; +> connect-src 'self' https://*.posthog.com; +> worker-src 'self' blob: data:; +> ``` +> +> `script-src` covers the snippet and the lazy-loaded bundles, `connect-src` covers event ingestion and feature flags, and `worker-src` covers session replay. The [toolbar needs a few more](/docs/advanced/content-security-policy.md), or use a [reverse proxy](/docs/advanced/proxy.md) so everything is first-party. Failing to do so causes silent failures where `capture` and `identify` calls never send, so the integration looks complete while zero events arrive. Remember `connect-src` falls back to `default-src`, so `default-src 'self'` blocks event delivery even when the script itself is bundled. + +Add your environment variables to your `.env.local` file and to your hosting provider (e.g. Vercel, Netlify, AWS). You can find your project token in your [project settings](https://app.posthog.com/project/settings). + +.env.local + +PostHog AI + +```shell +NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN= +NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com +``` + +These values need to start with `NEXT_PUBLIC_` to be accessible on the client-side. + +## Integration + +Next.js provides the [`instrumentation-client.ts|js`](https://nextjs.org/docs/app/api-reference/file-conventions/instrumentation-client) file for client-side setup. Add it to the root of your Next.js app (for both app and pages router) and initialize PostHog in it like this: + +PostHog AI + +### instrumentation-client.js + +```javascript +import posthog from 'posthog-js' +posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN, { + api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST, + defaults: '2026-05-30' +}); +``` + +### instrumentation-client.ts + +```typescript +import posthog from 'posthog-js' +posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, { + api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST, + defaults: '2026-05-30' +}); +``` + +Bootstrapping with `instrumentation-client` + +When using `instrumentation-client`, the values you pass to `posthog.init` remain fixed for the entire session. This means bootstrapping only works if you evaluate flags **before your app renders** (for example, on the server). + +If you need flag values after the app has rendered, you’ll want to: + +- Evaluate the flag on the server and pass the value into your app, or +- Evaluate the flag in an earlier page/state, then store and re-use it when needed. + +Both approaches avoid flicker and give you the same outcome as bootstrapping, as long as you use the same `distinct_id` across client and server. + +See the [bootstrapping guide](/docs/feature-flags/bootstrapping.md) for more information. + +## Identifying users + +> **Identifying users is required.** Call `posthog.identify('your-user-id')` after login to link events to a known user. This is what connects frontend event captures, [session replays](/docs/session-replay.md), [LLM traces](/docs/ai-engineering.md), and [error tracking](/docs/error-tracking.md) to the same person — and lets backend events link back too. +> +> Use a stable ID from your auth system when possible, not an email or display name. Send those as person properties instead. If your app has no other stable key, email works as a fallback if they are unique. Never a shared literal like `"anonymous"` or `"user"`, which pools many people onto one person and corrupts their data. When no ID is available at all, skip the identify and retain the anonymous distinct ID that's automatically assigned. +> +> Call `posthog.reset()` on logout, so the next person to use the browser doesn't inherit the last one's identity. +> +> See our guide on [identifying users](/docs/getting-started/identify-users.md) for how to set this up. + +### Linking client and server events + +Next.js apps usually capture on both sides. To keep them on the same person, use the same distinct ID in both, and let the browser tell your server which one that is. + +If your app calls your own backend, `tracing_headers` adds `X-POSTHOG-DISTINCT-ID` and `X-POSTHOG-SESSION-ID` to matching `fetch` and `XMLHttpRequest` requests. This lets server-side SDKs link backend events, errors, and LLM traces back to frontend sessions and replays. Use hostnames only, without protocols or paths. + +JavaScript + +PostHog AI + +```javascript +posthog.init('', { + api_host: 'https://us.i.posthog.com', + // Optional: send PostHog session/user context to your backend + tracing_headers: ['api.example.com'], +}) +``` + +This works in local development too, but match on the hostname alone: use `'localhost'`, not `'localhost:3000'`. Ports are never part of a hostname, so a value with one in it never matches anything. `localhost` and `127.0.0.1` are also different hostnames — use whichever your app actually calls. + +Tracing headers help you attribute events across front and backend consistently. When this isn't available, use your server-side stable IDs to deduce the matching `distinctId`, and pass it in when capturing the event. + +Set up a reverse proxy (recommended) + +We recommend [setting up a reverse proxy](/docs/advanced/proxy.md), so that events are less likely to be intercepted by tracking blockers. + +We have our [own managed reverse proxy service](/docs/advanced/proxy/managed-reverse-proxy.md), which is free for all PostHog Cloud users, routes through our infrastructure, and makes setting up your proxy easy. + +If you don't want to use our managed service then there are several other options for creating a reverse proxy, including using [Cloudflare](/docs/advanced/proxy/cloudflare.md), [AWS Cloudfront](/docs/advanced/proxy/cloudfront.md), and [Vercel](/docs/advanced/proxy/vercel.md). + +Grouping products in one project (recommended) + +If you have multiple customer-facing products (e.g. a marketing website + mobile app + web app), it's best to install PostHog on them all and [group them in one project](/docs/settings/projects.md). + +This makes it possible to track users across their entire journey (e.g. from visiting your marketing website to signing up for your product), or how they use your product across multiple platforms. + +Add IPs to Firewall/WAF allowlists (recommended) + +For certain features like [heatmaps](/docs/toolbar/heatmaps.md), your Web Application Firewall (WAF) may be blocking PostHog's requests to your site. Add these IP addresses to your WAF allowlist or rules to let PostHog access your site. + +**EU**: `3.75.65.221`, `18.197.246.42`, `3.120.223.253` + +**US**: `44.205.89.55`, `52.4.194.122`, `44.208.188.173` + +These are public, stable IPs used by PostHog services (e.g., Celery tasks for snapshots). + +## Accessing PostHog + +Once initialized in `instrumentation-client.js|ts`, import `posthog` from `posthog-js` anywhere and call the methods you need on the `posthog` object. + +JavaScript + +PostHog AI + +```javascript +"use client"; +import posthog from "posthog-js"; +export default function Home() { + return ( +
+ +
+ ); +} +``` + +### Using React hooks + +The [React feature flag hooks](/docs/libraries/react.md#feature-flags) work automatically when PostHog is initialized via `instrumentation-client.ts`. The hooks use the initialized posthog-js singleton: + +JavaScript + +PostHog AI + +```javascript +"use client"; +import { useFeatureFlagEnabled } from "@posthog/react"; +export default function FeatureComponent() { + const showNewFeature = useFeatureFlagEnabled("new-feature"); + return showNewFeature ? : ; +} +``` + +### Usage + +See the [React SDK docs](/docs/libraries/react.md) for examples of how to use: + +- [`posthog-js` functions like custom event capture, user identification, and more.](/docs/libraries/react.md#using-posthog-js-functions) +- [Feature flags including variants and payloads.](/docs/libraries/react.md#feature-flags) + +You can also read [the full `posthog-js` documentation](/docs/libraries/js/usage.md) for all the usable functions. + +## Server-side analytics + +Next.js enables you to both server-side render pages and add server-side functionality. To integrate PostHog into your Next.js app on the server-side, you can use the [Node SDK](/docs/libraries/node.md). + +First, install the `posthog-node` library: + +PostHog AI + +### npm + +```bash +npm install posthog-node --save +``` + +### Yarn + +```bash +yarn add posthog-node +``` + +### pnpm + +```bash +pnpm add posthog-node +``` + +### Bun + +```bash +bun add posthog-node +``` + +### Router-specific instructions + +## App router + +For the app router, we can initialize the `posthog-node` SDK once with a `PostHogClient` function, and import it into files. + +This enables us to send events and fetch data from PostHog on the server – without making client-side requests. + +JavaScript + +PostHog AI + +```javascript +// app/posthog.js +import { PostHog } from 'posthog-node' +export default function PostHogClient() { + const posthogClient = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN, { + host: process.env.NEXT_PUBLIC_POSTHOG_HOST, + flushAt: 1, + flushInterval: 0 + }) + return posthogClient +} +``` + +> **Note:** Because server-side functions in Next.js can be short-lived, we set `flushAt` to `1` and `flushInterval` to `0`. +> +> - `flushAt` sets how many capture calls we should flush the queue (in one batch). +> - `flushInterval` sets how many milliseconds we should wait before flushing the queue. Setting them to the lowest number ensures events are sent immediately and not batched. We also need to call `await posthog.shutdown()` once done. + +To use this client, we import it into our pages and call it with the `PostHogClient` function: + +JavaScript + +PostHog AI + +```javascript +import Link from 'next/link' +import PostHogClient from '../posthog' +export default async function About() { + const posthog = PostHogClient() + const flags = await posthog.getAllFlags( + 'user_distinct_id' // replace with a user's distinct ID + ); + await posthog.shutdown() + return ( +
+

About

+ Go home + { flags['main-cta'] && + Go to PostHog + } +
+ ) +} +``` + +## Pages router + +For the pages router, we can use the `getServerSideProps` function to access PostHog on the server-side, send events, evaluate feature flags, and more. + +This looks like this: + +JavaScript + +PostHog AI + +```javascript +// pages/posts/[id].js +import { useContext, useEffect, useState } from 'react' +import { getServerSession } from "next-auth/next" +import { authOptions } from '@/lib/auth' +import { PostHog } from 'posthog-node' +export default function Post({ post, flags }) { + const [ctaState, setCtaState] = useState() + useEffect(() => { + if (flags) { + setCtaState(flags['blog-cta']) + } + }) + return ( +
+

{post.title}

+

By: {post.author}

+

{post.content}

+ {ctaState && +

Go to PostHog

+ } + +
+ ) +} +export async function getServerSideProps(ctx) { + // Pass authOptions, or your session callbacks don't run. + const session = await getServerSession(ctx.req, ctx.res, authOptions) + let flags = null + if (session) { + const client = new PostHog( + process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN, + { + host: process.env.NEXT_PUBLIC_POSTHOG_HOST, + } + ) + // A stable ID from your auth system, not an email. See the note below. + const distinctId = session.user.id + flags = await client.getAllFlags(distinctId); + client.capture({ + distinctId, + event: 'loaded blog article', + properties: { + $current_url: ctx.req.url, + }, + }); + await client.shutdown() + } + const { posts } = await import('../../blog.json') + const post = posts.find((post) => post.id.toString() === ctx.params.id) + return { + props: { + post, + flags + }, + } +} +``` + +> **Note**: next-auth doesn't put a user ID on the session by default. Its session is `{ name, email, image }`, so `session.user.id` is `undefined` until you add it yourself with a session callback in your `authOptions`: +> +> JavaScript +> +> PostHog AI +> +> ```javascript +> // lib/auth.js +> export const authOptions = { +> callbacks: { +> session({ session, token, user }) { +> // JWT sessions (the default) carry the user ID in token.sub. +> // Database sessions get it from user.id instead. +> session.user.id = token?.sub ?? user.id +> return session +> }, +> }, +> } +> ``` +> +> Capturing with an `undefined` distinct ID creates events that belong to nobody, so check that the ID arrives before relying on it. + +> **Note**: Make sure to *always* call `await client.shutdown()` after sending events from the server-side. PostHog queues events into larger batches, and this call forces all batched events to be flushed immediately. + +### Server-side configuration + +Next.js overrides the default `fetch` behavior on the server to introduce their own cache. PostHog ignores that cache by default, as this is Next.js's default behavior for any fetch call. + +You can override that configuration when initializing PostHog, but make sure you understand the pros/cons of using Next.js's cache and that you might get cached results rather than the actual result our server would return. This is important for feature flags, for example. + +TSX + +PostHog AI + +```jsx +posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN, { + // ... your configuration + fetch_options: { + cache: 'force-cache', // Use Next.js cache + next_options: { // Passed to the `next` option for `fetch` + revalidate: 60, // Cache for 60 seconds + tags: ['posthog'], // Can be used with Next.js `revalidateTag` function + }, + } +}) +``` + +## Configuring a reverse proxy to PostHog + +To improve the reliability of client-side tracking and make requests less likely to be intercepted by tracking blockers, you can setup a reverse proxy in Next.js. Read more about deploying a reverse proxy using [Next.js rewrites](/docs/advanced/proxy/nextjs.md), [Next.js middleware](/docs/advanced/proxy/nextjs-middleware.md), and [Vercel rewrites](/docs/advanced/proxy/vercel.md). + +## Further reading + +- [How to set up Next.js analytics, feature flags, and more](/tutorials/nextjs-analytics.md) +- [How to set up Next.js pages router analytics, feature flags, and more](/tutorials/nextjs-pages-analytics.md) +- [How to set up Next.js A/B tests](/tutorials/nextjs-ab-tests.md) + +### Still have questions? + +Ask PostHog AI + +### Was this page useful? + +HelpfulCould be better \ No newline at end of file diff --git a/next.config.js b/next.config.js index 4a9e2741..347e62f7 100644 --- a/next.config.js +++ b/next.config.js @@ -6,6 +6,8 @@ await import("./src/env.js"); /** @type {import("next").NextConfig} */ const config = { + // Required to support PostHog trailing slash API requests + skipTrailingSlashRedirect: true, swcMinify: false, images: { remotePatterns: [ @@ -15,6 +17,22 @@ const config = { }, ], }, + async rewrites() { + return [ + { + source: "/ingest/static/:path*", + destination: "https://us-assets.i.posthog.com/static/:path*", + }, + { + source: "/ingest/array/:path*", + destination: "https://us-assets.i.posthog.com/array/:path*", + }, + { + source: "/ingest/:path*", + destination: "https://us.i.posthog.com/:path*", + }, + ]; + }, async headers() { return [ { diff --git a/package.json b/package.json index 9ba67c4b..1c869576 100644 --- a/package.json +++ b/package.json @@ -61,6 +61,8 @@ "next-themes": "^0.3.0", "pdf-lib": "^1.17.1", "pdfjs-dist": "4.8.69", + "posthog-js": "^1.419.4", + "posthog-node": "^5.51.2", "prettier": "^3.5.3", "prettier-plugin-tailwindcss": "^0.6.11", "raw-loader": "^4.0.2", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6b5ea547..47701830 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -22,28 +22,28 @@ importers: version: 3.2.2(react@18.3.1) '@embedpdf/core': specifier: ^2.14.0 - version: 2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + version: 2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) '@embedpdf/engines': specifier: ^2.14.0 - version: 2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + version: 2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) '@embedpdf/plugin-document-manager': specifier: ^2.14.0 - version: 2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + version: 2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) '@embedpdf/plugin-export': specifier: ^2.14.0 - version: 2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + version: 2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) '@embedpdf/plugin-render': specifier: ^2.14.0 - version: 2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + version: 2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) '@embedpdf/plugin-scroll': specifier: ^2.14.0 - version: 2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-viewport@2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + version: 2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-viewport@2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) '@embedpdf/plugin-viewport': specifier: ^2.14.0 - version: 2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + version: 2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) '@embedpdf/plugin-zoom': specifier: ^2.14.0 - version: 2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-scroll@2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-viewport@2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-viewport@2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + version: 2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-scroll@2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-viewport@2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-viewport@2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) '@google-cloud/storage': specifier: ^7.17.1 version: 7.17.1 @@ -161,6 +161,12 @@ importers: pdfjs-dist: specifier: 4.8.69 version: 4.8.69 + posthog-js: + specifier: ^1.419.4 + version: 1.419.4(@types/react@18.3.25)(react@18.3.1) + posthog-node: + specifier: ^5.51.2 + version: 5.51.2 prettier: specifier: ^3.5.3 version: 3.6.2 @@ -580,6 +586,15 @@ packages: resolution: {integrity: sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==} engines: {node: '>=14'} + '@posthog/browser-common@0.6.0': + resolution: {integrity: sha512-d6yBE7VeoU3JTpaab3CaCoDCseh0Ytx7sTe0v2ZxhtHNxoKk7rdqr92+bUz9F1T2CuJO5/OTkes4HWT2VHNrTA==} + + '@posthog/core@1.48.11': + resolution: {integrity: sha512-fvKbxGaUM8RuCDB1jdhSqAHYjk42INfJDWT1KVezn74sCrfnr1YaUafxzmcS+87D5FzbA2tu7IT0GQRV2WkkRg==} + + '@posthog/types@1.406.1': + resolution: {integrity: sha512-RhA00AvWrcEW3wbYgvIPr4EeUTu1BDHJx8eajwJ1moOYIchQtgkQcqgnUjwXz6jL1a8XJAIaZ9w7SZfYo1b/Rw==} + '@radix-ui/number@1.1.1': resolution: {integrity: sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==} @@ -1797,6 +1812,9 @@ packages: concat-map@0.0.1: resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==} + core-js@3.50.0: + resolution: {integrity: sha512-BRWgOLKkFeCgRudR6zrs8p9XJZcE14grzKMMssoYrk6krtuEZ7MTKPIY5RzOnqsEKIR9kst7wNzphttraT+Yqw==} + core-util-is@1.0.3: resolution: {integrity: sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==} @@ -1915,6 +1933,9 @@ packages: resolution: {integrity: sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==} engines: {node: '>=6.0.0'} + dompurify@3.4.14: + resolution: {integrity: sha512-dVoH9z+MY+C9IilgGCk3YfFqjLi3fChm2OiKJMzh6axrJ5qwxqWaZamgmHrpv22CN/KdbZJuGEGgfQoL00LTdg==} + dunder-proto@1.0.1: resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==} engines: {node: '>= 0.4'} @@ -2193,6 +2214,9 @@ packages: resolution: {integrity: sha512-7yAQpD2UMJzLi1Dqv7qFYnPbaPx7ZfFK6PiIxQ4PfkGPyNyl2Ugx+a/umUonmKqjhM4DnfbMvdX6otXq83soQQ==} engines: {node: ^12.20 || >= 14.13} + fflate@0.4.9: + resolution: {integrity: sha512-zdxgIEddhfsyCaWpJ2SdXEP8ZMrKJ6+5jl4OupODcywU0IhRk6gdXuVGcPICyfx2H97hVK7xmJtRLPjkxAX8Vw==} + file-entry-cache@6.0.1: resolution: {integrity: sha512-7Gps/XWymbLk2QLYK4NzpMOrYjMhdIxXuIvy2QBsLE6ljuodKvdkWs/cpyJJ3CVIVpH0Oi1Hvg1ovbMzLdFBBg==} engines: {node: ^10.12.0 || >=12.0.0} @@ -3126,8 +3150,33 @@ packages: resolution: {integrity: sha512-7a70Nsot+EMX9fFU3064K/kdHWZqGVY+BADLyXc8Dfv+mTLLVl6JzJpPaCZ2kQL9gIJvKXSLMHhqdRRjwQeFtw==} engines: {node: ^10 || ^12 || >=14} - preact@10.29.1: - resolution: {integrity: sha512-gQCLc/vWroE8lIpleXtdJhTFDogTdZG9AjMUpVkDf2iTCNwYNWA+u16dL41TqUDJO4gm2IgrcMv3uTpjd4Pwmg==} + posthog-js@1.419.4: + resolution: {integrity: sha512-SpEgcWtHZ54HxtWl5jCxjHiG9C6t90iQVIra1T+U3veN9Q8vNx3yYsUuEV+dNF6g4M7HeV8Y1ZpNlTalWI8EYw==} + peerDependencies: + '@types/react': '>=16.8.0' + react: '>=16.8.0' + peerDependenciesMeta: + '@types/react': + optional: true + react: + optional: true + + posthog-node@5.51.2: + resolution: {integrity: sha512-K+aQnqyHEtx2O5YmjxByh3WnXXMsrAisW0hNSXwejM4v7cngrbqoA6rZevMSyaXNqx9xhBedTxz0orb1Xwxyew==} + engines: {node: ^20.20.0 || >=22.22.0} + peerDependencies: + rxjs: ^7.0.0 + peerDependenciesMeta: + rxjs: + optional: true + + preact@10.29.8: + resolution: {integrity: sha512-ej2aVZ+vZ8WO7tvlQWRM9N63A0KzF9q4mWJfDUHgYaIofWY9hu74QdnQrjoPMmZi2/nZ5gN0bJCQF49xQqx09Q==} + peerDependencies: + preact-render-to-string: '>=5' + peerDependenciesMeta: + preact-render-to-string: + optional: true prebuild-install@7.1.3: resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==} @@ -3232,6 +3281,9 @@ packages: resolution: {integrity: sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==} engines: {node: '>=0.6'} + query-selector-shadow-dom@1.0.1: + resolution: {integrity: sha512-lT5yCqEBgfoMYpf3F2xQRK7zEr1rhIIZuceDK6+xRkJQ4NMbHTwXqk4NkwDwQMNqXgG9r9fyHnzwNVs6zV5KRw==} + queue-microtask@1.2.3: resolution: {integrity: sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==} @@ -3853,6 +3905,12 @@ packages: resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==} engines: {node: '>= 8'} + web-vitals@5.3.0: + resolution: {integrity: sha512-q6LWsLatGYZp5VGBIOvbTj6JBV2nOmC8KvWztXBmwJcfFAzhwKwbOxhUH306XY3CcaZDUlSmSuNPBsCn0bFu+g==} + + web-vitals@6.0.0: + resolution: {integrity: sha512-Guaibvy/+uNtL6Bsu4jmMJGzuSl91oeRH5iO9pPRbYftnFUr3yqT1TUNX/OE4o9HexuEMU3Kb/Wg7iKhlffZUA==} + webidl-conversions@3.0.1: resolution: {integrity: sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==} @@ -4007,17 +4065,17 @@ snapshots: react: 18.3.1 tslib: 2.8.1 - '@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3))': + '@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3))': dependencies: - '@embedpdf/engines': 2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + '@embedpdf/engines': 2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) '@embedpdf/models': 2.14.0 - preact: 10.29.1 + preact: 10.29.8 react: 18.3.1 react-dom: 18.3.1(react@18.3.1) svelte: 5.55.2 vue: 3.5.32(typescript@5.9.3) - '@embedpdf/engines@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3))': + '@embedpdf/engines@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3))': dependencies: '@embedpdf/fonts-arabic': 1.0.0 '@embedpdf/fonts-hebrew': 1.0.0 @@ -4028,7 +4086,7 @@ snapshots: '@embedpdf/fonts-tc': 1.0.0 '@embedpdf/models': 2.14.0 '@embedpdf/pdfium': 2.14.0 - preact: 10.29.1 + preact: 10.29.8 react: 18.3.1 react-dom: 18.3.1(react@18.3.1) svelte: 5.55.2 @@ -4052,64 +4110,64 @@ snapshots: '@embedpdf/pdfium@2.14.0': {} - '@embedpdf/plugin-document-manager@2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3))': + '@embedpdf/plugin-document-manager@2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3))': dependencies: - '@embedpdf/core': 2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + '@embedpdf/core': 2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) '@embedpdf/models': 2.14.0 - preact: 10.29.1 + preact: 10.29.8 react: 18.3.1 react-dom: 18.3.1(react@18.3.1) svelte: 5.55.2 vue: 3.5.32(typescript@5.9.3) - '@embedpdf/plugin-export@2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3))': + '@embedpdf/plugin-export@2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3))': dependencies: - '@embedpdf/core': 2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + '@embedpdf/core': 2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) '@embedpdf/models': 2.14.0 - preact: 10.29.1 + preact: 10.29.8 react: 18.3.1 react-dom: 18.3.1(react@18.3.1) svelte: 5.55.2 vue: 3.5.32(typescript@5.9.3) - '@embedpdf/plugin-render@2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3))': + '@embedpdf/plugin-render@2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3))': dependencies: - '@embedpdf/core': 2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + '@embedpdf/core': 2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) '@embedpdf/models': 2.14.0 - preact: 10.29.1 + preact: 10.29.8 react: 18.3.1 react-dom: 18.3.1(react@18.3.1) svelte: 5.55.2 vue: 3.5.32(typescript@5.9.3) - '@embedpdf/plugin-scroll@2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-viewport@2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3))': + '@embedpdf/plugin-scroll@2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-viewport@2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3))': dependencies: - '@embedpdf/core': 2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + '@embedpdf/core': 2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) '@embedpdf/models': 2.14.0 - '@embedpdf/plugin-viewport': 2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) - preact: 10.29.1 + '@embedpdf/plugin-viewport': 2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + preact: 10.29.8 react: 18.3.1 react-dom: 18.3.1(react@18.3.1) svelte: 5.55.2 vue: 3.5.32(typescript@5.9.3) - '@embedpdf/plugin-viewport@2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3))': + '@embedpdf/plugin-viewport@2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3))': dependencies: - '@embedpdf/core': 2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + '@embedpdf/core': 2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) '@embedpdf/models': 2.14.0 - preact: 10.29.1 + preact: 10.29.8 react: 18.3.1 react-dom: 18.3.1(react@18.3.1) svelte: 5.55.2 vue: 3.5.32(typescript@5.9.3) - ? '@embedpdf/plugin-zoom@2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-scroll@2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-viewport@2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-viewport@2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3))' + ? '@embedpdf/plugin-zoom@2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-scroll@2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-viewport@2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-viewport@2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3))' : dependencies: - '@embedpdf/core': 2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + '@embedpdf/core': 2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) '@embedpdf/models': 2.14.0 - '@embedpdf/plugin-scroll': 2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-viewport@2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) - '@embedpdf/plugin-viewport': 2.14.0(@embedpdf/core@2.14.0(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.1)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) - preact: 10.29.1 + '@embedpdf/plugin-scroll': 2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(@embedpdf/plugin-viewport@2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + '@embedpdf/plugin-viewport': 2.14.0(@embedpdf/core@2.14.0(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)))(preact@10.29.8)(react-dom@18.3.1(react@18.3.1))(react@18.3.1)(svelte@5.55.2)(vue@3.5.32(typescript@5.9.3)) + preact: 10.29.8 react: 18.3.1 react-dom: 18.3.1(react@18.3.1) svelte: 5.55.2 @@ -4325,6 +4383,17 @@ snapshots: '@pkgjs/parseargs@0.11.0': optional: true + '@posthog/browser-common@0.6.0': + dependencies: + '@posthog/core': 1.48.11 + '@posthog/types': 1.406.1 + + '@posthog/core@1.48.11': + dependencies: + '@posthog/types': 1.406.1 + + '@posthog/types@1.406.1': {} + '@radix-ui/number@1.1.1': {} '@radix-ui/primitive@1.0.1': @@ -5606,6 +5675,8 @@ snapshots: concat-map@0.0.1: {} + core-js@3.50.0: {} + core-util-is@1.0.3: {} cross-spawn@7.0.6: @@ -5702,6 +5773,10 @@ snapshots: dependencies: esutils: 2.0.3 + dompurify@3.4.14: + optionalDependencies: + '@types/trusted-types': 2.0.7 + dunder-proto@1.0.1: dependencies: call-bind-apply-helpers: 1.0.2 @@ -5871,8 +5946,8 @@ snapshots: '@typescript-eslint/parser': 8.45.0(eslint@8.57.1)(typescript@5.9.3) eslint: 8.57.1 eslint-import-resolver-node: 0.3.9 - eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0)(eslint@8.57.1) - eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@8.57.1) + eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1))(eslint@8.57.1) + eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1))(eslint@8.57.1))(eslint@8.57.1) eslint-plugin-jsx-a11y: 6.10.2(eslint@8.57.1) eslint-plugin-react: 7.37.5(eslint@8.57.1) eslint-plugin-react-hooks: 5.0.0-canary-7118f5dd7-20230705(eslint@8.57.1) @@ -5891,7 +5966,7 @@ snapshots: transitivePeerDependencies: - supports-color - eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0)(eslint@8.57.1): + eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1))(eslint@8.57.1): dependencies: '@nolyfill/is-core-module': 1.0.39 debug: 4.4.3 @@ -5902,22 +5977,22 @@ snapshots: tinyglobby: 0.2.15 unrs-resolver: 1.11.1 optionalDependencies: - eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@8.57.1) + eslint-plugin-import: 2.32.0(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1))(eslint@8.57.1))(eslint@8.57.1) transitivePeerDependencies: - supports-color - eslint-module-utils@2.12.1(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0)(eslint@8.57.1))(eslint@8.57.1): + eslint-module-utils@2.12.1(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1))(eslint@8.57.1))(eslint@8.57.1): dependencies: debug: 3.2.7 optionalDependencies: '@typescript-eslint/parser': 8.45.0(eslint@8.57.1)(typescript@5.9.3) eslint: 8.57.1 eslint-import-resolver-node: 0.3.9 - eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0)(eslint@8.57.1) + eslint-import-resolver-typescript: 3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1))(eslint@8.57.1) transitivePeerDependencies: - supports-color - eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1)(eslint@8.57.1): + eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1))(eslint@8.57.1))(eslint@8.57.1): dependencies: '@rtsao/scc': 1.1.0 array-includes: 3.1.9 @@ -5928,7 +6003,7 @@ snapshots: doctrine: 2.1.0 eslint: 8.57.1 eslint-import-resolver-node: 0.3.9 - eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0)(eslint@8.57.1))(eslint@8.57.1) + eslint-module-utils: 2.12.1(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint-import-resolver-node@0.3.9)(eslint-import-resolver-typescript@3.10.1(eslint-plugin-import@2.32.0(@typescript-eslint/parser@8.45.0(eslint@8.57.1)(typescript@5.9.3))(eslint@8.57.1))(eslint@8.57.1))(eslint@8.57.1) hasown: 2.0.2 is-core-module: 2.16.1 is-glob: 4.0.3 @@ -6118,6 +6193,8 @@ snapshots: node-domexception: 1.0.0 web-streams-polyfill: 3.3.3 + fflate@0.4.9: {} + file-entry-cache@6.0.1: dependencies: flat-cache: 3.2.0 @@ -7080,7 +7157,29 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.1 - preact@10.29.1: {} + posthog-js@1.419.4(@types/react@18.3.25)(react@18.3.1): + dependencies: + '@posthog/browser-common': 0.6.0 + '@posthog/core': 1.48.11 + '@posthog/types': 1.406.1 + core-js: 3.50.0 + dompurify: 3.4.14 + fflate: 0.4.9 + preact: 10.29.8 + query-selector-shadow-dom: 1.0.1 + web-vitals: 5.3.0 + web-vitals-soft-navs: web-vitals@6.0.0 + optionalDependencies: + '@types/react': 18.3.25 + react: 18.3.1 + transitivePeerDependencies: + - preact-render-to-string + + posthog-node@5.51.2: + dependencies: + '@posthog/core': 1.48.11 + + preact@10.29.8: {} prebuild-install@7.1.3: dependencies: @@ -7136,6 +7235,8 @@ snapshots: dependencies: side-channel: 1.1.0 + query-selector-shadow-dom@1.0.1: {} + queue-microtask@1.2.3: {} raf-schd@4.0.3: {} @@ -7886,6 +7987,10 @@ snapshots: web-streams-polyfill@3.3.3: {} + web-vitals@5.3.0: {} + + web-vitals@6.0.0: {} + webidl-conversions@3.0.1: {} webidl-conversions@7.0.0: {} diff --git a/src/app/api/request/route.ts b/src/app/api/request/route.ts index a0fbf2c6..15a6327b 100644 --- a/src/app/api/request/route.ts +++ b/src/app/api/request/route.ts @@ -1,6 +1,8 @@ import { success, failure } from "@/lib/utils/response"; -import { createPaperRequest } from "@/lib/services/paper" -import type { CreatePaperInputType } from "@/lib/services/paper" +import { createPaperRequest } from "@/lib/services/paper"; +import type { CreatePaperInputType } from "@/lib/services/paper"; +import { getPostHogClient } from "@/lib/posthog-server"; +import { randomUUID } from "crypto"; export async function POST(req: Request) { try { @@ -11,6 +13,21 @@ export async function POST(req: Request) { } const newRequest = await createPaperRequest({subject, exam, slot, year}); + + const posthog = getPostHogClient(); + if (posthog) { + posthog.capture({ + distinctId: randomUUID(), + event: "paper_request_created", + properties: { + exam, + slot, + year, + }, + }); + await posthog.flush(); + } + return success({ message: "Paper request submitted successfully!", request: newRequest }, "Created", 201); } catch (error) { console.error("Error creating paper request:", error); diff --git a/src/app/api/upload/route.ts b/src/app/api/upload/route.ts index 471b5cb0..782a48ca 100644 --- a/src/app/api/upload/route.ts +++ b/src/app/api/upload/route.ts @@ -1,5 +1,7 @@ import { success, failure } from "@/lib/utils/response"; import { uploadPaper } from "@/lib/services/upload"; +import { getPostHogClient } from "@/lib/posthog-server"; +import { randomUUID } from "crypto"; export const runtime = "nodejs"; @@ -21,6 +23,20 @@ export async function POST(req: Request) { return failure(result.message, result.status); } + const posthog = getPostHogClient(); + if (posthog) { + posthog.capture({ + distinctId: randomUUID(), + event: "paper_upload_completed", + properties: { + file_count: files.length, + is_pdf: isPdf, + campus: campus ?? "unknown", + }, + }); + await posthog.flush(); + } + return success( { file_url: result.file_url, thumbnail_url: result.thumbnail_url }, "Created", diff --git a/src/app/layout.tsx b/src/app/layout.tsx index a62c9e8e..175ea07b 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -8,6 +8,7 @@ import Navbar from "@/components/Navbar"; import Footer from "@/components/Footer"; import ChildrenWrapper from "@/components/ChildrenWrapper"; import { CoursesProvider } from "@/context/courseContext"; +import { PostHogProvider } from "@/components/PostHogProvider"; export const metadata: Metadata = { metadataBase: new URL("https://papers.codechefvit.com/"), @@ -113,21 +114,23 @@ export default function RootLayout({ - - -
- - - {children} -
- -
-
+ + + +
+ + + {children} +
+ +
+
+
); diff --git a/src/app/request/page.tsx b/src/app/request/page.tsx index 56ee4ee3..b2f697c7 100644 --- a/src/app/request/page.tsx +++ b/src/app/request/page.tsx @@ -12,6 +12,7 @@ import { import { exams, slots, years } from "@/components/select_options"; import { Input } from "@/components/ui/input"; import axios from "axios"; +import posthog from "posthog-js"; import Fuse from "fuse.js"; import { type IUpcomingPaper } from "@/interface"; import UpcomingPaper from "../../components/UpcomingPaper"; @@ -118,6 +119,12 @@ export default function PaperRequest() { }, ); + posthog.capture("paper_request_submitted", { + exam: selectedExam, + slot: selectedSlot, + year: selectedYear, + }); + setSearchText(""); setSelectedSubject(null); setSelectedExam(null); diff --git a/src/app/upload/page.tsx b/src/app/upload/page.tsx index 4ff1347d..94e13527 100644 --- a/src/app/upload/page.tsx +++ b/src/app/upload/page.tsx @@ -24,6 +24,7 @@ import { import { CSS } from "@dnd-kit/utilities"; import Dropzone from "react-dropzone"; import { Upload, XIcon } from "lucide-react"; +import posthog from "posthog-js"; import { GlobalWorkerOptions } from "pdfjs-dist"; import type { ApiResponse } from "@/interface"; @@ -274,6 +275,9 @@ export default function Page() { setIsUploading(true); + const fileTypes = [...new Set(files.map((f) => f.type))]; + const fileCount = files.length; + try { await toast.promise( async () => { @@ -300,6 +304,12 @@ export default function Page() { }, ); + posthog.capture("paper_upload_submitted", { + file_count: fileCount, + file_types: fileTypes, + is_pdf: isPdf, + }); + clearAllFiles(); } finally { setIsUploading(false); diff --git a/src/components/CatalogueContent.tsx b/src/components/CatalogueContent.tsx index 967a8671..bf83bf3f 100644 --- a/src/components/CatalogueContent.tsx +++ b/src/components/CatalogueContent.tsx @@ -16,6 +16,7 @@ import SearchBarChild from "./Searchbar/searchbar-child"; import Link from "next/link"; import { useCourses } from "@/context/courseContext"; import { FilterProvider, useFilters } from "@/context/filterContext"; +import posthog from "posthog-js"; import EmptyState from "./ui/EmptyState"; import SelectionToolbar from "./SelectionToolbar"; import SortComponent from "./ui/sorting"; @@ -143,6 +144,10 @@ const CatalogueContentInner = ({ subject }: { subject: string | null }) => { : saved.filter((s) => s !== subject); localStorage.setItem("userSubjects", JSON.stringify(updated)); + + posthog.capture(current ? "subject_pinned" : "subject_unpinned", { + subject: subject?.split(" [")[0]?.trim() ?? subject, + }); }; // Fetch papers ONLY when subject changes (not when filters change!) diff --git a/src/components/Footer.tsx b/src/components/Footer.tsx index 945b0944..a747849b 100644 --- a/src/components/Footer.tsx +++ b/src/components/Footer.tsx @@ -15,6 +15,7 @@ import { import { Mail } from "lucide-react"; import toast from "react-hot-toast"; import type { ApiResponse } from '@/interface' +import posthog from "posthog-js"; export default function Footer() { const [email, setEmail] = useState(""); @@ -42,6 +43,8 @@ export default function Footer() { }, ); + posthog.capture("newsletter_subscribed"); + setEmail(""); }; diff --git a/src/components/PostHogProvider.tsx b/src/components/PostHogProvider.tsx new file mode 100644 index 00000000..65bae554 --- /dev/null +++ b/src/components/PostHogProvider.tsx @@ -0,0 +1,28 @@ +"use client"; + +import posthog from "posthog-js"; +import { PostHogProvider as PHProvider } from "posthog-js/react"; +import { useEffect } from "react"; + +export function PostHogProvider({ children }: { children: React.ReactNode }) { + useEffect(() => { + const token = process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN; + if (!token) { + if (process.env.NODE_ENV !== "production") { + console.error( + "NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN is configured", + ); + } + return; + } + posthog.init(token, { + api_host: "/ingest", + ui_host: "https://us.posthog.com", + defaults: "2026-01-30", + capture_exceptions: true, + debug: process.env.NODE_ENV === "development", + }); + }, []); + + return {children}; +} diff --git a/src/components/ReportTagModal.tsx b/src/components/ReportTagModal.tsx index f056f498..b0360cc2 100644 --- a/src/components/ReportTagModal.tsx +++ b/src/components/ReportTagModal.tsx @@ -15,7 +15,8 @@ import { MultiSelect } from "@/components/multi-select"; import LabeledInput from "@/components/ui/LabeledInput"; import LabeledSelect from "@/components/ui/LabeledSelect"; import axios from "axios"; -import toast from "react-hot-toast"; +import toast from "react-hot-toast"; +import posthog from "posthog-js"; import { type ApiResponse } from '@/interface' type ReportResponse = ApiResponse<{ error?: string; message?: string }>; @@ -236,6 +237,11 @@ if (reportedFields.length === 0 && comment.trim().length === 0) { } ) .then(() => { + posthog.capture("paper_reported", { + fields_reported: reportedFields.map((f) => f.field), + fields_reported_count: reportedFields.length, + has_comment: comment.trim().length > 0, + }); modalSetOpen(false); setComment(""); setEmail(""); diff --git a/src/components/ShareButton.tsx b/src/components/ShareButton.tsx index d9387b77..9490b0b7 100644 --- a/src/components/ShareButton.tsx +++ b/src/components/ShareButton.tsx @@ -15,6 +15,7 @@ import { FaShare } from "react-icons/fa"; import QR from "./qr"; import { Button } from "./ui/button"; import { usePathname } from "next/navigation"; +import posthog from "posthog-js"; interface ShareButtonProps { isFullscreen: boolean; @@ -63,6 +64,7 @@ export default function ShareButton({ isFullscreen, viewerRef }: ShareButtonProp loading: "Copying link...", error: "Error copying link", }); + posthog.capture("paper_shared", { method: "link_copied" }); }} >

Copy Link To Clipboard

diff --git a/src/components/newPdfViewer.tsx b/src/components/newPdfViewer.tsx index a249ffb7..6556ec66 100644 --- a/src/components/newPdfViewer.tsx +++ b/src/components/newPdfViewer.tsx @@ -10,6 +10,7 @@ import { ExportPluginPackage } from '@embedpdf/plugin-export/react'; import { Download, ZoomIn, ZoomOut, Maximize2, Minimize2, BookOpenText, X } from "lucide-react"; + import posthog from "posthog-js"; import { memo, useCallback, useEffect, useMemo, useRef, useState } from "react"; import { downloadFile } from "../lib/utils/download"; import { Button } from "./ui/button"; @@ -478,6 +479,9 @@ paper_title: name, paper_url: url, }); + posthog.capture("paper_downloaded", { + paper_name: name, + }); await downloadFile(url, `${name}.pdf`); }, [url, name]); @@ -508,6 +512,7 @@ const toggleReadingMode = useCallback(() => { setIsReadingMode((r) => { const next = !r; + posthog.capture("reading_mode_toggled", { enabled: next }); onReadingModeChange?.(next); return next; }); diff --git a/src/context/filterContext.tsx b/src/context/filterContext.tsx index 557038b9..f0cb3fb7 100644 --- a/src/context/filterContext.tsx +++ b/src/context/filterContext.tsx @@ -14,6 +14,7 @@ import { useSearchParams, } from "next/navigation"; import { type IPaper, type Filters } from "@/interface"; +import posthog from "posthog-js"; import JSZip from "jszip"; import { toast } from "react-hot-toast"; import { getSecureUrl, generateFileName } from "@/lib/utils/download"; @@ -208,6 +209,12 @@ export const FilterProvider: React.FC = ({ a.remove(); URL.revokeObjectURL(url); + posthog.capture("papers_bulk_downloaded", { + download_count: uniquePapers.length - failedCount, + total_selected: uniquePapers.length, + failed_count: failedCount, + }); + if (failedCount > 0) { toast.success( `Downloaded ${uniquePapers.length - failedCount} of ${uniquePapers.length} papers (${failedCount} failed).`, diff --git a/src/lib/posthog-server.ts b/src/lib/posthog-server.ts new file mode 100644 index 00000000..592779f1 --- /dev/null +++ b/src/lib/posthog-server.ts @@ -0,0 +1,23 @@ +import { PostHog } from "posthog-node"; + +let posthogClient: PostHog | null = null; + +export function getPostHogClient(): PostHog | null { + const token = process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN; + if (!token) { + if (process.env.NODE_ENV !== "production") { + console.error( + "NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN is configured", + ); + } + return null; + } + if (!posthogClient) { + posthogClient = new PostHog(token, { + host: process.env.NEXT_PUBLIC_POSTHOG_HOST, + flushAt: 1, + flushInterval: 0, + }); + } + return posthogClient; +} From 63074e2513a438a39da12be33dfd371c67ed1dca Mon Sep 17 00:00:00 2001 From: abhitrueprogrammer Date: Wed, 26 Aug 2026 12:51:51 +0530 Subject: [PATCH 2/6] update env.example with posthog env vars --- .env.example | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.env.example b/.env.example index 2a6e557a..39fbe6b2 100644 --- a/.env.example +++ b/.env.example @@ -30,4 +30,7 @@ GOOGLE_APPLICATION_CREDENTIALS_JSON="" # The content of the JSON file you d # Upstash_Redis UPSTASH_REDIS_REST_URL="" # REST URL of your Upstash Redis database -UPSTASH_REDIS_REST_TOKEN="" # REST API token for Upstash Redis \ No newline at end of file +UPSTASH_REDIS_REST_TOKEN="" # REST API token for Upstash Redis + +NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN="" +NEXT_PUBLIC_POSTHOG_HOST="" From 04c5a505b54f9b4a71398a62031beb3ee01a486f Mon Sep 17 00:00:00 2001 From: abhitrueprogrammer Date: Wed, 26 Aug 2026 13:22:10 +0530 Subject: [PATCH 3/6] fix: satisfy PostHog client lint rule --- src/lib/posthog-server.ts | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/src/lib/posthog-server.ts b/src/lib/posthog-server.ts index 592779f1..fe4f3e20 100644 --- a/src/lib/posthog-server.ts +++ b/src/lib/posthog-server.ts @@ -12,12 +12,10 @@ export function getPostHogClient(): PostHog | null { } return null; } - if (!posthogClient) { - posthogClient = new PostHog(token, { - host: process.env.NEXT_PUBLIC_POSTHOG_HOST, - flushAt: 1, - flushInterval: 0, - }); - } + posthogClient ??= new PostHog(token, { + host: process.env.NEXT_PUBLIC_POSTHOG_HOST, + flushAt: 1, + flushInterval: 0, + }); return posthogClient; } From 8db21f63d15156e1f875ba1428f802acfae4814a Mon Sep 17 00:00:00 2001 From: abhitrueprogrammer Date: Wed, 26 Aug 2026 14:42:57 +0530 Subject: [PATCH 4/6] chore: remove PostHog wizard artifacts --- .../.posthog-wizard | 0 .../integration-nextjs-app-router/SKILL.md | 81 -- .../references/1-begin.md | 56 -- .../references/2-edit.md | 36 - .../references/3-revise.md | 22 - .../references/4-conclude.md | 143 ---- .../references/COMMANDMENTS.md | 35 - .../references/EXAMPLE.md | 712 ------------------ .../references/identify-users.md | 307 -------- .../references/next-js.md | 453 ----------- 10 files changed, 1845 deletions(-) delete mode 100644 .claude/skills/integration-nextjs-app-router/.posthog-wizard delete mode 100644 .claude/skills/integration-nextjs-app-router/SKILL.md delete mode 100644 .claude/skills/integration-nextjs-app-router/references/1-begin.md delete mode 100644 .claude/skills/integration-nextjs-app-router/references/2-edit.md delete mode 100644 .claude/skills/integration-nextjs-app-router/references/3-revise.md delete mode 100644 .claude/skills/integration-nextjs-app-router/references/4-conclude.md delete mode 100644 .claude/skills/integration-nextjs-app-router/references/COMMANDMENTS.md delete mode 100644 .claude/skills/integration-nextjs-app-router/references/EXAMPLE.md delete mode 100644 .claude/skills/integration-nextjs-app-router/references/identify-users.md delete mode 100644 .claude/skills/integration-nextjs-app-router/references/next-js.md diff --git a/.claude/skills/integration-nextjs-app-router/.posthog-wizard b/.claude/skills/integration-nextjs-app-router/.posthog-wizard deleted file mode 100644 index e69de29b..00000000 diff --git a/.claude/skills/integration-nextjs-app-router/SKILL.md b/.claude/skills/integration-nextjs-app-router/SKILL.md deleted file mode 100644 index 6eec3de8..00000000 --- a/.claude/skills/integration-nextjs-app-router/SKILL.md +++ /dev/null @@ -1,81 +0,0 @@ ---- -name: integration-nextjs-app-router -description: PostHog integration for Next.js App Router applications -metadata: - author: PostHog - version: 1.49.0 ---- - -# PostHog integration for Next.js App Router - -This skill helps you add PostHog analytics to Next.js App Router applications. - -## Workflow - -Follow these steps in order to complete the integration: - -1. `references/1-begin.md` - PostHog Setup - Begin ← **Start here** -2. `references/2-edit.md` - PostHog Setup - Edit -3. `references/3-revise.md` - PostHog Setup - Revise -4. `references/4-conclude.md` - PostHog Setup - Conclusion - -## Reference files - -- `references/EXAMPLE.md` - Next.js App Router example project code -- `references/1-begin.md` - Start the event tracking setup process by analyzing the project and creating an event tracking plan -- `references/2-edit.md` - Implement PostHog event tracking in the identified files, following best practices and the example project -- `references/3-revise.md` - Review and fix any errors in the PostHog integration implementation -- `references/4-conclude.md` - Review and fix any errors in the PostHog integration implementation -- `references/next-js.md` - Next.js - docs -- `references/identify-users.md` - Identify users - docs -- `references/COMMANDMENTS.md` - Framework-specific rules the integration must follow - -The example project shows the target implementation pattern. Consult the documentation for API details. - -## Key principles - -- **Environment variables**: Always use environment variables for PostHog keys. Never hardcode them. -- **Minimal changes**: Add PostHog code alongside existing integrations. Don't replace or restructure existing code. -- **Match the example**: Your implementation should follow the example project's patterns as closely as possible. - -## Framework guidelines - -- A missing PostHog configuration must never break the app — read keys optionally (never a required setting), guard init and capture behind their presence, and keep build and boot working with no PostHog environment set — but never silently: in development or debug builds fail loudly, using the language's idiomatic error, with the message " variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once is configured" (substituting the actual variable name); production stays a no-op -- For Next.js 15.3+, initialize PostHog in instrumentation-client.ts for the simplest setup -- For feature flags, use useFeatureFlagEnabled() or useFeatureFlagPayload() hooks - they handle loading states and external sync automatically -- Add analytics capture in event handlers where user actions occur, NOT in useEffect reacting to state changes -- Do NOT use useEffect for data transformation - calculate derived values during render instead -- Do NOT use useEffect to respond to user events - put that logic in the event handler itself -- Do NOT use useEffect to chain state updates - calculate all related updates together in the event handler -- Do NOT use useEffect to notify parent components - call the parent callback alongside setState in the event handler -- To reset component state when a prop changes, pass the prop as the component's key instead of using useEffect -- useEffect is ONLY for synchronizing with external systems (non-React widgets, browser APIs, network subscriptions) -- Remember that source code is available in the node_modules directory -- Check package.json for type checking or build scripts to validate changes -- When identity comes from framework-bridged state (Inertia or SSR shared props, a serialized session), confirm the backend actually shares that field — add the share server-side if missing — before identifying from it -- When a reverse proxy is configured, both /static/* AND /array/* must route to the assets origin (us-assets.i.posthog.com or eu-assets.i.posthog.com). -- posthog-js is the JavaScript SDK package name -- posthog.init() MUST be called before any other PostHog methods (capture, identify, etc.) -- posthog-js is browser-only — do NOT import it in Node.js or server-side contexts (use posthog-node instead) -- Autocapture is ON by default with posthog-js (tracks clicks, form submissions, pageviews). Keep autocapture enabled unless the user explicitly asks to turn it off. -- NEVER send PII in posthog.capture() event properties — no emails, full names, phone numbers, physical addresses, IP addresses, or user-generated content -- PII belongs in posthog.identify() person properties (email, name, role), NOT in capture() event properties -- Call posthog.identify(userId, { email, name, role }) on login AND on page refresh if the user is already logged in -- Call posthog.reset() on logout — the transition out of an identified session, never an initially anonymous page load (that discards the anonymous id and its history) — and before identify() when switching directly between accounts -- For SPAs without a framework router, capture pageviews with posthog.capture($pageview) or use the capture_pageview history_change option in init for History API routing -- When verifying with an automated browser (Playwright, Puppeteer, Selenium), posthog-js's bot filter silently drops every capture while flags and asset loads still succeed. Override navigator.webdriver, the user agent, AND navigator.userAgentData before concluding events do not send. Diagnose with ?__posthog_debug=true ("likely bot" in the console). -- posthog-node is the Node.js server-side SDK package name; posthog-js is browser-only, so use posthog-node on the server instead -- Include enableExceptionAutocapture: true in the PostHog constructor options -- Add posthog.capture() calls in route handlers for meaningful user actions – every route that creates, updates, or deletes data should track an event with contextual properties -- Add posthog.captureException(err, distinctId) in the application's error handler (e.g., Express error middleware, Fastify setErrorHandler, Koa app.on('error')) -- The SDK batches events and flushes asynchronously. await flush() or await shutdown() before letting that process exit. If unsure, set flushAt 1 and flushInterval 0. -- `posthog.capture()` enqueues synchronously and returns; the batched HTTP send happens afterwards. Treat every per-request handler as short-lived even when the framework feels like a server: Next.js / Nuxt / SvelteKit / Remix route handlers, serverless and edge functions, and Lambda are torn down per invocation before the send runs. Create the client with flushAt 1 and flushInterval 0, then await the send before returning. Always use `await posthog.flush()` for a shared/singleton client, `await posthog.shutdown()` for a per-request client. Never skip the awaited flush or risk the enqueued event being silently dropped. -- Reverse proxy is NOT needed for server-side Node.js – only client-side JavaScript needs a proxy to avoid ad blockers - -## Identifying users - -Identify users during login and signup events. Refer to the example code and documentation for the correct identify pattern for this framework. If both frontend and backend code exist, pass the client-side session and distinct ID using `X-POSTHOG-DISTINCT-ID` and `X-POSTHOG-SESSION-ID` headers to maintain correlation. - -## Error tracking - -Add PostHog error tracking to relevant files, particularly around critical user flows and API boundaries. diff --git a/.claude/skills/integration-nextjs-app-router/references/1-begin.md b/.claude/skills/integration-nextjs-app-router/references/1-begin.md deleted file mode 100644 index 55f0a832..00000000 --- a/.claude/skills/integration-nextjs-app-router/references/1-begin.md +++ /dev/null @@ -1,56 +0,0 @@ ---- -title: PostHog Setup - Begin -description: Start the event tracking setup process by analyzing the project and creating an event tracking plan ---- - -We're making an event tracking plan for this project. - -This is the first of several phases — plan the events, implement them, revise and validate changes, then conclude by creating a dashboard and writing a setup report. - -## Task list - -As soon as you've read this description and have a rough sense of the work, make a single **call `TaskCreate` immediately** before reading any reference file or beginning analysis. The user is watching the task pane and shouldn't see it sit empty. - -It's fine if your first list is incomplete or imprecise. Seed it with whatever high-level items you can infer from the overview above, then call `TaskCreate` again (or `TaskUpdate` to refine existing items) every time your understanding sharpens: after a phase reveals work you didn't anticipate, after planning surfaces concrete sub-items, after you hit something new. Use `TaskUpdate` to mark items `in_progress` when you start them and `completed` when you finish. Keeping the list current matters more than getting it right on the first call. - -Keep task titles broad and job-oriented. Describe the purpose or area of work with wording like "Planning event tracking", "Identifying users", "Installing PostHog", "Capturing events", or "Creating dashboards", not the specific files, paths, or symbols involved. Adjust the task names according to the user's project and context. - -Before proceeding, find any existing `posthog.capture()` code. Make note of event name formatting. - -From the project's file list, select between 10 and 15 files that might have interesting business value for event tracking, especially conversion and churn events. Also look for additional files related to login that could be used for identifying users, along with error handling. Read the files. If a file is already well-covered by PostHog events, replace it with another option. Do not spawn subagents. - -Look for opportunities to track client-side events. - -**IMPORTANT: Server-side events are REQUIRED** if the project includes any instrumentable server-side code. If the project has API routes (e.g., `app/api/**/route.ts`) or Server Actions, you MUST include server-side events for critical business operations like: - - - Payment/checkout completion - - Webhook handlers - - Authentication endpoints - -Do not skip server-side events - they capture actions that cannot be tracked client-side. - -Create a new file with a JSON array at the root of the project: .posthog-events.json. It should include one object for each event we want to add with these exact field names: `event_name` (the event name), `event_description` (one sentence), and `file` (the file path the event goes in). The wizard reads this file to surface the plan in the UI. If events already exist, don't duplicate them; supplement them. - -Track actions only, not pageviews. These can be captured automatically. Exceptions can be made for "viewed"-type events that correspond to the top of a conversion funnel. - -As you review files, make an internal note of opportunities to identify users and catch errors. We'll need them for the next step. - -## Status - -Before beginning a phase of the setup, you will send a status message with the exact prefix '[STATUS]', as in: - -[STATUS] Checking project structure. - -Status to report in this phase: - -- Checking project structure -- Verifying PostHog dependencies -- Generating events based on project - -## Abort statuses - -If and only if the instructions have `[ABORT]` states specified, and you clearly match the conditions for an abort, emit the abort message. Do NOT attempt to exit or halt yourself — the wizard's middleware catches `[ABORT]` and terminates the run for you. - ---- - -**Upon completion, continue with:** [2-edit.md](2-edit.md) \ No newline at end of file diff --git a/.claude/skills/integration-nextjs-app-router/references/2-edit.md b/.claude/skills/integration-nextjs-app-router/references/2-edit.md deleted file mode 100644 index e5f7ffd1..00000000 --- a/.claude/skills/integration-nextjs-app-router/references/2-edit.md +++ /dev/null @@ -1,36 +0,0 @@ ---- -title: PostHog Setup - Edit -description: Implement PostHog event tracking in the identified files, following best practices and the example project ---- - -For each of the files and events noted in .posthog-events.json, make edits to capture events using PostHog. Make sure to set up any helper files needed. Carefully examine the included example project code: your implementation should match it as closely as possible. Do not spawn subagents. - -Use environment variables for PostHog keys. Do not hardcode PostHog keys. - -If a file already has existing integration code for other tools or services, don't overwrite or remove that code. Place PostHog code below it. - -For each event, add useful properties, and use your access to the PostHog source code to ensure correctness. You also have access to documentation about creating new events with PostHog. Consider this documentation carefully and follow it closely before adding events. Your integration should be based on documented best practices. Carefully consider how the user project's framework version may impact the correct PostHog integration approach. - -Remember that you can find the source code for any dependency in the node_modules directory. This may be necessary to properly populate property names. There are also example project code files available via the PostHog MCP; use these for reference. - -Where possible, add calls for PostHog's identify() function on the client side upon events like logins and signups. Use the contents of login and signup forms to identify users on submit. If there is server-side code, pass the client-side session and distinct ID to the server-side code to identify the user. On the server side, make sure events have a matching distinct ID where relevant. - -It's essential to do this in both client code and server code, so that user behavior from both domains is easy to correlate. - -You should also add PostHog exception capture error tracking to these files where relevant. - -Remember: Do not alter the fundamental architecture of existing files. Make your additions minimal and targeted. - -Remember the documentation and example project resources you were provided at the beginning. Read them now. - -## Status - -Status to report in this phase: - -- Inserting PostHog capture code -- A status message for each file whose edits you are planning, including a high level summary of changes -- A status message for each file you have edited - ---- - -**Upon completion, continue with:** [3-revise.md](3-revise.md) \ No newline at end of file diff --git a/.claude/skills/integration-nextjs-app-router/references/3-revise.md b/.claude/skills/integration-nextjs-app-router/references/3-revise.md deleted file mode 100644 index 3b07f506..00000000 --- a/.claude/skills/integration-nextjs-app-router/references/3-revise.md +++ /dev/null @@ -1,22 +0,0 @@ ---- -title: PostHog Setup - Revise -description: Review and fix any errors in the PostHog integration implementation ---- - -Check the project for errors. Read the package.json file for any type checking or build scripts that may provide input about what to fix. Remember that you can find the source code for any dependency in the node_modules directory. Do not spawn subagents. - -Ensure that any components created were actually used. - -Once all other tasks are complete, run any linter or prettier-like scripts found in the package.json, but ONLY on the files you have edited or created during this session. Do not run formatting or linting across the entire project's codebase. - -## Status - -Status to report in this phase: - -- Finding and correcting errors -- Report details of any errors you fix -- Linting, building and prettying - ---- - -**Upon completion, continue with:** [4-conclude.md](4-conclude.md) \ No newline at end of file diff --git a/.claude/skills/integration-nextjs-app-router/references/4-conclude.md b/.claude/skills/integration-nextjs-app-router/references/4-conclude.md deleted file mode 100644 index 200933a9..00000000 --- a/.claude/skills/integration-nextjs-app-router/references/4-conclude.md +++ /dev/null @@ -1,143 +0,0 @@ ---- -title: PostHog Setup - Conclusion -description: Review and fix any errors in the PostHog integration implementation ---- - -Create a live PostHog dashboard named "Analytics basics (wizard)" from the events you just instrumented, then populate it with up to five insights — lead with the business-critical views: conversion funnels, churn events, and other key signals. Use the exact same event names as implemented in the code. Keep the `(wizard)` tag with that exact casing so anyone browsing PostHog can see the wizard created this dashboard, and so a quick search for `(wizard)` surfaces every wizard-created artifact in one go. - -Always create the dashboard and insights based on the intended captures, regardless of whether those events have been observed yet. An insight is a definition over event names, not a snapshot of current data: it is expected to render empty until the first events arrive, and it fills in on its own once they do. "No data ingested yet", "the events aren't in the schema", or "the query would return nothing today" are never reasons to skip or defer insights — a dashboard handed off without them is an incomplete integration, not a cautious one. - -## How to call PostHog MCP tools - -The PostHog MCP server exposes a single `exec` tool. Every PostHog operation is driven by a CLI-style command string passed in its `command` parameter — the tool may be namespaced by the host (`mcp__posthog__exec`, `mcp__posthog-wizard__exec`), but the command grammar is the same. Tool names and schemas are not predictable, so discover and inspect before you call. - -**Grammar** — run in this order: - -```text -exec({ "command": "search " }) # find tools by name/title/description; `tools` lists them all -exec({ "command": "info " }) # REQUIRED before every call — description + input schema -exec({ "command": "schema " }) # drill into a field the schema flags with a `hint` -exec({ "command": "call " }) # run the tool -``` - -Running `info ` before `call ` is mandatory, the same way you read a file before editing it. `info` returns the full schema for simple tools; for large ones it summarizes and attaches `hint` entries pointing at fields to drill into with `schema`. Dot-notation descends objects (`query.source`), array items (`series.0.properties`), and unions. Never guess the structure of a field that carries a hint — drill first. - -Every PostHog tool goes through `exec` this way — there is no separate named tool to call directly. The inner tool names and JSON payloads below are what you pass to `call`. - -**Errors** carry a suggestion and similar tool names — read it before retrying. If a name isn't found it may have been renamed; run `search ` or `tools` again to find the current one. - -Create the parent dashboard first with `dashboard-create`, capture its returned `id`, then attach every insight to it via `dashboards: []`: - -```json -{ - "name": "Analytics basics (wizard)", - "description": "Key views for the events instrumented by the PostHog wizard.", - "tags": ["wizard"] -} -``` - -When calling `insight-create`, use these known-good query shapes — they are verified against the MCP schema, and the common variations around them are rejected: - -A trends insight with a breakdown (breakdowns go in `breakdownFilter.breakdowns`, an array — there is NO top-level `breakdown` field on `TrendsQuery`): - -```json -{ - "name": "Signups by plan (wizard)", - "dashboards": [], - "query": { - "kind": "InsightVizNode", - "source": { - "kind": "TrendsQuery", - "series": [{ "kind": "EventsNode", "event": "user_signed_up", "math": "total" }], - "interval": "day", - "dateRange": { "date_from": "-30d" }, - "breakdownFilter": { "breakdowns": [{ "type": "event", "property": "plan" }] }, - "trendsFilter": { "display": "ActionsBar" } - } - } -} -``` - -A conversion funnel (the window fields are camelCase and live INSIDE `funnelsFilter` — not at the top level of `FunnelsQuery`, and not snake_case): - -```json -{ - "name": "Signup funnel (wizard)", - "dashboards": [], - "query": { - "kind": "InsightVizNode", - "source": { - "kind": "FunnelsQuery", - "series": [ - { "kind": "EventsNode", "event": "page_viewed" }, - { "kind": "EventsNode", "event": "user_signed_up" } - ], - "dateRange": { "date_from": "-30d" }, - "funnelsFilter": { - "funnelVizType": "steps", - "funnelOrderType": "ordered", - "funnelWindowInterval": 14, - "funnelWindowIntervalUnit": "day" - } - } - } -} -``` - -Valid `trendsFilter.display` values are `ActionsLineGraph`, `ActionsBar`, `ActionsAreaGraph`, `ActionsPie`, `ActionsStackedBar`, `BoldNumber`, and `ActionsTable` — names like `ActionsBarChart` or `ActionsBarGraph` are rejected. If an insight call is rejected anyway, fix the payload against these examples rather than retrying variations. - -Once the dashboard exists, emit its URL on its own line in your assistant message using this exact marker: `[DASHBOARD_URL] `. The wizard parses this marker from your visible message and surfaces the link in the success summary. Mentioning the URL only in thinking or in prose without the marker means the link is dropped. - -Search for a file called `.posthog-events.json` and read it for available events. - -Do not spawn subagents. - -Compose the setup report as markdown — do NOT write it to a file in the project. It should include a summary of the integration edits, a table with the event names, event descriptions, and files where events were added, a list of links for the dashboard and insights created, and a "Verify before merging" checklist (see below). Follow this format: - - -# PostHog post-wizard report - -The wizard has completed a deep integration of your project. [Detailed summary of changes] - -[table of events/descriptions/files] - -## Next steps - -We've built some insights and a dashboard for you to keep an eye on user behavior, based on the events we just instrumented: - -[links] - -## Verify before merging - -[checklist] - -### Agent skill - -We've left an agent skill folder in your project. You can use this context for further agent development when using Claude Code. This will help ensure the model provides the most up-to-date approaches for integrating PostHog. - - - -For the "Verify before merging" checklist, write GitHub-style checkboxes (`- [ ] ...`) covering what the developer (or their coding agent) still needs to do to take this from "wizard finished" to "merged". Include ONLY the items that actually apply to the integration you just performed — judge each against the code you changed in this run, and drop any that don't fit. Phrase each item as a concrete, checkable action. Candidate items, with the condition for including each: - -- Always: "Run a full production build (the wizard only verified the files it touched) and fix any lint or type errors introduced by the generated code." -- Always: "Run the test suite — call sites that were rewritten or instrumented may need updated mocks or fixtures." -- If you added environment variables: "Add the exact PostHog env var names you added to `.env.example` and any monorepo/bootstrap scripts so collaborators know what to set." -- If this integration ships a minified production browser bundle (most SPA/SSR web frameworks — e.g. Next.js, Nuxt, SvelteKit, Astro, Vite-based apps): "Wire source-map upload (`posthog-cli sourcemap` or your bundler's upload step) into CI so production stack traces de-minify." -- If LLM analytics was set up in this run: "Trigger the LLM call path(s) you instrumented and confirm `$ai_generation` events appear in PostHog AI Observability." -- If the app has user auth and an `identify` call was added: "Confirm the returning-visitor path also calls `identify` — a handler that only identifies on fresh login can leave returning sessions on anonymous distinct IDs." - -Do not invent items beyond what applies. If only the two "Always" items apply, the checklist is just those two. - -Then publish the report to the wizard session with a single `publish_handoff` call, passing the complete report markdown as `content`. This call is how the report reaches the user — do not write it to a file instead. - -Then mirror the report into a shareable PostHog notebook so the user has an in-app copy to link and comment on. Call `notebooks-create-markdown` with a `title` (e.g. `PostHog setup (wizard) – `) and the report verbatim as `markdown` — the title becomes the notebook's leading heading, so start the markdown at the first section below it. Take the `short_id` from the response, build the notebook URL as `/project//notebooks/`, and emit it on its own line so the wizard can surface it: `[NOTEBOOK_URL]` followed by that URL. - -Upon completion, update `.posthog-events.json` so it matches the events you actually implemented, then remove it with your file tools. If removal is blocked or fails in your environment, leave the file in place and move on — the wizard host cleans it up after the run. Do not retry the removal or reach for shell commands to force it. - -## Status - -Status to report in this phase: - -- Configured dashboard: [insert PostHog dashboard URL] -- Published setup report to the wizard session -- Created notebook: [insert PostHog notebook URL] \ No newline at end of file diff --git a/.claude/skills/integration-nextjs-app-router/references/COMMANDMENTS.md b/.claude/skills/integration-nextjs-app-router/references/COMMANDMENTS.md deleted file mode 100644 index 9cc1e933..00000000 --- a/.claude/skills/integration-nextjs-app-router/references/COMMANDMENTS.md +++ /dev/null @@ -1,35 +0,0 @@ -# Framework rules - -Follow these when integrating PostHog into this framework. - -- A missing PostHog configuration must never break the app — read keys optionally (never a required setting), guard init and capture behind their presence, and keep build and boot working with no PostHog environment set — but never silently: in development or debug builds fail loudly, using the language's idiomatic error, with the message " variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once is configured" (substituting the actual variable name); production stays a no-op -- For Next.js 15.3+, initialize PostHog in instrumentation-client.ts for the simplest setup -- For feature flags, use useFeatureFlagEnabled() or useFeatureFlagPayload() hooks - they handle loading states and external sync automatically -- Add analytics capture in event handlers where user actions occur, NOT in useEffect reacting to state changes -- Do NOT use useEffect for data transformation - calculate derived values during render instead -- Do NOT use useEffect to respond to user events - put that logic in the event handler itself -- Do NOT use useEffect to chain state updates - calculate all related updates together in the event handler -- Do NOT use useEffect to notify parent components - call the parent callback alongside setState in the event handler -- To reset component state when a prop changes, pass the prop as the component's key instead of using useEffect -- useEffect is ONLY for synchronizing with external systems (non-React widgets, browser APIs, network subscriptions) -- Remember that source code is available in the node_modules directory -- Check package.json for type checking or build scripts to validate changes -- When identity comes from framework-bridged state (Inertia or SSR shared props, a serialized session), confirm the backend actually shares that field — add the share server-side if missing — before identifying from it -- When a reverse proxy is configured, both /static/* AND /array/* must route to the assets origin (us-assets.i.posthog.com or eu-assets.i.posthog.com). -- posthog-js is the JavaScript SDK package name -- posthog.init() MUST be called before any other PostHog methods (capture, identify, etc.) -- posthog-js is browser-only — do NOT import it in Node.js or server-side contexts (use posthog-node instead) -- Autocapture is ON by default with posthog-js (tracks clicks, form submissions, pageviews). Keep autocapture enabled unless the user explicitly asks to turn it off. -- NEVER send PII in posthog.capture() event properties — no emails, full names, phone numbers, physical addresses, IP addresses, or user-generated content -- PII belongs in posthog.identify() person properties (email, name, role), NOT in capture() event properties -- Call posthog.identify(userId, { email, name, role }) on login AND on page refresh if the user is already logged in -- Call posthog.reset() on logout — the transition out of an identified session, never an initially anonymous page load (that discards the anonymous id and its history) — and before identify() when switching directly between accounts -- For SPAs without a framework router, capture pageviews with posthog.capture($pageview) or use the capture_pageview history_change option in init for History API routing -- When verifying with an automated browser (Playwright, Puppeteer, Selenium), posthog-js's bot filter silently drops every capture while flags and asset loads still succeed. Override navigator.webdriver, the user agent, AND navigator.userAgentData before concluding events do not send. Diagnose with ?__posthog_debug=true ("likely bot" in the console). -- posthog-node is the Node.js server-side SDK package name; posthog-js is browser-only, so use posthog-node on the server instead -- Include enableExceptionAutocapture: true in the PostHog constructor options -- Add posthog.capture() calls in route handlers for meaningful user actions – every route that creates, updates, or deletes data should track an event with contextual properties -- Add posthog.captureException(err, distinctId) in the application's error handler (e.g., Express error middleware, Fastify setErrorHandler, Koa app.on('error')) -- The SDK batches events and flushes asynchronously. await flush() or await shutdown() before letting that process exit. If unsure, set flushAt 1 and flushInterval 0. -- `posthog.capture()` enqueues synchronously and returns; the batched HTTP send happens afterwards. Treat every per-request handler as short-lived even when the framework feels like a server: Next.js / Nuxt / SvelteKit / Remix route handlers, serverless and edge functions, and Lambda are torn down per invocation before the send runs. Create the client with flushAt 1 and flushInterval 0, then await the send before returning. Always use `await posthog.flush()` for a shared/singleton client, `await posthog.shutdown()` for a per-request client. Never skip the awaited flush or risk the enqueued event being silently dropped. -- Reverse proxy is NOT needed for server-side Node.js – only client-side JavaScript needs a proxy to avoid ad blockers diff --git a/.claude/skills/integration-nextjs-app-router/references/EXAMPLE.md b/.claude/skills/integration-nextjs-app-router/references/EXAMPLE.md deleted file mode 100644 index 1f6c0fd5..00000000 --- a/.claude/skills/integration-nextjs-app-router/references/EXAMPLE.md +++ /dev/null @@ -1,712 +0,0 @@ -# PostHog Next.js App Router Example Project - -Repository: https://github.com/PostHog/context-mill -Path: example-apps/next-app-router - ---- - -## README.md - -# PostHog Next.js app router example - -This is a [Next.js](https://nextjs.org) App Router example demonstrating PostHog integration with product analytics, session replay, feature flags, and error tracking. - -## Features - -- **Product analytics**: Track user events and behaviors -- **Session replay**: Record and replay user sessions -- **Error tracking**: Capture and track errors -- **User authentication**: Demo login system with PostHog user identification -- **Server-side & Client-side tracking**: Examples of both tracking methods -- **Reverse proxy**: PostHog ingestion through Next.js rewrites - -## Getting started - -### 1. Install dependencies - -```bash -npm install -# or -pnpm install -``` - -### 2. Configure environment variables - -Create a `.env.local` file in the root directory: - -```bash -NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN=your_posthog_project_token -NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com -``` - -Get your PostHog project token from your [PostHog project settings](https://app.posthog.com/project/settings). - -### 3. Run the development server - -```bash -npm run dev -# or -pnpm dev -``` - -Open [http://localhost:3000](http://localhost:3000) with your browser to see the app. - -## Project structure - -``` -src/ -├── app/ -│ ├── api/ -│ │ └── auth/ -│ │ └── login/ -│ │ └── route.ts # Login API with server-side tracking -│ ├── burrito/ -│ │ └── page.tsx # Demo feature page with event tracking -│ ├── profile/ -│ │ └── page.tsx # User profile with error tracking demo -│ ├── layout.tsx # Root layout with providers -│ ├── page.tsx # Home/Login page -│ └── globals.css # Global styles -├── components/ -│ └── Header.tsx # Navigation header with auth state -├── contexts/ -│ └── AuthContext.tsx # Authentication context with PostHog integration -└── lib/ - └── posthog-server.ts # Server-side PostHog client - -instrumentation-client.ts # Client-side PostHog initialization -``` - -## Key integration points - -### Client-side initialization (instrumentation-client.ts) - -```typescript -import posthog from "posthog-js" - -posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, { - api_host: "/ingest", - ui_host: "https://us.posthog.com", - defaults: '2026-01-30', - capture_exceptions: true, - debug: process.env.NODE_ENV === "development", -}); -``` - -### User identification (AuthContext.tsx) - -```typescript -posthog.identify(username, { - username: username, -}); -``` - -### Event tracking (burrito/page.tsx) - -```typescript -posthog.capture('burrito_considered', { - total_considerations: count, - username: username, -}); -``` - -### Error tracking (profile/page.tsx) - -```typescript -posthog.captureException(error); -``` - -### Server-side tracking (app/api/auth/login/route.ts) - -```typescript -const posthog = getPostHogClient(); -posthog.capture({ - distinctId: username, - event: 'server_login', - properties: { ... } -}); -``` - -## App router differences from pages router - -This example uses Next.js App Router instead of Pages Router. Key differences: - -1. **File-based routing**: Pages in `src/app/` instead of `src/pages/` -2. **layout.tsx**: Root layout component wraps all pages -3. **API Routes**: Located in `src/app/api/` with `route.ts` files -4. **'use client'**: Client components need explicit directive -5. **useRouter**: From `next/navigation` instead of `next/router` -6. **Metadata**: Exported from layout/page instead of Head component -7. **Server Components**: Components are server-side by default - -## Learn more - -- [PostHog Documentation](https://posthog.com/docs) -- [Next.js App Router Documentation](https://nextjs.org/docs/app) -- [PostHog Next.js Integration Guide](https://posthog.com/docs/libraries/next-js) - -## Deploy on Vercel - -The easiest way to deploy your Next.js app is to use the [Vercel Platform](https://vercel.com/new). - -Check out the [Next.js deployment documentation](https://nextjs.org/docs/app/building-your-application/deploying) for more details. - ---- - -## .env.example - -```example -# PostHog Configuration -# Get your PostHog project token from: https://app.posthog.com/project/settings -NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN=your_posthog_project_token_here -# NEXT_PUBLIC_POSTHOG_HOST=https://eu.i.posthog.com -NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com -``` - ---- - -## instrumentation-client.ts - -```ts -import posthog from "posthog-js" - -posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, { - api_host: "/ingest", - ui_host: "https://us.posthog.com", - // Include the defaults option as required by PostHog - defaults: '2026-01-30', - // Enables capturing unhandled exceptions via Error Tracking - capture_exceptions: true, - // Turn on debug in development mode - debug: process.env.NODE_ENV === "development", -}); - -//IMPORTANT: Never combine this approach with other client-side PostHog initialization approaches, especially components like a PostHogProvider. instrumentation-client.ts is the correct solution for initializating client-side PostHog in Next.js 15.3+ apps. -``` - ---- - -## next.config.ts - -```ts -import type { NextConfig } from "next"; - -const nextConfig: NextConfig = { - /* config options here */ - async rewrites() { - return [ - { - source: "/ingest/static/:path*", - destination: "https://us-assets.i.posthog.com/static/:path*", - }, - { - source: "/ingest/array/:path*", - destination: "https://us-assets.i.posthog.com/array/:path*", - }, - { - source: "/ingest/:path*", - destination: "https://us.i.posthog.com/:path*", - }, - ]; - }, - // This is required to support PostHog trailing slash API requests - skipTrailingSlashRedirect: true, -}; - -export default nextConfig; - -``` - ---- - -## src/app/api/auth/login/route.ts - -```ts -import { NextResponse } from 'next/server'; -import { getPostHogClient } from '@/lib/posthog-server'; - -const users = new Map(); - -export async function POST(request: Request) { - const { username, password } = await request.json(); - - if (!username || !password) { - return NextResponse.json({ error: 'Username and password required' }, { status: 400 }); - } - - let user = users.get(username); - const isNewUser = !user; - - if (!user) { - user = { username, burritoConsiderations: 0 }; - users.set(username, user); - } - - // Capture server-side login event - const posthog = getPostHogClient(); - posthog.capture({ - distinctId: username, - event: 'server_login', - properties: { - isNewUser: isNewUser, - source: 'api' - } - }); - - // Identify user on server side - posthog.identify({ - distinctId: username, - properties: { - username: username, - createdAt: isNewUser ? new Date().toISOString() : undefined - } - }); - - // This handler is short-lived; flush so the enqueued events send before it returns - await posthog.flush(); - - return NextResponse.json({ success: true, user }); -} -``` - ---- - -## src/app/burrito/page.tsx - -```tsx -'use client'; - -import { useState } from 'react'; -import { useAuth } from '@/contexts/AuthContext'; -import { useRouter } from 'next/navigation'; -import posthog from 'posthog-js'; - -export default function BurritoPage() { - const { user, incrementBurritoConsiderations } = useAuth(); - const router = useRouter(); - const [hasConsidered, setHasConsidered] = useState(false); - - // Redirect to home if not logged in - if (!user) { - router.push('/'); - return null; - } - - const handleConsideration = () => { - incrementBurritoConsiderations(); - setHasConsidered(true); - setTimeout(() => setHasConsidered(false), 2000); - - // Capture burrito consideration event - posthog.capture('burrito_considered', { - total_considerations: user.burritoConsiderations + 1, - username: user.username, - }); - }; - - return ( -
-

Burrito consideration zone

-

Take a moment to truly consider the potential of burritos.

- -
- - - {hasConsidered && ( -

- Thank you for your consideration! Count: {user.burritoConsiderations} -

- )} -
- -
-

Consideration stats

-

Total considerations: {user.burritoConsiderations}

-
-
- ); -} -``` - ---- - -## src/app/layout.tsx - -```tsx -import type { Metadata } from "next"; -import "./globals.css"; -import { AuthProvider } from "@/contexts/AuthContext"; -import Header from "@/components/Header"; - -export const metadata: Metadata = { - title: "Burrito Consideration App", - description: "Consider the potential of burritos", -}; - -export default function RootLayout({ - children, -}: Readonly<{ - children: React.ReactNode; -}>) { - return ( - - - -
-
{children}
- - - - ); -} - -``` - ---- - -## src/app/page.tsx - -```tsx -'use client'; - -import { useState } from 'react'; -import { useAuth } from '@/contexts/AuthContext'; - -export default function Home() { - const { user, login } = useAuth(); - const [username, setUsername] = useState(''); - const [password, setPassword] = useState(''); - const [error, setError] = useState(''); - - const handleSubmit = async (e: React.FormEvent) => { - e.preventDefault(); - setError(''); - - try { - const success = await login(username, password); - if (success) { - setUsername(''); - setPassword(''); - } else { - setError('Please provide both username and password'); - } - } catch (err) { - console.error('Login failed:', err); - setError('An error occurred during login'); - } - }; - - if (user) { - return ( -
-

Welcome back, {user.username}!

-

You are logged in. Feel free to explore:

-
    -
  • Consider the potential of burritos
  • -
  • View your profile and statistics
  • -
-
- ); - } - - return ( -
-

Welcome to Burrito Consideration App

-

Please sign in to begin your burrito journey

- -
-
- - setUsername(e.target.value)} - placeholder="Enter any username" - /> -
- -
- - setPassword(e.target.value)} - placeholder="Enter any password" - /> -
- - {error &&

{error}

} - - -
- -

- Note: This is a demo app. Use any username and password to sign in. -

-
- ); -} -``` - ---- - -## src/app/profile/page.tsx - -```tsx -'use client'; - -import { useAuth } from '@/contexts/AuthContext'; -import { useRouter } from 'next/navigation'; -import posthog from 'posthog-js'; - -export default function ProfilePage() { - const { user } = useAuth(); - const router = useRouter(); - - // Redirect to home if not logged in - if (!user) { - router.push('/'); - return null; - } - - const triggerTestError = () => { - try { - throw new Error('Test error for PostHog error tracking'); - } catch (err) { - posthog.captureException(err); - console.error('Captured error:', err); - alert('Error captured and sent to PostHog!'); - } - }; - - return ( -
-

User Profile

- -
-

Your Information

-

Username: {user.username}

-

Burrito Considerations: {user.burritoConsiderations}

-
- -
- -
- -
-

Your Burrito Journey

- {user.burritoConsiderations === 0 ? ( -

You haven't considered any burritos yet. Visit the Burrito Consideration page to start!

- ) : user.burritoConsiderations === 1 ? ( -

You've considered the burrito potential once. Keep going!

- ) : user.burritoConsiderations < 5 ? ( -

You're getting the hang of burrito consideration!

- ) : user.burritoConsiderations < 10 ? ( -

You're becoming a burrito consideration expert!

- ) : ( -

You are a true burrito consideration master! 🌯

- )} -
-
- ); -} -``` - ---- - -## src/components/Header.tsx - -```tsx -'use client'; - -import Link from 'next/link'; -import { useAuth } from '@/contexts/AuthContext'; - -export default function Header() { - const { user, logout } = useAuth(); - - return ( -
-
- -
- {user ? ( - <> - Welcome, {user.username}! - - - ) : ( - Not logged in - )} -
-
-
- ); -} -``` - ---- - -## src/contexts/AuthContext.tsx - -```tsx -'use client'; - -import { createContext, useContext, useState, ReactNode } from 'react'; -import posthog from 'posthog-js'; - -interface User { - username: string; - burritoConsiderations: number; -} - -interface AuthContextType { - user: User | null; - login: (username: string, password: string) => Promise; - logout: () => void; - incrementBurritoConsiderations: () => void; -} - -const AuthContext = createContext(undefined); - -const users: Map = new Map(); - -export function AuthProvider({ children }: { children: ReactNode }) { - // Use lazy initializer to read from localStorage only once on mount - const [user, setUser] = useState(() => { - if (typeof window === 'undefined') return null; - - const storedUsername = localStorage.getItem('currentUser'); - if (storedUsername) { - const existingUser = users.get(storedUsername); - if (existingUser) { - return existingUser; - } - } - return null; - }); - - const login = async (username: string, password: string): Promise => { - try { - const response = await fetch('/api/auth/login', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ username, password }), - }); - - if (response.ok) { - const { user: userData } = await response.json(); - - let localUser = users.get(username); - if (!localUser) { - localUser = userData as User; - users.set(username, localUser); - } - - setUser(localUser); - localStorage.setItem('currentUser', username); - - // Identify user in PostHog using username as distinct ID - posthog.identify(username, { - username: username, - }); - - // Capture login event - posthog.capture('user_logged_in', { - username: username, - }); - - return true; - } - return false; - } catch (error) { - console.error('Login error:', error); - return false; - } - }; - - const logout = () => { - // Capture logout event before resetting - posthog.capture('user_logged_out'); - posthog.reset(); - - setUser(null); - localStorage.removeItem('currentUser'); - }; - - const incrementBurritoConsiderations = () => { - if (user) { - user.burritoConsiderations++; - users.set(user.username, user); - setUser({ ...user }); - } - }; - - return ( - - {children} - - ); -} - -export function useAuth() { - const context = useContext(AuthContext); - if (context === undefined) { - throw new Error('useAuth must be used within an AuthProvider'); - } - return context; -} -``` - ---- - -## src/lib/posthog-server.ts - -```ts -import { PostHog } from 'posthog-node'; - -let posthogClient: PostHog | null = null; - -export function getPostHogClient() { - if (!posthogClient) { - posthogClient = new PostHog( - process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, - { - host: process.env.NEXT_PUBLIC_POSTHOG_HOST, - flushAt: 1, - flushInterval: 0 - } - ); - posthogClient.debug(true); - } - return posthogClient; -} - -export async function shutdownPostHog() { - if (posthogClient) { - await posthogClient.shutdown(); - } -} -``` - ---- - diff --git a/.claude/skills/integration-nextjs-app-router/references/identify-users.md b/.claude/skills/integration-nextjs-app-router/references/identify-users.md deleted file mode 100644 index 8647dcb3..00000000 --- a/.claude/skills/integration-nextjs-app-router/references/identify-users.md +++ /dev/null @@ -1,307 +0,0 @@ -> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt - -# Identify users - Docs - -Copy page - -# Identify users - Docs - -Linking events to specific users enables you to build a full picture of how they're using your product across different sessions, devices, and platforms. - -This is straightforward to do when [capturing backend events](/docs/product-analytics/capture-events?tab=Node.js.md), as you associate events to a specific user using a `distinct_id`, which is a required argument. - -However, in the frontend of a [web](/docs/libraries/js/usage.md#capturing-events) or [mobile app](/docs/libraries/ios.md#capturing-events), a `distinct_id` is not a required argument — PostHog's SDKs will generate an anonymous `distinct_id` for you automatically and you can capture events anonymously, provided you use the appropriate [configuration](/docs/libraries/js/usage.md#capturing-anonymous-events). - -To link events to specific users, call `identify`: - -PostHog AI - -### Web - -```javascript -posthog.identify( - 'distinct_id', // Replace 'distinct_id' with your user's unique identifier - { email: 'max@hedgehogmail.com', name: 'Max Hedgehog' } // optional: set additional person properties -); -``` - -### Android - -```kotlin -PostHog.identify( - distinctId = distinctID, // Replace 'distinctID' with your user's unique identifier - // optional: set additional person properties - userProperties = mapOf( - "name" to "Max Hedgehog", - "email" to "max@hedgehogmail.com" - ) -) -``` - -### iOS - -```swift -PostHogSDK.shared.identify("distinct_id", // Replace "distinct_id" with your user's unique identifier - userProperties: ["name": "Max Hedgehog", "email": "max@hedgehogmail.com"]) // optional: set additional person properties -``` - -### React Native - -```jsx -posthog.identify('distinct_id', { // Replace "distinct_id" with your user's unique identifier - email: 'max@hedgehogmail.com', // optional: set additional person properties - name: 'Max Hedgehog' -}) -``` - -### Dart - -```dart -await Posthog().identify( - userId: 'distinct_id', // Replace "distinct_id" with your user's unique identifier - userProperties: { - 'email': 'max@hedgehogmail.com', // optional: set additional person properties - 'name': 'Max Hedgehog', - }, -); -``` - -Events captured after calling `identify` are identified events and this creates a person profile if one doesn't exist already. - -Due to the cost of processing them, anonymous events can be up to 4x cheaper than identified events, so it's recommended you only capture identified events when needed. - -## How identify works - -When a user starts browsing your website or app, PostHog automatically assigns them an **anonymous ID**, which is stored locally. - -Provided you've [configured persistence](/docs/libraries/js/persistence.md) to use cookies or `localStorage`, this enables us to track anonymous users – even across different sessions. - -By calling `identify` with a `distinct_id` of your choice (usually the user's ID in your database, or their email), you link the anonymous ID and distinct ID together. - -Thus, all past and future events made with that anonymous ID are now associated with the distinct ID. - -This enables you to do things like associate events with a user from before they log in for the first time, or associate their events across different devices or platforms. - -Using identify in the backend - -Although you can call `identify` using our backend SDKs, it is used most in frontends. This is because there is no concept of anonymous sessions in the backend SDKs, so calling `identify` only updates person profiles. - -## Best practices when using `identify` - -### 1\. Call `identify` as soon as you're able to - -In your frontend, you should call `identify` as soon as you're able to. - -Typically, this is every time your **app loads** for the first time, and directly after your **users log in**. - -This ensures that events sent during your users' sessions are correctly associated with them. - -You only need to call `identify` once per session, and you should avoid calling it multiple times unnecessarily. - -If you call `identify` multiple times with the same data without reloading the page in between, PostHog will ignore the subsequent calls. - -#### Identify users when the web SDK loads - -If your app already knows the signed-in user when you initialize the JavaScript web SDK, the [`loaded` callback](/docs/libraries/js/config.md) is a convenient place to call `identify`. This identifies the user as soon as the SDK has loaded: - -Web - -PostHog AI - -```javascript -posthog.init('', { - api_host: 'https://us.i.posthog.com', - defaults: '2026-05-30', - loaded: (posthog) => { - if (currentUser?.id) { - posthog.identify(currentUser.id, { - email: currentUser.email, - name: currentUser.name, - }) - } - }, -}) -``` - -In this example, `currentUser` represents user data already available from your authentication system. If your app loads the user asynchronously, call `posthog.identify()` as soon as that data becomes available instead. - -### 2\. Use unique strings for distinct IDs - -If two users have the same distinct ID, their data is merged and they are considered one user in PostHog. Two common ways this can happen are: - -- Your logic for generating IDs does not generate sufficiently strong IDs and you can end up with a clash where 2 users have the same ID. -- There's a bug, typo, or mistake in your code leading to most or all users being identified with generic IDs like `null`, `true`, or `distinctId`. - -PostHog also has built-in protections to stop the most common distinct ID mistakes. - -### 3\. Reset after logout - -If a user logs out on your frontend, you should call `reset()` to unlink any future events made on that device with that user. - -This is important if your users are sharing a computer, as otherwise all of those users are grouped together into a single user due to shared cookies between sessions. - -**We strongly recommend you call `reset` on logout even if you don't expect users to share a computer.** - -You can do that like so: - -PostHog AI - -### Web - -```javascript -posthog.reset() -``` - -### iOS - -```swift -PostHogSDK.shared.reset() -``` - -### Android - -```kotlin -PostHog.reset() -``` - -### React Native - -```jsx -posthog.reset() -``` - -### Dart - -```dart -await Posthog().reset(); -``` - -If you *also* want to reset the `device_id` so that the device will be considered a new device in future events, you can pass `true` as an argument: - -Web - -PostHog AI - -```javascript -posthog.reset(true) -``` - -### 4\. Person profiles and properties - -You'll notice that one of the parameters in the `identify` method is a `properties` object. - -This enables you to set [person properties](/docs/product-analytics/person-properties.md). - -Whenever possible, we recommend passing in all person properties you have available each time you call identify, as this ensures their person profile on PostHog is up to date. - -Person properties can also be set being adding a `$set` property to a event `capture` call. - -**\`$set\` and \`$set\_once\` aren't stored on events** - -These properties only tell PostHog how to update person data during ingestion — they aren't kept on the stored event, so you can't filter, break down, or query events by them. To query the values you set, use [person properties](/docs/product-analytics/person-properties.md) instead. - -See our [person properties docs](/docs/product-analytics/person-properties.md) for more details on how to work with them and best practices. - -### 5\. Use deep links between platforms - -We recommend you call `identify` [as soon as you're able](#1-call-identify-as-soon-as-youre-able), typically when a user signs up or logs in. - -This doesn't work if one or both platforms are unauthenticated. Some examples of such cases are: - -- Onboarding and signup flows before authentication. -- Unauthenticated web pages redirecting to authenticated mobile apps. -- Authenticated web apps prompting an app download. - -In these cases, you can use a [deep link](https://developer.android.com/training/app-links/deep-linking) on Android and [universal links](https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app) on iOS to identify users. - -1. Use `posthog.get_distinct_id()` to get the current distinct ID. Even if you cannot call identify because the user is unauthenticated, this will return an anonymous distinct ID generated by PostHog. -2. Add the distinct ID to the deep link as query parameters, along with other properties like UTM parameters. -3. When the user is redirected to the app, parse the deep link and handle the following cases: - -- The mobile app is already authenticated. In this case, call [`posthog.alias()`](/docs/libraries/js/usage.md#alias) with the distinct ID from the web. This associates the two distinct IDs as a single person. -- The mobile app is unauthenticated. In this case, call [`posthog.identify()`](/docs/libraries/js/usage.md#identifying-users) with the distinct ID from the web so pre-login mobile events stay connected to the web session. When the user later logs in on mobile, call `identify()` again with your canonical user ID. - -As long as you associate the distinct IDs with `posthog.identify()` or `posthog.alias()`, you can track events generated across platforms. - -Here's an example implementation for handling deep links from web to mobile: - -PostHog AI - -### iOS - -```swift -import PostHog -class DeepLinkIdentityManager { - static let shared = DeepLinkIdentityManager() - // MARK: - Deep Link Received - func handleDeepLink(_ url: URL, isAuthenticatedOnMobile: Bool) { - guard let webDistinctId = URLComponents(url: url, resolvingAgainstBaseURL: true)? - .queryItems?.first(where: { $0.name == "ph_distinct_id" })?.value else { - return - } - if isAuthenticatedOnMobile { - // The mobile app already knows the current user. - // Alias the incoming web distinct ID to that user. - PostHogSDK.shared.alias(webDistinctId) - } else { - // Reuse the web distinct ID until login on mobile. - PostHogSDK.shared.identify(webDistinctId) - } - } - // MARK: - Login/Signup - func handleLogin(canonicalUserId: String) { - // Switch from the web distinct ID (or a mobile anon ID) - // to your canonical user ID. - PostHogSDK.shared.identify(canonicalUserId) - // Set user properties, track signup event, etc. - } - func handleLogout() { - PostHogSDK.shared.reset() - } -} -``` - -### Android - -```kotlin -import android.net.Uri -import com.posthog.PostHog -object DeepLinkIdentityManager { - // Deep Link Received - fun handleDeepLink(uri: Uri, isAuthenticatedOnMobile: Boolean) { - val webDistinctId = uri.getQueryParameter("ph_distinct_id") ?: return - if (isAuthenticatedOnMobile) { - // The mobile app already knows the current user. - // Alias the incoming web distinct ID to that user. - PostHog.alias(webDistinctId) - } else { - // Reuse the web distinct ID until login on mobile. - PostHog.identify(webDistinctId) - } - } - // Login/Signup - fun handleLogin(canonicalUserId: String) { - // Switch from the web distinct ID (or a mobile anon ID) - // to your canonical user ID. - PostHog.identify(canonicalUserId) - // Set user properties, track signup event, etc. - } - fun handleLogout() { - PostHog.reset() - } -} -``` - -## Further reading - -- [Identifying users docs](/docs/product-analytics/identify.md) -- [How person processing works](/docs/how-posthog-works/ingestion-pipeline.md#2-person-processing) -- [An introductory guide to identifying users in PostHog](/tutorials/identifying-users-guide.md) - -### Still have questions? - -Ask PostHog AI - -### Was this page useful? - -HelpfulCould be better \ No newline at end of file diff --git a/.claude/skills/integration-nextjs-app-router/references/next-js.md b/.claude/skills/integration-nextjs-app-router/references/next-js.md deleted file mode 100644 index 13c9c804..00000000 --- a/.claude/skills/integration-nextjs-app-router/references/next-js.md +++ /dev/null @@ -1,453 +0,0 @@ -> AI agents: this is one page from PostHog's docs. Full index of Markdown docs for LLMs: https://posthog.com/llms.txt - -# Next.js - Docs - -Copy page - -# Next.js - Docs - -PostHog makes it easy to get data about traffic and usage of your [Next.js](https://nextjs.org/) app. Integrating PostHog into your site enables analytics about user behavior, custom events capture, session recordings, feature flags, and more. - -This guide walks you through integrating PostHog into your Next.js app using the [React](/docs/libraries/react.md) and the [Node.js](/docs/libraries/node.md) SDKs. - -> You can see a working example of this integration in our [Next.js demo app](https://github.com/PostHog/posthog-js/tree/main/playground/nextjs). - -Next.js has both client and server-side rendering, as well as pages and app routers. We'll cover all of these options in this guide. - -> **Try `@posthog/next` (pre-release):** A simplified Next.js integration with synchronized client/server identity, server-side flag bootstrapping, and a built-in API proxy. [Read the setup guide →](/docs/libraries/next-js/posthog-next.md) - -## Prerequisites - -To follow this guide along, you need: - -1. A PostHog instance (either [Cloud](https://app.posthog.com/signup) or [self-hosted](/docs/self-host.md)) -2. A Next.js application - -## Beta: integration via LLM - -Install PostHog for Next.js in seconds with our wizard by running this prompt with [LLM coding agents](/blog/envoy-wizard-llm-agent.md) like Cursor and Bolt, or by running it in your terminal. - -`npx @posthog/wizard` - -[Learn more](/wizard.md) - -Or, to integrate manually, continue with the rest of this guide. - -## Client-side setup - -Install `posthog-js` using your package manager: - -PostHog AI - -### npm - -```bash -npm install --save posthog-js -``` - -### Yarn - -```bash -yarn add posthog-js -``` - -### pnpm - -```bash -pnpm add posthog-js -``` - -### Bun - -```bash -bun add posthog-js -``` - -> **If your site sets a Content-Security-Policy**, it needs to allow PostHog. This applies to the snippet and to package installs alike: the SDK lazy-loads extra bundles (session replay, surveys) from PostHog's CDN, and sends events to the ingestion host. PostHog serves from subdomains of `posthog.com` that change over time, so allow the wildcard: -> -> PostHog AI -> -> ``` -> script-src 'self' https://*.posthog.com; -> connect-src 'self' https://*.posthog.com; -> worker-src 'self' blob: data:; -> ``` -> -> `script-src` covers the snippet and the lazy-loaded bundles, `connect-src` covers event ingestion and feature flags, and `worker-src` covers session replay. The [toolbar needs a few more](/docs/advanced/content-security-policy.md), or use a [reverse proxy](/docs/advanced/proxy.md) so everything is first-party. Failing to do so causes silent failures where `capture` and `identify` calls never send, so the integration looks complete while zero events arrive. Remember `connect-src` falls back to `default-src`, so `default-src 'self'` blocks event delivery even when the script itself is bundled. - -Add your environment variables to your `.env.local` file and to your hosting provider (e.g. Vercel, Netlify, AWS). You can find your project token in your [project settings](https://app.posthog.com/project/settings). - -.env.local - -PostHog AI - -```shell -NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN= -NEXT_PUBLIC_POSTHOG_HOST=https://us.i.posthog.com -``` - -These values need to start with `NEXT_PUBLIC_` to be accessible on the client-side. - -## Integration - -Next.js provides the [`instrumentation-client.ts|js`](https://nextjs.org/docs/app/api-reference/file-conventions/instrumentation-client) file for client-side setup. Add it to the root of your Next.js app (for both app and pages router) and initialize PostHog in it like this: - -PostHog AI - -### instrumentation-client.js - -```javascript -import posthog from 'posthog-js' -posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN, { - api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST, - defaults: '2026-05-30' -}); -``` - -### instrumentation-client.ts - -```typescript -import posthog from 'posthog-js' -posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN!, { - api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST, - defaults: '2026-05-30' -}); -``` - -Bootstrapping with `instrumentation-client` - -When using `instrumentation-client`, the values you pass to `posthog.init` remain fixed for the entire session. This means bootstrapping only works if you evaluate flags **before your app renders** (for example, on the server). - -If you need flag values after the app has rendered, you’ll want to: - -- Evaluate the flag on the server and pass the value into your app, or -- Evaluate the flag in an earlier page/state, then store and re-use it when needed. - -Both approaches avoid flicker and give you the same outcome as bootstrapping, as long as you use the same `distinct_id` across client and server. - -See the [bootstrapping guide](/docs/feature-flags/bootstrapping.md) for more information. - -## Identifying users - -> **Identifying users is required.** Call `posthog.identify('your-user-id')` after login to link events to a known user. This is what connects frontend event captures, [session replays](/docs/session-replay.md), [LLM traces](/docs/ai-engineering.md), and [error tracking](/docs/error-tracking.md) to the same person — and lets backend events link back too. -> -> Use a stable ID from your auth system when possible, not an email or display name. Send those as person properties instead. If your app has no other stable key, email works as a fallback if they are unique. Never a shared literal like `"anonymous"` or `"user"`, which pools many people onto one person and corrupts their data. When no ID is available at all, skip the identify and retain the anonymous distinct ID that's automatically assigned. -> -> Call `posthog.reset()` on logout, so the next person to use the browser doesn't inherit the last one's identity. -> -> See our guide on [identifying users](/docs/getting-started/identify-users.md) for how to set this up. - -### Linking client and server events - -Next.js apps usually capture on both sides. To keep them on the same person, use the same distinct ID in both, and let the browser tell your server which one that is. - -If your app calls your own backend, `tracing_headers` adds `X-POSTHOG-DISTINCT-ID` and `X-POSTHOG-SESSION-ID` to matching `fetch` and `XMLHttpRequest` requests. This lets server-side SDKs link backend events, errors, and LLM traces back to frontend sessions and replays. Use hostnames only, without protocols or paths. - -JavaScript - -PostHog AI - -```javascript -posthog.init('', { - api_host: 'https://us.i.posthog.com', - // Optional: send PostHog session/user context to your backend - tracing_headers: ['api.example.com'], -}) -``` - -This works in local development too, but match on the hostname alone: use `'localhost'`, not `'localhost:3000'`. Ports are never part of a hostname, so a value with one in it never matches anything. `localhost` and `127.0.0.1` are also different hostnames — use whichever your app actually calls. - -Tracing headers help you attribute events across front and backend consistently. When this isn't available, use your server-side stable IDs to deduce the matching `distinctId`, and pass it in when capturing the event. - -Set up a reverse proxy (recommended) - -We recommend [setting up a reverse proxy](/docs/advanced/proxy.md), so that events are less likely to be intercepted by tracking blockers. - -We have our [own managed reverse proxy service](/docs/advanced/proxy/managed-reverse-proxy.md), which is free for all PostHog Cloud users, routes through our infrastructure, and makes setting up your proxy easy. - -If you don't want to use our managed service then there are several other options for creating a reverse proxy, including using [Cloudflare](/docs/advanced/proxy/cloudflare.md), [AWS Cloudfront](/docs/advanced/proxy/cloudfront.md), and [Vercel](/docs/advanced/proxy/vercel.md). - -Grouping products in one project (recommended) - -If you have multiple customer-facing products (e.g. a marketing website + mobile app + web app), it's best to install PostHog on them all and [group them in one project](/docs/settings/projects.md). - -This makes it possible to track users across their entire journey (e.g. from visiting your marketing website to signing up for your product), or how they use your product across multiple platforms. - -Add IPs to Firewall/WAF allowlists (recommended) - -For certain features like [heatmaps](/docs/toolbar/heatmaps.md), your Web Application Firewall (WAF) may be blocking PostHog's requests to your site. Add these IP addresses to your WAF allowlist or rules to let PostHog access your site. - -**EU**: `3.75.65.221`, `18.197.246.42`, `3.120.223.253` - -**US**: `44.205.89.55`, `52.4.194.122`, `44.208.188.173` - -These are public, stable IPs used by PostHog services (e.g., Celery tasks for snapshots). - -## Accessing PostHog - -Once initialized in `instrumentation-client.js|ts`, import `posthog` from `posthog-js` anywhere and call the methods you need on the `posthog` object. - -JavaScript - -PostHog AI - -```javascript -"use client"; -import posthog from "posthog-js"; -export default function Home() { - return ( -
- -
- ); -} -``` - -### Using React hooks - -The [React feature flag hooks](/docs/libraries/react.md#feature-flags) work automatically when PostHog is initialized via `instrumentation-client.ts`. The hooks use the initialized posthog-js singleton: - -JavaScript - -PostHog AI - -```javascript -"use client"; -import { useFeatureFlagEnabled } from "@posthog/react"; -export default function FeatureComponent() { - const showNewFeature = useFeatureFlagEnabled("new-feature"); - return showNewFeature ? : ; -} -``` - -### Usage - -See the [React SDK docs](/docs/libraries/react.md) for examples of how to use: - -- [`posthog-js` functions like custom event capture, user identification, and more.](/docs/libraries/react.md#using-posthog-js-functions) -- [Feature flags including variants and payloads.](/docs/libraries/react.md#feature-flags) - -You can also read [the full `posthog-js` documentation](/docs/libraries/js/usage.md) for all the usable functions. - -## Server-side analytics - -Next.js enables you to both server-side render pages and add server-side functionality. To integrate PostHog into your Next.js app on the server-side, you can use the [Node SDK](/docs/libraries/node.md). - -First, install the `posthog-node` library: - -PostHog AI - -### npm - -```bash -npm install posthog-node --save -``` - -### Yarn - -```bash -yarn add posthog-node -``` - -### pnpm - -```bash -pnpm add posthog-node -``` - -### Bun - -```bash -bun add posthog-node -``` - -### Router-specific instructions - -## App router - -For the app router, we can initialize the `posthog-node` SDK once with a `PostHogClient` function, and import it into files. - -This enables us to send events and fetch data from PostHog on the server – without making client-side requests. - -JavaScript - -PostHog AI - -```javascript -// app/posthog.js -import { PostHog } from 'posthog-node' -export default function PostHogClient() { - const posthogClient = new PostHog(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN, { - host: process.env.NEXT_PUBLIC_POSTHOG_HOST, - flushAt: 1, - flushInterval: 0 - }) - return posthogClient -} -``` - -> **Note:** Because server-side functions in Next.js can be short-lived, we set `flushAt` to `1` and `flushInterval` to `0`. -> -> - `flushAt` sets how many capture calls we should flush the queue (in one batch). -> - `flushInterval` sets how many milliseconds we should wait before flushing the queue. Setting them to the lowest number ensures events are sent immediately and not batched. We also need to call `await posthog.shutdown()` once done. - -To use this client, we import it into our pages and call it with the `PostHogClient` function: - -JavaScript - -PostHog AI - -```javascript -import Link from 'next/link' -import PostHogClient from '../posthog' -export default async function About() { - const posthog = PostHogClient() - const flags = await posthog.getAllFlags( - 'user_distinct_id' // replace with a user's distinct ID - ); - await posthog.shutdown() - return ( -
-

About

- Go home - { flags['main-cta'] && - Go to PostHog - } -
- ) -} -``` - -## Pages router - -For the pages router, we can use the `getServerSideProps` function to access PostHog on the server-side, send events, evaluate feature flags, and more. - -This looks like this: - -JavaScript - -PostHog AI - -```javascript -// pages/posts/[id].js -import { useContext, useEffect, useState } from 'react' -import { getServerSession } from "next-auth/next" -import { authOptions } from '@/lib/auth' -import { PostHog } from 'posthog-node' -export default function Post({ post, flags }) { - const [ctaState, setCtaState] = useState() - useEffect(() => { - if (flags) { - setCtaState(flags['blog-cta']) - } - }) - return ( -
-

{post.title}

-

By: {post.author}

-

{post.content}

- {ctaState && -

Go to PostHog

- } - -
- ) -} -export async function getServerSideProps(ctx) { - // Pass authOptions, or your session callbacks don't run. - const session = await getServerSession(ctx.req, ctx.res, authOptions) - let flags = null - if (session) { - const client = new PostHog( - process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN, - { - host: process.env.NEXT_PUBLIC_POSTHOG_HOST, - } - ) - // A stable ID from your auth system, not an email. See the note below. - const distinctId = session.user.id - flags = await client.getAllFlags(distinctId); - client.capture({ - distinctId, - event: 'loaded blog article', - properties: { - $current_url: ctx.req.url, - }, - }); - await client.shutdown() - } - const { posts } = await import('../../blog.json') - const post = posts.find((post) => post.id.toString() === ctx.params.id) - return { - props: { - post, - flags - }, - } -} -``` - -> **Note**: next-auth doesn't put a user ID on the session by default. Its session is `{ name, email, image }`, so `session.user.id` is `undefined` until you add it yourself with a session callback in your `authOptions`: -> -> JavaScript -> -> PostHog AI -> -> ```javascript -> // lib/auth.js -> export const authOptions = { -> callbacks: { -> session({ session, token, user }) { -> // JWT sessions (the default) carry the user ID in token.sub. -> // Database sessions get it from user.id instead. -> session.user.id = token?.sub ?? user.id -> return session -> }, -> }, -> } -> ``` -> -> Capturing with an `undefined` distinct ID creates events that belong to nobody, so check that the ID arrives before relying on it. - -> **Note**: Make sure to *always* call `await client.shutdown()` after sending events from the server-side. PostHog queues events into larger batches, and this call forces all batched events to be flushed immediately. - -### Server-side configuration - -Next.js overrides the default `fetch` behavior on the server to introduce their own cache. PostHog ignores that cache by default, as this is Next.js's default behavior for any fetch call. - -You can override that configuration when initializing PostHog, but make sure you understand the pros/cons of using Next.js's cache and that you might get cached results rather than the actual result our server would return. This is important for feature flags, for example. - -TSX - -PostHog AI - -```jsx -posthog.init(process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN, { - // ... your configuration - fetch_options: { - cache: 'force-cache', // Use Next.js cache - next_options: { // Passed to the `next` option for `fetch` - revalidate: 60, // Cache for 60 seconds - tags: ['posthog'], // Can be used with Next.js `revalidateTag` function - }, - } -}) -``` - -## Configuring a reverse proxy to PostHog - -To improve the reliability of client-side tracking and make requests less likely to be intercepted by tracking blockers, you can setup a reverse proxy in Next.js. Read more about deploying a reverse proxy using [Next.js rewrites](/docs/advanced/proxy/nextjs.md), [Next.js middleware](/docs/advanced/proxy/nextjs-middleware.md), and [Vercel rewrites](/docs/advanced/proxy/vercel.md). - -## Further reading - -- [How to set up Next.js analytics, feature flags, and more](/tutorials/nextjs-analytics.md) -- [How to set up Next.js pages router analytics, feature flags, and more](/tutorials/nextjs-pages-analytics.md) -- [How to set up Next.js A/B tests](/tutorials/nextjs-ab-tests.md) - -### Still have questions? - -Ask PostHog AI - -### Was this page useful? - -HelpfulCould be better \ No newline at end of file From 7b68cb955d7fe71cbbc9b912d76106c76ec27f7b Mon Sep 17 00:00:00 2001 From: abhitrueprogrammer Date: Wed, 26 Aug 2026 15:01:12 +0530 Subject: [PATCH 5/6] fix: avoid duplicate completion events --- src/app/request/page.tsx | 7 ------- src/app/upload/page.tsx | 10 ---------- 2 files changed, 17 deletions(-) diff --git a/src/app/request/page.tsx b/src/app/request/page.tsx index b2f697c7..56ee4ee3 100644 --- a/src/app/request/page.tsx +++ b/src/app/request/page.tsx @@ -12,7 +12,6 @@ import { import { exams, slots, years } from "@/components/select_options"; import { Input } from "@/components/ui/input"; import axios from "axios"; -import posthog from "posthog-js"; import Fuse from "fuse.js"; import { type IUpcomingPaper } from "@/interface"; import UpcomingPaper from "../../components/UpcomingPaper"; @@ -119,12 +118,6 @@ export default function PaperRequest() { }, ); - posthog.capture("paper_request_submitted", { - exam: selectedExam, - slot: selectedSlot, - year: selectedYear, - }); - setSearchText(""); setSelectedSubject(null); setSelectedExam(null); diff --git a/src/app/upload/page.tsx b/src/app/upload/page.tsx index 94e13527..4ff1347d 100644 --- a/src/app/upload/page.tsx +++ b/src/app/upload/page.tsx @@ -24,7 +24,6 @@ import { import { CSS } from "@dnd-kit/utilities"; import Dropzone from "react-dropzone"; import { Upload, XIcon } from "lucide-react"; -import posthog from "posthog-js"; import { GlobalWorkerOptions } from "pdfjs-dist"; import type { ApiResponse } from "@/interface"; @@ -275,9 +274,6 @@ export default function Page() { setIsUploading(true); - const fileTypes = [...new Set(files.map((f) => f.type))]; - const fileCount = files.length; - try { await toast.promise( async () => { @@ -304,12 +300,6 @@ export default function Page() { }, ); - posthog.capture("paper_upload_submitted", { - file_count: fileCount, - file_types: fileTypes, - is_pdf: isPdf, - }); - clearAllFiles(); } finally { setIsUploading(false); From 8e5c8751f477f125ba285ab25fe6fd173ae6912a Mon Sep 17 00:00:00 2001 From: abhitrueprogrammer Date: Wed, 26 Aug 2026 16:07:47 +0530 Subject: [PATCH 6/6] fix: use managed PostHog proxy --- .env.example | 2 +- next.config.js | 18 ------------------ src/components/PostHogProvider.tsx | 7 ++++--- 3 files changed, 5 insertions(+), 22 deletions(-) diff --git a/.env.example b/.env.example index 39fbe6b2..d3cfae53 100644 --- a/.env.example +++ b/.env.example @@ -33,4 +33,4 @@ UPSTASH_REDIS_REST_URL="" # REST URL of your Upstash Redis database UPSTASH_REDIS_REST_TOKEN="" # REST API token for Upstash Redis NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN="" -NEXT_PUBLIC_POSTHOG_HOST="" +NEXT_PUBLIC_POSTHOG_HOST="https://e.papers.codechefvit.com" diff --git a/next.config.js b/next.config.js index 347e62f7..4a9e2741 100644 --- a/next.config.js +++ b/next.config.js @@ -6,8 +6,6 @@ await import("./src/env.js"); /** @type {import("next").NextConfig} */ const config = { - // Required to support PostHog trailing slash API requests - skipTrailingSlashRedirect: true, swcMinify: false, images: { remotePatterns: [ @@ -17,22 +15,6 @@ const config = { }, ], }, - async rewrites() { - return [ - { - source: "/ingest/static/:path*", - destination: "https://us-assets.i.posthog.com/static/:path*", - }, - { - source: "/ingest/array/:path*", - destination: "https://us-assets.i.posthog.com/array/:path*", - }, - { - source: "/ingest/:path*", - destination: "https://us.i.posthog.com/:path*", - }, - ]; - }, async headers() { return [ { diff --git a/src/components/PostHogProvider.tsx b/src/components/PostHogProvider.tsx index 65bae554..3d8989bf 100644 --- a/src/components/PostHogProvider.tsx +++ b/src/components/PostHogProvider.tsx @@ -7,16 +7,17 @@ import { useEffect } from "react"; export function PostHogProvider({ children }: { children: React.ReactNode }) { useEffect(() => { const token = process.env.NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN; - if (!token) { + const host = process.env.NEXT_PUBLIC_POSTHOG_HOST; + if (!token || !host) { if (process.env.NODE_ENV !== "production") { console.error( - "NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN variable required by PostHog is missing or un-configured, this causes events to be silently missed. This error stops appearing once NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN is configured", + "NEXT_PUBLIC_POSTHOG_PROJECT_TOKEN and NEXT_PUBLIC_POSTHOG_HOST variables required by PostHog are missing or un-configured, this causes events to be silently missed. This error stops appearing once both variables are configured", ); } return; } posthog.init(token, { - api_host: "/ingest", + api_host: host, ui_host: "https://us.posthog.com", defaults: "2026-01-30", capture_exceptions: true,