Skip to content

Commit 5f5e2ba

Browse files
committed
feat: 补 /docs 页面自家 analytics page_view 埋点
- 新增 DocsPageViewTracker 客户端组件,usePathname+useEffect 监听路由 - sessionStorage 去重,同一会话同一 path 不重复上报 - POST /api/analytics,携带 x-satoken(有 token 时),匿名用户 userId 由后端解析为 null - 在 app/docs/layout.tsx 中挂载
1 parent 356cecc commit 5f5e2ba

2 files changed

Lines changed: 37 additions & 0 deletions

File tree

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"use client";
2+
3+
import { usePathname } from "next/navigation";
4+
import { useEffect } from "react";
5+
6+
export function DocsPageViewTracker() {
7+
const pathname = usePathname();
8+
9+
useEffect(() => {
10+
if (!pathname) return;
11+
12+
const key = `pv_reported:${pathname}`;
13+
if (sessionStorage.getItem(key)) return;
14+
15+
sessionStorage.setItem(key, "1");
16+
17+
const token =
18+
typeof window !== "undefined" ? localStorage.getItem("satoken") : null;
19+
const headers: Record<string, string> = {
20+
"Content-Type": "application/json",
21+
};
22+
if (token) headers["x-satoken"] = token;
23+
24+
fetch("/api/analytics", {
25+
method: "POST",
26+
headers,
27+
body: JSON.stringify({
28+
eventType: "page_view",
29+
eventData: { path: pathname, title: document.title },
30+
}),
31+
}).catch(() => {});
32+
}, [pathname]);
33+
34+
return null;
35+
}

app/docs/layout.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import type { ReactNode } from "react";
55
import { DocsRouteFlag } from "@/app/components/RouteFlags";
66
import type { PageTree } from "fumadocs-core/server";
77
import { CopyTracking } from "@/app/components/CopyTracking";
8+
import { DocsPageViewTracker } from "@/app/components/DocsPageViewTracker";
89

910
function pruneEmptyFolders(root: PageTree.Root): PageTree.Root {
1011
const transformNode = (node: PageTree.Node): PageTree.Node | null => {
@@ -71,6 +72,7 @@ export default async function Layout({ children }: { children: ReactNode }) {
7172
{/* Add a class on <html> while in docs to adjust global backgrounds */}
7273
<CopyTracking />
7374
<DocsRouteFlag />
75+
<DocsPageViewTracker />
7476
<DocsLayout
7577
tree={tree}
7678
{...options}

0 commit comments

Comments
 (0)