doccupine 0.0.127 → 0.0.128
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/templates/components/PostHogProviderLazy.d.ts +1 -1
- package/dist/templates/components/PostHogProviderLazy.js +21 -1
- package/dist/templates/mdx/analytics.mdx.d.ts +1 -1
- package/dist/templates/mdx/analytics.mdx.js +23 -5
- package/dist/templates/mdx/platform/analytics.mdx.d.ts +1 -1
- package/dist/templates/mdx/platform/analytics.mdx.js +1 -1
- package/dist/templates/next.config.js +5 -4
- package/dist/templates/package.js +2 -3
- package/dist/templates/proxy.js +118 -25
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const postHogProviderLazyTemplate = "\"use client\";\n\nimport posthog from \"posthog-js\";\nimport { Suspense, useEffect, useRef, useState } from \"react\";\nimport { usePathname, useSearchParams } from \"next/navigation\";\nimport rawAnalyticsConfig from \"@/analytics.json\";\n\ninterface AnalyticsConfig {\n provider?: string;\n posthog?: {\n key?: string;\n host?: string;\n };\n}\n\nconst analyticsConfig = rawAnalyticsConfig as AnalyticsConfig;\n\nconst posthogKey =\n analyticsConfig?.provider === \"posthog\" ? analyticsConfig.posthog?.key : null;\n\nfunction PostHogInit({ onReady }: { onReady: () => void }) {\n const initRef = useRef(false);\n\n useEffect(() => {\n if (initRef.current || !posthogKey) return;\n initRef.current = true;\n\n posthog.init(posthogKey, {\n api_host: \"/ingest\",\n ui_host:
|
|
1
|
+
export declare const postHogProviderLazyTemplate = "\"use client\";\n\nimport posthog from \"posthog-js\";\nimport { Suspense, useEffect, useRef, useState } from \"react\";\nimport { usePathname, useSearchParams } from \"next/navigation\";\nimport rawAnalyticsConfig from \"@/analytics.json\";\n\ninterface AnalyticsConfig {\n provider?: string;\n posthog?: {\n key?: string;\n host?: string;\n };\n}\n\nconst analyticsConfig = rawAnalyticsConfig as AnalyticsConfig;\n\nconst posthogKey =\n analyticsConfig?.provider === \"posthog\" ? analyticsConfig.posthog?.key : null;\n\n// `host` is the *ingestion* endpoint (us.i.posthog.com); `ui_host` wants the\n// dashboard it belongs to (us.posthog.com), which is what \"view in PostHog\"\n// links and the toolbar point at. Self-hosted instances serve both from one\n// origin, so leaving those untouched is correct.\nconst uiHost = (analyticsConfig.posthog?.host || \"https://us.i.posthog.com\")\n .replace(\".i.posthog.com\", \".posthog.com\");\n\nfunction PostHogInit({ onReady }: { onReady: () => void }) {\n const initRef = useRef(false);\n\n useEffect(() => {\n if (initRef.current || !posthogKey) return;\n initRef.current = true;\n\n posthog.init(posthogKey, {\n api_host: \"/ingest\",\n ui_host: uiHost,\n capture_pageview: false,\n capture_pageleave: true,\n loaded: onReady,\n });\n }, [onReady]);\n\n return null;\n}\n\n/**\n * Captures soft navigations only.\n *\n * The document load that got the reader here was already captured in the\n * middleware (see proxy.ts), so counting it again here is what produced two\n * `$pageview` events per page load. Server owns document loads, client owns\n * soft navigations: disjoint, so neither double-counts nor leaves a gap.\n */\nfunction PostHogPageviewTracker() {\n const pathname = usePathname();\n const searchParams = useSearchParams();\n const isFirstRun = useRef(true);\n\n useEffect(() => {\n if (isFirstRun.current) {\n isFirstRun.current = false;\n return;\n }\n if (pathname) {\n const url = searchParams?.size\n ? `${pathname}?${searchParams.toString()}`\n : pathname;\n posthog.capture(\"$pageview\", { $current_url: url });\n }\n }, [pathname, searchParams]);\n\n return null;\n}\n\nexport function PostHogSetup() {\n const [ready, setReady] = useState(false);\n\n if (!posthogKey) {\n return null;\n }\n\n return (\n <>\n <PostHogInit onReady={() => setReady(true)} />\n <Suspense fallback={null}>{ready && <PostHogPageviewTracker />}</Suspense>\n </>\n );\n}\n";
|
|
@@ -18,6 +18,13 @@ const analyticsConfig = rawAnalyticsConfig as AnalyticsConfig;
|
|
|
18
18
|
const posthogKey =
|
|
19
19
|
analyticsConfig?.provider === "posthog" ? analyticsConfig.posthog?.key : null;
|
|
20
20
|
|
|
21
|
+
// \`host\` is the *ingestion* endpoint (us.i.posthog.com); \`ui_host\` wants the
|
|
22
|
+
// dashboard it belongs to (us.posthog.com), which is what "view in PostHog"
|
|
23
|
+
// links and the toolbar point at. Self-hosted instances serve both from one
|
|
24
|
+
// origin, so leaving those untouched is correct.
|
|
25
|
+
const uiHost = (analyticsConfig.posthog?.host || "https://us.i.posthog.com")
|
|
26
|
+
.replace(".i.posthog.com", ".posthog.com");
|
|
27
|
+
|
|
21
28
|
function PostHogInit({ onReady }: { onReady: () => void }) {
|
|
22
29
|
const initRef = useRef(false);
|
|
23
30
|
|
|
@@ -27,7 +34,7 @@ function PostHogInit({ onReady }: { onReady: () => void }) {
|
|
|
27
34
|
|
|
28
35
|
posthog.init(posthogKey, {
|
|
29
36
|
api_host: "/ingest",
|
|
30
|
-
ui_host:
|
|
37
|
+
ui_host: uiHost,
|
|
31
38
|
capture_pageview: false,
|
|
32
39
|
capture_pageleave: true,
|
|
33
40
|
loaded: onReady,
|
|
@@ -37,11 +44,24 @@ function PostHogInit({ onReady }: { onReady: () => void }) {
|
|
|
37
44
|
return null;
|
|
38
45
|
}
|
|
39
46
|
|
|
47
|
+
/**
|
|
48
|
+
* Captures soft navigations only.
|
|
49
|
+
*
|
|
50
|
+
* The document load that got the reader here was already captured in the
|
|
51
|
+
* middleware (see proxy.ts), so counting it again here is what produced two
|
|
52
|
+
* \`$pageview\` events per page load. Server owns document loads, client owns
|
|
53
|
+
* soft navigations: disjoint, so neither double-counts nor leaves a gap.
|
|
54
|
+
*/
|
|
40
55
|
function PostHogPageviewTracker() {
|
|
41
56
|
const pathname = usePathname();
|
|
42
57
|
const searchParams = useSearchParams();
|
|
58
|
+
const isFirstRun = useRef(true);
|
|
43
59
|
|
|
44
60
|
useEffect(() => {
|
|
61
|
+
if (isFirstRun.current) {
|
|
62
|
+
isFirstRun.current = false;
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
45
65
|
if (pathname) {
|
|
46
66
|
const url = searchParams?.size
|
|
47
67
|
? \`\${pathname}?\${searchParams.toString()}\`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const analyticsMdxTemplate = "---\ntitle: \"Analytics\"\ndescription: \"Add PostHog analytics to your documentation site with an analytics.json file for both client-side and server-side tracking.\"\ndate: \"2026-02-24\"\ncategory: \"Configuration\"\ncategoryOrder: 3\norder: 10\n---\n# Analytics\n\nTrack how users interact with your documentation using PostHog. Doccupine
|
|
1
|
+
export declare const analyticsMdxTemplate = "---\ntitle: \"Analytics\"\ndescription: \"Add PostHog analytics to your documentation site with an analytics.json file for both client-side and server-side tracking.\"\ndate: \"2026-02-24\"\ncategory: \"Configuration\"\ncategoryOrder: 3\norder: 10\n---\n# Analytics\n\nTrack how users interact with your documentation using PostHog. Doccupine captures page views in two layers out of the box - in the browser and on the server - so readers running ad blockers are still counted. Browser traffic is proxied through your own domain rather than going to PostHog directly.\n\n## analytics.json\n\nPlace an `analytics.json` at your project root (the same directory where you execute `npx doccupine`).\n\n```json\n{\n \"provider\": \"posthog\",\n \"posthog\": {\n \"key\": \"phc_your_project_api_key\",\n \"host\": \"https://us.i.posthog.com\"\n }\n}\n```\n\n## Fields\n\n- **provider**: The analytics provider to use. Currently only `\"posthog\"` is supported.\n- **posthog.key**: Your PostHog project API key. You can find this in your PostHog project settings under \"Project API Key\". This is a public identifier - it is safe to commit to version control.\n- **posthog.host**: The PostHog ingestion endpoint. Use `https://us.i.posthog.com` for US Cloud or `https://eu.i.posthog.com` for EU Cloud. If you self-host PostHog, use your instance URL.\n\n<Callout type=\"note\">\n The PostHog project API key is a public identifier used to send events. It is not a secret and is safe to include in your repository.\n</Callout>\n\n## What gets tracked\n\nWhen `analytics.json` is configured, Doccupine enables two layers of tracking:\n\n### Client-side\n\n- **Page views**: Captured on client-side (soft) navigations using Next.js router hooks. The initial page load is counted by the server instead, so one view is never counted twice.\n- **Page leave**: Automatically captured when a user navigates away from a page.\n\n### Server-side\n\n- **Page views**: Captured in middleware on document requests - the initial load of a page. Requests behind client-side navigations carry an `RSC` header and are skipped, because the browser already counts those.\n- **Request metadata**: URL, pathname, host, referrer, and user agent are sent with each event.\n- **Smart filtering**: API routes, internal Next.js routes, and prefetch requests are automatically excluded.\n- **Ad-blocked readers**: because this half runs on your server, readers who block PostHog in the browser are still counted.\n\n## Privacy proxy\n\nDoccupine routes **browser** analytics traffic through your documentation domain using Next.js rewrites. Instead of the browser talking to PostHog directly (which ad blockers intercept), requests go through `/ingest` on your own domain and are proxied on.\n\nThis means:\n\n- No third-party domains appear in the browser's network requests.\n- Ad blockers are less likely to interfere with tracking.\n- Your users' browsing data stays within your domain boundary before reaching PostHog.\n\nThe proxy destinations are derived automatically from the `host` field in your configuration.\n\n<Callout type=\"warning\">\n The proxy covers browser traffic only. Server-side page views are sent from\n your server straight to PostHog - that is exactly what lets them survive an\n ad blocker.\n</Callout>\n\n## Cookies\n\nAn analytics-enabled site sets two first-party cookies:\n\n- `ph_<key>_posthog` - set by posthog-js, holding its anonymous distinct id and session.\n- `dcp_anon_id` - httpOnly, one year, set by the server so an ad-blocked reader (who never receives the posthog-js cookie) counts as one person instead of a new person on every request.\n\nBoth hold nothing but a random identifier. Whether they require a consent notice\nunder GDPR/ePrivacy depends on your jurisdiction and what you do with the data;\nthat call is yours.\n\n## Getting a PostHog key\n\n1. Sign up at [posthog.com](https://posthog.com) (free tier available).\n2. Create a new project.\n3. Go to **Project Settings** and copy the **Project API Key**.\n4. Paste it into your `analytics.json` as the `posthog.key` value.\n\n## Behavior\n\n- **Placement**: Put `analytics.json` in the project root alongside `config.json` and `theme.json`.\n- **Hot reload**: Changes to `analytics.json` are picked up automatically in watch mode. The layout, middleware, and Next.js config are regenerated.\n- **Graceful degradation**: If `analytics.json` is missing, empty, or has an invalid configuration, no tracking code runs. Your site works exactly the same without it.\n- **Dev server restart**: After adding or removing `analytics.json` for the first time, you may need to restart the Next.js dev server for proxy rewrites to take effect.\n\n<Callout type=\"warning\">\n After adding `analytics.json` for the first time, restart the dev server so the proxy rewrites are picked up by Next.js.\n</Callout>\n\n## Regions\n\nPostHog offers two cloud regions. Set the `host` field accordingly:\n\n| Region | Host |\n| -------- | -------------------------- |\n| US Cloud | `https://us.i.posthog.com` |\n| EU Cloud | `https://eu.i.posthog.com` |\n\nIf you omit the `host` field, it defaults to the US Cloud endpoint.\n\n## Example\n\n### Minimal configuration (US Cloud)\n\n```json\n{\n \"provider\": \"posthog\",\n \"posthog\": {\n \"key\": \"phc_your_project_api_key\"\n }\n}\n```\n\n### EU Cloud\n\n```json\n{\n \"provider\": \"posthog\",\n \"posthog\": {\n \"key\": \"phc_your_project_api_key\",\n \"host\": \"https://eu.i.posthog.com\"\n }\n}\n```\n\n## Tips\n\n- **Start simple**: Add the config with just your key and verify events appear in your PostHog dashboard before customizing further.\n- **Check your dashboard**: After deploying, visit your PostHog project to confirm page view events are flowing in.\n- **Production only**: Consider adding `analytics.json` only in your production/deployment setup to avoid tracking local development traffic.";
|
|
@@ -8,7 +8,7 @@ order: 10
|
|
|
8
8
|
---
|
|
9
9
|
# Analytics
|
|
10
10
|
|
|
11
|
-
Track how users interact with your documentation using PostHog. Doccupine
|
|
11
|
+
Track how users interact with your documentation using PostHog. Doccupine captures page views in two layers out of the box - in the browser and on the server - so readers running ad blockers are still counted. Browser traffic is proxied through your own domain rather than going to PostHog directly.
|
|
12
12
|
|
|
13
13
|
## analytics.json
|
|
14
14
|
|
|
@@ -40,27 +40,45 @@ When \`analytics.json\` is configured, Doccupine enables two layers of tracking:
|
|
|
40
40
|
|
|
41
41
|
### Client-side
|
|
42
42
|
|
|
43
|
-
- **Page views**: Captured on
|
|
43
|
+
- **Page views**: Captured on client-side (soft) navigations using Next.js router hooks. The initial page load is counted by the server instead, so one view is never counted twice.
|
|
44
44
|
- **Page leave**: Automatically captured when a user navigates away from a page.
|
|
45
45
|
|
|
46
46
|
### Server-side
|
|
47
47
|
|
|
48
|
-
- **Page views**: Captured in middleware on
|
|
48
|
+
- **Page views**: Captured in middleware on document requests - the initial load of a page. Requests behind client-side navigations carry an \`RSC\` header and are skipped, because the browser already counts those.
|
|
49
49
|
- **Request metadata**: URL, pathname, host, referrer, and user agent are sent with each event.
|
|
50
50
|
- **Smart filtering**: API routes, internal Next.js routes, and prefetch requests are automatically excluded.
|
|
51
|
+
- **Ad-blocked readers**: because this half runs on your server, readers who block PostHog in the browser are still counted.
|
|
51
52
|
|
|
52
53
|
## Privacy proxy
|
|
53
54
|
|
|
54
|
-
Doccupine routes
|
|
55
|
+
Doccupine routes **browser** analytics traffic through your documentation domain using Next.js rewrites. Instead of the browser talking to PostHog directly (which ad blockers intercept), requests go through \`/ingest\` on your own domain and are proxied on.
|
|
55
56
|
|
|
56
57
|
This means:
|
|
57
58
|
|
|
58
|
-
- No third-party domains appear in network requests.
|
|
59
|
+
- No third-party domains appear in the browser's network requests.
|
|
59
60
|
- Ad blockers are less likely to interfere with tracking.
|
|
60
61
|
- Your users' browsing data stays within your domain boundary before reaching PostHog.
|
|
61
62
|
|
|
62
63
|
The proxy destinations are derived automatically from the \`host\` field in your configuration.
|
|
63
64
|
|
|
65
|
+
<Callout type="warning">
|
|
66
|
+
The proxy covers browser traffic only. Server-side page views are sent from
|
|
67
|
+
your server straight to PostHog - that is exactly what lets them survive an
|
|
68
|
+
ad blocker.
|
|
69
|
+
</Callout>
|
|
70
|
+
|
|
71
|
+
## Cookies
|
|
72
|
+
|
|
73
|
+
An analytics-enabled site sets two first-party cookies:
|
|
74
|
+
|
|
75
|
+
- \`ph_<key>_posthog\` - set by posthog-js, holding its anonymous distinct id and session.
|
|
76
|
+
- \`dcp_anon_id\` - httpOnly, one year, set by the server so an ad-blocked reader (who never receives the posthog-js cookie) counts as one person instead of a new person on every request.
|
|
77
|
+
|
|
78
|
+
Both hold nothing but a random identifier. Whether they require a consent notice
|
|
79
|
+
under GDPR/ePrivacy depends on your jurisdiction and what you do with the data;
|
|
80
|
+
that call is yours.
|
|
81
|
+
|
|
64
82
|
## Getting a PostHog key
|
|
65
83
|
|
|
66
84
|
1. Sign up at [posthog.com](https://posthog.com) (free tier available).
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const platformAnalyticsMdxTemplate = "---\ntitle: \"Analytics\"\ndescription: \"Enable PostHog analytics to track page views on your documentation site.\"\ndate: \"2026-02-24\"\ncategory: \"Configuration\"\ncategoryOrder: 2\norder: 3\nsection: \"Platform\"\n---\n# Analytics\n\nThe Analytics settings page lets you add PostHog analytics to your documentation site. Page views are
|
|
1
|
+
export declare const platformAnalyticsMdxTemplate = "---\ntitle: \"Analytics\"\ndescription: \"Enable PostHog analytics to track page views on your documentation site.\"\ndate: \"2026-02-24\"\ncategory: \"Configuration\"\ncategoryOrder: 2\norder: 3\nsection: \"Platform\"\n---\n# Analytics\n\nThe Analytics settings page lets you add PostHog analytics to your documentation site. Page views are captured both in the browser and on your server, so readers running ad blockers are still counted. Browser traffic is proxied through your own domain; server-side events go from your server to PostHog directly.\n\n## Enabling analytics\n\nUse the **Enable Analytics** toggle to turn tracking on or off. When disabled, no tracking code is added to your site.\n\n## Configuration\n\n### PostHog Project API Key\n\nYour project API key from PostHog (starts with `phc_`). This is a public identifier and is safe to commit to your repository.\n\nTo find your key:\n\n1. Log in to [PostHog](https://posthog.com).\n2. Open your project settings.\n3. Copy the **Project API Key**.\n\n### Region\n\nSelect the PostHog cloud region that matches your project:\n\n- **US Cloud** - `us.i.posthog.com`\n- **EU Cloud** - `eu.i.posthog.com`\n\n## How it works\n\nAnalytics settings are stored in `analytics.json` at the root of your repository. Here's an example:\n\n```json\n{\n \"provider\": \"posthog\",\n \"posthog\": {\n \"key\": \"phc_your_project_api_key\",\n \"host\": \"https://us.i.posthog.com\"\n }\n}\n```\n\nWhen enabled, Doccupine routes all analytics traffic through your documentation domain using Next.js rewrites. Instead of sending data directly to PostHog (which ad blockers may intercept), requests go through `/ingest` on your own domain and are proxied to PostHog.\n\n<Callout type=\"note\">\n Changes to analytics settings are staged as pending changes. Click **Publish** to commit them to your repository and trigger a deploy.\n</Callout>\n\nSee the [Analytics](/analytics) page for the full configuration reference and additional details on the privacy proxy.";
|
|
@@ -9,7 +9,7 @@ section: "Platform"
|
|
|
9
9
|
---
|
|
10
10
|
# Analytics
|
|
11
11
|
|
|
12
|
-
The Analytics settings page lets you add PostHog analytics to your documentation site. Page views are
|
|
12
|
+
The Analytics settings page lets you add PostHog analytics to your documentation site. Page views are captured both in the browser and on your server, so readers running ad blockers are still counted. Browser traffic is proxied through your own domain; server-side events go from your server to PostHog directly.
|
|
13
13
|
|
|
14
14
|
## Enabling analytics
|
|
15
15
|
|
|
@@ -19,10 +19,11 @@ export default nextConfig;
|
|
|
19
19
|
`;
|
|
20
20
|
}
|
|
21
21
|
const host = analyticsConfig.posthog.host || "https://us.i.posthog.com";
|
|
22
|
-
// Derive the assets host from the API host
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
22
|
+
// Derive the assets host from the API host
|
|
23
|
+
// (https://us.i.posthog.com -> https://us-assets.i.posthog.com). Self-hosted
|
|
24
|
+
// instances have no ".i." segment and serve assets from the same origin, so
|
|
25
|
+
// they correctly fall through unchanged.
|
|
26
|
+
const assetsHost = host.replace(".i.", "-assets.i.");
|
|
26
27
|
return `import type { NextConfig } from "next";
|
|
27
28
|
|
|
28
29
|
const nextConfig: NextConfig = {
|
|
@@ -17,7 +17,6 @@ export const packageJsonTemplate = JSON.stringify({
|
|
|
17
17
|
"@langchain/openai": "^1.5.5",
|
|
18
18
|
"@mdx-js/react": "^3.1.1",
|
|
19
19
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
20
|
-
"@posthog/react": "^1.10.3",
|
|
21
20
|
"beautiful-mermaid": "^1.1.3",
|
|
22
21
|
"cherry-styled-components": "^0.2.11",
|
|
23
22
|
langchain: "^1.5.3",
|
|
@@ -43,8 +42,8 @@ export const packageJsonTemplate = JSON.stringify({
|
|
|
43
42
|
"@types/node": "^26",
|
|
44
43
|
"@types/react": "^19",
|
|
45
44
|
"@types/react-dom": "^19",
|
|
46
|
-
"@typescript-eslint/eslint-plugin": "^8.
|
|
47
|
-
"@typescript-eslint/parser": "^8.
|
|
45
|
+
"@typescript-eslint/eslint-plugin": "^8.65.0",
|
|
46
|
+
"@typescript-eslint/parser": "^8.65.0",
|
|
48
47
|
"@typescript/native-preview": "^7.0.0-dev.20260707.2",
|
|
49
48
|
eslint: "^10",
|
|
50
49
|
"eslint-plugin-import": "^2.32.0",
|
package/dist/templates/proxy.js
CHANGED
|
@@ -8,36 +8,96 @@ export const proxyTemplate = (analyticsConfig = null) => {
|
|
|
8
8
|
? `
|
|
9
9
|
const SKIP_PAGEVIEW_PATTERN = /^\\/(api|ingest|_next)\\//;
|
|
10
10
|
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
11
|
+
/**
|
|
12
|
+
* First-party anonymous id.
|
|
13
|
+
*
|
|
14
|
+
* posthog-js keeps its own id in \`ph_<key>_posthog\`, but an ad blocker stops
|
|
15
|
+
* that script from ever running, so a blocked reader never gets one. Without an
|
|
16
|
+
* id of our own we minted a fresh UUID per request, which made every single
|
|
17
|
+
* pageview a brand-new "person" and badly inflated unique-visitor counts. This
|
|
18
|
+
* cookie is what makes one anonymous reader one person across requests.
|
|
19
|
+
*
|
|
20
|
+
* It is first-party and httpOnly: only the edge reads it, and it never leaves
|
|
21
|
+
* your domain except as a PostHog distinct_id.
|
|
22
|
+
*/
|
|
23
|
+
const ANON_ID_COOKIE = "dcp_anon_id";
|
|
24
|
+
|
|
25
|
+
const ANON_ID_MAX_AGE = 60 * 60 * 24 * 365;
|
|
26
|
+
|
|
27
|
+
interface TrackingIdentity {
|
|
28
|
+
distinctId: string;
|
|
29
|
+
/** Set only when the id was just minted and still needs writing to a cookie. */
|
|
30
|
+
anonIdToPersist?: string;
|
|
31
|
+
sessionId?: string;
|
|
32
|
+
deviceId?: string;
|
|
33
|
+
}
|
|
20
34
|
|
|
21
|
-
|
|
22
|
-
|
|
35
|
+
/**
|
|
36
|
+
* Resolves who this pageview belongs to: whatever posthog-js already
|
|
37
|
+
* established for this browser, else our own anonymous cookie, else a fresh id
|
|
38
|
+
* that the caller persists.
|
|
39
|
+
*/
|
|
40
|
+
function resolveTrackingIdentity(req: NextRequest): TrackingIdentity {
|
|
41
|
+
let distinctId: string | undefined;
|
|
42
|
+
let sessionId: string | undefined;
|
|
43
|
+
let deviceId: string | undefined;
|
|
23
44
|
|
|
24
45
|
const phCookie = req.cookies.get(
|
|
25
46
|
"ph_${analyticsConfig.posthog.key}_posthog",
|
|
26
47
|
)?.value;
|
|
27
|
-
let distinctId: string | undefined;
|
|
28
48
|
if (phCookie) {
|
|
29
49
|
try {
|
|
30
|
-
|
|
50
|
+
const parsed = JSON.parse(phCookie);
|
|
51
|
+
if (typeof parsed.distinct_id === "string") distinctId = parsed.distinct_id;
|
|
52
|
+
// \`$sesid\` is [lastActivityTs, sessionId, sessionStartTs]. Forwarding it
|
|
53
|
+
// keeps server events inside the client's session instead of floating free.
|
|
54
|
+
if (Array.isArray(parsed.$sesid) && typeof parsed.$sesid[1] === "string") {
|
|
55
|
+
sessionId = parsed.$sesid[1];
|
|
56
|
+
}
|
|
57
|
+
if (typeof parsed.$device_id === "string") deviceId = parsed.$device_id;
|
|
31
58
|
} catch {
|
|
32
59
|
// ignore malformed cookie
|
|
33
60
|
}
|
|
34
61
|
}
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
62
|
+
|
|
63
|
+
if (distinctId) return { distinctId, sessionId, deviceId };
|
|
64
|
+
|
|
65
|
+
const anonId = req.cookies.get(ANON_ID_COOKIE)?.value;
|
|
66
|
+
if (anonId) return { distinctId: anonId, sessionId, deviceId };
|
|
67
|
+
|
|
68
|
+
const minted = crypto.randomUUID();
|
|
69
|
+
return { distinctId: minted, anonIdToPersist: minted, sessionId, deviceId };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Server captures document loads; the client tracker captures soft navigations.
|
|
74
|
+
* Splitting by navigation type is what stops the two from both counting the
|
|
75
|
+
* same view — previously every page load produced two \`$pageview\` events.
|
|
76
|
+
*/
|
|
77
|
+
function captureServerPageview(
|
|
78
|
+
req: NextRequest,
|
|
79
|
+
event: NextFetchEvent,
|
|
80
|
+
): TrackingIdentity | null {
|
|
81
|
+
const pathname = req.nextUrl.pathname;
|
|
82
|
+
|
|
83
|
+
if (SKIP_PAGEVIEW_PATTERN.test(pathname)) return null;
|
|
84
|
+
|
|
85
|
+
const isPrefetch =
|
|
86
|
+
req.headers.get("next-router-prefetch") === "1" ||
|
|
87
|
+
req.headers.get("purpose") === "prefetch";
|
|
88
|
+
if (isPrefetch) return null;
|
|
89
|
+
|
|
90
|
+
// A soft navigation fetches an RSC payload rather than a document, and
|
|
91
|
+
// carries this header. The client tracker owns those.
|
|
92
|
+
if (req.headers.get("RSC")) return null;
|
|
93
|
+
|
|
94
|
+
const posthog = getPostHogServerClient();
|
|
95
|
+
if (!posthog) return null;
|
|
96
|
+
|
|
97
|
+
const identity = resolveTrackingIdentity(req);
|
|
38
98
|
|
|
39
99
|
posthog.capture({
|
|
40
|
-
distinctId,
|
|
100
|
+
distinctId: identity.distinctId,
|
|
41
101
|
event: "$pageview",
|
|
42
102
|
properties: {
|
|
43
103
|
$current_url: req.url,
|
|
@@ -45,16 +105,46 @@ function captureServerPageview(req: NextRequest, event: NextFetchEvent) {
|
|
|
45
105
|
$host: req.headers.get("host") ?? undefined,
|
|
46
106
|
$referrer: req.headers.get("referer") ?? undefined,
|
|
47
107
|
$user_agent: req.headers.get("user-agent") ?? undefined,
|
|
108
|
+
$session_id: identity.sessionId,
|
|
109
|
+
$device_id: identity.deviceId,
|
|
48
110
|
_server_side: true,
|
|
49
111
|
},
|
|
50
112
|
});
|
|
51
113
|
event.waitUntil(posthog.flush());
|
|
114
|
+
|
|
115
|
+
return identity;
|
|
52
116
|
}
|
|
53
117
|
`
|
|
54
118
|
: "";
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
119
|
+
// Applied at every exit so the anonymous id is persisted whichever branch the
|
|
120
|
+
// request takes (gate rewrite, redirect, or the normal response). Without it
|
|
121
|
+
// a reader stuck behind the password gate would keep minting new ids.
|
|
122
|
+
const applyTrackingFn = hasPostHog
|
|
123
|
+
? `
|
|
124
|
+
function applyTracking(
|
|
125
|
+
res: NextResponse,
|
|
126
|
+
tracking: TrackingIdentity | null,
|
|
127
|
+
): NextResponse {
|
|
128
|
+
if (tracking?.anonIdToPersist) {
|
|
129
|
+
res.cookies.set(ANON_ID_COOKIE, tracking.anonIdToPersist, {
|
|
130
|
+
path: "/",
|
|
131
|
+
maxAge: ANON_ID_MAX_AGE,
|
|
132
|
+
sameSite: "lax",
|
|
133
|
+
httpOnly: true,
|
|
134
|
+
secure: process.env.NODE_ENV === "production",
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
return res;
|
|
138
|
+
}
|
|
139
|
+
`
|
|
140
|
+
: `
|
|
141
|
+
function applyTracking(res: NextResponse, _tracking: null): NextResponse {
|
|
142
|
+
return res;
|
|
143
|
+
}
|
|
144
|
+
`;
|
|
145
|
+
const trackingInit = hasPostHog
|
|
146
|
+
? ` const tracking = captureServerPageview(req, event);\n`
|
|
147
|
+
: ` const tracking = null;\n`;
|
|
58
148
|
const fnSignature = hasPostHog
|
|
59
149
|
? `export async function proxy(req: NextRequest, event: NextFetchEvent)`
|
|
60
150
|
: `export async function proxy(req: NextRequest)`;
|
|
@@ -73,9 +163,9 @@ function captureServerPageview(req: NextRequest, event: NextFetchEvent) {
|
|
|
73
163
|
const matcher = `["/:path*"]`;
|
|
74
164
|
return `import { NextResponse } from "next/server";
|
|
75
165
|
import type { NextRequest${eventImport} } from "next/server";
|
|
76
|
-
${gateImport}${posthogImport}${posthogPageviewFn}
|
|
166
|
+
${gateImport}${posthogImport}${posthogPageviewFn}${applyTrackingFn}
|
|
77
167
|
${fnSignature} {
|
|
78
|
-
${
|
|
168
|
+
${trackingInit} const pathname = req.nextUrl.pathname;
|
|
79
169
|
const sitePassword = process.env.SITE_PASSWORD;
|
|
80
170
|
|
|
81
171
|
// API key auth for /api/mcp when DOCS_API_KEY is configured
|
|
@@ -119,12 +209,15 @@ ${posthogCall} const pathname = req.nextUrl.pathname;
|
|
|
119
209
|
if (!unlocked && !pathname.startsWith("/api") && pathname !== "/gate") {
|
|
120
210
|
const res = NextResponse.rewrite(new URL("/gate", req.url));
|
|
121
211
|
res.headers.set("X-Robots-Tag", "noindex, nofollow");
|
|
122
|
-
return res;
|
|
212
|
+
return applyTracking(res, tracking);
|
|
123
213
|
}
|
|
124
214
|
|
|
125
215
|
// Unlocked visitors never need the gate screen.
|
|
126
216
|
if (unlocked && pathname === "/gate") {
|
|
127
|
-
return
|
|
217
|
+
return applyTracking(
|
|
218
|
+
NextResponse.redirect(new URL("/", req.url)),
|
|
219
|
+
tracking,
|
|
220
|
+
);
|
|
128
221
|
}
|
|
129
222
|
}
|
|
130
223
|
|
|
@@ -136,7 +229,7 @@ ${posthogCall} const pathname = req.nextUrl.pathname;
|
|
|
136
229
|
res.headers.set("X-Robots-Tag", "noindex, nofollow");
|
|
137
230
|
}
|
|
138
231
|
|
|
139
|
-
return res;
|
|
232
|
+
return applyTracking(res, tracking);
|
|
140
233
|
}
|
|
141
234
|
|
|
142
235
|
export const config = {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "doccupine",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.128",
|
|
4
4
|
"description": "Free and open-source documentation platform. Write MDX, get a production-ready site with AI chat, built-in components, and an MCP server - in one command.",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"bin": {
|