🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Track outbound events (#536)
Stijnbfd160dd7f6e
diff --git a/client/src/api/analytics/events/useGetOutboundLinks.ts b/client/src/api/analytics/events/useGetOutboundLinks.tsnew file mode 100644index 000000000..4a7221014--- /dev/null+++ b/client/src/api/analytics/events/useGetOutboundLinks.ts@@ -0,0 +1,36 @@+import { useQuery } from "@tanstack/react-query";+import {+ useStore,+ getFilteredFilters,+ EVENT_FILTERS,+} from "../../../lib/store";+import { authedFetch, getQueryParams } from "../../utils";++export type OutboundLink = {+ url: string;+ count: number;+ lastClicked: string;+};++export function useGetOutboundLinks() {+ const { site, time, filters } = useStore();++ const timeParams = getQueryParams(time);+ const filteredFilters = getFilteredFilters(EVENT_FILTERS);++ return useQuery({+ queryKey: ["outbound-links", site, timeParams, filteredFilters],+ enabled: !!site,+ queryFn: () => {+ const params = {+ ...timeParams,+ filters: filteredFilters.length > 0 ? filteredFilters : undefined,+ };++ return authedFetch<{ data: OutboundLink[] }>(+ `/events/outbound/${site}`,+ params+ ).then((res) => res.data);+ },+ });+}\ No newline at end of filediff --git a/client/src/api/analytics/userSessions.ts b/client/src/api/analytics/userSessions.tsindex be0319600..016234618 100644--- a/client/src/api/analytics/userSessions.ts+++ b/client/src/api/analytics/userSessions.ts@@ -37,6 +37,7 @@ export type GetSessionsResponse = {pageviews: number;events: number;errors: number;+ outbound: number;}[];export function useGetSessionsInfinite(userId?: string) {diff --git a/client/src/app/[site]/events/components/EventLogItem.tsx b/client/src/app/[site]/events/components/EventLogItem.tsxindex cf4d35e58..508a344ec 100644--- a/client/src/app/[site]/events/components/EventLogItem.tsx+++ b/client/src/app/[site]/events/components/EventLogItem.tsx@@ -6,7 +6,7 @@ import {TooltipContent,TooltipTrigger,} from "@/components/ui/tooltip";-import { FileText, Laptop, MousePointerClick, Smartphone } from "lucide-react";+import { ExternalLink, FileText, Laptop, MousePointerClick, Smartphone } from "lucide-react";import { DateTime } from "luxon";import Link from "next/link";import { useParams } from "next/navigation";@@ -49,8 +49,9 @@ export function EventLogItem({ event }: EventLogItemProps) {zone: "utc",}).toLocal();- // Determine if it's a pageview or custom event+ // Determine event typeconst isPageview = event.type === "pageview";+ const isOutbound = event.type === "outbound";const fullPath = `https://${event.hostname}${event.pathname}${event.querystring ? `${event.querystring}` : ""@@ -77,6 +78,8 @@ export function EventLogItem({ event }: EventLogItemProps) {<div className="flex-shrink-0">{isPageview ? (<FileText className="w-4 h-4 text-blue-500" />+ ) : isOutbound ? (+ <ExternalLink className="w-4 h-4 text-purple-500" />) : (<MousePointerClick className="w-4 h-4 text-amber-500" />)}@@ -97,6 +100,22 @@ export function EventLogItem({ event }: EventLogItemProps) {)}</div></Link>+ ) : isOutbound ? (+ // For outbound events, show the destination URL from properties+ eventProperties.url ? (+ <Link href={eventProperties.url} target="_blank" rel="noopener noreferrer">+ <div+ className="text-sm truncate hover:underline text-purple-400"+ title={eventProperties.url}+ >+ {truncatePath(eventProperties.url)}+ </div>+ </Link>+ ) : (+ <div className="text-sm font-medium truncate text-purple-400">+ Outbound Link+ </div>+ )) : (<div className="text-sm font-medium truncate">{event.event_name}diff --git a/client/src/app/[site]/events/components/OutboundLinksList.tsx b/client/src/app/[site]/events/components/OutboundLinksList.tsxnew file mode 100644index 000000000..bf8697766--- /dev/null+++ b/client/src/app/[site]/events/components/OutboundLinksList.tsx@@ -0,0 +1,201 @@+"use client";++import NumberFlow from "@number-flow/react";+import { ExternalLink } from "lucide-react";+import { DateTime } from "luxon";+import { memo } from "react";+import { OutboundLink } from "../../../../api/analytics/events/useGetOutboundLinks";+import { cn } from "../../../../lib/utils";++// Skeleton component for OutboundLinksList+const OutboundLinksListSkeleton = memo(+ ({ size = "small" }: { size?: "small" | "large" }) => {+ // Generate widths following Pareto principle with top item at 100%+ const widths = Array.from({ length: 10 }, (_, i) => {+ if (i === 0) {+ return 100;+ } else if (i === 1) {+ return 60 + Math.random() * 20;+ } else {+ const factor = 1 - (i - 2) / 8;+ return 10 + factor * 30;+ }+ });++ const labelWidths = Array.from({ length: 10 }, (_, i) => {+ return i < 3 ? 150 + Math.random() * 100 : 80 + Math.random() * 120;+ });++ const valueWidths = Array.from(+ { length: 10 },+ () => 20 + Math.random() * 40+ );++ return (+ <div className="flex flex-col gap-2 pr-2">+ {Array.from({ length: 10 }).map((_, index) => (+ <div+ key={index}+ className={cn(+ "relative flex items-center",+ size === "small" ? "h-6" : "h-9"+ )}+ >+ <div+ className="absolute inset-0 bg-neutral-800 py-2 rounded-md animate-pulse"+ style={{ width: `${widths[index]}%` }}+ ></div>+ <div+ className={cn(+ "z-5 mx-2 flex justify-between items-center w-full",+ size === "small" ? "text-xs" : "text-sm"+ )}+ >+ <div className="flex items-center gap-1">+ <div className="h-4 w-4 bg-neutral-800 rounded animate-pulse mr-1"></div>+ <div+ className="h-4 bg-neutral-800 rounded animate-pulse"+ style={{ width: `${labelWidths[index]}px` }}+ ></div>+ </div>+ <div+ className={cn(+ "flex gap-2",+ size === "small" ? "text-xs" : "text-sm"+ )}+ >+ <div+ className="h-4 bg-neutral-800 rounded animate-pulse"+ style={{ width: `${valueWidths[index]}px` }}+ ></div>+ </div>+ </div>+ </div>+ ))}+ </div>+ );+ }+);++interface OutboundLinksListProps {+ outboundLinks: OutboundLink[];+ isLoading: boolean;+ size?: "small" | "large";+}++// Function to truncate URL for display+function truncateUrl(url: string, maxLength: number = 60) {+ if (!url) return "-";+ if (url.length <= maxLength) return url;++ try {+ const urlObj = new URL(url);+ const domain = urlObj.hostname;+ const path = urlObj.pathname + urlObj.search;++ if (domain.length + path.length <= maxLength) {+ return `${domain}${path}`;+ }++ // If still too long, truncate the path+ const availableSpace = maxLength - domain.length - 3; // 3 for "..."+ if (availableSpace > 0) {+ return `${domain}${path.substring(0, availableSpace)}...`;+ } else {+ return `${domain.substring(0, maxLength - 3)}...`;+ }+ } catch (e) {+ // If URL parsing fails, just truncate the string+ return `${url.substring(0, maxLength - 3)}...`;+ }+}++export function OutboundLinksList({+ outboundLinks,+ isLoading,+ size = "small",+}: OutboundLinksListProps) {+ if (isLoading) {+ return <OutboundLinksListSkeleton size={size} />;+ }++ if (!outboundLinks || outboundLinks.length === 0) {+ return (+ <div className="flex flex-col gap-2">+ <div className="text-neutral-100 w-full text-center mt-6 flex flex-row gap-2 items-center justify-center">+ <ExternalLink className="w-5 h-5" />+ No outbound clicks tracked+ </div>+ <div className="text-neutral-400 w-full text-center mt-2 text-sm">+ External link clicks will appear here+ </div>+ </div>+ );+ }++ // Find the total count to calculate percentages+ const totalCount = outboundLinks.reduce((sum, link) => sum + link.count, 0);++ return (+ <div className="flex flex-col gap-2">+ {outboundLinks.map((link, index) => {+ const percentage = (link.count / totalCount) * 100;+ const lastClicked = DateTime.fromSQL(link.lastClicked, {+ zone: "utc",+ }).toLocal();++ return (+ <div+ key={`${link.url}-${index}`}+ className={cn(+ "relative flex items-center hover:bg-neutral-850 group px-2 rounded-md",+ size === "small" ? "h-6" : "h-9"+ )}+ >+ <div+ className="absolute inset-0 bg-purple-500 py-2 opacity-25 rounded-md"+ style={{ width: `${percentage}%` }}+ ></div>+ <div+ className={cn(+ "z-10 flex justify-between items-center w-full",+ size === "small" ? "text-xs" : "text-sm"+ )}+ >+ <div className="font-medium truncate max-w-[70%] flex items-center gap-1">+ <ExternalLink className="h-4 w-4 text-purple-400 flex-shrink-0" />+ <a+ href={link.url}+ target="_blank"+ rel="noopener noreferrer"+ className="text-purple-400 hover:text-purple-300 hover:underline truncate"+ title={link.url}+ >+ {truncateUrl(link.url)}+ </a>+ </div>+ <div+ className={cn(+ "text-sm flex gap-2 items-center",+ size === "small" ? "text-xs" : "text-sm"+ )}+ >+ <div className="hidden group-hover:block text-neutral-400 text-xs">+ {Math.round(percentage * 10) / 10}%+ </div>+ <div className="hidden group-hover:block text-neutral-400 text-xs">+ {lastClicked.toRelative()}+ </div>+ <NumberFlow+ respectMotionPreference={false}+ value={link.count}+ format={{ notation: "compact" }}+ />+ </div>+ </div>+ </div>+ );+ })}+ </div>+ );+}\ No newline at end of filediff --git a/client/src/app/[site]/events/page.tsx b/client/src/app/[site]/events/page.tsxindex d9c40e6fe..32d6f07e7 100644--- a/client/src/app/[site]/events/page.tsx+++ b/client/src/app/[site]/events/page.tsx@@ -3,30 +3,48 @@import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";import { EVENT_FILTERS } from "@/lib/store";import { useGetEventNames } from "../../../api/analytics/events/useGetEventNames";+import { useGetOutboundLinks } from "../../../api/analytics/events/useGetOutboundLinks";import { DisabledOverlay } from "../../../components/DisabledOverlay";import { useSetPageTitle } from "../../../hooks/useSetPageTitle";import { SubHeader } from "../components/SubHeader/SubHeader";import { EventList } from "./components/EventList";import { EventLog } from "./components/EventLog";+import { OutboundLinksList } from "./components/OutboundLinksList";export default function EventsPage() {useSetPageTitle("Rybbit · Events");const { data: eventNamesData, isLoading: isLoadingEventNames } = useGetEventNames();+ const { data: outboundLinksData, isLoading: isLoadingOutboundLinks } = useGetOutboundLinks();return (<DisabledOverlay message="Events" featurePath="events"><div className="p-2 md:p-4 max-w-[1300px] mx-auto space-y-3"><SubHeader availableFilters={EVENT_FILTERS} />- <Card>- <CardHeader>- <CardTitle>Custom Events</CardTitle>- </CardHeader>- <CardContent>- <EventList events={eventNamesData || []} isLoading={isLoadingEventNames} size="large" />- </CardContent>- </Card>+ <div className="grid grid-cols-1 lg:grid-cols-2 gap-3">+ <Card>+ <CardHeader>+ <CardTitle>Custom Events</CardTitle>+ </CardHeader>+ <CardContent>+ <EventList events={eventNamesData || []} isLoading={isLoadingEventNames} size="large" />+ </CardContent>+ </Card>++ <Card>+ <CardHeader>+ <CardTitle>Outbound Clicks</CardTitle>+ </CardHeader>+ <CardContent>+ <OutboundLinksList+ outboundLinks={outboundLinksData || []}+ isLoading={isLoadingOutboundLinks}+ size="large"+ />+ </CardContent>+ </Card>+ </div><Card><CardHeader>diff --git a/client/src/app/[site]/main/components/sections/OutboundLinks.tsx b/client/src/app/[site]/main/components/sections/OutboundLinks.tsxnew file mode 100644index 000000000..ea36d9b70--- /dev/null+++ b/client/src/app/[site]/main/components/sections/OutboundLinks.tsx@@ -0,0 +1,55 @@+import { useState } from "react";+import {+ Tabs,+ TabsContent,+ TabsList,+ TabsTrigger,+} from "../../../../../components/ui/basic-tabs";+import {+ Card,+ CardContent,+ CardLoader,+} from "../../../../../components/ui/card";+import { useGetOutboundLinks } from "../../../../../api/analytics/events/useGetOutboundLinks";+import { OutboundLinksList } from "../../../events/components/OutboundLinksList";++type Tab = "outbound";++export function OutboundLinks() {+ const [tab, setTab] = useState<Tab>("outbound");+ const { data: outboundLinksData, isLoading: isLoadingOutboundLinks } =+ useGetOutboundLinks();++ return (+ <Card>+ <CardContent className="mt-2">+ <Tabs+ defaultValue="outbound"+ value={tab}+ onValueChange={(value) => setTab(value as Tab)}+ >+ <TabsList>+ <TabsTrigger value="outbound">Outbound Clicks</TabsTrigger>+ </TabsList>+ <TabsContent value="outbound">+ {isLoadingOutboundLinks && (+ <div className="absolute top-[-8px] left-0 w-full h-full">+ <CardLoader />+ </div>+ )}+ <div className="relative">+ <div className="flex flex-row gap-2 justify-between pr-1 text-xs text-neutral-400 mb-2">+ <div>External Links</div>+ <div>Clicks</div>+ </div>+ <OutboundLinksList+ outboundLinks={outboundLinksData || []}+ isLoading={isLoadingOutboundLinks}+ />+ </div>+ </TabsContent>+ </Tabs>+ </CardContent>+ </Card>+ );+}\ No newline at end of filediff --git a/client/src/app/[site]/main/page.tsx b/client/src/app/[site]/main/page.tsxindex 224d0e9b9..89d1e7f61 100644--- a/client/src/app/[site]/main/page.tsx+++ b/client/src/app/[site]/main/page.tsx@@ -7,6 +7,7 @@ import { MainSection } from "./components/MainSection/MainSection";import { Countries } from "./components/sections/Countries";import { Devices } from "./components/sections/Devices";import { Events } from "./components/sections/Events";+import { OutboundLinks } from "./components/sections/OutboundLinks";import { Pages } from "./components/sections/Pages";import { Referrers } from "./components/sections/Referrers";import { Weekdays } from "./components/sections/Weekdays";@@ -34,6 +35,7 @@ function MainPageContent() {<Referrers /><Countries /><Events />+ <OutboundLinks /><Weekdays /></div></div>diff --git a/client/src/components/Sessions/SessionCard.tsx b/client/src/components/Sessions/SessionCard.tsxindex 14551bb1c..6a174c2bd 100644--- a/client/src/components/Sessions/SessionCard.tsx+++ b/client/src/components/Sessions/SessionCard.tsx@@ -1,6 +1,6 @@import { Skeleton } from "@/components/ui/skeleton";import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";-import { ArrowRight, ChevronDown, ChevronRight, FileText, MousePointerClick, TriangleAlert } from "lucide-react";+import { ArrowRight, ChevronDown, ChevronRight, ExternalLink, FileText, MousePointerClick, TriangleAlert } from "lucide-react";import { DateTime } from "luxon";import { memo, useState } from "react";import { GetSessionsResponse } from "../../api/analytics/userSessions";@@ -100,6 +100,15 @@ export function SessionCard({ session, onClick, userId }: SessionCardProps) {</TooltipTrigger><TooltipContent>Errors</TooltipContent></Tooltip>+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge variant="outline" className="flex items-center gap-1 bg-neutral-800 text-gray-300">+ <ExternalLink className="w-4 h-4 text-purple-500" />+ <span>{formatter(session.outbound)}</span>+ </Badge>+ </TooltipTrigger>+ <TooltipContent>Outbound Clicks</TooltipContent>+ </Tooltip></div>{/* Pages section with tooltips for long paths */}@@ -198,6 +207,7 @@ export const SessionCardSkeleton = memo(() => {<Skeleton className="h-[21px] w-12 rounded-sm" /><Skeleton className="h-[21px] w-12 rounded-sm" /><Skeleton className="h-[21px] w-12 rounded-sm" />+ <Skeleton className="h-[21px] w-12 rounded-sm" /></div>{/* Entry/Exit paths with randomized widths */}diff --git a/client/src/components/Sessions/SessionDetails.tsx b/client/src/components/Sessions/SessionDetails.tsxindex a9cb9261e..26d4fcd25 100644--- a/client/src/components/Sessions/SessionDetails.tsx+++ b/client/src/components/Sessions/SessionDetails.tsx@@ -6,6 +6,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";import {ArrowRight,Clock,+ ExternalLink,FileText,Loader2,Monitor,@@ -44,6 +45,7 @@ function PageviewItem({const isError = item.type === "error";const isEvent = item.type === "custom_event";const isPageview = item.type === "pageview";+ const isOutbound = item.type === "outbound";const timestamp = DateTime.fromSQL(item.timestamp, { zone: "utc" }).toLocal();const formattedTime = timestamp.toFormat(hour12 ? "h:mm:ss a" : "HH:mm:ss");@@ -75,6 +77,8 @@ function PageviewItem({? "bg-amber-900/30 border-amber-500/50": isError? "bg-red-900/30 border-red-500/50"+ : isOutbound+ ? "bg-purple-900/30 border-purple-500/50": "bg-blue-900/30 border-blue-500/50")}>@@ -89,6 +93,8 @@ function PageviewItem({<MousePointerClick className="w-4 h-4 text-amber-500" />) : isError ? (<TriangleAlert className="w-4 h-4 text-red-500" />+ ) : isOutbound ? (+ <ExternalLink className="w-4 h-4 text-purple-500" />) : (<FileText className="w-4 h-4 text-blue-500" />)}@@ -112,8 +118,24 @@ function PageviewItem({{item.querystring ? `${item.querystring}` : ""}</div></Link>+ ) : isOutbound && item.props?.url ? (+ <Link+ href={String(item.props.url)}+ target="_blank"+ rel="noopener noreferrer"+ >+ <div+ className="text-sm truncate hover:underline text-purple-400"+ title={String(item.props.url)}+ style={{+ maxWidth: "calc(min(100vw, 1150px) - 250px)",+ }}+ >+ {String(item.props.url)}+ </div>+ </Link>) : (- <div className="text-sm truncate">{item.event_name}</div>+ <div className="text-sm truncate">{item.event_name || 'Outbound Click'}</div>)}</div>@@ -146,6 +168,32 @@ function PageviewItem({</div></div>)}+ {isOutbound && (+ <div className="flex items-center pl-7 mt-1">+ <div className="text-xs text-neutral-400">+ {item.props && Object.keys(item.props).length > 0 ? (+ <span className="flex flex-wrap gap-2 mt-1">+ {item.props.text ? (+ <Badge+ variant="outline"+ className="px-1.5 py-0 h-5 text-xs bg-neutral-800 text-neutral-100 font-medium"+ >+ <span className="text-neutral-300 font-light mr-1">text:</span> {String(item.props.text)}+ </Badge>+ ) : null}+ {item.props.target ? (+ <Badge+ variant="outline"+ className="px-1.5 py-0 h-5 text-xs bg-neutral-800 text-neutral-100 font-medium"+ >+ <span className="text-neutral-300 font-light mr-1">target:</span> {String(item.props.target)}+ </Badge>+ ) : null}+ </span>+ ) : null}+ </div>+ </div>+ )}{isError && (<div className="flex items-center pl-7 mt-1"><div className="text-xs text-neutral-400">@@ -262,6 +310,10 @@ export function SessionDetails({ session, userId }: SessionDetailsProps) {return allEvents.filter((p: SessionEvent) => p.type === "error").length;}, [allEvents]);+ const totalOutbound = useMemo(() => {+ return allEvents.filter((p: SessionEvent) => p.type === "outbound").length;+ }, [allEvents]);+const { getRegionName } = useGetRegionName();return (diff --git a/server/src/api/analytics/events/getEvents.ts b/server/src/api/analytics/events/getEvents.tsindex 51277e06c..484ba3310 100644--- a/server/src/api/analytics/events/getEvents.ts+++ b/server/src/api/analytics/events/getEvents.ts@@ -76,7 +76,7 @@ export async function getEvents(FROM eventsWHEREsite_id = {siteId:Int32}- AND (type = 'custom_event' OR type = 'pageview')+ AND (type = 'custom_event' OR type = 'pageview' OR type = 'outbound')${timeStatement}${filterStatement}`;@@ -112,7 +112,7 @@ export async function getEvents(FROM eventsWHEREsite_id = {siteId:Int32}- AND (type = 'custom_event' OR type = 'pageview')+ AND (type = 'custom_event' OR type = 'pageview' OR type = 'outbound')${timeStatement}${filterStatement}ORDER BY timestamp DESCdiff --git a/server/src/api/analytics/events/getOutboundLinks.ts b/server/src/api/analytics/events/getOutboundLinks.tsnew file mode 100644index 000000000..8cea02832--- /dev/null+++ b/server/src/api/analytics/events/getOutboundLinks.ts@@ -0,0 +1,108 @@+import { FastifyReply, FastifyRequest } from "fastify";+import { clickhouse } from "../../../db/clickhouse/clickhouse.js";+import {+ getTimeStatement,+ processResults,+ getFilterStatement,+} from "../utils.js";+import { getUserHasAccessToSitePublic } from "../../../lib/auth-utils.js";+import { FilterParams } from "@rybbit/shared";++export type GetOutboundLinksResponse = {+ url: string;+ count: number;+ lastClicked: string;+}[];++export interface GetOutboundLinksRequest {+ Params: {+ site: string;+ };+ Querystring: FilterParams<{}>;+}++export async function getOutboundLinks(+ req: FastifyRequest<GetOutboundLinksRequest>,+ res: FastifyReply+) {+ const {+ startDate,+ endDate,+ timeZone,+ filters,+ pastMinutesStart,+ pastMinutesEnd,+ } = req.query;+ const site = req.params.site;+ const userHasAccessToSite = await getUserHasAccessToSitePublic(req, site);+ if (!userHasAccessToSite) {+ return res.status(403).send({ error: "Forbidden" });+ }++ const timeStatement = getTimeStatement(req.query);+ const filterStatement = filters ? getFilterStatement(filters) : "";++ const query = `+ SELECT+ toString(props) as properties,+ timestamp+ FROM events+ WHERE+ site_id = {siteId:Int32}+ AND type = 'outbound'+ ${timeStatement}+ ${filterStatement}+ ORDER BY timestamp DESC+ `;++ try {+ const result = await clickhouse.query({+ query,+ format: "JSONEachRow",+ query_params: {+ siteId: Number(site),+ },+ });++ interface RawOutboundEvent {+ properties: string;+ timestamp: string;+ }++ const rawData = await processResults<RawOutboundEvent>(result);++ const urlCounts = new Map<string, { count: number; lastClicked: string }>();++ rawData.forEach(event => {+ try {+ const props = JSON.parse(event.properties);+ const url = props.url;+ if (url) {+ const existing = urlCounts.get(url);+ if (existing) {+ existing.count++;+ // Keep the most recent timestamp+ if (event.timestamp > existing.lastClicked) {+ existing.lastClicked = event.timestamp;+ }+ } else {+ urlCounts.set(url, { count: 1, lastClicked: event.timestamp });+ }+ }+ } catch (e) {+ // Skip events with invalid JSON+ }+ });++ // Convert to response format+ const data: GetOutboundLinksResponse = Array.from(urlCounts.entries())+ .map(([url, { count, lastClicked }]) => ({ url, count, lastClicked }))+ .sort((a, b) => b.count - a.count); // Sort by count descending++ return res.send({ data });+ } catch (error) {+ console.error("Generated Query:", query);+ console.error("Error fetching outbound links:", error);+ return res.status(500).send({ error: "Failed to fetch outbound links" });+ }+}\ No newline at end of filediff --git a/server/src/api/analytics/getSessions.ts b/server/src/api/analytics/getSessions.tsindex 7cae02c8d..42b357565 100644--- a/server/src/api/analytics/getSessions.ts+++ b/server/src/api/analytics/getSessions.ts@@ -37,6 +37,7 @@ export type GetSessionsResponse = {pageviews: number;events: number;errors: number;+ outbound: number;}[];export interface GetSessionsRequest {@@ -94,7 +95,8 @@ export async function getSessions(argMaxIf(pathname, timestamp, type = 'pageview') AS exit_page,countIf(type = 'pageview') AS pageviews,countIf(type = 'custom_event') AS events,- countIf(type = 'error') AS errors+ countIf(type = 'error') AS errors,+ countIf(type = 'outbound') AS outboundFROM eventsWHEREsite_id = {siteId:Int32}diff --git a/server/src/index.ts b/server/src/index.tsindex 4656d1deb..8505cf29f 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -10,6 +10,7 @@ import { getAdminSites } from "./api/admin/getAdminSites.js";import { getEventNames } from "./api/analytics/events/getEventNames.js";import { getEventProperties } from "./api/analytics/events/getEventProperties.js";import { getEvents } from "./api/analytics/events/getEvents.js";+import { getOutboundLinks } from "./api/analytics/events/getOutboundLinks.js";import { createFunnel } from "./api/analytics/funnels/createFunnel.js";import { deleteFunnel } from "./api/analytics/funnels/deleteFunnel.js";import { getFunnel } from "./api/analytics/funnels/getFunnel.js";@@ -247,6 +248,7 @@ const ANALYTICS_ROUTES = ["/api/analytics/events/names/","/api/analytics/events/properties/","/api/events/",+ "/api/events/outbound/","/api/get-site","/api/performance/overview/","/api/performance/time-series/",@@ -333,6 +335,7 @@ server.delete("/api/goal/:goalId", deleteGoal);server.put("/api/goal/update", updateGoal);server.get("/api/events/names/:site", getEventNames);server.get("/api/events/properties/:site", getEventProperties);+server.get("/api/events/outbound/:site", getOutboundLinks);server.get("/api/org-event-count/:organizationId", getOrgEventCount);// Performance Analyticsdiff --git a/server/src/services/tracker/trackEvent.ts b/server/src/services/tracker/trackEvent.tsindex c01321129..2cf7e6899 100644--- a/server/src/services/tracker/trackEvent.ts+++ b/server/src/services/tracker/trackEvent.ts@@ -91,6 +91,51 @@ export const trackingPayloadSchema = z.discriminatedUnion("type", [ttfb: z.number().min(0).nullable().optional(),}).strict(),+ z+ .object({+ type: z.literal("outbound"),+ site_id: z.string().min(1),+ hostname: z.string().max(253).optional(),+ pathname: z.string().max(2048).optional(),+ querystring: z.string().max(2048).optional(),+ screenWidth: z.number().int().positive().optional(),+ screenHeight: z.number().int().positive().optional(),+ language: z.string().max(35).optional(),+ page_title: z.string().max(512).optional(),+ referrer: z.string().max(2048).optional(),+ event_name: z.string().max(256).optional(), // Empty for outbound events+ properties: z+ .string()+ .max(2048)+ .refine(+ (val) => {+ try {+ const parsed = JSON.parse(val);+ // Validate outbound-specific properties+ if (typeof parsed.url !== "string" || parsed.url.length === 0) return false;+ if (parsed.text && typeof parsed.text !== "string") return false;+ if (parsed.target && typeof parsed.target !== "string") return false;++ // Validate URL format+ try {+ new URL(parsed.url);+ } catch {+ return false;+ }++ return true;+ } catch (e) {+ return false;+ }+ },+ { message: "Properties must be valid JSON with outbound link fields (url required, text and target optional)" },+ ),+ user_id: z.string().max(255).optional(),+ api_key: z.string().max(35).optional(), // rb_ prefix + 32 hex chars+ ip_address: z.string().ip().optional(), // Custom IP for geolocation+ user_agent: z.string().max(512).optional(), // Custom user agent+ })+ .strict(),z.object({type: z.literal("error"),diff --git a/server/src/services/tracker/utils.ts b/server/src/services/tracker/utils.tsindex f9a3f35ee..f6d24ba3f 100644--- a/server/src/services/tracker/utils.ts+++ b/server/src/services/tracker/utils.ts@@ -84,7 +84,7 @@ export function clearSelfReferrer(referrer: string, hostname: string): string {// Create base tracking payload from requestexport function createBasePayload(request: FastifyRequest,- eventType: "pageview" | "custom_event" | "performance" | "error" = "pageview",+ eventType: "pageview" | "custom_event" | "performance" | "error" | "outbound" = "pageview",validatedBody: ValidatedTrackingPayload,): TotalTrackingPayload {// Use custom user agent if provided, otherwise fall back to header