The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
refactor sending webhook
Kiran Ke80effcab299
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.tsindex 07227df357..3d50b97920 100644--- a/apps/web/app/api/links/[linkId]/route.ts+++ b/apps/web/app/api/links/[linkId]/route.ts@@ -10,7 +10,7 @@ import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";import { prisma } from "@/lib/prisma";import { NewLinkProps } from "@/lib/types";-import { sendWebhook } from "@/lib/webhook/publish";+import { sendWorkspaceWebhook } from "@/lib/webhook/publish";import { updateLinkBodySchema } from "@/lib/zod/schemas/links";import { deepEqual } from "@dub/utils";import { waitUntil } from "@vercel/functions";@@ -124,7 +124,7 @@ export const PATCH = withWorkspace(});waitUntil(- sendWebhook("link.updated", {+ sendWorkspaceWebhook("link.updated", {workspace,data: response,}),@@ -166,7 +166,7 @@ export const DELETE = withWorkspace(await deleteLink(link.id);waitUntil(- sendWebhook("link.deleted", {+ sendWorkspaceWebhook("link.deleted", {workspace,data: {...transformLink(link),diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.tsindex 599fb2d018..89e82110cb 100644--- a/apps/web/app/api/links/route.ts+++ b/apps/web/app/api/links/route.ts@@ -5,7 +5,7 @@ import { throwIfLinksUsageExceeded } from "@/lib/api/links/usage-checks";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";import { ratelimit } from "@/lib/upstash";-import { sendWebhook } from "@/lib/webhook/publish";+import { sendWorkspaceWebhook } from "@/lib/webhook/publish";import {createLinkBodySchema,getLinksQuerySchemaExtended,@@ -100,7 +100,7 @@ export const POST = withWorkspace(const response = await createLink(link);waitUntil(- sendWebhook("link.created", {+ sendWorkspaceWebhook("link.created", {data: response,workspace,}),diff --git a/apps/web/app/api/stripe/connect/webhook/checkout-session-completed.ts b/apps/web/app/api/stripe/connect/webhook/checkout-session-completed.tsindex ccb67e4465..1cd1058637 100644--- a/apps/web/app/api/stripe/connect/webhook/checkout-session-completed.ts+++ b/apps/web/app/api/stripe/connect/webhook/checkout-session-completed.ts@@ -1,7 +1,7 @@import { prisma } from "@/lib/prisma";import { getLeadEvent, recordSale } from "@/lib/tinybird";import { redis } from "@/lib/upstash";-import { sendWebhook } from "@/lib/webhook/publish";+import { sendLinkWebhook } from "@/lib/webhook/publish";import { nanoid } from "@dub/utils";import { waitUntil } from "@vercel/functions";import type Stripe from "stripe";@@ -73,13 +73,15 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {}),};+ const linkId = leadEvent.data[0].link_id;+await Promise.all([recordSale(saleData),// update link sales countprisma.link.update({where: {- id: leadEvent.data[0].link_id,+ id: linkId,},data: {sales: {@@ -91,18 +93,8 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {waitUntil((async () => {- const workspace = await prisma.project.findUniqueOrThrow({- where: {- id: customer.projectId,- },- select: {- id: true,- webhookEnabled: true,- },- });-- sendWebhook("sale.created", {- workspace,+ sendLinkWebhook("sale.created", {+ linkId,data: {...customer,...saleData,diff --git a/apps/web/app/api/stripe/connect/webhook/customer-created.ts b/apps/web/app/api/stripe/connect/webhook/customer-created.tsindex e4d715b8a7..3457dcd69e 100644--- a/apps/web/app/api/stripe/connect/webhook/customer-created.ts+++ b/apps/web/app/api/stripe/connect/webhook/customer-created.ts@@ -1,6 +1,6 @@import { prisma } from "@/lib/prisma";import { getClickEvent, recordCustomer, recordLead } from "@/lib/tinybird";-import { sendWebhook } from "@/lib/webhook/publish-edge";+import { sendLinkWebhook } from "@/lib/webhook/publish";import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";import { nanoid } from "@dub/utils";import { waitUntil } from "@vercel/functions";@@ -94,18 +94,8 @@ export async function customerCreated(event: Stripe.Event) {waitUntil((async () => {- const workspace = await prisma.project.findUniqueOrThrow({- where: {- id: customer.projectId,- },- select: {- id: true,- webhookEnabled: true,- },- });-- sendWebhook("lead.created", {- workspace,+ sendLinkWebhook("lead.created", {+ linkId: clickData.link_id,data: {...customer,...leadData,diff --git a/apps/web/app/api/stripe/connect/webhook/invoice-paid.ts b/apps/web/app/api/stripe/connect/webhook/invoice-paid.tsindex 85b2c3072a..efff4c3de6 100644--- a/apps/web/app/api/stripe/connect/webhook/invoice-paid.ts+++ b/apps/web/app/api/stripe/connect/webhook/invoice-paid.ts@@ -1,7 +1,7 @@import { prisma } from "@/lib/prisma";import { getLeadEvent, recordSale } from "@/lib/tinybird";import { redis } from "@/lib/upstash";-import { sendWebhook } from "@/lib/webhook/publish";+import { sendLinkWebhook } from "@/lib/webhook/publish";import { nanoid } from "@dub/utils";import { waitUntil } from "@vercel/functions";import type Stripe from "stripe";@@ -58,13 +58,15 @@ export async function invoicePaid(event: Stripe.Event) {}),};+ const linkId = leadEvent.data[0].link_id;+await Promise.all([recordSale(saleData),// update link sales countprisma.link.update({where: {- id: leadEvent.data[0].link_id,+ id: linkId,},data: {sales: {@@ -76,18 +78,8 @@ export async function invoicePaid(event: Stripe.Event) {waitUntil((async () => {- const workspace = await prisma.project.findUniqueOrThrow({- where: {- id: customer.projectId,- },- select: {- id: true,- webhookEnabled: true,- },- });-- sendWebhook("sale.created", {- workspace,+ sendLinkWebhook("sale.created", {+ linkId,data: {...customer,...saleData,diff --git a/apps/web/app/api/track/lead/route.ts b/apps/web/app/api/track/lead/route.tsindex d7b86543b3..f334bf6a09 100644--- a/apps/web/app/api/track/lead/route.ts+++ b/apps/web/app/api/track/lead/route.ts@@ -5,7 +5,7 @@ import { generateRandomName } from "@/lib/names";import { prismaEdge } from "@/lib/prisma/edge";import { getClickEvent, recordCustomer, recordLead } from "@/lib/tinybird";import { ratelimit } from "@/lib/upstash";-import { sendWebhook } from "@/lib/webhook/publish-edge";+import { sendLinkWebhookOnEdge } from "@/lib/webhook/publish-edge";import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";import {trackLeadRequestSchema,@@ -140,8 +140,7 @@ export const POST = withWorkspaceEdge(});waitUntil(- sendWebhook("lead.created", {- workspace,+ sendLinkWebhookOnEdge("lead.created", {linkId: clickData.link_id,data: {...response,diff --git a/apps/web/app/api/track/sale/route.ts b/apps/web/app/api/track/sale/route.tsindex 58a5aada12..4737cc166b 100644--- a/apps/web/app/api/track/sale/route.ts+++ b/apps/web/app/api/track/sale/route.ts@@ -3,7 +3,7 @@ import { parseRequestBody } from "@/lib/api/utils";import { withWorkspaceEdge } from "@/lib/auth/workspace-edge";import { prismaEdge } from "@/lib/prisma/edge";import { getLeadEvent, recordSale } from "@/lib/tinybird";-import { sendWebhook } from "@/lib/webhook/publish-edge";+import { sendLinkWebhookOnEdge } from "@/lib/webhook/publish-edge";import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";import {trackSaleRequestSchema,@@ -111,8 +111,7 @@ export const POST = withWorkspaceEdge(});waitUntil(- sendWebhook("sale.created", {- workspace,+ sendLinkWebhookOnEdge("sale.created", {linkId: clickData.link_id,data: {...response,diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.tsindex b1753ae04d..060194e214 100644--- a/apps/web/lib/middleware/link.ts+++ b/apps/web/lib/middleware/link.ts@@ -105,6 +105,7 @@ export default async function LinkMiddleware(geo,expiredUrl,doIndex,+ webhookIds,} = link;// by default, we only index default dub domain links (e.g. dub.sh)@@ -193,6 +194,7 @@ export default async function LinkMiddleware(linkId,clickId,url,+ webhookIds,}),);@@ -236,6 +238,7 @@ export default async function LinkMiddleware(linkId,clickId,url,+ webhookIds,}),);@@ -268,6 +271,7 @@ export default async function LinkMiddleware(linkId,clickId,url,+ webhookIds,}),);@@ -315,6 +319,7 @@ export default async function LinkMiddleware(linkId,clickId,url: ios,+ webhookIds,}),);@@ -343,6 +348,7 @@ export default async function LinkMiddleware(linkId,clickId,url: android,+ webhookIds,}),);@@ -371,6 +377,7 @@ export default async function LinkMiddleware(linkId,clickId,url: geo[country],+ webhookIds,}),);@@ -399,6 +406,7 @@ export default async function LinkMiddleware(linkId,clickId,url,+ webhookIds,}),);diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.tsindex 2027335194..871473d0d3 100644--- a/apps/web/lib/tinybird/record-click.ts+++ b/apps/web/lib/tinybird/record-click.ts@@ -16,6 +16,8 @@ import {} from "../middleware/utils";import { conn } from "../planetscale";import { ratelimit } from "../upstash";+import { webhookCache } from "../webhook/cache";+import { sendWebhooks } from "../webhook/qstash";/*** Recording clicks with geo, ua, referer and timestamp data@@ -25,11 +27,13 @@ export async function recordClick({linkId,clickId,url,+ webhookIds,}: {req: NextRequest;linkId: string;clickId?: string;url?: string;+ webhookIds?: string[];}) {const searchParams = req.nextUrl.searchParams;@@ -76,7 +80,40 @@ export async function recordClick({const finalUrl = url ? getFinalUrlForRecordClick({ req, url }) : "";- return await Promise.allSettled([+ const clickData = {+ timestamp: new Date(Date.now()).toISOString(),+ identity_hash,+ click_id: clickId || nanoid(16),+ link_id: linkId,+ alias_link_id: "",+ url: finalUrl,+ ip:+ // only record IP if it's a valid IP and not from a EU country+ typeof ip === "string" && ip.trim().length > 0 && !isEuCountry ? 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)",+ };++ await Promise.allSettled([fetch(`${process.env.TINYBIRD_API_URL}/v0/events?name=dub_click_events&wait=true`,{@@ -84,42 +121,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: finalUrl,- ip:- // only record IP if it's a valid IP and not from a EU country- typeof ip === "string" && ip.trim().length > 0 && !isEuCountry- ? 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(clickData),},).then((res) => res.json()),@@ -136,4 +138,12 @@ export async function recordClick({[linkId],),]);++ // Send webhook events if link has webhooks enabled+ if (webhookIds && webhookIds.length > 0) {+ sendWebhooks("link.clicked", {+ webhooks: await webhookCache.mget(webhookIds),+ data: clickData,+ });+ }}diff --git a/apps/web/lib/webhook/prepare-payload.ts b/apps/web/lib/webhook/prepare-payload.tsindex d66a40bd0c..e12f1f8d26 100644--- a/apps/web/lib/webhook/prepare-payload.ts+++ b/apps/web/lib/webhook/prepare-payload.ts@@ -2,11 +2,14 @@ import { nanoid } from "@dub/utils";import { WebhookTrigger } from "../types";import { webhookPayloadSchema } from "../zod/schemas/webhooks";import { WEBHOOK_EVENT_ID_PREFIX } from "./constants";-import { transformLead, transformSale } from "./transform";+import { transformClick, transformLead, transformSale } from "./transform";// Transform the payload to the format expected by the webhookexport const prepareWebhookPayload = (trigger: WebhookTrigger, data: any) => {switch (trigger) {+ case "link.clicked":+ data = transformClick(data);+ break;case "lead.created":data = transformLead(data);break;diff --git a/apps/web/lib/webhook/publish-edge.ts b/apps/web/lib/webhook/publish-edge.tsindex e417e6c1e3..1733e4229b 100644--- a/apps/web/lib/webhook/publish-edge.ts+++ b/apps/web/lib/webhook/publish-edge.ts@@ -1,34 +1,41 @@-import { WebhookCacheProps, WebhookTrigger } from "../types";-import { prepareWebhookPayload } from "./prepare-payload";-import { sendWebhookEventToQStash } from "./qstash";+import { prismaEdge } from "../prisma/edge";+import { WebhookTrigger } from "../types";+import { sendWebhooks } from "./qstash";-interface SendWebhookProps {- webhooks: WebhookCacheProps[];- data: any;-}--export const sendWebhook = async (+export const sendLinkWebhookOnEdge = async (trigger: WebhookTrigger,- { webhooks, data }: SendWebhookProps,+ props: {+ linkId: string;+ data: any;+ },) => {- // Filter webhooks that match the trigger- const matchedWebhooks = webhooks.filter((webhook) => {- return webhook.triggers && (webhook.triggers as string[]).includes(trigger);+ const { data, linkId } = props;++ const linkWebhooks = await prismaEdge.linkWebhook.findMany({+ where: {+ linkId,+ webhook: {+ triggers: {+ array_contains: [trigger],+ },+ },+ },+ include: {+ webhook: {+ select: {+ id: true,+ url: true,+ secret: true,+ },+ },+ },});- if (matchedWebhooks.length === 0) {+ if (linkWebhooks.length === 0) {return;}- // Final payload to be sent to Webhook- const payload = prepareWebhookPayload(trigger, data);+ const webhooks = linkWebhooks.map(({ webhook }) => webhook);- await Promise.all(- matchedWebhooks.map((webhook) =>- sendWebhookEventToQStash({- webhook,- payload,- }),- ),- );-};\ No newline at end of file+ return sendWebhooks(trigger, { webhooks, data });+};diff --git a/apps/web/lib/webhook/publish.ts b/apps/web/lib/webhook/publish.tsindex 585022bdba..7915cd7693 100644--- a/apps/web/lib/webhook/publish.ts+++ b/apps/web/lib/webhook/publish.ts@@ -1,19 +1,16 @@import { prisma } from "@/lib/prisma";import { WebhookTrigger, WorkspaceProps } from "../types";-import { prepareWebhookPayload } from "./prepare-payload";-import { sendWebhookEventToQStash } from "./qstash";+import { sendWebhooks } from "./qstash";-interface SendWebhookProps {- workspace: Pick<WorkspaceProps, "id" | "webhookEnabled">;- data: any;- linkId?: string;-}--export const sendWebhook = async (+// Send workspace level webhook+export const sendWorkspaceWebhook = async (trigger: WebhookTrigger,- props: SendWebhookProps,+ props: {+ workspace: Pick<WorkspaceProps, "id" | "webhookEnabled">;+ data: any;+ },) => {- const { workspace, linkId, data } = props;+ const { workspace, data } = props;if (!workspace.webhookEnabled) {return;@@ -25,13 +22,6 @@ export const sendWebhook = async (triggers: {array_contains: [trigger],},- ...(linkId && {- links: {- some: {- linkId,- },- },- }),},select: {id: true,@@ -40,19 +30,44 @@ export const sendWebhook = async (},});- if (webhooks.length === 0) {+ return sendWebhooks(trigger, { webhooks, data });+};++// Send link level webhook+export const sendLinkWebhook = async (+ trigger: WebhookTrigger,+ props: {+ linkId: string;+ data: any;+ },+) => {+ const { data, linkId } = props;++ const linkWebhooks = await prisma.linkWebhook.findMany({+ where: {+ linkId,+ webhook: {+ triggers: {+ array_contains: [trigger],+ },+ },+ },+ include: {+ webhook: {+ select: {+ id: true,+ url: true,+ secret: true,+ },+ },+ },+ });++ if (linkWebhooks.length === 0) {return;}- // Final payload to be sent to Webhook- const payload = prepareWebhookPayload(trigger, data);-- await Promise.all(- webhooks.map((webhook) =>- sendWebhookEventToQStash({- webhook,- payload,- }),- ),- );+ const webhooks = linkWebhooks.map(({ webhook }) => webhook);++ return sendWebhooks(trigger, { webhooks, data });};diff --git a/apps/web/lib/webhook/qstash.ts b/apps/web/lib/webhook/qstash.tsindex a90a3f94b8..fb8d0ade9a 100644--- a/apps/web/lib/webhook/qstash.ts+++ b/apps/web/lib/webhook/qstash.ts@@ -1,11 +1,38 @@import { qstash } from "@/lib/cron";import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import { Webhook } from "@prisma/client";+import { WebhookTrigger } from "../types";import z from "../zod";import { webhookPayloadSchema } from "../zod/schemas/webhooks";+import { prepareWebhookPayload } from "./prepare-payload";import { createWebhookSignature } from "./signature";-export const sendWebhookEventToQStash = async ({+export const sendWebhooks = async (+ trigger: WebhookTrigger,+ props: {+ webhooks: Pick<Webhook, "id" | "url" | "secret">[];+ data: any;+ },+) => {+ const { webhooks, data } = props;++ if (webhooks.length === 0) {+ return;+ }++ const payload = prepareWebhookPayload(trigger, data);++ return await Promise.all(+ webhooks.map((webhook) =>+ publishWebhookEventToQStash({+ webhook,+ payload,+ }),+ ),+ );+};++export const publishWebhookEventToQStash = async ({webhook,payload,}: {diff --git a/apps/web/lib/webhook/transform.ts b/apps/web/lib/webhook/transform.tsindex b51df4d9fe..f9ff06fa8d 100644--- a/apps/web/lib/webhook/transform.ts+++ b/apps/web/lib/webhook/transform.ts@@ -18,6 +18,14 @@ export const transformWebhook = (webhook: TransformWebhookProps) => {};};+export const transformClick = (click: any) => {+ const camelCaseClick = Object.fromEntries(+ Object.entries(click).map(([key, value]) => [toCamelCase(key), value]),+ );++ return camelCaseClick;+};+export const transformLead = (lead: any) => {const camelCaseLead = Object.fromEntries(Object.entries(lead).map(([key, value]) => [toCamelCase(key), value]),diff --git a/apps/web/ui/webhooks/webhook-events.tsx b/apps/web/ui/webhooks/webhook-events.tsxindex 5bc1e155a6..b46673cd94 100644--- a/apps/web/ui/webhooks/webhook-events.tsx+++ b/apps/web/ui/webhooks/webhook-events.tsx@@ -1,10 +1,10 @@"use client";import { WebhookEventProps } from "@/lib/types";+import { usePagination } from "@dub/ui/src/hooks/use-pagination";import { nFormatter, PAGINATION_LIMIT } from "@dub/utils";import { CircleCheck, Clock4 } from "lucide-react";import { PropsWithChildren } from "react";-import usePagination from "../analytics/events/use-pagination";export type EventListProps = PropsWithChildren<{events: WebhookEventProps[];