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.

Add zod-bird for click analytics

Steven Teyf3c9bcc21551
diff --git a/apps/web/app/api/admin/analytics/[endpoint]/route.ts b/apps/web/app/api/admin/analytics/[endpoint]/route.ts
deleted file mode 100644
index ff5c41cb5d..0000000000
--- a/apps/web/app/api/admin/analytics/[endpoint]/route.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { getAnalytics } from "@/lib/analytics";
-import { withAdmin } from "@/lib/auth";
-import {
- analyticsEndpointSchema,
- getAnalyticsQuerySchema,
-} from "@/lib/zod/schemas";
-import { NextResponse } from "next/server";
-
-// GET /api/admin/analytics/[endpoint] – get analytics for a specific endpoint
-export const GET = withAdmin(async ({ params, searchParams }) => {
- const { endpoint } = analyticsEndpointSchema.parse(params);
- const parsedParams = getAnalyticsQuerySchema.parse(searchParams);
-
- const response = await getAnalytics({
- endpoint,
- ...parsedParams,
- });
- return NextResponse.json(response);
-});
diff --git a/apps/web/app/api/admin/analytics/clicks/route.ts b/apps/web/app/api/admin/analytics/clicks/route.ts
new file mode 100644
index 0000000000..fb114e84fc
--- /dev/null
+++ b/apps/web/app/api/admin/analytics/clicks/route.ts
@@ -0,0 +1,13 @@
+import { getClicks } from "@/lib/analytics";
+import { withAdmin } from "@/lib/auth";
+import { clickAnalyticsQuerySchema } from "@/lib/zod/schemas";
+import { NextResponse } from "next/server";
+
+// GET /api/admin/analytics/[endpoint] – get analytics for a specific endpoint
+export const GET = withAdmin(async ({ searchParams }) => {
+ const parsedParams = clickAnalyticsQuerySchema.parse(searchParams);
+
+ const response = await getClicks(parsedParams);
+
+ return NextResponse.json(response);
+});
diff --git a/apps/web/app/api/analytics/[endpoint]/route.ts b/apps/web/app/api/analytics/[endpoint]/route.ts
deleted file mode 100644
index 2659f9c7ea..0000000000
--- a/apps/web/app/api/analytics/[endpoint]/route.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { getAnalytics, validDateRangeForPlan } from "@/lib/analytics";
-import { withWorkspace } from "@/lib/auth";
-import { getDomainViaEdge } from "@/lib/planetscale";
-import {
- analyticsEndpointSchema,
- getAnalyticsQuerySchema,
-} from "@/lib/zod/schemas";
-import { NextResponse } from "next/server";
-
-// GET /api/analytics/[endpoint] – get analytics for a specific endpoint
-export const GET = withWorkspace(
- async ({ params, searchParams, workspace, link }) => {
- const { endpoint } = analyticsEndpointSchema.parse(params);
- const parsedParams = getAnalyticsQuerySchema.parse(searchParams);
-
- let { domain, key, interval, start, end } = parsedParams;
-
- // swap start and end if start is greater than end
- if (start && end && start > end) {
- [start, end] = [end, start];
- }
-
- validDateRangeForPlan({
- plan: workspace.plan,
- interval,
- start,
- end,
- throwError: true,
- });
-
- const linkId = link
- ? link.id
- : domain && key === "_root"
- ? await getDomainViaEdge(domain).then((d) => d?.id)
- : null;
-
- const response = await getAnalytics({
- workspaceId: workspace.id,
- ...(linkId && { linkId }),
- endpoint,
- ...parsedParams,
- start,
- end,
- });
-
- return NextResponse.json(response);
- },
- {
- needNotExceededClicks: true,
- },
-);
diff --git a/apps/web/app/api/analytics/clicks/route.ts b/apps/web/app/api/analytics/clicks/route.ts
new file mode 100644
index 0000000000..895ea6488f
--- /dev/null
+++ b/apps/web/app/api/analytics/clicks/route.ts
@@ -0,0 +1,39 @@
+import { getClicks, validDateRangeForPlan } from "@/lib/analytics";
+import { withWorkspace } from "@/lib/auth";
+import { getDomainViaEdge } from "@/lib/planetscale";
+import { clickAnalyticsQuerySchema } from "@/lib/zod/schemas";
+import { NextResponse } from "next/server";
+
+// GET /api/analytics/clicks – get click analytics
+export const GET = withWorkspace(
+ async ({ searchParams, workspace, link }) => {
+ const parsedProps = clickAnalyticsQuerySchema.parse(searchParams);
+
+ let { domain, key, interval, start, end } = parsedProps;
+
+ validDateRangeForPlan({
+ plan: workspace.plan,
+ interval,
+ start,
+ end,
+ throwError: true,
+ });
+
+ const linkId = link
+ ? link.id
+ : domain && key === "_root"
+ ? await getDomainViaEdge(domain).then((d) => d?.id)
+ : null;
+
+ const response = await getClicks({
+ ...parsedProps,
+ ...(linkId && { linkId }),
+ workspaceId: workspace.id,
+ });
+
+ return NextResponse.json(response);
+ },
+ {
+ needNotExceededClicks: true,
+ },
+);
diff --git a/apps/web/app/api/analytics/edge/[endpoint]/route.ts b/apps/web/app/api/analytics/edge/[endpoint]/route.ts
index 4861045a34..9e5d751841 100644
--- a/apps/web/app/api/analytics/edge/[endpoint]/route.ts
+++ b/apps/web/app/api/analytics/edge/[endpoint]/route.ts
@@ -1,4 +1,4 @@
-import { getAnalytics } from "@/lib/analytics";
+import { getClicks } from "@/lib/analytics";
import {
DubApiError,
exceededLimitError,
@@ -8,7 +8,7 @@ import { getDomainOrLink, getWorkspaceViaEdge } from "@/lib/planetscale";
import { ratelimit } from "@/lib/upstash";
import {
analyticsEndpointSchema,
- getAnalyticsEdgeQuerySchema,
+ clickAnalyticsQuerySchema,
} from "@/lib/zod/schemas";
import { DUB_DEMO_LINKS, DUB_WORKSPACE_ID, getSearchParams } from "@dub/utils";
import { ipAddress } from "@vercel/edge";
@@ -23,7 +23,7 @@ export const GET = async (
try {
const searchParams = getSearchParams(req.url);
const { endpoint } = analyticsEndpointSchema.parse(params);
- const parsedParams = getAnalyticsEdgeQuerySchema.parse(searchParams);
+ const parsedParams = clickAnalyticsQuerySchema.parse(searchParams);
const { domain, key, interval } = parsedParams;
let link;
@@ -85,7 +85,7 @@ export const GET = async (
}
}
- const response = await getAnalytics({
+ const response = await getClicks({
// workspaceId can be undefined (for public links that haven't been claimed/synced to a workspace)
...(link.projectId && { workspaceId: link.projectId }),
linkId: link.id,
diff --git a/apps/web/app/api/analytics/export/route.ts b/apps/web/app/api/analytics/export/route.ts
index c0337a1587..f2a8463a5b 100644
--- a/apps/web/app/api/analytics/export/route.ts
+++ b/apps/web/app/api/analytics/export/route.ts
@@ -1,9 +1,9 @@
-import { VALID_TINYBIRD_ENDPOINTS, getAnalytics } from "@/lib/analytics";
+import { VALID_TINYBIRD_ENDPOINTS, getClicks } from "@/lib/analytics";
import { DubApiError } from "@/lib/api/errors";
import { withWorkspace } from "@/lib/auth";
import { getDomainViaEdge } from "@/lib/planetscale";
import prisma from "@/lib/prisma";
-import { getAnalyticsQuerySchema } from "@/lib/zod/schemas";
+import { clickAnalyticsQuerySchema } from "@/lib/zod/schemas";
import { linkConstructor } from "@dub/utils";
import { json2csv } from "json-2-csv";
import JSZip from "jszip";
@@ -23,7 +23,7 @@ const convertToCSV = (data: object[]) => {
// GET /api/analytics/[endpoint]/export – get export data for analytics
export const GET = withWorkspace(
async ({ searchParams, workspace, link }) => {
- const parsedParams = getAnalyticsQuerySchema.parse(searchParams);
+ const parsedParams = clickAnalyticsQuerySchema.parse(searchParams);
const { domain, key, interval } = parsedParams;
// return 403 if project is on the free plan and interval is 90d or all
@@ -52,9 +52,9 @@ export const GET = withWorkspace(
// since this is just a single link
if (linkId) return;
- const data = await getAnalytics({
+ const data = await getClicks({
workspaceId: workspace.id,
- endpoint: "top_links",
+ groupBy: "top_links",
...parsedParams,
});
@@ -124,10 +124,10 @@ export const GET = withWorkspace(
// we're not fetching top URLs data if linkId is not defined
if (endpoint === "top_urls" && !linkId) return;
- const response = await getAnalytics({
+ const response = await getClicks({
workspaceId: workspace.id,
...(linkId && { linkId }),
- endpoint,
+ groupBy: endpoint,
...parsedParams,
});
if (!response || response.length === 0) return;
diff --git a/apps/web/app/api/cron/usage/utils.ts b/apps/web/app/api/cron/usage/utils.ts
index ef98fb464f..3b796c1f44 100644
--- a/apps/web/app/api/cron/usage/utils.ts
+++ b/apps/web/app/api/cron/usage/utils.ts
@@ -1,4 +1,4 @@
-import { getAnalytics } from "@/lib/analytics";
+import { getClicks } from "@/lib/analytics";
import { limiter, qstash, sendLimitEmail } from "@/lib/cron";
import prisma from "@/lib/prisma";
import { WorkspaceProps } from "@/lib/types";
@@ -115,9 +115,9 @@ export const updateUsage = async (skip?: number) => {
) {
const topLinks =
workspace.usage > 0
- ? await getAnalytics({
+ ? await getClicks({
workspaceId: workspace.id,
- endpoint: "top_links",
+ groupBy: "top_links",
interval: "30d",
root: false,
}).then(async (data) => {
diff --git a/apps/web/app/api/domains/[domain]/transfer/route.ts b/apps/web/app/api/domains/[domain]/transfer/route.ts
index 86224467f3..bb0130db2a 100644
--- a/apps/web/app/api/domains/[domain]/transfer/route.ts
+++ b/apps/web/app/api/domains/[domain]/transfer/route.ts
@@ -1,4 +1,4 @@
-import { getAnalytics } from "@/lib/analytics";
+import { getClicks } from "@/lib/analytics";
import { setRootDomain } from "@/lib/api/domains";
import { DubApiError } from "@/lib/api/errors";
import { withWorkspace } from "@/lib/auth";
@@ -88,10 +88,9 @@ export const POST = withWorkspace(
});
}
- const totalLinkClicks = await getAnalytics({
+ const totalLinkClicks = await getClicks({
domain,
workspaceId: workspace.id,
- endpoint: "clicks",
interval: "30d",
root: false,
});
diff --git a/apps/web/app/api/links/[linkId]/transfer/route.ts b/apps/web/app/api/links/[linkId]/transfer/route.ts
index a8ecbafcb3..aa9a793abd 100644
--- a/apps/web/app/api/links/[linkId]/transfer/route.ts
+++ b/apps/web/app/api/links/[linkId]/transfer/route.ts
@@ -1,4 +1,4 @@
-import { getAnalytics } from "@/lib/analytics";
+import { getClicks } from "@/lib/analytics";
import { DubApiError } from "@/lib/api/errors";
import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
@@ -67,9 +67,8 @@ export const POST = withWorkspace(
});
}
- const linkClicks = await getAnalytics({
+ const linkClicks = await getClicks({
linkId: link.id,
- endpoint: "clicks",
interval: "30d",
});
diff --git a/apps/web/app/api/og/analytics/route.tsx b/apps/web/app/api/og/analytics/route.tsx
index 0c9309cee1..e03300c7a3 100644
--- a/apps/web/app/api/og/analytics/route.tsx
+++ b/apps/web/app/api/og/analytics/route.tsx
@@ -1,4 +1,4 @@
-import { getAnalytics } from "@/lib/analytics";
+import { getClicks } from "@/lib/analytics";
import { getDomainOrLink } from "@/lib/planetscale";
import {
GOOGLE_FAVICON_URL,
@@ -26,11 +26,11 @@ export async function GET(req: NextRequest) {
});
}
- const data = await getAnalytics({
+ const data = await getClicks({
// workspaceId can be undefined (for public links that haven't been claimed/synced to a workspace)
...(link.projectId && { workspaceId: link.projectId }),
linkId: link.id,
- endpoint: "timeseries",
+ groupBy: "timeseries",
interval: "24h",
});
diff --git a/apps/web/lib/analytics/clicks.ts b/apps/web/lib/analytics/clicks.ts
new file mode 100644
index 0000000000..7e0d9b5da4
--- /dev/null
+++ b/apps/web/lib/analytics/clicks.ts
@@ -0,0 +1,77 @@
+import { conn } from "@/lib/planetscale";
+import { tb } from "@/lib/tinybird";
+import z from "@/lib/zod";
+import { getDaysDifference } from "@dub/utils";
+import { intervalData } from ".";
+import {
+ clickAnalyticsQuerySchema,
+ getClickAnalytics,
+ getClickAnalyticsResponse,
+} from "../zod/schemas";
+
+export const getClicks = async (
+ props: z.infer<typeof clickAnalyticsQuerySchema> & {
+ workspaceId?: string;
+ },
+) => {
+ let { workspaceId, groupBy, linkId, interval, start, end } = props;
+
+ // get all-time clicks count if:
+ // 1. linkId is defined
+ // 2. groupBy is not defined
+ // 3. interval is not defined
+ if (linkId && !groupBy && !interval) {
+ let response = await conn.execute(
+ "SELECT clicks FROM Link WHERE `id` = ?",
+ [linkId],
+ );
+
+ if (response.rows.length === 0) {
+ response = await conn.execute(
+ "SELECT clicks FROM Domain WHERE `id` = ?",
+ [linkId],
+ );
+ if (response.rows.length === 0) {
+ return 0;
+ }
+ }
+ return response.rows[0]["clicks"];
+ }
+
+ const pipe = tb.buildPipe({
+ pipe: groupBy || "clicks",
+ parameters: getClickAnalytics,
+ data: getClickAnalyticsResponse[groupBy || "clicks"],
+ });
+
+ let granularity: "minute" | "hour" | "day" | "month" = "day";
+
+ if (interval) {
+ start = intervalData[interval].startDate;
+ end = new Date(Date.now());
+ granularity = intervalData[interval].granularity;
+ } else {
+ start = new Date(start!);
+ end = end ? new Date(end) : new Date(Date.now());
+ if (getDaysDifference(start, end) > 180) {
+ granularity = "month";
+ }
+
+ // swap start and end if start is greater than end
+ if (start > end) {
+ [start, end] = [end, start];
+ }
+ }
+
+ const res = await pipe(
+ getClickAnalytics.parse({
+ ...props,
+ projectId: workspaceId,
+ start: start.toISOString().replace("T", " ").replace("Z", ""),
+ end: end.toISOString().replace("T", " ").replace("Z", ""),
+ granularity,
+ }),
+ );
+
+ return res.data;
+};
diff --git a/apps/web/lib/analytics/constants.ts b/apps/web/lib/analytics/constants.ts
index b58e3805fe..1944d79cca 100644
--- a/apps/web/lib/analytics/constants.ts
+++ b/apps/web/lib/analytics/constants.ts
@@ -44,7 +44,13 @@ export const INTERVALS = [
},
];
-export const intervalData = {
+export const intervalData: Record<
+ string,
+ {
+ startDate: Date;
+ granularity: "minute" | "hour" | "day" | "month";
+ }
+> = {
"1h": {
startDate: new Date(Date.now() - 3600000),
granularity: "minute",
diff --git a/apps/web/lib/analytics/get-analytics.ts b/apps/web/lib/analytics/get-analytics.ts
deleted file mode 100644
index 33ad99b178..0000000000
--- a/apps/web/lib/analytics/get-analytics.ts
+++ /dev/null
@@ -1,131 +0,0 @@
-import { getDaysDifference } from "@dub/utils";
-import { DATABASE_URL, conn } from "../planetscale";
-import z from "../zod";
-import { getAnalyticsQuerySchema } from "../zod/schemas/analytics";
-import {
- VALID_ANALYTICS_FILTERS,
- VALID_TINYBIRD_ENDPOINTS,
- intervalData,
-} from "./constants";
-
-export const getAnalytics = async ({
- workspaceId,
- linkId,
- domain,
- endpoint,
- interval,
- start,
- end,
- ...rest
-}: z.infer<typeof getAnalyticsQuerySchema> & {
- workspaceId?: string;
- linkId?: string;
- endpoint: (typeof VALID_TINYBIRD_ENDPOINTS)[number];
-}) => {
- // Note: we're using decodeURIComponent in this function because that's how we store it in MySQL and Tinybird
- if (
- !DATABASE_URL ||
- !process.env.TINYBIRD_API_KEY ||
- !VALID_TINYBIRD_ENDPOINTS.includes(endpoint)
- ) {
- return [];
- }
-
- // get all-time clicks count if:
- // 1. endpoint is /clicks
- // 2. interval is not defined
- // 3. linkId is defined
- if (endpoint === "clicks" && !interval && linkId) {
- let response = await conn.execute(
- "SELECT clicks FROM Link WHERE `id` = ?",
- [linkId],
- );
-
- if (response.rows.length === 0) {
- response = await conn.execute(
- "SELECT clicks FROM Domain WHERE `id` = ?",
- [linkId],
- );
- if (response.rows.length === 0) {
- return 0;
- }
- }
- return response.rows[0]["clicks"];
- }
-
- let url = new URL(
- `${process.env.TINYBIRD_API_URL}/v0/pipes/${endpoint}.json`,
- );
- if (workspaceId) {
- url.searchParams.append("projectId", workspaceId);
- }
- if (linkId) {
- url.searchParams.append("linkId", linkId);
- } else if (domain) {
- url.searchParams.append("domain", domain);
- }
-
- if (interval) {
- url.searchParams.append(
- "start",
- intervalData[interval].startDate
- .toISOString()
- .replace("T", " ")
- .replace("Z", ""),
- );
- url.searchParams.append(
- "end",
- new Date(Date.now()).toISOString().replace("T", " ").replace("Z", ""),
- );
-
- url.searchParams.append("granularity", intervalData[interval].granularity);
- } else if (start) {
- url.searchParams.append(
- "start",
- new Date(start).toISOString().replace("T", " ").replace("Z", ""),
- );
- if (!end) {
- end = new Date(Date.now());
- }
-
- url.searchParams.append(
- "end",
- new Date(end).toISOString().replace("T", " ").replace("Z", ""),
- );
-
- url.searchParams.append(
- "granularity",
- getDaysDifference(start, end) > 180 ? "month" : "day",
- );
- }
-
- VALID_ANALYTICS_FILTERS.forEach((filter) => {
- if (rest[filter] !== undefined) {
- url.searchParams.append(filter, rest[filter]);
- }
- });
-
- return await fetch(url.toString(), {
- headers: {
- Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
- },
- })
- .then(async (res) => {
- if (res.ok) {
- return res.json();
- }
- const error = await res.text();
- console.error(error);
- })
- .then(({ data }) => {
- if (endpoint === "clicks") {
- try {
- const clicks = data[0]["count()"];
- return clicks || 0;
- } catch (e) {
- console.log(e);
- }
- }
- return data;
- });
-};
diff --git a/apps/web/lib/analytics/index.ts b/apps/web/lib/analytics/index.ts
index ab8f164405..d506cb35f0 100644
--- a/apps/web/lib/analytics/index.ts
+++ b/apps/web/lib/analytics/index.ts
@@ -1,4 +1,4 @@
+export * from "./clicks";
export * from "./constants";
-export * from "./get-analytics";
export * from "./types";
export * from "./utils";
diff --git a/apps/web/lib/api/errors.ts b/apps/web/lib/api/errors.ts
index 07d0ab331c..186496d746 100644
--- a/apps/web/lib/api/errors.ts
+++ b/apps/web/lib/api/errors.ts
@@ -118,7 +118,7 @@ export function fromZodError(error: ZodError): ErrorResponse {
}
export function handleApiError(error: any): ErrorResponse & { status: number } {
- console.error("API error occurred", error);
+ console.error("API error occurred", JSON.stringify(error, null, 2));
// Zod errors
if (error instanceof ZodError) {
diff --git a/apps/web/lib/openapi/analytics/browser.ts b/apps/web/lib/openapi/analytics/browser.ts
index a53bd3f597..b3e9abc45b 100644
--- a/apps/web/lib/openapi/analytics/browser.ts
+++ b/apps/web/lib/openapi/analytics/browser.ts
@@ -1,8 +1,8 @@
import { openApiErrorResponses } from "@/lib/openapi/responses";
import z from "@/lib/zod";
import {
- analyticsResponseSchema,
- getAnalyticsQuerySchema,
+ clickAnalyticsQuerySchema,
+ getClickAnalyticsResponse,
} from "@/lib/zod/schemas";
import { ZodOpenApiOperationObject } from "zod-openapi";
import { workspaceParamsSchema } from "../request";
@@ -14,14 +14,14 @@ export const getBrowserAnalytics: ZodOpenApiOperationObject = {
description:
"Retrieve the top browsers by number of clicks for a link, a domain, or the authenticated workspace.",
requestParams: {
- query: workspaceParamsSchema.merge(getAnalyticsQuerySchema),
+ query: workspaceParamsSchema.merge(clickAnalyticsQuerySchema),
},
responses: {
"200": {
description: "The top browsers by number of clicks",
content: {
"application/json": {
- schema: z.array(analyticsResponseSchema["browser"]),
+ schema: z.array(getClickAnalyticsResponse["browser"]),
},
},
},
diff --git a/apps/web/lib/openapi/analytics/city.ts b/apps/web/lib/openapi/analytics/city.ts
index 7f9091f2d5..f1697f5dec 100644
--- a/apps/web/lib/openapi/analytics/city.ts
+++ b/apps/web/lib/openapi/analytics/city.ts
@@ -1,8 +1,8 @@
import { openApiErrorResponses } from "@/lib/openapi/responses";
import z from "@/lib/zod";
import {
- analyticsResponseSchema,
- getAnalyticsQuerySchema,
+ clickAnalyticsQuerySchema,
+ getClickAnalyticsResponse,
} from "@/lib/zod/schemas";
import { ZodOpenApiOperationObject } from "zod-openapi";
import { workspaceParamsSchema } from "../request";
@@ -14,14 +14,14 @@ export const getCityAnalytics: ZodOpenApiOperationObject = {
description:
"Retrieve the top countries by number of clicks for a link, a domain, or the authenticated workspace.",
requestParams: {
- query: workspaceParamsSchema.merge(getAnalyticsQuerySchema),
+ query: workspaceParamsSchema.merge(clickAnalyticsQuerySchema),
},
responses: {
"200": {
description: "The top cities by number of clicks",
content: {
"application/json": {
- schema: z.array(analyticsResponseSchema["city"]),
+ schema: z.array(getClickAnalyticsResponse["city"]),
},
},
},
diff --git a/apps/web/lib/openapi/analytics/clicks.ts b/apps/web/lib/openapi/analytics/clicks.ts
index 22a35ec1d4..ce92b3dc7b 100644
--- a/apps/web/lib/openapi/analytics/clicks.ts
+++ b/apps/web/lib/openapi/analytics/clicks.ts
@@ -1,5 +1,5 @@
import { openApiErrorResponses } from "@/lib/openapi/responses";
-import { getAnalyticsQuerySchema } from "@/lib/zod/schemas";
+import { clickAnalyticsQuerySchema } from "@/lib/zod/schemas";
import { ZodOpenApiOperationObject } from "zod-openapi";
import { workspaceParamsSchema } from "../request";
@@ -10,7 +10,7 @@ export const getClicksAnalytics: ZodOpenApiOperationObject = {
description:
"Retrieve the number of clicks for a link, a domain, or the authenticated workspace.",
requestParams: {
- query: workspaceParamsSchema.merge(getAnalyticsQuerySchema),
+ query: workspaceParamsSchema.merge(clickAnalyticsQuerySchema),
},
responses: {
"200": {
diff --git a/apps/web/lib/openapi/analytics/country.ts b/apps/web/lib/openapi/analytics/country.ts
index 098206f0ff..20790f66b8 100644
--- a/apps/web/lib/openapi/analytics/country.ts
+++ b/apps/web/lib/openapi/analytics/country.ts
@@ -1,8 +1,8 @@
import { openApiErrorResponses } from "@/lib/openapi/responses";
import z from "@/lib/zod";
import {
- analyticsResponseSchema,
- getAnalyticsQuerySchema,
+ clickAnalyticsQuerySchema,
+ getClickAnalyticsResponse,
} from "@/lib/zod/schemas";
import { ZodOpenApiOperationObject } from "zod-openapi";
import { workspaceParamsSchema } from "../request";
@@ -14,14 +14,14 @@ export const getCountryAnalytics: ZodOpenApiOperationObject = {
description:
"Retrieve the top countries by number of clicks for a link, a domain, or the authenticated workspace.",
requestParams: {
- query: workspaceParamsSchema.merge(getAnalyticsQuerySchema),
+ query: workspaceParamsSchema.merge(clickAnalyticsQuerySchema),
},
responses: {
"200": {
description: "The top countries by number of clicks",
content: {
"application/json": {
- schema: z.array(analyticsResponseSchema["country"]),
+ schema: z.array(getClickAnalyticsResponse["country"]),
},
},
},
diff --git a/apps/web/lib/openapi/analytics/device.ts b/apps/web/lib/openapi/analytics/device.ts
index 7fec3d1bc7..666db076dc 100644
--- a/apps/web/lib/openapi/analytics/device.ts
+++ b/apps/web/lib/openapi/analytics/device.ts
@@ -1,8 +1,8 @@
import { openApiErrorResponses } from "@/lib/openapi/responses";
import z from "@/lib/zod";
import {
- analyticsResponseSchema,
- getAnalyticsQuerySchema,
+ clickAnalyticsQuerySchema,
+ getClickAnalyticsResponse,
} from "@/lib/zod/schemas";
import { ZodOpenApiOperationObject } from "zod-openapi";
import { workspaceParamsSchema } from "../request";
@@ -14,14 +14,14 @@ export const getDeviceAnalytics: ZodOpenApiOperationObject = {
description:
"Retrieve the top devices by number of clicks for a link, a domain, or the authenticated workspace.",
requestParams: {
- query: workspaceParamsSchema.merge(getAnalyticsQuerySchema),
+ query: workspaceParamsSchema.merge(clickAnalyticsQuerySchema),
},
responses: {
"200": {
description: "The top devices by number of clicks",
content: {
"application/json": {
- schema: z.array(analyticsResponseSchema["device"]),
+ schema: z.array(getClickAnalyticsResponse["device"]),
},
},
},
diff --git a/apps/web/lib/openapi/analytics/os.ts b/apps/web/lib/openapi/analytics/os.ts
index 260ac870a2..4b723acae3 100644
--- a/apps/web/lib/openapi/analytics/os.ts
+++ b/apps/web/lib/openapi/analytics/os.ts
@@ -1,8 +1,8 @@
import { openApiErrorResponses } from "@/lib/openapi/responses";
import z from "@/lib/zod";
import {
- analyticsResponseSchema,
- getAnalyticsQuerySchema,
+ clickAnalyticsQuerySchema,
+ getClickAnalyticsResponse,
} from "@/lib/zod/schemas";
import { ZodOpenApiOperationObject } from "zod-openapi";
import { workspaceParamsSchema } from "../request";
@@ -14,14 +14,14 @@ export const getOSAnalytics: ZodOpenApiOperationObject = {
description:
"Retrieve the top OS by number of clicks for a link, a domain, or the authenticated workspace.",
requestParams: {
- query: workspaceParamsSchema.merge(getAnalyticsQuerySchema),
+ query: workspaceParamsSchema.merge(clickAnalyticsQuerySchema),
},
responses: {
"200": {
description: "The top OS by number of clicks",
content: {
"application/json": {
- schema: z.array(analyticsResponseSchema["os"]),
+ schema: z.array(getClickAnalyticsResponse["os"]),
},
},
},
diff --git a/apps/web/lib/openapi/analytics/referer.ts b/apps/web/lib/openapi/analytics/referer.ts
index ba3e001168..3773734f40 100644
--- a/apps/web/lib/openapi/analytics/referer.ts
+++ b/apps/web/lib/openapi/analytics/referer.ts
@@ -1,8 +1,8 @@
import { openApiErrorResponses } from "@/lib/openapi/responses";
import z from "@/lib/zod";
import {
- analyticsResponseSchema,
- getAnalyticsQuerySchema,
+ clickAnalyticsQuerySchema,
+ getClickAnalyticsResponse,
} from "@/lib/zod/schemas";
import { ZodOpenApiOperationObject } from "zod-openapi";
import { workspaceParamsSchema } from "../request";
@@ -14,14 +14,14 @@ export const getRefererAnalytics: ZodOpenApiOperationObject = {
description:
"Retrieve the top referers by number of clicks for a link, a domain, or the authenticated workspace.",
requestParams: {
- query: workspaceParamsSchema.merge(getAnalyticsQuerySchema),
+ query: workspaceParamsSchema.merge(clickAnalyticsQuerySchema),
},
responses: {
"200": {
description: "The top referers by number of clicks",
content: {
"application/json": {
- schema: z.array(analyticsResponseSchema["referer"]),
+ schema: z.array(getClickAnalyticsResponse["referer"]),
},
},
},
diff --git a/apps/web/lib/openapi/analytics/timeseries.ts b/apps/web/lib/openapi/analytics/timeseries.ts
index 28790ce9dd..bd9071207e 100644
--- a/apps/web/lib/openapi/analytics/timeseries.ts
+++ b/apps/web/lib/openapi/analytics/timeseries.ts
@@ -1,8 +1,8 @@
import { openApiErrorResponses } from "@/lib/openapi/responses";
import z from "@/lib/zod";
import {
- analyticsResponseSchema,
- getAnalyticsQuerySchema,
+ clickAnalyticsQuerySchema,
+ getClickAnalyticsResponse,
} from "@/lib/zod/schemas";
import { ZodOpenApiOperationObject } from "zod-openapi";
import { workspaceParamsSchema } from "../request";
@@ -14,14 +14,14 @@ export const getTimeseriesAnalytics: ZodOpenApiOperationObject = {
description:
"Retrieve the number of clicks for a link, a domain, or the authenticated workspace over a period of time.",
requestParams: {
- query: workspaceParamsSchema.merge(getAnalyticsQuerySchema),
+ query: workspaceParamsSchema.merge(clickAnalyticsQuerySchema),
},
responses: {
"200": {
description: "The number of clicks over a period of time",
content: {
"application/json": {
- schema: z.array(analyticsResponseSchema["timeseries"]),
+ schema: z.array(getClickAnalyticsResponse["timeseries"]),
},
},
},
diff --git a/apps/web/lib/openapi/analytics/top-links.ts b/apps/web/lib/openapi/analytics/top-links.ts
index 00fb4950b8..f929a7dace 100644
--- a/apps/web/lib/openapi/analytics/top-links.ts
+++ b/apps/web/lib/openapi/analytics/top-links.ts
@@ -1,8 +1,8 @@
import { openApiErrorResponses } from "@/lib/openapi/responses";
import z from "@/lib/zod";
import {
- analyticsResponseSchema,
- getAnalyticsQuerySchema,
+ clickAnalyticsQuerySchema,
+ getClickAnalyticsResponse,
} from "@/lib/zod/schemas";
import { ZodOpenApiOperationObject } from "zod-openapi";
import { workspaceParamsSchema } from "../request";
@@ -14,14 +14,14 @@ export const getTopLinks: ZodOpenApiOperationObject = {
description:
"Retrieve the top links by number of clicks for a domain or the authenticated workspace.",
requestParams: {
- query: workspaceParamsSchema.merge(getAnalyticsQuerySchema),
+ query: workspaceParamsSchema.merge(clickAnalyticsQuerySchema),
},
responses: {
"200": {
description: "The top links by number of clicks",
content: {
"application/json": {
- schema: z.array(analyticsResponseSchema["topLinks"]),
+ schema: z.array(getClickAnalyticsResponse["topLinks"]),
},
},
},
diff --git a/apps/web/lib/openapi/analytics/top-urls.ts b/apps/web/lib/openapi/analytics/top-urls.ts
index 0b1923e41c..af9e14009b 100644
--- a/apps/web/lib/openapi/analytics/top-urls.ts
+++ b/apps/web/lib/openapi/analytics/top-urls.ts
@@ -1,8 +1,8 @@
import { openApiErrorResponses } from "@/lib/openapi/responses";
import z from "@/lib/zod";
import {
- analyticsResponseSchema,
- getAnalyticsQuerySchema,
+ clickAnalyticsQuerySchema,
+ getClickAnalyticsResponse,
} from "@/lib/zod/schemas";
import { ZodOpenApiOperationObject } from "zod-openapi";
import { workspaceParamsSchema } from "../request";
@@ -14,14 +14,14 @@ export const getTopURLs: ZodOpenApiOperationObject = {
description:
"Retrieve the top URLs by number of clicks for a given short link.",
requestParams: {
- query: workspaceParamsSchema.merge(getAnalyticsQuerySchema),
+ query: workspaceParamsSchema.merge(clickAnalyticsQuerySchema),
},
responses: {
"200": {
description: "The top URLs by number of clicks",
content: {
"application/json": {
- schema: z.array(analyticsResponseSchema["topUrls"]),
+ schema: z.array(getClickAnalyticsResponse["topUrls"]),
},
},
},
diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.ts
index 5dad342a72..e7fd96d64d 100644
--- a/apps/web/lib/zod/schemas/analytics.ts
+++ b/apps/web/lib/zod/schemas/analytics.ts
@@ -4,8 +4,20 @@ import { COUNTRY_CODES } from "@dub/utils";
import { booleanQuerySchema } from "./misc";
import { parseDateSchema } from "./utils";
-export const getAnalyticsQuerySchema = z.object({
- domain: z.string().optional().describe("The domain of the short link."),
+export const clickAnalyticsQuerySchema = z.object({
+ groupBy: z
+ .enum(VALID_TINYBIRD_ENDPOINTS, {
+ errorMap: (_issue, _ctx) => {
+ return {
+ message: `Invalid groupBy value. Valid endpoints are: ${VALID_TINYBIRD_ENDPOINTS.join(", ")}`,
+ };
+ },
+ })
+ .optional()
+ .describe(
+ "The group by endpoint. If left empty, returns the total click count.",
+ ),
+ domain: z.string().optional().describe("The domain to filter analytics for."),
key: z.string().optional().describe("The short link slug."),
linkId: z
.string()
@@ -84,27 +96,37 @@ export const getAnalyticsQuerySchema = z.object({
),
});
-export const getAnalyticsEdgeQuerySchema = getAnalyticsQuerySchema.required({
- domain: true,
-});
-
-export const analyticsEndpointSchema = z.object({
- endpoint: z.enum(VALID_TINYBIRD_ENDPOINTS, {
- errorMap: (_issue, _ctx) => {
- return {
- message: `Invalid endpoint. Valid endpoints are: ${VALID_TINYBIRD_ENDPOINTS.join(", ")}`,
- };
- },
- }),
-});
+export const getClickAnalytics = clickAnalyticsQuerySchema
+ .omit({
+ groupBy: true,
+ interval: true,
+ externalId: true,
+ key: true,
+ start: true,
+ end: true,
+ root: true,
+ qr: true,
+ })
+ .extend({
+ projectId: z.string().optional(),
+ root: z.boolean().optional(),
+ qr: z.boolean().optional(),
+ start: z.string(),
+ end: z.string(),
+ granularity: z.enum(["minute", "hour", "day", "month"]).optional(),
+ });
// Analytics response schemas
-export const analyticsResponseSchema = {
+export const getClickAnalyticsResponse = {
+ clicks: z
+ .object({
+ "count()": z.number().describe("The total number of clicks"),
+ })
+ .transform((data) => data["count()"]),
timeseries: z.object({
start: z.string().describe("The starting timestamp of the interval"),
clicks: z.number().describe("The number of clicks in the interval"),
}),
-
country: z.object({
country: z
.enum(COUNTRY_CODES)
@@ -142,12 +164,12 @@ export const analyticsResponseSchema = {
clicks: z.number().describe("The number of clicks from this referer"),
}),
- topLinks: z.object({
+ top_links: z.object({
link: z.string().describe("The unique ID of the short link"),
clicks: z.number().describe("The number of clicks from this link"),
}),
- topUrls: z.object({
+ top_urls: z.object({
url: z.string().describe("The destination URL"),
clicks: z.number().describe("The number of clicks from this URL"),
}),
diff --git a/apps/web/scripts/download-top-links.ts b/apps/web/scripts/download-top-links.ts
index 09fe864237..3b5153eeac 100644
--- a/apps/web/scripts/download-top-links.ts
+++ b/apps/web/scripts/download-top-links.ts
@@ -1,4 +1,4 @@
-import { getAnalytics } from "@/lib/analytics";
+import { getClicks } from "@/lib/analytics";
import prisma from "@/lib/prisma";
import { linkConstructor } from "@dub/utils";
import "dotenv-flow/config";
@@ -6,9 +6,9 @@ import * as fs from "fs";
import * as Papa from "papaparse";
async function main() {
- const topLinks = await getAnalytics({
+ const topLinks = await getClicks({
workspaceId: "xxx",
- endpoint: "top_links",
+ groupBy: "top_links",
interval: "30d",
root: false,
}).then(async (data) => {
diff --git a/apps/web/scripts/get-top-links-for-workspace.ts b/apps/web/scripts/get-top-links-for-workspace.ts
index 532f455874..c262516d98 100644
--- a/apps/web/scripts/get-top-links-for-workspace.ts
+++ b/apps/web/scripts/get-top-links-for-workspace.ts
@@ -1,4 +1,4 @@
-import { getAnalytics } from "@/lib/analytics";
+import { getClicks } from "@/lib/analytics";
import prisma from "@/lib/prisma";
import { linkConstructor } from "@dub/utils";
import "dotenv-flow/config";
@@ -34,9 +34,9 @@ async function main() {
console.log("No workspace found");
return;
}
- const topLinks = await getAnalytics({
+ const topLinks = await getClicks({
workspaceId: workspace.id,
- endpoint: "top_links",
+ groupBy: "top_links",
interval: "30d",
root: false,
}).then(async (data) => {
diff --git a/apps/web/tests/analytics/browser.test.ts b/apps/web/tests/analytics/browser.test.ts
index 519a636137..18d87e845c 100644
--- a/apps/web/tests/analytics/browser.test.ts
+++ b/apps/web/tests/analytics/browser.test.ts
@@ -1,5 +1,5 @@
import z from "@/lib/zod";
-import { analyticsResponseSchema } from "@/lib/zod/schemas";
+import { getClickAnalyticsResponse } from "@/lib/zod/schemas";
import { expect, test } from "vitest";
import { env } from "../utils/env";
import { IntegrationHarness } from "../utils/integration";
@@ -18,6 +18,6 @@ test.runIf(env.CI)("GET /analytics/browser", async (ctx) => {
expect(status).toEqual(200);
expect(data.length).toBeGreaterThanOrEqual(0);
expect(
- z.array(analyticsResponseSchema["browser"].strict()).safeParse(data),
+ z.array(getClickAnalyticsResponse["browser"].strict()).safeParse(data),
).toBeTruthy();
});
diff --git a/apps/web/tests/analytics/city.test.ts b/apps/web/tests/analytics/city.test.ts
index 815a91e463..0c45311d01 100644
--- a/apps/web/tests/analytics/city.test.ts
+++ b/apps/web/tests/analytics/city.test.ts
@@ -1,5 +1,5 @@
import z from "@/lib/zod";
-import { analyticsResponseSchema } from "@/lib/zod/schemas";
+import { getClickAnalyticsResponse } from "@/lib/zod/schemas";
import { expect, test } from "vitest";
import { env } from "../utils/env";
import { IntegrationHarness } from "../utils/integration";
@@ -18,6 +18,6 @@ test.runIf(env.CI)("GET /analytics/city", async (ctx) => {
expect(status).toEqual(200);
expect(data.length).toBeGreaterThanOrEqual(0);
expect(
- z.array(analyticsResponseSchema["city"].strict()).safeParse(data),
+ z.array(getClickAnalyticsResponse["city"].strict()).safeParse(data),
).toBeTruthy();
});
diff --git a/apps/web/tests/analytics/country.test.ts b/apps/web/tests/analytics/country.test.ts
index 4ba192e139..9d892f8e4a 100644
--- a/apps/web/tests/analytics/country.test.ts
+++ b/apps/web/tests/analytics/country.test.ts
@@ -1,5 +1,5 @@
import z from "@/lib/zod";
-import { analyticsResponseSchema } from "@/lib/zod/schemas";
+import { getClickAnalyticsResponse } from "@/lib/zod/schemas";
import { expect, test } from "vitest";
import { env } from "../utils/env";
import { IntegrationHarness } from "../utils/integration";
@@ -18,6 +18,6 @@ test.runIf(env.CI)("GET /analytics/country", async (ctx) => {
expect(status).toEqual(200);
expect(data.length).toBeGreaterThanOrEqual(0);
expect(
- z.array(analyticsResponseSchema["country"].strict()).safeParse(data),
+ z.array(getClickAnalyticsResponse["country"].strict()).safeParse(data),
).toBeTruthy();
});
diff --git a/apps/web/tests/analytics/device.test.ts b/apps/web/tests/analytics/device.test.ts
index b6ca460dab..e03cde76fa 100644
--- a/apps/web/tests/analytics/device.test.ts
+++ b/apps/web/tests/analytics/device.test.ts
@@ -1,5 +1,5 @@
import z from "@/lib/zod";
-import { analyticsResponseSchema } from "@/lib/zod/schemas";
+import { getClickAnalyticsResponse } from "@/lib/zod/schemas";
import { expect, test } from "vitest";
import { env } from "../utils/env";
import { IntegrationHarness } from "../utils/integration";
@@ -18,6 +18,6 @@ test.runIf(env.CI)("GET /analytics/device", async (ctx) => {
expect(status).toEqual(200);
expect(data.length).toBeGreaterThanOrEqual(0);
expect(
- z.array(analyticsResponseSchema["device"].strict()).safeParse(data),
+ z.array(getClickAnalyticsResponse["device"].strict()).safeParse(data),
).toBeTruthy();
});
diff --git a/apps/web/tests/analytics/os.test.ts b/apps/web/tests/analytics/os.test.ts
index 3dad2261e3..1a3b4bfa6f 100644
--- a/apps/web/tests/analytics/os.test.ts
+++ b/apps/web/tests/analytics/os.test.ts
@@ -1,5 +1,5 @@
import z from "@/lib/zod";
-import { analyticsResponseSchema } from "@/lib/zod/schemas";
+import { getClickAnalyticsResponse } from "@/lib/zod/schemas";
import { expect, test } from "vitest";
import { env } from "../utils/env";
import { IntegrationHarness } from "../utils/integration";
@@ -18,6 +18,6 @@ test.runIf(env.CI)("GET /analytics/os", async (ctx) => {
expect(status).toEqual(200);
expect(data.length).toBeGreaterThanOrEqual(0);
expect(
- z.array(analyticsResponseSchema["os"].strict()).safeParse(data),
+ z.array(getClickAnalyticsResponse["os"].strict()).safeParse(data),
).toBeTruthy();
});
diff --git a/apps/web/tests/analytics/referer.test.ts b/apps/web/tests/analytics/referer.test.ts
index 41aa4eacfc..003fbf0524 100644
--- a/apps/web/tests/analytics/referer.test.ts
+++ b/apps/web/tests/analytics/referer.test.ts
@@ -1,5 +1,5 @@
import z from "@/lib/zod";
-import { analyticsResponseSchema } from "@/lib/zod/schemas";
+import { getClickAnalyticsResponse } from "@/lib/zod/schemas";
import { expect, test } from "vitest";
import { env } from "../utils/env";
import { IntegrationHarness } from "../utils/integration";
@@ -18,6 +18,6 @@ test.runIf(env.CI)("GET /analytics/referer", async (ctx) => {
expect(status).toEqual(200);
expect(data.length).toBeGreaterThanOrEqual(0);
expect(
- z.array(analyticsResponseSchema["referer"].strict()).safeParse(data),
+ z.array(getClickAnalyticsResponse["referer"].strict()).safeParse(data),
).toBeTruthy();
});
diff --git a/apps/web/tests/analytics/timeseries.test.ts b/apps/web/tests/analytics/timeseries.test.ts
index 8a5daa684b..e5f1b127d7 100644
--- a/apps/web/tests/analytics/timeseries.test.ts
+++ b/apps/web/tests/analytics/timeseries.test.ts
@@ -1,5 +1,5 @@
import z from "@/lib/zod";
-import { analyticsResponseSchema } from "@/lib/zod/schemas";
+import { getClickAnalyticsResponse } from "@/lib/zod/schemas";
import { expect, test } from "vitest";
import { env } from "../utils/env";
import { IntegrationHarness } from "../utils/integration";
@@ -18,6 +18,6 @@ test.runIf(env.CI)("GET /analytics/timeseries", async (ctx) => {
expect(status).toEqual(200);
expect(data.length).toBeGreaterThanOrEqual(0);
expect(
- z.array(analyticsResponseSchema["timeseries"].strict()).safeParse(data),
+ z.array(getClickAnalyticsResponse["timeseries"].strict()).safeParse(data),
).toBeTruthy();
});
diff --git a/apps/web/tests/analytics/top-links.test.ts b/apps/web/tests/analytics/top-links.test.ts
index ef1eaa4fb5..9f65f20e99 100644
--- a/apps/web/tests/analytics/top-links.test.ts
+++ b/apps/web/tests/analytics/top-links.test.ts
@@ -1,5 +1,5 @@
import z from "@/lib/zod";
-import { analyticsResponseSchema } from "@/lib/zod/schemas";
+import { getClickAnalyticsResponse } from "@/lib/zod/schemas";
import { expect, test } from "vitest";
import { env } from "../utils/env";
import { IntegrationHarness } from "../utils/integration";
@@ -18,6 +18,6 @@ test.runIf(env.CI)("GET /analytics/top_links", async (ctx) => {
expect(status).toEqual(200);
expect(data.length).toBeGreaterThanOrEqual(0);
expect(
- z.array(analyticsResponseSchema["topLinks"].strict()).safeParse(data),
+ z.array(getClickAnalyticsResponse["topLinks"].strict()).safeParse(data),
).toBeTruthy();
});
diff --git a/apps/web/tests/analytics/top-urls.test.ts b/apps/web/tests/analytics/top-urls.test.ts
index ba6f166884..34eb741126 100644
--- a/apps/web/tests/analytics/top-urls.test.ts
+++ b/apps/web/tests/analytics/top-urls.test.ts
@@ -1,5 +1,5 @@
import z from "@/lib/zod";
-import { analyticsResponseSchema } from "@/lib/zod/schemas";
+import { getClickAnalyticsResponse } from "@/lib/zod/schemas";
import { expect, test } from "vitest";
import { env } from "../utils/env";
import { IntegrationHarness } from "../utils/integration";
@@ -18,6 +18,6 @@ test.runIf(env.CI)("GET /analytics/top_urls", async (ctx) => {
expect(status).toEqual(200);
expect(data.length).toBeGreaterThanOrEqual(0);
expect(
- z.array(analyticsResponseSchema["topUrls"].strict()).safeParse(data),
+ z.array(getClickAnalyticsResponse["topUrls"].strict()).safeParse(data),
).toBeTruthy();
});
diff --git a/apps/web/ui/analytics/clicks-chart.tsx b/apps/web/ui/analytics/clicks-chart.tsx
index c713232640..d760c39ce4 100644
--- a/apps/web/ui/analytics/clicks-chart.tsx
+++ b/apps/web/ui/analytics/clicks-chart.tsx
@@ -12,7 +12,7 @@ export default function ClicksChart() {
const { baseApiPath, queryString, interval } = useContext(AnalyticsContext);
const { data } = useSWR<{ start: Date; clicks: number }[]>(
- `${baseApiPath}/timeseries?${queryString}`,
+ `${baseApiPath}?${queryString}&groupBy=timeseries`,
fetcher,
);
diff --git a/apps/web/ui/analytics/devices.tsx b/apps/web/ui/analytics/devices.tsx
index 374894edb6..a85911d839 100644
--- a/apps/web/ui/analytics/devices.tsx
+++ b/apps/web/ui/analytics/devices.tsx
@@ -17,7 +17,7 @@ export default function Devices() {
({
[key in DeviceTabs]: string;
} & { clicks: number })[]
- >(`${baseApiPath}/${tab}?${queryString}`, fetcher);
+ >(`${baseApiPath}?${queryString}&groupBy=${tab}`, fetcher);
const { queryParams } = useRouterStuff();
const [showModal, setShowModal] = useState(false);
diff --git a/apps/web/ui/analytics/index.tsx b/apps/web/ui/analytics/index.tsx
index 7d7b4dd028..5d24b7d4be 100644
--- a/apps/web/ui/analytics/index.tsx
+++ b/apps/web/ui/analytics/index.tsx
@@ -66,13 +66,13 @@ export default function Analytics({
if (admin) {
return {
basePath: `/analytics`,
- baseApiPath: `/api/admin/analytics`,
+ baseApiPath: `/api/admin/analytics/clicks`,
domain: domainSlug,
};
} else if (slug) {
return {
basePath: `/${slug}/analytics`,
- baseApiPath: `/api/analytics`,
+ baseApiPath: `/api/analytics/clicks`,
domain: domainSlug,
};
} else {
@@ -106,7 +106,7 @@ export default function Analytics({
}, [id, domain, key, searchParams, interval, tagId]);
const { data: totalClicks } = useSWR<number>(
- `${baseApiPath}/clicks?${queryString}`,
+ `${baseApiPath}?${queryString}`,
fetcher,
);
diff --git a/apps/web/ui/analytics/locations.tsx b/apps/web/ui/analytics/locations.tsx
index c2e2607e17..7aad6a1bea 100644
--- a/apps/web/ui/analytics/locations.tsx
+++ b/apps/web/ui/analytics/locations.tsx
@@ -13,7 +13,7 @@ export default function Locations() {
const { baseApiPath, queryString } = useContext(AnalyticsContext);
const { data } = useSWR<{ country: string; city: string; clicks: number }[]>(
- `${baseApiPath}/${tab}?${queryString}`,
+ `${baseApiPath}?${queryString}&groupBy=${tab}`,
fetcher,
);
diff --git a/apps/web/ui/analytics/referer.tsx b/apps/web/ui/analytics/referer.tsx
index 53a4ef7ad9..8ef4284691 100644
--- a/apps/web/ui/analytics/referer.tsx
+++ b/apps/web/ui/analytics/referer.tsx
@@ -10,7 +10,7 @@ export default function Referer() {
const { baseApiPath, queryString } = useContext(AnalyticsContext);
const { data } = useSWR<{ referer: string; clicks: number }[]>(
- `${baseApiPath}/referer?${queryString}`,
+ `${baseApiPath}?${queryString}&groupBy=referer`,
fetcher,
);
diff --git a/apps/web/ui/analytics/top-links.tsx b/apps/web/ui/analytics/top-links.tsx
index 5a6244c57b..624ac278cd 100644
--- a/apps/web/ui/analytics/top-links.tsx
+++ b/apps/web/ui/analytics/top-links.tsx
@@ -27,7 +27,7 @@ export default function TopLinks() {
({ domain: string; key: string } & {
[key in TopLinksTabs]: string;
} & { clicks: number })[]
- >(`${baseApiPath}/top_${tab}s?${queryString}`, fetcher);
+ >(`${baseApiPath}?${queryString}&groupBy=top_${tab}s`, fetcher);
const { queryParams } = useRouterStuff();
const searchParams = useSearchParams();