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.

use clicks/count

Steven Tey220a3fde4ebe
diff --git a/apps/web/app/api/analytics/admin/clicks/[endpoint]/route.ts b/apps/web/app/api/analytics/admin/clicks/[endpoint]/route.ts
index 756a27cb54..c18f1f3585 100644
--- a/apps/web/app/api/analytics/admin/clicks/[endpoint]/route.ts
+++ b/apps/web/app/api/analytics/admin/clicks/[endpoint]/route.ts
@@ -1 +1,20 @@
-export * from "../route";
+import { getClicks } from "@/lib/analytics";
+import { withAdmin } from "@/lib/auth";
+import {
+ analyticsEndpointSchema,
+ clickAnalyticsQuerySchema,
+} from "@/lib/zod/schemas";
+import { NextResponse } from "next/server";
+
+// GET /api/admin/analytics/clicks – get click analytics for admin
+export const GET = withAdmin(async ({ params, searchParams }) => {
+ const { endpoint } = analyticsEndpointSchema.parse(params);
+ const parsedParams = clickAnalyticsQuerySchema.parse(searchParams);
+
+ const response = await getClicks({
+ ...parsedParams,
+ endpoint,
+ });
+
+ return NextResponse.json(response);
+});
diff --git a/apps/web/app/api/analytics/admin/clicks/route.ts b/apps/web/app/api/analytics/admin/clicks/route.ts
deleted file mode 100644
index c18f1f3585..0000000000
--- a/apps/web/app/api/analytics/admin/clicks/route.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { getClicks } from "@/lib/analytics";
-import { withAdmin } from "@/lib/auth";
-import {
- analyticsEndpointSchema,
- clickAnalyticsQuerySchema,
-} from "@/lib/zod/schemas";
-import { NextResponse } from "next/server";
-
-// GET /api/admin/analytics/clicks – get click analytics for admin
-export const GET = withAdmin(async ({ params, searchParams }) => {
- const { endpoint } = analyticsEndpointSchema.parse(params);
- const parsedParams = clickAnalyticsQuerySchema.parse(searchParams);
-
- const response = await getClicks({
- ...parsedParams,
- endpoint,
- });
-
- return NextResponse.json(response);
-});
diff --git a/apps/web/app/api/analytics/clicks/[endpoint]/route.ts b/apps/web/app/api/analytics/clicks/[endpoint]/route.ts
index 756a27cb54..6863cf07df 100644
--- a/apps/web/app/api/analytics/clicks/[endpoint]/route.ts
+++ b/apps/web/app/api/analytics/clicks/[endpoint]/route.ts
@@ -1 +1,44 @@
-export * from "../route";
+import { getClicks, validDateRangeForPlan } from "@/lib/analytics";
+import { withWorkspace } from "@/lib/auth";
+import { getDomainViaEdge } from "@/lib/planetscale";
+import {
+ analyticsEndpointSchema,
+ clickAnalyticsQuerySchema,
+} from "@/lib/zod/schemas";
+import { NextResponse } from "next/server";
+
+// GET /api/analytics/clicks/[endpoint] – get click analytics
+export const GET = withWorkspace(
+ async ({ params, searchParams, workspace, link }) => {
+ const { endpoint = "count" } = analyticsEndpointSchema.parse(params);
+
+ const parsedParams = clickAnalyticsQuerySchema.parse(searchParams);
+ const { domain, key, interval, start, end } = parsedParams;
+
+ 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({
+ ...parsedParams,
+ endpoint,
+ ...(linkId && { linkId }),
+ workspaceId: workspace.id,
+ });
+
+ 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
index bb6ef4c6f9..2782b51d75 100644
--- a/apps/web/app/api/analytics/clicks/route.ts
+++ b/apps/web/app/api/analytics/clicks/route.ts
@@ -1,44 +1 @@
-import { getClicks, validDateRangeForPlan } from "@/lib/analytics";
-import { withWorkspace } from "@/lib/auth";
-import { getDomainViaEdge } from "@/lib/planetscale";
-import {
- analyticsEndpointSchema,
- clickAnalyticsQuerySchema,
-} from "@/lib/zod/schemas";
-import { NextResponse } from "next/server";
-
-// GET /api/analytics/clicks – get click analytics
-export const GET = withWorkspace(
- async ({ params, searchParams, workspace, link }) => {
- const { endpoint } = analyticsEndpointSchema.parse(params);
-
- const parsedParams = clickAnalyticsQuerySchema.parse(searchParams);
- const { domain, key, interval, start, end } = parsedParams;
-
- 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({
- ...parsedParams,
- endpoint,
- ...(linkId && { linkId }),
- workspaceId: workspace.id,
- });
-
- return NextResponse.json(response);
- },
- {
- needNotExceededClicks: true,
- },
-);
+export * from "./[endpoint]/route";
diff --git a/apps/web/app/api/analytics/edge/[endpoint]/route.ts b/apps/web/app/api/analytics/edge/[endpoint]/route.ts
deleted file mode 100644
index 5a3fc0d436..0000000000
--- a/apps/web/app/api/analytics/edge/[endpoint]/route.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from "../clicks/route";
diff --git a/apps/web/app/api/analytics/edge/clicks/[endpoint]/route.ts b/apps/web/app/api/analytics/edge/clicks/[endpoint]/route.ts
index 756a27cb54..a32f7fe413 100644
--- a/apps/web/app/api/analytics/edge/clicks/[endpoint]/route.ts
+++ b/apps/web/app/api/analytics/edge/clicks/[endpoint]/route.ts
@@ -1 +1,107 @@
-export * from "../route";
+import { getClicks, validDateRangeForPlan } from "@/lib/analytics";
+import {
+ DubApiError,
+ exceededLimitError,
+ handleAndReturnErrorResponse,
+} from "@/lib/api/errors";
+import { getDomainOrLink, getWorkspaceViaEdge } from "@/lib/planetscale";
+import { ratelimit } from "@/lib/upstash";
+import {
+ analyticsEndpointSchema,
+ clickAnalyticsQuerySchema,
+} from "@/lib/zod/schemas";
+import { DUB_DEMO_LINKS, DUB_WORKSPACE_ID, getSearchParams } from "@dub/utils";
+import { ipAddress } from "@vercel/edge";
+import { NextResponse, type NextRequest } from "next/server";
+
+export const runtime = "edge";
+
+export const GET = async (
+ req: NextRequest,
+ { params }: { params: Record<string, string> },
+) => {
+ try {
+ const { endpoint } = analyticsEndpointSchema.parse(params);
+
+ const searchParams = getSearchParams(req.url);
+ const parsedParams = clickAnalyticsQuerySchema.parse(searchParams);
+
+ const { domain, key, interval } = parsedParams;
+
+ if (!domain || !key) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Missing domain or key query parameter",
+ });
+ }
+
+ let link;
+
+ const demoLink = DUB_DEMO_LINKS.find(
+ (l) => l.domain === domain && l.key === key,
+ );
+
+ // if it's a demo link
+ if (demoLink) {
+ // Rate limit in production
+ if (process.env.NODE_ENV !== "development") {
+ const ip = ipAddress(req);
+ const { success } = await ratelimit(
+ 15,
+ endpoint ? "1 m" : "10 s",
+ ).limit(`demo-analytics:${demoLink.id}:${ip}:${endpoint || "clicks"}`);
+
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message: "Don't DDoS me pls 🥺",
+ });
+ }
+ }
+ link = {
+ id: demoLink.id,
+ projectId: DUB_WORKSPACE_ID,
+ };
+ } else if (domain) {
+ link = await getDomainOrLink({ domain, key });
+ // if the link is explicitly private (publicStats === false)
+ if (!link?.publicStats) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Analytics for this link are not public",
+ });
+ }
+ const workspace =
+ link?.projectId && (await getWorkspaceViaEdge(link.projectId));
+
+ validDateRangeForPlan({
+ plan: workspace.plan,
+ interval,
+ throwError: true,
+ });
+
+ if (workspace && workspace.usage > workspace.usageLimit) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: exceededLimitError({
+ plan: workspace.plan,
+ limit: workspace.usageLimit,
+ type: "clicks",
+ }),
+ });
+ }
+ }
+
+ const response = await getClicks({
+ ...parsedParams,
+ // workspaceId can be undefined (for public links that haven't been claimed/synced to a workspace)
+ ...(link.projectId && { workspaceId: link.projectId }),
+ endpoint,
+ linkId: link.id,
+ });
+
+ return NextResponse.json(response);
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
+};
diff --git a/apps/web/app/api/analytics/edge/clicks/route.ts b/apps/web/app/api/analytics/edge/clicks/route.ts
deleted file mode 100644
index a32f7fe413..0000000000
--- a/apps/web/app/api/analytics/edge/clicks/route.ts
+++ /dev/null
@@ -1,107 +0,0 @@
-import { getClicks, validDateRangeForPlan } from "@/lib/analytics";
-import {
- DubApiError,
- exceededLimitError,
- handleAndReturnErrorResponse,
-} from "@/lib/api/errors";
-import { getDomainOrLink, getWorkspaceViaEdge } from "@/lib/planetscale";
-import { ratelimit } from "@/lib/upstash";
-import {
- analyticsEndpointSchema,
- clickAnalyticsQuerySchema,
-} from "@/lib/zod/schemas";
-import { DUB_DEMO_LINKS, DUB_WORKSPACE_ID, getSearchParams } from "@dub/utils";
-import { ipAddress } from "@vercel/edge";
-import { NextResponse, type NextRequest } from "next/server";
-
-export const runtime = "edge";
-
-export const GET = async (
- req: NextRequest,
- { params }: { params: Record<string, string> },
-) => {
- try {
- const { endpoint } = analyticsEndpointSchema.parse(params);
-
- const searchParams = getSearchParams(req.url);
- const parsedParams = clickAnalyticsQuerySchema.parse(searchParams);
-
- const { domain, key, interval } = parsedParams;
-
- if (!domain || !key) {
- throw new DubApiError({
- code: "bad_request",
- message: "Missing domain or key query parameter",
- });
- }
-
- let link;
-
- const demoLink = DUB_DEMO_LINKS.find(
- (l) => l.domain === domain && l.key === key,
- );
-
- // if it's a demo link
- if (demoLink) {
- // Rate limit in production
- if (process.env.NODE_ENV !== "development") {
- const ip = ipAddress(req);
- const { success } = await ratelimit(
- 15,
- endpoint ? "1 m" : "10 s",
- ).limit(`demo-analytics:${demoLink.id}:${ip}:${endpoint || "clicks"}`);
-
- if (!success) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message: "Don't DDoS me pls 🥺",
- });
- }
- }
- link = {
- id: demoLink.id,
- projectId: DUB_WORKSPACE_ID,
- };
- } else if (domain) {
- link = await getDomainOrLink({ domain, key });
- // if the link is explicitly private (publicStats === false)
- if (!link?.publicStats) {
- throw new DubApiError({
- code: "forbidden",
- message: "Analytics for this link are not public",
- });
- }
- const workspace =
- link?.projectId && (await getWorkspaceViaEdge(link.projectId));
-
- validDateRangeForPlan({
- plan: workspace.plan,
- interval,
- throwError: true,
- });
-
- if (workspace && workspace.usage > workspace.usageLimit) {
- throw new DubApiError({
- code: "forbidden",
- message: exceededLimitError({
- plan: workspace.plan,
- limit: workspace.usageLimit,
- type: "clicks",
- }),
- });
- }
- }
-
- const response = await getClicks({
- ...parsedParams,
- // workspaceId can be undefined (for public links that haven't been claimed/synced to a workspace)
- ...(link.projectId && { workspaceId: link.projectId }),
- endpoint,
- linkId: link.id,
- });
-
- return NextResponse.json(response);
- } catch (error) {
- return handleAndReturnErrorResponse(error);
- }
-};
diff --git a/apps/web/app/api/analytics/export/route.ts b/apps/web/app/api/analytics/export/route.ts
index aeecfadc7c..326bcdb5f4 100644
--- a/apps/web/app/api/analytics/export/route.ts
+++ b/apps/web/app/api/analytics/export/route.ts
@@ -1,4 +1,4 @@
-import { VALID_TINYBIRD_ENDPOINTS, getClicks } from "@/lib/analytics";
+import { VALID_ANALYTICS_ENDPOINTS, getClicks } from "@/lib/analytics";
import { DubApiError } from "@/lib/api/errors";
import { withWorkspace } from "@/lib/auth";
import { getDomainViaEdge } from "@/lib/planetscale";
@@ -46,7 +46,7 @@ export const GET = withWorkspace(
const zip = new JSZip();
await Promise.all(
- VALID_TINYBIRD_ENDPOINTS.map(async (endpoint) => {
+ VALID_ANALYTICS_ENDPOINTS.map(async (endpoint) => {
if (endpoint === "top_links") {
// no need to fetch top links data if linkId is defined
// since this is just a single link
diff --git a/apps/web/lib/analytics/clicks.ts b/apps/web/lib/analytics/clicks.ts
index cf544c29a7..04fd3b5bad 100644
--- a/apps/web/lib/analytics/clicks.ts
+++ b/apps/web/lib/analytics/clicks.ts
@@ -21,7 +21,7 @@ export const getClicks = async (
// 1. linkId is defined
// 2. endpoint is not defined
// 3. interval is all time
- if (linkId && !endpoint && interval === "all") {
+ if (linkId && endpoint === "count" && interval === "all") {
let response = await conn.execute(
"SELECT clicks FROM Link WHERE `id` = ?",
[linkId],
@@ -40,9 +40,9 @@ export const getClicks = async (
}
const pipe = tb.buildPipe({
- pipe: endpoint || "clicks",
+ pipe: `clicks_${endpoint || "count"}`,
parameters: getClickAnalytics,
- data: getClickAnalyticsResponse[endpoint || "clicks"],
+ data: getClickAnalyticsResponse[endpoint || "count"],
});
let granularity: "minute" | "hour" | "day" | "month" = "day";
@@ -74,7 +74,7 @@ export const getClicks = async (
}),
);
- // for total clicks (endpoint undefined), we return just the value;
+ // for total clicks, we return just the value;
// everything else we return an array of values
- return endpoint ? res.data : res.data[0];
+ return endpoint === "count" ? res.data[0].clicks : res.data;
};
diff --git a/apps/web/lib/analytics/constants.ts b/apps/web/lib/analytics/constants.ts
index 88b3328e5b..11a3af90e6 100644
--- a/apps/web/lib/analytics/constants.ts
+++ b/apps/web/lib/analytics/constants.ts
@@ -86,7 +86,8 @@ export const intervalData: Record<
},
};
-export const VALID_TINYBIRD_ENDPOINTS = [
+export const VALID_ANALYTICS_ENDPOINTS = [
+ "count",
"timeseries",
"country",
"city",
@@ -96,7 +97,6 @@ export const VALID_TINYBIRD_ENDPOINTS = [
"referer",
"top_links",
"top_urls",
- // "top_aliases",
] as const;
export const VALID_ANALYTICS_FILTERS = [
diff --git a/apps/web/lib/analytics/types.ts b/apps/web/lib/analytics/types.ts
index b1d12796b1..c1e972c6d0 100644
--- a/apps/web/lib/analytics/types.ts
+++ b/apps/web/lib/analytics/types.ts
@@ -2,7 +2,7 @@ import { intervals } from "./constants";
export type IntervalProps = (typeof intervals)[number];
export type AnalyticsEndpoints =
- | undefined
+ | "count"
| "timeseries"
| "country"
| "city"
@@ -14,4 +14,4 @@ export type AnalyticsEndpoints =
| "top_urls";
export type LocationTabs = "country" | "city";
export type TopLinksTabs = "link" | "url";
-export type DeviceTabs = "device" | "browser" | "os" | "ua";
+export type DeviceTabs = "device" | "browser" | "os";
diff --git a/apps/web/lib/api/errors.ts b/apps/web/lib/api/errors.ts
index 1ea7f133ea..0f69d2f734 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", JSON.stringify(error, null, 2));
+ console.error("API error occurred", error, JSON.stringify(error, null, 2));
// Zod errors
if (error instanceof ZodError) {
diff --git a/apps/web/lib/zod/schemas/analytics.ts b/apps/web/lib/zod/schemas/analytics.ts
index db6c1f51ad..f40483d6b7 100644
--- a/apps/web/lib/zod/schemas/analytics.ts
+++ b/apps/web/lib/zod/schemas/analytics.ts
@@ -1,4 +1,7 @@
-import { intervals, VALID_TINYBIRD_ENDPOINTS } from "@/lib/analytics/constants";
+import {
+ intervals,
+ VALID_ANALYTICS_ENDPOINTS,
+} from "@/lib/analytics/constants";
import z from "@/lib/zod";
import { COUNTRY_CODES } from "@dub/utils";
import { booleanQuerySchema } from "./misc";
@@ -6,10 +9,10 @@ import { parseDateSchema } from "./utils";
export const analyticsEndpointSchema = z.object({
endpoint: z
- .enum(VALID_TINYBIRD_ENDPOINTS, {
+ .enum(VALID_ANALYTICS_ENDPOINTS, {
errorMap: (_issue, _ctx) => {
return {
- message: `Invalid endpoint value. Valid endpoints are: ${VALID_TINYBIRD_ENDPOINTS.join(", ")}`,
+ message: `Invalid endpoint value. Valid endpoints are: ${VALID_ANALYTICS_ENDPOINTS.join(", ")}`,
};
},
})
@@ -131,11 +134,9 @@ export const getClickAnalytics = clickAnalyticsQuerySchema
// Analytics response schemas
export const getClickAnalyticsResponse = {
- clicks: z
- .object({
- "count()": z.number().describe("The total number of clicks"),
- })
- .transform((data) => data["count()"]),
+ count: z.object({
+ clicks: z.number().describe("The total number of clicks"),
+ }),
timeseries: z.object({
start: z.string().describe("The starting timestamp of the interval"),
clicks: z.number().describe("The number of clicks in the interval"),
diff --git a/apps/web/tests/analytics/clicks.test.ts b/apps/web/tests/analytics/clicks.test.ts
index 58593cfd5b..7a9a27ebcc 100644
--- a/apps/web/tests/analytics/clicks.test.ts
+++ b/apps/web/tests/analytics/clicks.test.ts
@@ -1,4 +1,4 @@
-import { VALID_TINYBIRD_ENDPOINTS } from "@/lib/analytics";
+import { VALID_ANALYTICS_ENDPOINTS } from "@/lib/analytics";
import z from "@/lib/zod";
import { getClickAnalyticsResponse } from "@/lib/zod/schemas";
import { describe, expect, test } from "vitest";
@@ -11,37 +11,45 @@ describe.runIf(env.CI).sequential("GET /analytics/clicks", async () => {
const { workspace, http } = await h.init();
const { workspaceId } = workspace;
- test("clicks count", async () => {
- const { status, data: clicks } = await http.get<number>({
- path: "/analytics/clicks",
- query: { workspaceId, ...filter },
- });
-
- expect(status).toEqual(200);
- expect(clicks).toEqual(expect.any(Number));
- expect(clicks).toBeGreaterThanOrEqual(0);
- });
-
- VALID_TINYBIRD_ENDPOINTS.map((endpoint) => {
+ VALID_ANALYTICS_ENDPOINTS.map((endpoint) => {
test(`by ${endpoint}`, async () => {
const { status, data } = await http.get<any[]>({
path: `/analytics/clicks/${endpoint}`,
query: { workspaceId, ...filter },
});
- const parsed = z
- .array(getClickAnalyticsResponse[endpoint].strict())
- .safeParse(data);
+ if (endpoint === "count") {
+ expect(status).toEqual(200);
+ expect(data).toEqual(expect.any(Number));
+ expect(data).toBeGreaterThanOrEqual(0);
+ } else {
+ const parsed = z
+ .array(getClickAnalyticsResponse[endpoint].strict())
+ .safeParse(data);
- expect(status).toEqual(200);
- expect(data.length).toBeGreaterThanOrEqual(0);
- expect(parsed.success).toBeTruthy();
+ expect(status).toEqual(200);
+ expect(data.length).toBeGreaterThanOrEqual(0);
+ expect(parsed.success).toBeTruthy();
+ }
});
});
// deprecated, backwards compatiblity
- VALID_TINYBIRD_ENDPOINTS.map((endpoint) => {
- test(`by ${endpoint}`, async () => {
+ test("deprecated: clicks count", async () => {
+ const { status, data: clicks } = await http.get<number>({
+ path: "/analytics/clicks",
+ query: { workspaceId, ...filter },
+ });
+
+ expect(status).toEqual(200);
+ expect(clicks).toEqual(expect.any(Number));
+ expect(clicks).toBeGreaterThanOrEqual(0);
+ });
+
+ // deprecated, backwards compatiblity
+ VALID_ANALYTICS_ENDPOINTS.map((endpoint) => {
+ if (endpoint === "count") return;
+ test(`deprecated: by ${endpoint}`, async () => {
const { status, data } = await http.get<any[]>({
path: `/analytics/${endpoint}`,
query: { workspaceId, ...filter },
diff --git a/apps/web/ui/analytics/index.tsx b/apps/web/ui/analytics/index.tsx
index 1d640fcad7..531dcb5fef 100644
--- a/apps/web/ui/analytics/index.tsx
+++ b/apps/web/ui/analytics/index.tsx
@@ -106,7 +106,7 @@ export default function Analytics({
}, [id, domain, key, searchParams, interval, tagId]);
const { data: totalClicks } = useSWR<number>(
- `${baseApiPath}?${queryString}`,
+ `${baseApiPath}/count?${queryString}`,
fetcher,
);