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.

Cache the click event data in Redis

Kiran K209c86d13cd9
diff --git a/apps/web/app/api/track/click/route.ts b/apps/web/app/api/track/click/route.ts
index a396f1b081..dab2968992 100644
--- a/apps/web/app/api/track/click/route.ts
+++ b/apps/web/app/api/track/click/route.ts
@@ -64,6 +64,7 @@ export const POST = withAxiom(
workspaceId: link.projectId,
skipRatelimit: true,
...(referrer && { referrer }),
+ trackConversion: link.trackConversion,
}),
);
}
diff --git a/apps/web/app/api/track/lead/route.ts b/apps/web/app/api/track/lead/route.ts
index 7c1ec74ac7..73bb7f6f7d 100644
--- a/apps/web/app/api/track/lead/route.ts
+++ b/apps/web/app/api/track/lead/route.ts
@@ -9,6 +9,7 @@ import { getClickEvent, recordLead, recordLeadSync } from "@/lib/tinybird";
import { redis } from "@/lib/upstash";
import { sendWorkspaceWebhook } from "@/lib/webhook/publish";
import { transformLeadEventData } from "@/lib/webhook/transform";
+import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";
import {
trackLeadRequestSchema,
trackLeadResponseSchema,
@@ -18,6 +19,9 @@ import { nanoid } from "@dub/utils";
import { Customer } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
+import { z } from "zod";
+
+type ClickData = z.infer<typeof clickEventSchemaTB>;
// POST /api/track/lead – Track a lead conversion event
export const POST = withWorkspace(
@@ -69,16 +73,33 @@ export const POST = withWorkspace(
}
// Find click event
+ let clickData: ClickData | null = null;
const clickEvent = await getClickEvent({ clickId });
- if (!clickEvent || clickEvent.data.length === 0) {
+ if (clickEvent && clickEvent.data && clickEvent.data.length > 0) {
+ clickData = clickEvent.data[0];
+ }
+
+ if (!clickData) {
+ clickData = await redis.get<ClickData>(`click:${clickId}`);
+
+ if (clickData) {
+ clickData = {
+ ...clickData,
+ timestamp: clickData.timestamp.replace("T", " ").replace("Z", ""),
+ qr: clickData.qr ? 1 : 0,
+ bot: clickData.bot ? 1 : 0,
+ };
+ }
+ }
+
+ if (!clickData) {
throw new DubApiError({
code: "not_found",
message: `Click event not found for clickId: ${clickId}`,
});
}
- const clickData = clickEvent.data[0];
const finalCustomerName =
customerName || customerEmail || generateRandomName();
const leadEventId = nanoid(16);
diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.ts
index 5f7fc86e9c..8a45972866 100644
--- a/apps/web/lib/middleware/link.ts
+++ b/apps/web/lib/middleware/link.ts
@@ -248,6 +248,7 @@ export default async function LinkMiddleware(
url,
webhookIds,
workspaceId,
+ trackConversion,
}),
);
@@ -295,6 +296,7 @@ export default async function LinkMiddleware(
url,
webhookIds,
workspaceId,
+ trackConversion,
}),
);
@@ -331,6 +333,7 @@ export default async function LinkMiddleware(
url,
webhookIds,
workspaceId,
+ trackConversion,
}),
);
@@ -369,6 +372,7 @@ export default async function LinkMiddleware(
url: ios,
webhookIds,
workspaceId,
+ trackConversion,
}),
);
@@ -401,6 +405,7 @@ export default async function LinkMiddleware(
url: android,
webhookIds,
workspaceId,
+ trackConversion,
}),
);
@@ -433,6 +438,7 @@ export default async function LinkMiddleware(
url: geo[country],
webhookIds,
workspaceId,
+ trackConversion,
}),
);
@@ -465,6 +471,7 @@ export default async function LinkMiddleware(
url,
webhookIds,
workspaceId,
+ trackConversion,
}),
);
diff --git a/apps/web/lib/planetscale/get-link-with-allowed-hostnames.ts b/apps/web/lib/planetscale/get-link-with-allowed-hostnames.ts
index 4c2e8b373c..257af2d257 100644
--- a/apps/web/lib/planetscale/get-link-with-allowed-hostnames.ts
+++ b/apps/web/lib/planetscale/get-link-with-allowed-hostnames.ts
@@ -12,8 +12,9 @@ export const getLinkWithAllowedHostnames = async (
folderId: string | null;
userId: string;
allowedHostnames: string[];
+ trackConversion: boolean;
}>(
- "SELECT Link.id, Link.url, projectId, folderId, userId, allowedHostnames FROM Link LEFT JOIN Project ON Link.projectId = Project.id WHERE domain = ? AND `key` = ?",
+ "SELECT Link.id, Link.url, projectId, folderId, userId, allowedHostnames, trackConversion FROM Link LEFT JOIN Project ON Link.projectId = Project.id WHERE domain = ? AND `key` = ?",
[domain, punyEncode(decodeURIComponent(key))],
);
diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.ts
index afb400910e..b580ede890 100644
--- a/apps/web/lib/tinybird/record-click.ts
+++ b/apps/web/lib/tinybird/record-click.ts
@@ -36,6 +36,7 @@ export async function recordClick({
skipRatelimit,
timestamp,
referrer,
+ trackConversion,
}: {
req: Request;
clickId: string;
@@ -48,6 +49,7 @@ export async function recordClick({
skipRatelimit?: boolean;
timestamp?: string;
referrer?: string;
+ trackConversion?: boolean;
}) {
const searchParams = new URL(req.url).searchParams;
@@ -136,6 +138,8 @@ export async function recordClick({
referer_url: referer || "(direct)",
};
+ console.log({ trackConversion });
+
const hasWebhooks = webhookIds && webhookIds.length > 0;
const [, , , , workspaceRows] = await Promise.all([
@@ -155,6 +159,13 @@ export async function recordClick({
ex: 60 * 60,
}),
+ // cache the click data for 15 mins
+ // we're doing this because ingested click events are not available immediately in Tinybird
+ trackConversion &&
+ redis.set(`click:${clickId}`, clickData, {
+ ex: 60 * 15,
+ }),
+
// increment the click count for the link (based on their ID)
// we have to use planetscale connection directly (not prismaEdge) because of connection pooling
conn.execute(