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 events and analytics

Kiran Ka7df9906c0ba
diff --git a/apps/web/app/api/analytics/client/route.ts b/apps/web/app/api/analytics/client/route.ts
new file mode 100644
index 0000000000..3335215dd6
--- /dev/null
+++ b/apps/web/app/api/analytics/client/route.ts
@@ -0,0 +1,17 @@
+import { getAnalytics } from "@/lib/analytics/get-analytics";
+import { withAuth } from "@/lib/referrals/auth";
+import { analyticsQuerySchema } from "@/lib/zod/schemas/analytics";
+import { NextResponse } from "next/server";
+
+// GET /api/analytics/client - get analytics for the current link
+export const GET = withAuth(async ({ workspace, link, searchParams }) => {
+ const parsedParams = analyticsQuerySchema.parse(searchParams);
+
+ const response = await getAnalytics({
+ ...parsedParams,
+ linkId: link.id,
+ workspaceId: workspace.id,
+ });
+
+ return NextResponse.json(response);
+});
diff --git a/apps/web/app/api/events/client/route.ts b/apps/web/app/api/events/client/route.ts
new file mode 100644
index 0000000000..0a771e2642
--- /dev/null
+++ b/apps/web/app/api/events/client/route.ts
@@ -0,0 +1,17 @@
+import { getEvents } from "@/lib/analytics/get-events";
+import { withAuth } from "@/lib/referrals/auth";
+import { eventsQuerySchema } from "@/lib/zod/schemas/analytics";
+import { NextResponse } from "next/server";
+
+// GET /api/events/client - get events for the current link
+export const GET = withAuth(async ({ searchParams, workspace, link }) => {
+ const parsedParams = eventsQuerySchema.parse(searchParams);
+
+ const response = await getEvents({
+ ...parsedParams,
+ linkId: link.id,
+ workspaceId: workspace.id,
+ });
+
+ return NextResponse.json(response);
+});
diff --git a/apps/web/lib/referrals/auth.ts b/apps/web/lib/referrals/auth.ts
new file mode 100644
index 0000000000..8ac0d0c0ba
--- /dev/null
+++ b/apps/web/lib/referrals/auth.ts
@@ -0,0 +1,136 @@
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { prisma } from "@/lib/prisma";
+import { ratelimit } from "@/lib/upstash";
+import { getSearchParams } from "@dub/utils";
+import { Link, Project } from "@prisma/client";
+import { AxiomRequest, withAxiom } from "next-axiom";
+
+interface WithAuthHandler {
+ ({
+ req,
+ params,
+ searchParams,
+ workspace,
+ link,
+ }: {
+ req: Request;
+ params: Record<string, string>;
+ searchParams: Record<string, string>;
+ workspace: Project;
+ link: Link;
+ }): Promise<Response>;
+}
+
+export const withAuth = (handler: WithAuthHandler) => {
+ return withAxiom(
+ async (
+ req: AxiomRequest,
+ { params = {} }: { params: Record<string, string> | undefined },
+ ) => {
+ let headers = {};
+
+ try {
+ let link: Link | undefined = undefined;
+ let publicToken: string | undefined = undefined;
+
+ const rateLimit = 100;
+ const searchParams = getSearchParams(req.url);
+ const authorizationHeader = req.headers.get("Authorization");
+
+ if (!authorizationHeader) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Missing Authorization header.",
+ });
+ }
+
+ if (!authorizationHeader.includes("Bearer ")) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://d.to/auth",
+ });
+ }
+
+ publicToken = authorizationHeader.replace("Bearer ", "");
+
+ if (!publicToken) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Missing Authorization header.",
+ });
+ }
+
+ const referralToken =
+ await prisma.referralPublicToken.findUniqueOrThrow({
+ where: {
+ publicToken,
+ },
+ });
+
+ if (referralToken.expires < new Date()) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Public token expired.",
+ });
+ }
+
+ link = await prisma.link.findUniqueOrThrow({
+ where: {
+ id: referralToken.linkId,
+ },
+ });
+
+ if (!link.trackConversion) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Conversion tracking is not enabled for this link.",
+ });
+ }
+
+ const workspace = await prisma.project.findUniqueOrThrow({
+ where: {
+ id: link.projectId!,
+ },
+ });
+
+ const { success, limit, reset, remaining } = await ratelimit(
+ rateLimit,
+ "1 m",
+ ).limit(publicToken);
+
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message: "Too many requests.",
+ });
+ }
+
+ headers = {
+ "Retry-After": reset.toString(),
+ "X-RateLimit-Limit": limit.toString(),
+ "X-RateLimit-Remaining": remaining.toString(),
+ "X-RateLimit-Reset": reset.toString(),
+ };
+
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message: "Too many requests.",
+ });
+ }
+
+ return await handler({
+ req,
+ params,
+ searchParams,
+ workspace,
+ link,
+ });
+ } catch (error) {
+ req.log.error(error);
+ return handleAndReturnErrorResponse(error, headers);
+ }
+ },
+ );
+};