Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

feat: track in-document link click events

Marc Seitza1637b7e8d13
diff --git a/components/view/PagesViewerNew.tsx b/components/view/PagesViewerNew.tsx
index 31f50bbd..c01ea38d 100644
--- a/components/view/PagesViewerNew.tsx
+++ b/components/view/PagesViewerNew.tsx
@@ -728,6 +728,27 @@ export default function PagesViewer({
// Reset the start time for the new page
startTimeRef.current = Date.now();
}
+ } else {
+ // Track external link clicks
+ if (!isPreview && viewId) {
+ fetch("/api/record_click", {
+ method: "POST",
+ body: JSON.stringify({
+ timestamp: new Date().toISOString(),
+ sessionId: viewId,
+ linkId,
+ documentId,
+ viewId,
+ pageNumber: pageNumber.toString(),
+ href,
+ versionNumber,
+ dataroomId,
+ }),
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }).catch(console.error); // Non-blocking
+ }
}
};
diff --git a/components/visitors/visitor-clicks.tsx b/components/visitors/visitor-clicks.tsx
new file mode 100644
index 00000000..87d0bf36
--- /dev/null
+++ b/components/visitors/visitor-clicks.tsx
@@ -0,0 +1,108 @@
+import { format } from "date-fns";
+import { ExternalLink } from "lucide-react";
+import useSWR from "swr";
+
+import { fetcher } from "@/lib/utils";
+
+import { Card, CardContent, CardHeader, CardTitle } from "../ui/card";
+import { Skeleton } from "../ui/skeleton";
+
+type ClickEvent = {
+ timestamp: string;
+ document_id: string;
+ dataroom_id: string | null;
+ view_id: string;
+ page_number: string;
+ version_number: number;
+ href: string;
+};
+
+type ClickEventsResponse = {
+ data: ClickEvent[];
+};
+
+export default function VisitorClicks({
+ teamId,
+ documentId,
+ viewId,
+}: {
+ teamId: string;
+ documentId: string;
+ viewId: string;
+}) {
+ const { data: clickEvents, error } = useSWR<ClickEventsResponse>(
+ `/api/teams/${teamId}/documents/${documentId}/views/${viewId}/click-events`,
+ fetcher,
+ );
+
+ if (error) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-base font-medium">Link Clicks</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <div className="text-sm text-red-500">
+ Failed to load click events
+ </div>
+ </CardContent>
+ </Card>
+ );
+ }
+
+ if (!clickEvents) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-base font-medium">Link Clicks</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <div className="space-y-2">
+ <Skeleton className="h-4 w-full" />
+ <Skeleton className="h-4 w-3/4" />
+ </div>
+ </CardContent>
+ </Card>
+ );
+ }
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle className="text-base font-medium">Link Clicks</CardTitle>
+ </CardHeader>
+ <CardContent>
+ {clickEvents.data.length === 0 ? (
+ <div className="text-sm text-gray-500">No links clicked yet</div>
+ ) : (
+ <div className="space-y-4">
+ {clickEvents.data.map((event, index) => (
+ <div key={index} className="flex items-start space-x-3">
+ <ExternalLink className="mt-0.5 h-4 w-4 flex-shrink-0 text-gray-400" />
+ <div className="space-y-1">
+ <div className="text-sm">
+ <span className="font-medium">
+ Page {event.page_number}
+ </span>
+ :{" "}
+ <a
+ href={event.href}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-blue-600 hover:underline"
+ >
+ {event.href}
+ </a>
+ </div>
+ <div className="text-xs text-gray-500">
+ {format(new Date(event.timestamp), "MMM d, yyyy HH:mm:ss")}
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
diff --git a/components/visitors/visitors-table.tsx b/components/visitors/visitors-table.tsx
index 75e443cb..071d87ef 100644
--- a/components/visitors/visitors-table.tsx
+++ b/components/visitors/visitors-table.tsx
@@ -60,6 +60,7 @@ import {
} from "../ui/pagination";
import { VisitorAvatar } from "./visitor-avatar";
import VisitorChart from "./visitor-chart";
+import VisitorClicks from "./visitor-clicks";
import VisitorUserAgent from "./visitor-useragent";
import VisitorUserAgentPlaceholder from "./visitor-useragent-placeholder";
import VisitorVideoChart from "./visitor-video-chart";
@@ -424,6 +425,13 @@ export default function VisitorsTable({
versionNumber={view.versionNumber}
/>
)}
+ {!isFreePlan ? (
+ <VisitorClicks
+ teamId={view.teamId!}
+ documentId={view.documentId!}
+ viewId={view.id}
+ />
+ ) : null}
</TableCell>
</TableRow>
</>
diff --git a/lib/id-helper.ts b/lib/id-helper.ts
index 443fdc8b..86334574 100644
--- a/lib/id-helper.ts
+++ b/lib/id-helper.ts
@@ -45,4 +45,5 @@ export const newId = new IdGenerator({
webhookEvent: "evt",
webhookSecret: "whsec",
token: "pmk",
+ clickEvent: "click",
}).id;
diff --git a/lib/tinybird/datasources/click_events.datasource b/lib/tinybird/datasources/click_events.datasource
new file mode 100644
index 00000000..c14e07f9
--- /dev/null
+++ b/lib/tinybird/datasources/click_events.datasource
@@ -0,0 +1,20 @@
+VERSION 1
+
+DESCRIPTION >
+ Click events track when a user clicks a link within a document
+
+SCHEMA >
+ `timestamp` DateTime64(3) `json:$.timestamp`,
+ `event_id` String `json:$.event_id`,
+ `session_id` String `json:$.session_id`,
+ `link_id` String `json:$.link_id`,
+ `document_id` String `json:$.document_id`,
+ `dataroom_id` Nullable(String) `json:$.dataroom_id`,
+ `view_id` String `json:$.view_id`,
+ `page_number` LowCardinality(String) `json:$.page_number`,
+ `version_number` UInt16 `json:$.version_number`,
+ `href` String `json:$.href`
+
+ENGINE "MergeTree"
+ENGINE_SORTING_KEY "document_id,view_id,link_id,timestamp"
+ENGINE_PARTITION_KEY "toYYYYMM(timestamp)"
\ No newline at end of file
diff --git a/lib/tinybird/endpoints/get_click_events_by_view.pipe b/lib/tinybird/endpoints/get_click_events_by_view.pipe
new file mode 100644
index 00000000..89dba47d
--- /dev/null
+++ b/lib/tinybird/endpoints/get_click_events_by_view.pipe
@@ -0,0 +1,20 @@
+VERSION 1
+
+DESCRIPTION >
+ Get all click events for a specific view
+
+NODE endpoint
+SQL >
+ %
+ SELECT
+ timestamp,
+ document_id,
+ dataroom_id,
+ view_id,
+ page_number,
+ version_number,
+ href
+ FROM click_events
+ WHERE document_id = {{ String(document_id, required=True) }}
+ AND view_id = {{ String(view_id, required=True) }}
+ ORDER BY timestamp ASC
diff --git a/lib/tinybird/pipes.ts b/lib/tinybird/pipes.ts
index fc8c5abe..7ce63449 100644
--- a/lib/tinybird/pipes.ts
+++ b/lib/tinybird/pipes.ts
@@ -114,7 +114,7 @@ export const getVideoEventsByDocument = tb.buildPipe({
data: z.object({
timestamp: z.string(),
view_id: z.string(),
- event_type: z.string(),
+ event_type: z.enum(VIDEO_EVENT_TYPES),
start_time: z.number(),
end_time: z.number(),
playback_rate: z.number(),
@@ -138,3 +138,20 @@ export const getVideoEventsByView = tb.buildPipe({
end_time: z.number(),
}),
});
+
+export const getClickEventsByView = tb.buildPipe({
+ pipe: "get_click_events_by_view__v1",
+ parameters: z.object({
+ document_id: z.string(),
+ view_id: z.string(),
+ }),
+ data: z.object({
+ timestamp: z.string(),
+ document_id: z.string(),
+ dataroom_id: z.string().nullable(),
+ view_id: z.string(),
+ page_number: z.string(),
+ version_number: z.number(),
+ href: z.string(),
+ }),
+});
diff --git a/lib/tinybird/publish.ts b/lib/tinybird/publish.ts
index c39d5c2d..64f36c7f 100644
--- a/lib/tinybird/publish.ts
+++ b/lib/tinybird/publish.ts
@@ -94,3 +94,20 @@ export const recordVideoView = tb.buildIngestEndpoint({
ip_address: z.string().nullable(),
}),
});
+
+// Click event tracking when user clicks a link within a document
+export const recordClickEvent = tb.buildIngestEndpoint({
+ datasource: "click_events__v1",
+ event: z.object({
+ timestamp: z.string(),
+ event_id: z.string(),
+ session_id: z.string(),
+ link_id: z.string(),
+ document_id: z.string(),
+ view_id: z.string(),
+ page_number: z.string(),
+ href: z.string(),
+ version_number: z.number(),
+ dataroom_id: z.string().nullable(),
+ }),
+});
diff --git a/pages/api/record_click.ts b/pages/api/record_click.ts
new file mode 100644
index 00000000..f58b8559
--- /dev/null
+++ b/pages/api/record_click.ts
@@ -0,0 +1,85 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { z } from "zod";
+
+import { newId } from "@/lib/id-helper";
+import { recordClickEvent } from "@/lib/tinybird";
+import { log } from "@/lib/utils";
+
+const bodyValidation = z.object({
+ timestamp: z.string(),
+ event_id: z.string(),
+ session_id: z.string(),
+ link_id: z.string(),
+ document_id: z.string(),
+ view_id: z.string(),
+ page_number: z.string(),
+ href: z.string(),
+ version_number: z.number(),
+ dataroom_id: z.string().nullable(),
+});
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "POST") {
+ return res.status(405).json({ message: "Method not allowed" });
+ }
+
+ const {
+ timestamp,
+ sessionId,
+ linkId,
+ documentId,
+ viewId,
+ pageNumber,
+ href,
+ versionNumber,
+ dataroomId,
+ } = req.body as {
+ timestamp: string;
+ sessionId: string;
+ linkId: string;
+ documentId: string;
+ viewId: string;
+ pageNumber: string;
+ href: string;
+ versionNumber: number;
+ dataroomId: string | null;
+ };
+
+ const clickEventId = newId("clickEvent");
+
+ const clickEventObject = {
+ timestamp: timestamp,
+ event_id: clickEventId,
+ session_id: sessionId,
+ link_id: linkId,
+ document_id: documentId,
+ view_id: viewId,
+ page_number: pageNumber,
+ href: href,
+ version_number: versionNumber || 1,
+ dataroom_id: dataroomId || null,
+ };
+
+ const result = bodyValidation.safeParse(clickEventObject);
+ if (!result.success) {
+ return res
+ .status(400)
+ .json({ error: `Invalid body: ${result.error.message}` });
+ }
+
+ try {
+ await recordClickEvent(result.data);
+ res.status(200).json({ message: "Click event recorded" });
+ } catch (error) {
+ log({
+ message: `Failed to record click event (tinybird) for ${linkId}. \n\n ${error}`,
+ type: "error",
+ mention: true,
+ });
+ res.status(500).json({ error: "Failed to record click event" });
+ }
+}
diff --git a/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/click-events.ts b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/click-events.ts
new file mode 100644
index 00000000..be43a9b8
--- /dev/null
+++ b/pages/api/teams/[teamId]/documents/[id]/views/[viewId]/click-events.ts
@@ -0,0 +1,70 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import { authOptions } from "@/pages/api/auth/[...nextauth]";
+import { getServerSession } from "next-auth/next";
+
+import prisma from "@/lib/prisma";
+import { getClickEventsByView } from "@/lib/tinybird/pipes";
+import { CustomUser } from "@/lib/types";
+import { log } from "@/lib/utils";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "GET") {
+ return res.status(405).json({ message: "Method not allowed" });
+ }
+
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const { teamId, id, viewId } = req.query as {
+ teamId: string;
+ id: string;
+ viewId: string;
+ };
+
+ const userId = (session.user as CustomUser).id;
+
+ try {
+ const team = await prisma.team.findUnique({
+ where: {
+ id: teamId,
+ users: {
+ some: {
+ userId: userId,
+ },
+ },
+ },
+ select: {
+ id: true,
+ plan: true,
+ },
+ });
+
+ if (!team) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ if (team.plan.includes("free")) {
+ return res.status(403).end("Forbidden");
+ }
+
+ const data = await getClickEventsByView({
+ document_id: id,
+ view_id: viewId,
+ });
+
+ return res.status(200).json(data);
+ } catch (error) {
+ log({
+ message: `Failed to get click events for document ${id} and view ${viewId}. \n\n ${error}`,
+ type: "error",
+ mention: true,
+ });
+ return res.status(500).json({ error: "Failed to get click events" });
+ }
+}