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.

send partner data for /track/click

Kiran Kef157743ab26
diff --git a/apps/web/app/api/track/click/route.ts b/apps/web/app/api/track/click/route.ts
index 8098f7c78b..7f1a21647c 100644
--- a/apps/web/app/api/track/click/route.ts
+++ b/apps/web/app/api/track/click/route.ts
@@ -2,12 +2,15 @@ import { verifyAnalyticsAllowedHostnames } from "@/lib/analytics/verify-analytic
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { clickCache } from "@/lib/api/links/click-cache";
import { parseRequestBody } from "@/lib/api/utils";
-import { getLinkWithAllowedHostnames } from "@/lib/planetscale/get-link-with-allowed-hostnames";
+import { getLinkWithPartner } from "@/lib/planetscale/get-link-with-partner";
import { recordClick } from "@/lib/tinybird";
+import { DiscountSchema } from "@/lib/zod/schemas/discount";
+import { PartnerSchema } from "@/lib/zod/schemas/partners";
import { isValidUrl, LOCALHOST_IP, nanoid } from "@dub/utils";
import { ipAddress, waitUntil } from "@vercel/functions";
import { AxiomRequest, withAxiom } from "next-axiom";
import { NextResponse } from "next/server";
+import { z } from "zod";
export const runtime = "edge";
@@ -17,64 +20,91 @@ const CORS_HEADERS = {
"Access-Control-Allow-Headers": "Content-Type, Authorization",
};
+const trackClickSchema = z.object({
+ domain: z.string({ required_error: "domain is required." }),
+ key: z.string({ required_error: "key is required." }),
+ url: z.string().nullish(),
+ referrer: z.string().nullish(),
+});
+
+export const partnerDiscountSchema = z.object({
+ clickId: z.string(),
+ partner: PartnerSchema.pick({
+ id: true,
+ name: true,
+ image: true,
+ }).nullish(),
+ discount: DiscountSchema.pick({
+ id: true,
+ amount: true,
+ type: true,
+ maxDuration: true,
+ }).nullish(),
+});
+
// POST /api/track/click – Track a click event from the client-side
export const POST = withAxiom(async (req: AxiomRequest) => {
try {
- const { domain, key, url, referrer } = await parseRequestBody(req);
+ const { domain, key, url, referrer } = trackClickSchema.parse(
+ await parseRequestBody(req),
+ );
+
+ const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;
+
+ let clickId = await clickCache.get({
+ domain,
+ key,
+ ip,
+ });
- if (!domain || !key) {
+ // if the clickId is already cached in Redis, return it
+ if (clickId) {
+ return NextResponse.json({ clickId }, { headers: CORS_HEADERS });
+ }
+
+ // Otherwise, track the click event
+ const link = await getLinkWithPartner({
+ domain,
+ key,
+ });
+
+ if (!link) {
throw new DubApiError({
- code: "bad_request",
- message: "Missing domain or key",
+ code: "not_found",
+ message: `Link not found for domain: ${domain} and key: ${key}.`,
});
}
- const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;
+ verifyAnalyticsAllowedHostnames({
+ allowedHostnames: link.allowedHostnames,
+ req,
+ });
- let clickId = await clickCache.get({ domain, key, ip });
-
- // only generate + record a new click ID if it's not already cached in Redis
- if (!clickId) {
- clickId = nanoid(16);
-
- const link = await getLinkWithAllowedHostnames(domain, key);
-
- if (!link) {
- throw new DubApiError({
- code: "not_found",
- message: `Link not found for domain: ${domain} and key: ${key}.`,
- });
- }
-
- const allowedHostnames = link.allowedHostnames;
- verifyAnalyticsAllowedHostnames({ allowedHostnames, req });
-
- const finalUrl = isValidUrl(url) ? url : link.url;
-
- waitUntil(
- recordClick({
- req,
- clickId,
- linkId: link.id,
- domain,
- key,
- url: finalUrl,
- workspaceId: link.projectId,
- skipRatelimit: true,
- ...(referrer && { referrer }),
- trackConversion: link.trackConversion,
- }),
- );
- }
+ const finalUrl = url ? (isValidUrl(url) ? url : link.url) : link.url;
+ clickId = nanoid(16);
- return NextResponse.json(
- {
+ waitUntil(
+ recordClick({
+ req,
clickId,
- },
- {
- headers: CORS_HEADERS,
- },
+ linkId: link.id,
+ domain,
+ key,
+ url: finalUrl,
+ workspaceId: link.projectId,
+ skipRatelimit: true,
+ ...(referrer && { referrer }),
+ trackConversion: link.trackConversion,
+ }),
);
+
+ const response = partnerDiscountSchema.parse({
+ clickId,
+ ...(link.partner && { partner: link.partner }),
+ ...(link.discount && { discount: link.discount }),
+ });
+
+ return NextResponse.json(response, { headers: CORS_HEADERS });
} catch (error) {
return handleAndReturnErrorResponse(error, CORS_HEADERS);
}
diff --git a/apps/web/lib/api/links/utils/transform-link.ts b/apps/web/lib/api/links/utils/transform-link.ts
index 5c73f546a9..55428328a4 100644
--- a/apps/web/lib/api/links/utils/transform-link.ts
+++ b/apps/web/lib/api/links/utils/transform-link.ts
@@ -1,3 +1,4 @@
+import { DiscountProps, PartnerProps } from "@/lib/types";
import { Dashboard, Link, Tag } from "@dub/prisma/client";
import { prefixWorkspaceId } from "../../workspace-id";
import { decodeLinkIfCaseSensitive } from "../case-sensitivity";
@@ -8,6 +9,11 @@ export type ExpandedLink = Link & {
tags?: { tag: Pick<Tag, "id" | "name" | "color"> }[];
webhooks?: { webhookId: string }[];
dashboard?: Dashboard | null;
+ partner?: Pick<PartnerProps, "id" | "name" | "image">;
+ discount?: Pick<
+ DiscountProps,
+ "id" | "amount" | "type" | "maxDuration"
+ > | null;
};
// Transform link with additional properties
diff --git a/apps/web/lib/planetscale/get-link-with-partner.ts b/apps/web/lib/planetscale/get-link-with-partner.ts
new file mode 100644
index 0000000000..c517208c5c
--- /dev/null
+++ b/apps/web/lib/planetscale/get-link-with-partner.ts
@@ -0,0 +1,100 @@
+import { punyEncode } from "@dub/utils";
+import {
+ decodeKeyIfCaseSensitive,
+ encodeKey,
+ isCaseSensitiveDomain,
+} from "../api/links/case-sensitivity";
+import { conn } from "./connection";
+import { EdgeLinkProps } from "./types";
+
+interface LinkWithPartnerProps extends EdgeLinkProps {
+ allowedHostnames: string[];
+ partner?: {
+ id: string;
+ name: string;
+ image: string | null;
+ } | null;
+ discount?: {
+ id: string;
+ amount: number;
+ type: "percentage" | "flat";
+ maxDuration: number | null;
+ } | null;
+}
+
+export const getLinkWithPartner = async ({
+ domain,
+ key,
+}: {
+ domain: string;
+ key: string;
+}): Promise<LinkWithPartnerProps | null> => {
+ const keyToQuery = isCaseSensitiveDomain(domain)
+ ? encodeKey(key)
+ : punyEncode(decodeURIComponent(key));
+
+ console.time("getLinkWithPartner");
+
+ const { rows } =
+ (await conn.execute(
+ `SELECT
+ l.*,
+ w.allowedHostnames,
+ p.id as partnerId,
+ p.name as partnerName,
+ p.image as partnerImage,
+ COALESCE(partDis.id, pgmDis.id) as discountId,
+ COALESCE(partDis.amount, pgmDis.amount) as discountAmount,
+ COALESCE(partDis.type, pgmDis.type) as discountType,
+ COALESCE(partDis.maxDuration, pgmDis.maxDuration) as discountMaxDuration
+ FROM Link l
+ LEFT JOIN ProgramEnrollment pe ON l.programId = pe.programId AND l.partnerId = pe.partnerId
+ LEFT JOIN Partner p ON pe.partnerId = p.id
+ LEFT JOIN Discount partDis ON pe.discountId = partDis.id
+ LEFT JOIN Program prog ON l.programId = prog.id
+ LEFT JOIN Discount pgmDis ON prog.defaultDiscountId = pgmDis.id
+ LEFT JOIN Project w ON l.projectId = w.id
+ WHERE l.domain = ? AND l.key = ?`,
+ [domain, keyToQuery],
+ )) || {};
+
+ console.timeEnd("getLinkWithPartner");
+
+ const link =
+ rows && Array.isArray(rows) && rows.length > 0 ? (rows[0] as any) : null;
+
+ if (!link) {
+ return null;
+ }
+
+ const {
+ partnerId,
+ partnerName,
+ partnerImage,
+ discountId,
+ discountAmount,
+ discountType,
+ discountMaxDuration,
+ ...rest
+ } = link;
+
+ return {
+ ...rest,
+ key: decodeKeyIfCaseSensitive({ domain, key }),
+ partner: partnerId
+ ? {
+ id: partnerId,
+ name: partnerName,
+ image: partnerImage,
+ }
+ : null,
+ discount: discountId
+ ? {
+ id: discountId,
+ amount: discountAmount,
+ type: discountType,
+ maxDuration: discountMaxDuration,
+ }
+ : null,
+ };
+};
diff --git a/apps/web/lib/planetscale/types.ts b/apps/web/lib/planetscale/types.ts
index 9a59ed3ef6..c867bc09a7 100644
--- a/apps/web/lib/planetscale/types.ts
+++ b/apps/web/lib/planetscale/types.ts
@@ -18,6 +18,7 @@ export interface EdgeLinkProps {
publicStats: number;
expiredUrl: string | null;
createdAt: string;
+ trackConversion: boolean;
}
export interface EdgeDomainProps {
diff --git a/apps/web/lib/upstash/format-redis-link.ts b/apps/web/lib/upstash/format-redis-link.ts
index 986ba656d7..2335d67b82 100644
--- a/apps/web/lib/upstash/format-redis-link.ts
+++ b/apps/web/lib/upstash/format-redis-link.ts
@@ -17,6 +17,8 @@ export function formatRedisLink(link: ExpandedLink): RedisLinkProps {
doIndex,
projectId,
webhooks,
+ partner,
+ discount,
} = link;
const webhookIds = webhooks?.map(({ webhookId }) => webhookId) ?? [];
@@ -39,5 +41,20 @@ export function formatRedisLink(link: ExpandedLink): RedisLinkProps {
...(projectId && { projectId }), // projectId can be undefined for anonymous links
...(doIndex && { doIndex: true }),
...(webhookIds.length > 0 && { webhookIds }),
+ ...(partner && {
+ partner: {
+ id: partner.id,
+ name: partner.name,
+ image: partner.image,
+ },
+ }),
+ ...(discount && {
+ discount: {
+ id: discount.id,
+ amount: discount.amount,
+ type: discount.type,
+ maxDuration: discount.maxDuration,
+ },
+ }),
};
}