The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Project-level Analytics
Steven Tey7478c062fdf8
diff --git a/apps/web/app/api/stats/[endpoint]/route.ts b/apps/web/app/api/stats/[endpoint]/route.tsindex b3e19a2cdc..3af2fa1c15 100644--- a/apps/web/app/api/stats/[endpoint]/route.ts+++ b/apps/web/app/api/stats/[endpoint]/route.ts@@ -4,12 +4,13 @@ import { NextResponse } from "next/server";// GET /api/stats/[endpoint] – get stats for a specific endpointexport const GET = withAuth(- async ({ params, searchParams }) => {+ async ({ params, searchParams, project }) => {const { endpoint } = params;const { domain, key, interval } = searchParams;const response = await getStats({- domain,+ domain:+ domain || project?.domains?.map((d) => d.slug).join(",") || "dub.sh",key,endpoint,interval,diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/auth.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/auth.tsxindex 61d13478f9..5b993b93f7 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/auth.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/auth.tsx@@ -4,28 +4,21 @@ import useDomains from "@/lib/swr/use-domains";import useProject from "@/lib/swr/use-project";import LinkNotFound from "@/ui/links/link-not-found";import ProjectExceededUsage from "@/ui/projects/project-exceeded-usage";-import { useRouter, useSearchParams } from "next/navigation";-import { ReactNode, useEffect } from "react";+import { useSearchParams } from "next/navigation";+import { ReactNode } from "react";export default function AnalyticsAuth({ children }: { children: ReactNode }) {- const { slug, exceededUsage } = useProject();+ const { exceededUsage } = useProject();if (exceededUsage) {return <ProjectExceededUsage />;}- const router = useRouter();- const { domains, primaryDomain, loading } = useDomains();+ const { domains, loading } = useDomains();const searchParams = useSearchParams();const domain = searchParams?.get("domain");- // TODO: remove this after we support project level analytics- useEffect(() => {- if (!domain) {- router.replace(`/${slug}/analytics?domain=${primaryDomain}`);- }- }, [primaryDomain, router, domain]);-if (!loading && domain && !domains?.find((d) => d.slug === domain)) {return <LinkNotFound />;}+return children;}diff --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.tsindex 88af5e0ea2..13f15b692f 100644--- a/apps/web/lib/auth/index.ts+++ b/apps/web/lib/auth/index.ts@@ -210,6 +210,11 @@ export const withAuth =role: true,},},+ domains: {+ select: {+ slug: true,+ },+ },},}),linkId &&@@ -232,15 +237,7 @@ export const withAuth =// prevent unauthorized access to domains that don't belong to the projectif (domain) {- const domainProjectId = await prisma.domain.findUnique({- where: {- slug: domain,- },- select: {- projectId: true,- },- });- if (domainProjectId?.projectId !== project.id) {+ if (!project.domains?.find((d) => d.slug === domain)) {return new Response("Domain not found.", {status: 404,headers,diff --git a/apps/web/lib/stats.ts b/apps/web/lib/stats.tsindex a5371bd474..8571eae93d 100644--- a/apps/web/lib/stats.ts+++ b/apps/web/lib/stats.ts@@ -64,6 +64,7 @@ export type DeviceTabs = "device" | "browser" | "os" | "ua";const VALID_TINYBIRD_ENDPOINTS = new Set(["timeseries","clicks",+ "top_links","country","city","device",@@ -116,7 +117,7 @@ export const getStats = async ({}let url = new URL(- `https://api.us-east.tinybird.co/v0/pipes/${endpoint}.json`,+ `https://api.us-east.tinybird.co/v0/pipes/${endpoint}_new.json`,);url.searchParams.append("domain", domain);url.searchParams.append("key", decodeURIComponent(key));diff --git a/apps/web/ui/links/link-card.tsx b/apps/web/ui/links/link-card.tsxindex d53ab2184e..d379879905 100644--- a/apps/web/ui/links/link-card.tsx+++ b/apps/web/ui/links/link-card.tsx@@ -243,7 +243,6 @@ export default function LinkCard({src={`${GOOGLE_FAVICON_URL}${apexDomain}`}alt={apexDomain}className="h-8 w-8 rounded-full sm:h-10 sm:w-10"- unoptimizedwidth={20}height={20}/>diff --git a/apps/web/ui/stats/bar-list.tsx b/apps/web/ui/stats/bar-list.tsxindex 3548195802..e77842a8ab 100644--- a/apps/web/ui/stats/bar-list.tsx+++ b/apps/web/ui/stats/bar-list.tsx@@ -5,6 +5,7 @@ import { cn, nFormatter } from "@dub/utils";import { motion } from "framer-motion";import Fuse from "fuse.js";import { Search } from "lucide-react";+import Link from "next/link";import { ReactNode, useMemo, useState } from "react";export default function BarList({@@ -16,8 +17,9 @@ export default function BarList({}: {tab: string;data: {- icon: ReactNode;+ icon?: ReactNode;title: string;+ href?: string;clicks: number;}[];totalClicks: number;@@ -45,28 +47,50 @@ export default function BarList({const bars = (<div className="grid gap-4">- {filteredData.map(({ icon, title, clicks }, idx) => (- <div key={idx} className="flex items-center justify-between">- <div className="relative z-10 flex w-full max-w-[calc(100%-3rem)] items-center">- <span className="z-10 flex items-center space-x-2 px-2">- {icon}- <p className="text-sm text-gray-800">{title}</p>- </span>- <motion.div- style={{- width: `${(clicks / (totalClicks || 0)) * 100}%`,- }}- className={cn("absolute h-8 origin-left", barBackground)}- transition={{ ease: "easeOut", duration: 0.3 }}- initial={{ transform: "scaleX(0)" }}- animate={{ transform: "scaleX(1)" }}- />+ {filteredData.map(({ icon, title, href, clicks }, idx) => {+ const bar = (+ <div key={idx} className="group flex items-center justify-between">+ <div className="relative z-10 flex w-full max-w-[calc(100%-3rem)] items-center">+ <span className="z-10 flex items-center space-x-2 px-2">+ {icon}+ <p+ className={cn(+ "text-sm text-gray-800",+ href && "underline-offset-4 group-hover:underline",+ )}+ >+ {title}+ </p>+ </span>+ <motion.div+ style={{+ width: `${(clicks / (totalClicks || 0)) * 100}%`,+ }}+ className={cn(+ "absolute h-8 origin-left rounded-sm",+ barBackground,+ )}+ transition={{ ease: "easeOut", duration: 0.3 }}+ initial={{ transform: "scaleX(0)" }}+ animate={{ transform: "scaleX(1)" }}+ />+ </div>+ <NumberTooltip value={clicks}>+ <p className="z-10 text-sm text-gray-600">{nFormatter(clicks)}</p>+ </NumberTooltip></div>- <NumberTooltip value={clicks}>- <p className="z-10 text-sm text-gray-600">{nFormatter(clicks)}</p>- </NumberTooltip>- </div>- ))}+ );++ if (href) {+ return (+ <Link key={idx} href={href} replace scroll={false}>+ {bar}+ </Link>+ );+ }++ return bar;+ })}</div>);diff --git a/apps/web/ui/stats/devices.tsx b/apps/web/ui/stats/devices.tsxindex 5cc93524dd..257cc2e823 100644--- a/apps/web/ui/stats/devices.tsx+++ b/apps/web/ui/stats/devices.tsx@@ -76,7 +76,7 @@ export default function Devices() {{!modal && data && data.length > 9 && (<buttononClick={() => setShowModal(true)}- className="absolute inset-x-0 bottom-4 z-10 mx-auto flex max-w-fit items-center space-x-2 rounded-md bg-white px-4 py-1.5 text-gray-500 transition-all hover:text-gray-800 active:scale-95"+ className="absolute inset-x-0 bottom-4 z-10 mx-auto flex w-full items-center justify-center space-x-2 rounded-md bg-gradient-to-b from-transparent to-white py-2 text-gray-500 transition-all hover:text-gray-800 active:scale-95"><Maximize className="h-4 w-4" /><p className="text-xs font-semibold uppercase">View all</p>diff --git a/apps/web/ui/stats/index.tsx b/apps/web/ui/stats/index.tsxindex 96fbdfd7b3..28129cb578 100644--- a/apps/web/ui/stats/index.tsx+++ b/apps/web/ui/stats/index.tsx@@ -17,6 +17,7 @@ import {} from "next/navigation";import { createContext, useMemo } from "react";import Clicks from "./clicks";+import TopLinks from "./top-links";import Devices from "./devices";import Locations from "./locations";import Referer from "./referer";@@ -28,8 +29,8 @@ import { fetcher } from "@dub/utils";export const StatsContext = createContext<{basePath: string;baseApiPath: string;- domain: string;- key: string;+ domain?: string;+ key?: string;queryString: string;interval: string;totalClicks?: number;@@ -89,7 +90,7 @@ export default function Stats({const queryString = useMemo(() => {return new URLSearchParams({- domain: domain!,+ ...(domain && { domain }),...(key && { key }),...(interval && { interval }),}).toString();@@ -100,14 +101,16 @@ export default function Stats({fetcher,);+ const isPublicStatsPage = basePath.startsWith("/stats");+return (<StatsContext.Providervalue={{basePath, // basePath for the page (e.g. /stats/[key], /links/[key], /[slug]/[domain]/[key])baseApiPath, // baseApiPath for the API (e.g. /api/edge/links/[key]/stats)queryString,- domain: domain!, // domain for the link (e.g. dub.sh, stey.me, etc.)- key: key ? decodeURIComponent(key) : "", // link key (e.g. github, weathergpt, etc.)+ domain: domain || undefined, // domain for the link (e.g. dub.sh, stey.me, etc.)+ key: key ? decodeURIComponent(key) : undefined, // link key (e.g. github, weathergpt, etc.)interval, // time interval (e.g. 24h, 7d, 30d, etc.)totalClicks, // total clicks for the linkmodal, // whether or not this is a modal@@ -128,9 +131,10 @@ export default function Stats({<Clicks /><div className="grid grid-cols-1 gap-5 md:grid-cols-2"><Locations />+ {!isPublicStatsPage && <TopLinks />}<Devices /><Referer />- <Feedback />+ {isPublicStatsPage && <Feedback />}</div></div></div>diff --git a/apps/web/ui/stats/locations.tsx b/apps/web/ui/stats/locations.tsxindex a282356b8b..a8e810bf67 100644--- a/apps/web/ui/stats/locations.tsx+++ b/apps/web/ui/stats/locations.tsx@@ -80,7 +80,7 @@ export default function Locations() {{!modal && data && data.length > 9 && (<buttononClick={() => setShowModal(true)}- className="absolute inset-x-0 bottom-4 z-10 mx-auto flex max-w-fit items-center space-x-2 rounded-md bg-white px-4 py-1.5 text-gray-500 transition-all hover:text-gray-800 active:scale-95"+ className="absolute inset-x-0 bottom-4 z-10 mx-auto flex w-full items-center justify-center space-x-2 rounded-md bg-gradient-to-b from-transparent to-white py-2 text-gray-500 transition-all hover:text-gray-800 active:scale-95"><Maximize className="h-4 w-4" /><p className="text-xs font-semibold uppercase">View all</p>diff --git a/apps/web/ui/stats/referer.tsx b/apps/web/ui/stats/referer.tsxindex d274579c35..cd90d96387 100644--- a/apps/web/ui/stats/referer.tsx+++ b/apps/web/ui/stats/referer.tsx@@ -77,7 +77,7 @@ export default function Referer() {{!modal && data && data.length > 9 && (<buttononClick={() => setShowModal(true)}- className="absolute inset-x-0 bottom-4 z-10 mx-auto flex max-w-fit items-center space-x-2 rounded-md bg-white px-4 py-1.5 text-gray-500 transition-all hover:text-gray-800 active:scale-95"+ className="absolute inset-x-0 bottom-4 z-10 mx-auto flex w-full items-center justify-center space-x-2 rounded-md bg-gradient-to-b from-transparent to-white py-2 text-gray-500 transition-all hover:text-gray-800 active:scale-95"><Maximize className="h-4 w-4" /><p className="text-xs font-semibold uppercase">View all</p>diff --git a/apps/web/ui/stats/toggle.tsx b/apps/web/ui/stats/toggle.tsxindex 868ed504d1..adb2e40e2d 100644--- a/apps/web/ui/stats/toggle.tsx+++ b/apps/web/ui/stats/toggle.tsx@@ -42,23 +42,23 @@ export default function Toggle() {return (<div- className={cn("sticky top-[6.9rem] z-10 mb-5 bg-gray-50 py-3 md:py-5", {+ className={cn("sticky top-[6.85rem] z-10 mb-5 bg-gray-50 py-3 md:py-5", {"top-14": isPublicStatsPage,"top-6 md:top-0": modal,"shadow-md": scrolled && !modal,})}><div className="mx-auto flex h-20 max-w-4xl flex-col items-center justify-between space-y-3 px-2.5 md:h-10 md:flex-row md:space-y-0 lg:px-0">- {domain ? (+ {domain && key ? (<aclassName="group flex text-lg font-semibold text-gray-800 md:text-xl"- href={linkConstructor({ key, domain })}+ href={linkConstructor({ domain, key })}target="_blank"rel="noreferrer">{linkConstructor({- key,domain: punycode.toUnicode(domain),+ key,pretty: true,})}<ExpandingArrow className="h-5 w-5" />@@ -113,12 +113,13 @@ export default function Toggle() {isPublicStatsPage? `interval=${value}`: `${new URLSearchParams({- domain: domain!,+ ...(domain && { domain }),...(key && key !== "_root" && { key }),interval: value,}).toString()}`}`}replace+ scroll={false}className="flex w-full items-center justify-between space-x-2 rounded-md p-2 hover:bg-gray-100 active:bg-gray-200"><p className="text-sm">{display}</p>@@ -157,7 +158,14 @@ export default function Toggle() {const SharePopover = () => {const [openSharePopover, setopenSharePopoverPopover] = useState(false);- const { baseApiPath, queryString, domain, key } = useContext(StatsContext);+ const { baseApiPath, queryString, domain, key } = useContext(+ StatsContext,+ ) as {+ baseApiPath: string;+ queryString: string;+ domain: string;+ key: string; // coerce to string since <SharePopover is not shown if key is undefined)+ };const { data: { publicStats } = {} } = useSWR<{ publicStats: boolean }>(`${baseApiPath}?${queryString}`,diff --git a/apps/web/ui/stats/top-links.tsx b/apps/web/ui/stats/top-links.tsxnew file mode 100644index 0000000000..5bf839322d--- /dev/null+++ b/apps/web/ui/stats/top-links.tsx@@ -0,0 +1,86 @@+import { BlurImage } from "@/ui/shared/blur-image";+import { LoadingSpinner, Modal } from "@dub/ui";+import { GOOGLE_FAVICON_URL, fetcher, linkConstructor } from "@dub/utils";+import { Link2, Maximize } from "lucide-react";+import { useContext, useState } from "react";+import useSWR from "swr";+import { StatsContext } from ".";+import BarList from "./bar-list";++export default function TopLinks() {+ const { basePath, baseApiPath, queryString, totalClicks, interval, modal } =+ useContext(StatsContext);++ const { data } = useSWR<{ domain: string; key: string; clicks: number }[]>(+ `${baseApiPath}/top_links?${queryString}`,+ fetcher,+ );++ const [showModal, setShowModal] = useState(false);++ const barList = (limit?: number) => (+ <BarList+ tab="Top Links"+ data={+ data?.map((d) => ({+ title: linkConstructor({+ domain: d.domain,+ key: d.key,+ pretty: true,+ }),+ href: `${basePath}?${new URLSearchParams({+ domain: d.domain,+ key: d.key,+ interval,+ }).toString()}`,+ clicks: d.clicks,+ })) || []+ }+ totalClicks={totalClicks || 0}+ barBackground="bg-blue-100"+ {...(limit && { limit })}+ />+ );++ return (+ <>+ <Modal+ showModal={showModal}+ setShowModal={setShowModal}+ className="max-w-lg"+ >+ <div className="border-b border-gray-200 px-6 py-4">+ <h1 className="text-xl font-semibold">Top Links</h1>+ </div>+ {barList()}+ </Modal>+ <div className="scrollbar-hide relative z-0 h-[400px] overflow-scroll border border-gray-200 bg-white px-7 py-5 sm:rounded-lg sm:border-gray-100 sm:shadow-lg">+ <div className="mb-5 flex">+ <h1 className="text-xl font-semibold">Top Links</h1>+ </div>+ {data ? (+ data.length > 0 ? (+ barList(9)+ ) : (+ <div className="flex h-[300px] items-center justify-center">+ <p className="text-sm text-gray-600">No data available</p>+ </div>+ )+ ) : (+ <div className="flex h-[300px] items-center justify-center">+ <LoadingSpinner />+ </div>+ )}+ {!modal && data && data.length > 9 && (+ <button+ onClick={() => setShowModal(true)}+ className="absolute inset-x-0 bottom-4 z-10 mx-auto flex w-full items-center justify-center space-x-2 rounded-md bg-gradient-to-b from-transparent to-white py-2 text-gray-500 transition-all hover:text-gray-800 active:scale-95"+ >+ <Maximize className="h-4 w-4" />+ <p className="text-xs font-semibold uppercase">View all</p>+ </button>+ )}+ </div>+ </>+ );+}