Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

feat: add UTM tracking

Snazzah18342d0042c5
diff --git a/components/stats/index.tsx b/components/stats/index.tsx
index a3f774b4eb..cb87b37234 100644
--- a/components/stats/index.tsx
+++ b/components/stats/index.tsx
@@ -3,6 +3,7 @@ import Clicks from "@/components/stats/clicks";
import Toggle from "@/components/stats/toggle";
import Devices from "@/components/stats/devices";
import Locations from "@/components/stats/locations";
+import UTM from "@/components/stats/utm";
import useSWR from "swr";
import { fetcher } from "@/lib/utils";
import { useRouter } from "next/router";
@@ -44,6 +45,7 @@ export default function Stats({
<div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
<Locations data={data!} />
<Devices data={data!} />
+ <UTM data={data!} />
</div>
</div>
</div>
diff --git a/components/stats/utm.tsx b/components/stats/utm.tsx
new file mode 100644
index 0000000000..e6768f54f4
--- /dev/null
+++ b/components/stats/utm.tsx
@@ -0,0 +1,94 @@
+import { AnimatePresence, motion } from 'framer-motion';
+import { UIEvent, useMemo, useState } from 'react';
+
+import BadgeSelect from '@/components/shared/badge-select';
+import { processUTMData, StatsProps, UTMTabs } from '@/lib/stats';
+import { nFormatter } from '@/lib/utils';
+
+import { LoadingDots } from "@/components/shared/icons";
+
+export default function UTM({ data: rawData }: { data: StatsProps }) {
+ const [tab, setTab] = useState<UTMTabs>('source / medium');
+ const data = {
+ ...rawData,
+ utmData: useMemo(() => {
+ if (rawData?.locationData) {
+ return processUTMData(rawData.utmData, tab);
+ } else {
+ return null;
+ }
+ }, [rawData, tab])
+ };
+
+ const [scrolled, setScrolled] = useState(false);
+
+ const handleScroll = (event: UIEvent<HTMLElement>) => {
+ if (event.currentTarget.scrollTop > 0) {
+ setScrolled(true);
+ } else {
+ setScrolled(false);
+ }
+ };
+
+ return (
+ <div
+ className="relative bg-white px-7 py-5 shadow-lg rounded-lg border border-gray-100 h-[420px] overflow-scroll scrollbar-hide"
+ onScroll={handleScroll}
+ >
+ <div className="mb-5 flex justify-between">
+ <h1 className="text-xl font-semibold">UTM</h1>
+ <BadgeSelect
+ options={['source / medium', 'source', 'medium']}
+ selected={tab}
+ // @ts-ignore
+ selectAction={setTab}
+ />
+ </div>
+ <div className={data.utmData && data.utmData.length > 0 ? 'grid gap-4' : 'h-[300px] flex justify-center items-center'}>
+ {data.utmData ? (
+ data.utmData.length > 0 ? (
+ data.utmData.map(({ display, count }, idx) => (
+ <div key={idx} className="flex justify-between items-center">
+ <div className="relative flex items-center z-10 w-full max-w-[calc(100%-3rem)]">
+ <span className="flex space-x-2 px-2 items-center z-10">
+ <p className="text-gray-800 text-sm">{display}</p>
+ </span>
+ <motion.div
+ style={{
+ width: `${(count / data.totalClicks) * 100}%`
+ }}
+ className="bg-blue-100 absolute h-8 origin-left"
+ transition={{ ease: 'easeOut', duration: 0.3 }}
+ initial={{ transform: 'scaleX(0)' }}
+ animate={{ transform: 'scaleX(1)' }}
+ />
+ </div>
+ <p className="text-gray-600 text-sm z-10">{nFormatter(count)}</p>
+ </div>
+ ))
+ ) : (
+ <p className="text-gray-600 text-sm">No data available</p>
+ )
+ ) : (
+ <LoadingDots color="#71717A" />
+ )}
+ </div>
+ <AnimatePresence>
+ {data.utmData && data.utmData.length > 9 && !scrolled && (
+ <motion.div
+ initial={{ opacity: 0, y: 50 }}
+ animate={{
+ opacity: 1,
+ y: 0,
+ transition: { type: 'linear', duration: 0.2 }
+ }}
+ exit={{ opacity: 0, y: 50, transition: { duration: 0 } }}
+ className="absolute w-full h-8 flex justify-center items-center bottom-0 left-0 right-0 bg-gradient-to-b from-white to-gray-100 text-sm text-gray-500"
+ >
+ Show more
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </div>
+ );
+}
\ No newline at end of file
diff --git a/lib/middleware/link.ts b/lib/middleware/link.ts
index b15b3c2015..321f38d5d0 100644
--- a/lib/middleware/link.ts
+++ b/lib/middleware/link.ts
@@ -15,7 +15,7 @@ export default async function LinkMiddleware(
ev: NextFetchEvent
) {
const url = req.nextUrl.clone();
- const { hostname, key } = parse(req);
+ const { hostname, key, query } = parse(req);
if (!hostname || !key) {
return NextResponse.next();
@@ -39,7 +39,7 @@ export default async function LinkMiddleware(
if (target) {
const isBot = detectBot(req);
- ev.waitUntil(recordClick(hostname, req, key)); // increment click count
+ ev.waitUntil(recordClick(hostname, req, query, key)); // increment click count
if (image && description && isBot) {
// rewrite to proxy page (dub.sh/proxy/[domain]/[key])
diff --git a/lib/middleware/utils.ts b/lib/middleware/utils.ts
index ed3f40c8c0..a31cdf083f 100644
--- a/lib/middleware/utils.ts
+++ b/lib/middleware/utils.ts
@@ -6,7 +6,7 @@ export const parse = (req: NextRequest) => {
if (HOME_HOSTNAMES.has(hostname)) hostname = "dub.sh";
const path = req.nextUrl.pathname;
const key = path.split("/")[1];
- return { hostname, path, key };
+ return { hostname, path, key, query: req.nextUrl.searchParams };
};
export const detectBot = (req: NextRequest) => {
diff --git a/lib/stats.ts b/lib/stats.ts
index 82245a0054..fc26fef1b0 100644
--- a/lib/stats.ts
+++ b/lib/stats.ts
@@ -6,6 +6,13 @@ export interface RawStatsProps {
ua: any;
referer: string;
timestamp: number;
+ utm?: {
+ source?: string;
+ medium?: string;
+ campaign?: string;
+ content?: string;
+ tags?: string;
+ };
}
export interface StatsProps {
@@ -20,6 +27,7 @@ export interface StatsProps {
region: string;
}[];
deviceData: { device: string; browser: string; os: string; bot: string }[];
+ utmData: { source: string; medium: string }[];
}
export type IntervalProps = "1h" | "24h" | "7d" | "30d";
@@ -140,6 +148,14 @@ export function processData(
};
});
+ const utmData = data.map(({ utm }) => {
+ const { source, medium } = utm || {};
+ return {
+ source: source ?? '(none)',
+ medium: medium ?? '(none)'
+ };
+ });
+
return {
key,
interval: interval || "24h",
@@ -147,6 +163,7 @@ export function processData(
clicksData,
locationData,
deviceData,
+ utmData
};
}
@@ -223,6 +240,32 @@ export const processDeviceData = (
.sort((a, b) => b.count - a.count);
};
+export interface UTMStatsProps {
+ display: string;
+ count: number;
+}
+
+export type UTMTabs = 'source / medium' | 'source' | 'medium';
+
+export const processUTMData = (data: StatsProps['utmData'], tab: UTMTabs): UTMStatsProps[] => {
+ const results =
+ data && data.length > 0
+ ? data.reduce<Record<string, number>>((acc, d) => {
+ const currentVal = tab === 'source / medium' ? `${d.source} / ${d.medium}` : d[tab];
+ const count = acc[currentVal] || 0;
+ acc[currentVal] = count + 1;
+ return acc;
+ }, {})
+ : {};
+
+ return Object.entries(results)
+ .map(([display, count]) => ({
+ display,
+ count
+ }))
+ .sort((a, b) => b.count - a.count);
+};
+
export const dummyData: StatsProps = {
key: "test",
interval: "24h",
@@ -235,6 +278,8 @@ export const dummyData: StatsProps = {
locationData: null,
// @ts-ignore
deviceData: null,
+ // @ts-ignore
+ utmData: null
};
export const handleDeviceEdgeCases = (ua: string): string => {
diff --git a/lib/upstash.ts b/lib/upstash.ts
index 6c80be7388..af3cde9b30 100644
--- a/lib/upstash.ts
+++ b/lib/upstash.ts
@@ -77,6 +77,7 @@ export async function checkIfKeyExists(hostname: string, key: string) {
return await redis.hexists(`${hostname}:links`, key);
}
+
/**
* Recording clicks with geo, ua, referer and timestamp data
* If key is not specified, record click as the root click
@@ -84,8 +85,12 @@ export async function checkIfKeyExists(hostname: string, key: string) {
export async function recordClick(
hostname: string,
req: NextRequest,
+ query: URLSearchParams,
key?: string
) {
+ const truncate = (v: null | string) =>
+ !v ? undefined : v.slice(0, 256);
+
return await redis.zadd(
key ? `${hostname}:clicks:${key}` : `${hostname}:root:clicks`,
{
@@ -95,6 +100,16 @@ export async function recordClick(
ua: userAgent(req),
referer: req.headers.get("referer"),
timestamp: Date.now(),
+ utm:
+ !query || !['utm_source', 'utm_medium', 'utm_campaign', 'utm_content', 'utm_term'].map((p) => query.has(p)).includes(true)
+ ? undefined
+ : {
+ source: truncate(query.get('utm_source')),
+ medium: truncate(query.get('utm_medium')),
+ compaign: truncate(query.get('utm_campaign')),
+ content: truncate(query.get('utm_content')),
+ term: truncate(query.get('utm_term'))
+ }
},
}
);