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 event to webhook url

Kiran K8c972ae10b7b
diff --git a/apps/web/app/api/webhooks/callback/route.ts b/apps/web/app/api/webhooks/callback/route.ts
new file mode 100644
index 0000000000..d9412173f5
--- /dev/null
+++ b/apps/web/app/api/webhooks/callback/route.ts
@@ -0,0 +1,20 @@
+import z from "@/lib/zod";
+
+const schema = z.object({
+ status: z.number(),
+ body: z.string(),
+ sourceMessageId: z.string(),
+ url: z.string(),
+ sourceBody: z.string(),
+ createdAt: z.number(),
+});
+
+// POST /api/webhooks/callback – listen to webhooks status from QStash
+export const POST = async (req: Request) => {
+ const body = await req.json();
+ const parsedPayload = schema.parse(body);
+
+ console.log("Webhook callback", parsedPayload);
+
+ return new Response("OK");
+};
diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.ts
index e87bba2f26..cb438658fb 100644
--- a/apps/web/lib/tinybird/record-click.ts
+++ b/apps/web/lib/tinybird/record-click.ts
@@ -10,6 +10,7 @@ import { NextRequest, userAgent } from "next/server";
import { detectBot, detectQr, getIdentityHash } from "../middleware/utils";
import { conn } from "../planetscale";
import { ratelimit } from "../upstash";
+import { sendToWebhook } from "../webhook/publish";
/**
* Recording clicks with geo, ua, referer and timestamp data
@@ -47,9 +48,45 @@ export async function recordClick({
const { success } = await ratelimit(1, "1 h").limit(
`recordClick:${ip}:${linkId}`,
);
- if (!success) {
- return null;
- }
+
+ // if (!success) {
+ // return null;
+ // }
+
+ const clickEvent = {
+ timestamp: new Date(Date.now()).toISOString(),
+ identity_hash,
+ click_id: clickId || nanoid(16),
+ link_id: linkId,
+ alias_link_id: "",
+ url: url || "",
+ ip:
+ // only record IP if it's a valid IP and not from EU
+ typeof ip === "string" && ip.trim().length > 0 && continent !== "EU"
+ ? ip
+ : "",
+ continent: continent || "",
+ country: geo?.country || "Unknown",
+ city: geo?.city || "Unknown",
+ region: geo?.region || "Unknown",
+ latitude: geo?.latitude || "Unknown",
+ longitude: geo?.longitude || "Unknown",
+ device: capitalize(ua.device.type) || "Desktop",
+ device_vendor: ua.device.vendor || "Unknown",
+ device_model: ua.device.model || "Unknown",
+ browser: ua.browser.name || "Unknown",
+ browser_version: ua.browser.version || "Unknown",
+ engine: ua.engine.name || "Unknown",
+ engine_version: ua.engine.version || "Unknown",
+ os: ua.os.name || "Unknown",
+ os_version: ua.os.version || "Unknown",
+ cpu_architecture: ua.cpu?.architecture || "Unknown",
+ ua: ua.ua || "Unknown",
+ bot: ua.isBot,
+ qr: isQr,
+ referer: referer ? getDomainWithoutWWW(referer) || "(direct)" : "(direct)",
+ referer_url: referer || "(direct)",
+ };
return await Promise.allSettled([
fetch(
@@ -59,42 +96,7 @@ export async function recordClick({
headers: {
Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
},
- body: JSON.stringify({
- timestamp: new Date(Date.now()).toISOString(),
- identity_hash,
- click_id: clickId || nanoid(16),
- link_id: linkId,
- alias_link_id: "",
- url: url || "",
- ip:
- // only record IP if it's a valid IP and not from EU
- typeof ip === "string" && ip.trim().length > 0 && continent !== "EU"
- ? ip
- : "",
- continent: continent || "",
- country: geo?.country || "Unknown",
- city: geo?.city || "Unknown",
- region: geo?.region || "Unknown",
- latitude: geo?.latitude || "Unknown",
- longitude: geo?.longitude || "Unknown",
- device: capitalize(ua.device.type) || "Desktop",
- device_vendor: ua.device.vendor || "Unknown",
- device_model: ua.device.model || "Unknown",
- browser: ua.browser.name || "Unknown",
- browser_version: ua.browser.version || "Unknown",
- engine: ua.engine.name || "Unknown",
- engine_version: ua.engine.version || "Unknown",
- os: ua.os.name || "Unknown",
- os_version: ua.os.version || "Unknown",
- cpu_architecture: ua.cpu?.architecture || "Unknown",
- ua: ua.ua || "Unknown",
- bot: ua.isBot,
- qr: isQr,
- referer: referer
- ? getDomainWithoutWWW(referer) || "(direct)"
- : "(direct)",
- referer_url: referer || "(direct)",
- }),
+ body: JSON.stringify(clickEvent),
},
).then((res) => res.json()),
@@ -110,5 +112,11 @@ export async function recordClick({
"UPDATE Project p JOIN Link l ON p.id = l.projectId SET p.usage = p.usage + 1 WHERE l.id = ?",
[linkId],
),
+
+ // send the click event to the webhook endpoint
+ sendToWebhook({
+ webhookUrl: "some-webhook-url",
+ data: clickEvent,
+ }),
]);
}
diff --git a/apps/web/lib/webhook/constants.ts b/apps/web/lib/webhook/constants.ts
index a9f7236c1f..6e627ff3c1 100644
--- a/apps/web/lib/webhook/constants.ts
+++ b/apps/web/lib/webhook/constants.ts
@@ -1,5 +1,3 @@
-// Webhook sources
-export const webhookSource = ["zapier", "make", "user"] as const;
+export const webhookSources = ["zapier", "make", "user"] as const;
-// Webhook triggers
-export const webhookTrigger = ["link.created", "link.clicked"] as const;
+export const webhookTriggers = ["link.created", "link.clicked"] as const;
diff --git a/apps/web/lib/webhook/publish.ts b/apps/web/lib/webhook/publish.ts
index 2f38aa9474..80d3414ead 100644
--- a/apps/web/lib/webhook/publish.ts
+++ b/apps/web/lib/webhook/publish.ts
@@ -1,18 +1,45 @@
import { qstash } from "@/lib/cron";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
+import { Webhook } from "@prisma/client";
import { WebhookTrigger } from "../types";
import { clickEventSchemaTB } from "../zod/schemas/clicks";
import { LinkSchema } from "../zod/schemas/links";
-export const publishWebhookEvent = async () => {
- const payload = transformPayload({}, "link.created");
+interface SendToWebhookArgs {
+ webhookUrl?: string;
+ webhook?: Webhook;
+ data: any;
+}
- await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/webhooks/publish`,
+// Publish webhook event to the webhook endpoint
+export const sendToWebhook = async ({
+ webhookUrl,
+ webhook,
+ data,
+}: SendToWebhookArgs) => {
+ const url = webhookUrl || webhook?.url;
+
+ if (!url) {
+ console.error("No webhook URL provided. Skipping webhook event.");
+ return;
+ }
+
+ // Receive webhook status from QStash at this URL
+ const callbackUrl = `${APP_DOMAIN_WITH_NGROK}/api/webhooks/callback`;
+
+ const response = await qstash.publishJSON({
+ url,
body: {
- //
+ data,
+ },
+ headers: {
+ "X-Dub-Header1": "Header Value 1",
},
+ callback: callbackUrl,
+ failureCallback: callbackUrl,
});
+
+ console.log("Webhook response", response);
};
// Transform payload to match the webhook event schema