The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Publish gated click events to Redis stream from recordClick
Kiran K0b3fc8f73060
diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.tsindex 067028b2a3..da81616e5f 100644--- a/apps/web/lib/middleware/link.ts+++ b/apps/web/lib/middleware/link.ts@@ -145,7 +145,6 @@ export async function LinkMiddleware(req: NextRequest, ev: NextFetchEvent) {android,expiredUrl,doIndex,- webhookIds,testVariants,testCompletedAt,projectId: workspaceId,@@ -292,7 +291,6 @@ export async function LinkMiddleware(req: NextRequest, ev: NextFetchEvent) {url,programId: cachedLink.programId,partnerId: cachedLink.partnerId,- webhookIds,shouldCacheClickId,}),);@@ -351,7 +349,6 @@ export async function LinkMiddleware(req: NextRequest, ev: NextFetchEvent) {url: finalUrl,programId: cachedLink.programId,partnerId: cachedLink.partnerId,- webhookIds,shouldCacheClickId,}),);@@ -387,7 +384,6 @@ export async function LinkMiddleware(req: NextRequest, ev: NextFetchEvent) {url: finalUrl,programId: cachedLink.programId,partnerId: cachedLink.partnerId,- webhookIds,shouldCacheClickId,}),);@@ -425,7 +421,6 @@ export async function LinkMiddleware(req: NextRequest, ev: NextFetchEvent) {url: finalUrl,programId: cachedLink.programId,partnerId: cachedLink.partnerId,- webhookIds,shouldCacheClickId,}),);@@ -494,7 +489,6 @@ export async function LinkMiddleware(req: NextRequest, ev: NextFetchEvent) {url: finalUrl,programId: cachedLink.programId,partnerId: cachedLink.partnerId,- webhookIds,shouldCacheClickId,}),);@@ -562,7 +556,6 @@ export async function LinkMiddleware(req: NextRequest, ev: NextFetchEvent) {url: finalUrl,programId: cachedLink.programId,partnerId: cachedLink.partnerId,- webhookIds,shouldCacheClickId,}),);@@ -596,7 +589,6 @@ export async function LinkMiddleware(req: NextRequest, ev: NextFetchEvent) {url: finalUrl,programId: cachedLink.programId,partnerId: cachedLink.partnerId,- webhookIds,shouldCacheClickId,}),);diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.tsindex c8d2c7d272..797701bd3a 100644--- a/apps/web/lib/tinybird/record-click.ts+++ b/apps/web/lib/tinybird/record-click.ts@@ -13,10 +13,11 @@ import { detectBot } from "../middleware/utils/detect-bot";import { detectQr } from "../middleware/utils/detect-qr";import { getIdentityHash } from "../middleware/utils/get-identity-hash";import { conn } from "../planetscale";-import { WorkspaceProps } from "../types";import { redis } from "../upstash";import { publishPartnerActivityEvent } from "../upstash/redis-streams/partner-activity";+import { publishClickEvent } from "../upstash/redis-streams/workspace-clicks";import { publishWorkspaceClicksUsageEvent } from "../upstash/redis-streams/workspace-clicks-usage";+import { clickEventSchemaTB } from "../zod/schemas/clicks";/*** Recording clicks with geo, ua, referer and timestamp data@@ -31,7 +32,6 @@ export async function recordClick({url,programId,partnerId,- webhookIds,skipRatelimit,timestamp,referrer,@@ -47,7 +47,6 @@ export async function recordClick({url?: string;programId?: string;partnerId?: string;- webhookIds?: string[];skipRatelimit?: boolean;timestamp?: string;referrer?: string;@@ -223,6 +222,8 @@ export async function recordClick({[programId, partnerId],);}),++ publishClickEvent(clickEventSchemaTB.parse(clickData)),]);// Find the rejected promises and log them@@ -256,100 +257,8 @@ export async function recordClick({})),});}-- // if the link has webhooks enabled, we need to check if the workspace usage has exceeded the limit- const hasWebhooks = webhookIds && webhookIds.length > 0;- if (workspaceId && hasWebhooks) {- const workspaceRows = await conn.execute(- "SELECT usage, usageLimit FROM Project WHERE id = ? LIMIT 1",- [workspaceId],- );-- const workspaceData =- workspaceRows.rows.length > 0- ? (workspaceRows.rows[0] as Pick<- WorkspaceProps,- "usage" | "usageLimit"- >)- : null;-- const hasExceededUsageLimit =- workspaceData && workspaceData.usage >= workspaceData.usageLimit;-- // Send webhook events if link has webhooks enabled and the workspace usage has not exceeded the limit- // if (!hasExceededUsageLimit) {- // await sendLinkClickWebhooks({ webhookIds, linkId, clickData });- // }- }})(),);return clickData;}--// async function sendLinkClickWebhooks({-// webhookIds,-// linkId,-// clickData,-// }: {-// webhookIds: string[];-// linkId: string;-// clickData: any;-// }) {-// const webhooks = await webhookCache.mget(webhookIds);--// // Couldn't find webhooks in the cache-// // TODO: Should we look them up in the database?-// if (!webhooks || webhooks.length === 0) {-// return;-// }--// const activeLinkWebhooks = webhooks.filter((webhook) => {-// return (-// !webhook.disabledAt &&-// webhook.triggers &&-// Array.isArray(webhook.triggers) &&-// webhook.triggers.includes("link.clicked")-// );-// });--// if (activeLinkWebhooks.length === 0) {-// return;-// }--// const link = await conn-// .execute(-// `-// SELECT-// l.*,-// JSON_ARRAYAGG(-// IF(t.id IS NOT NULL,-// JSON_OBJECT('tag', JSON_OBJECT('id', t.id, 'name', t.name, 'color', t.color)),-// NULL-// )-// ) as tags-// FROM Link l-// LEFT JOIN LinkTag lt ON l.id = lt.linkId-// LEFT JOIN Tag t ON lt.tagId = t.id-// WHERE l.id = ?-// GROUP BY l.id-// `,-// [linkId],-// )-// .then((res) => {-// const row = res.rows[0] as any;-// // Handle case where there are no tags (JSON_ARRAYAGG returns [null])-// row.tags = row.tags?.[0] === null ? [] : row.tags;-// return row;-// });--// await sendWebhooks({-// trigger: "link.clicked",-// webhooks: activeLinkWebhooks,-// // @ts-ignore – bot & qr should be boolean-// data: transformClickEventData({-// ...clickData,-// link: transformLink(link as ExpandedLink),-// }),-// });-// }diff --git a/apps/web/lib/upstash/redis-streams/workspace-clicks.ts b/apps/web/lib/upstash/redis-streams/workspace-clicks.tsnew file mode 100644index 0000000000..b1e51ddbb8--- /dev/null+++ b/apps/web/lib/upstash/redis-streams/workspace-clicks.ts@@ -0,0 +1,31 @@+import { clickWebhookWorkspaces } from "@/lib/webhook/click-webhook-workspaces";+import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";+import * as z from "zod/v4";+import { redis } from "../redis";+import { RedisStream } from "./client";++const STREAM_KEY = "workspace:click:events";++export const clickEventStream = new RedisStream(STREAM_KEY);++export const publishClickEvent = async (+ event: z.infer<typeof clickEventSchemaTB>,+) => {+ const { workspace_id: workspaceId } = event;++ const hasWebhooks = await clickWebhookWorkspaces.has(workspaceId);++ if (!hasWebhooks) {+ return;+ }++ try {+ return await redis.xadd(STREAM_KEY, "*", event);+ } catch (error) {+ console.error("Failed to publish click event to stream:", error);+ throw error;++ // TODO+ // Log to Axiom+ }+};diff --git a/apps/web/lib/webhook/click-webhook-workspaces.ts b/apps/web/lib/webhook/click-webhook-workspaces.tsindex a19a10f4a2..b7e7c5e7e3 100644--- a/apps/web/lib/webhook/click-webhook-workspaces.ts+++ b/apps/web/lib/webhook/click-webhook-workspaces.ts@@ -3,12 +3,16 @@ import { redis } from "@/lib/upstash";export const REDIS_KEY = "webhookClickWorkspaces";class ClickWebhookWorkspaces {- async set(workspaceId: string): Promise<void> {- await redis.sadd(REDIS_KEY, workspaceId);+ async set(workspaceId: string) {+ return await redis.sadd(REDIS_KEY, workspaceId);}- async remove(workspaceId: string): Promise<void> {- await redis.srem(REDIS_KEY, workspaceId);+ async remove(workspaceId: string) {+ return await redis.srem(REDIS_KEY, workspaceId);+ }++ async has(workspaceId: string) {+ return await redis.sismember(REDIS_KEY, workspaceId);}}