The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
prepare webhook payload
Kiran K24146d3341ca
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.tsindex 00362a01d9..e6f6da9e90 100644--- a/apps/web/app/api/links/[linkId]/route.ts+++ b/apps/web/app/api/links/[linkId]/route.ts@@ -169,7 +169,7 @@ export const DELETE = withWorkspace(dispatchWebhook("link.deleted", {workspace,data: {- id: link.id,+ ...transformLink(link),},}),);diff --git a/apps/web/app/api/webhooks/callback/route.ts b/apps/web/app/api/webhooks/callback/route.tsindex 31e2eb7867..53c07a2ea8 100644--- a/apps/web/app/api/webhooks/callback/route.ts+++ b/apps/web/app/api/webhooks/callback/route.ts@@ -4,7 +4,7 @@ import {webhookCallbackSchema,webhookPayloadSchema,} from "@/lib/zod/schemas/webhooks";-import { nanoid } from "@dub/utils";+import { getSearchParams } from "@dub/utils";// POST /api/webhooks/callback – listen to webhooks status from QStashexport const POST = async (req: Request) => {@@ -18,12 +18,16 @@ export const POST = async (req: Request) => {const request = Buffer.from(sourceBody, "base64").toString("utf-8");const response = Buffer.from(body, "base64").toString("utf-8");- const { event, webhookId } = webhookPayloadSchema.parse(JSON.parse(request));+ const { id: eventId, event } = webhookPayloadSchema.parse(+ JSON.parse(request),+ );++ const { webhookId } = getSearchParams(req.url);await recordWebhookEvent({url,event,- event_id: nanoid(16),+ event_id: eventId,http_status: status,webhook_id: webhookId,request_body: request,@@ -31,13 +35,5 @@ export const POST = async (req: Request) => {message_id: sourceMessageId,});- console.log("Webhook event recorded", {- url,- event,- webhookId,- status,- response,- });-return new Response("OK");};diff --git a/apps/web/lib/api/links/utils.ts b/apps/web/lib/api/links/utils.tsindex 957d86c6a7..fcbfe4f2cc 100644--- a/apps/web/lib/api/links/utils.ts+++ b/apps/web/lib/api/links/utils.ts@@ -16,7 +16,7 @@ import { Link, Tag } from "@prisma/client";import { DubApiError } from "../errors";export type LinkWithTags = Link & {- tags: { tag: Pick<Tag, "id" | "name" | "color"> }[];+ tags?: { tag: Pick<Tag, "id" | "name" | "color"> }[];};/**diff --git a/apps/web/lib/tinybird/record-webhook-event.ts b/apps/web/lib/tinybird/record-webhook-event.tsindex 10790fc06a..65a708610e 100644--- a/apps/web/lib/tinybird/record-webhook-event.ts+++ b/apps/web/lib/tinybird/record-webhook-event.ts@@ -3,5 +3,5 @@ import { tb } from "./client";export const recordWebhookEvent = tb.buildIngestEndpoint({datasource: "dub_webhook_events",- event: webhookEventSchemaTB,+ event: webhookEventSchemaTB.omit({ timestamp: true }),});diff --git a/apps/web/lib/webhook/constants.ts b/apps/web/lib/webhook/constants.tsindex 8d5578a194..555939125e 100644--- a/apps/web/lib/webhook/constants.ts+++ b/apps/web/lib/webhook/constants.ts@@ -2,6 +2,8 @@ export const WEBHOOK_SECRET_LENGTH = 16;export const WEBHOOK_SECRET_PREFIX = "whsec_";+export const WEBHOOK_EVENT_ID_PREFIX = "event_";+export const WORKSPACE_LEVEL_WEBHOOK_TRIGGERS = ["link.created","link.updated",diff --git a/apps/web/lib/webhook/prepare-payload.ts b/apps/web/lib/webhook/prepare-payload.tsnew file mode 100644index 0000000000..039efbbdc3--- /dev/null+++ b/apps/web/lib/webhook/prepare-payload.ts@@ -0,0 +1,21 @@+import { nanoid } from "@dub/utils";+import { WebhookTrigger } from "../types";+import { webhookPayloadSchema } from "../zod/schemas/webhooks";+import { WEBHOOK_EVENT_ID_PREFIX } from "./constants";++// Transform the payload to the format expected by the webhook+export const prepareWebhookPayload = (trigger: WebhookTrigger, data: any) => {+ // Unique identifier for the event within Dub+ const eventId = `${WEBHOOK_EVENT_ID_PREFIX}${nanoid(16)}`;++ const payload = webhookPayloadSchema.parse({+ id: eventId,+ data: data,+ event: trigger,+ createdAt: new Date().toISOString(),+ });++ console.info("Webhook payload", payload);++ return payload;+};diff --git a/apps/web/lib/webhook/publish-edge.ts b/apps/web/lib/webhook/publish-edge.tsindex aedd19daed..f276d470bc 100644--- a/apps/web/lib/webhook/publish-edge.ts+++ b/apps/web/lib/webhook/publish-edge.ts@@ -1,5 +1,6 @@import { prismaEdge } from "@/lib/prisma/edge";import { WebhookTrigger, WorkspaceProps } from "../types";+import { prepareWebhookPayload } from "./prepare-payload";import { sendWebhookEventToQStash } from "./qstash";interface DispatchWebhookProps {@@ -43,12 +44,14 @@ export const dispatchWebhook = async (return;}+ // Final payload to be sent to Webhook+ const payload = prepareWebhookPayload(trigger, data);+await Promise.all(webhooks.map((webhook) =>sendWebhookEventToQStash({webhook,- data,- trigger,+ payload,}),),);diff --git a/apps/web/lib/webhook/publish.ts b/apps/web/lib/webhook/publish.tsindex 00a9f59c7d..61a348bf3a 100644--- a/apps/web/lib/webhook/publish.ts+++ b/apps/web/lib/webhook/publish.ts@@ -1,5 +1,6 @@import { prisma } from "@/lib/prisma";import { WebhookTrigger, WorkspaceProps } from "../types";+import { prepareWebhookPayload } from "./prepare-payload";import { sendWebhookEventToQStash } from "./qstash";interface DispatchWebhookProps {@@ -10,10 +11,8 @@ interface DispatchWebhookProps {export const dispatchWebhook = async (trigger: WebhookTrigger,- props: DispatchWebhookProps,+ { workspace, linkId, data }: DispatchWebhookProps,) => {- const { workspace, linkId, data } = props;-if (!workspace.webhookEnabled) {return;}@@ -43,12 +42,14 @@ export const dispatchWebhook = async (return;}+ // Final payload to be sent to Webhook+ const payload = prepareWebhookPayload(trigger, data);+await Promise.all(webhooks.map((webhook) =>sendWebhookEventToQStash({webhook,- data,- trigger,+ payload,}),),);diff --git a/apps/web/lib/webhook/qstash.ts b/apps/web/lib/webhook/qstash.tsindex 322111795e..a90a3f94b8 100644--- a/apps/web/lib/webhook/qstash.ts+++ b/apps/web/lib/webhook/qstash.ts@@ -1,27 +1,18 @@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 { createWebhookSignature } from "./signature";export const sendWebhookEventToQStash = async ({webhook,- trigger,- data,+ payload,}: {webhook: Pick<Webhook, "id" | "url" | "secret">;- trigger: WebhookTrigger;- data: any;+ payload: z.infer<typeof webhookPayloadSchema>;}) => {- const payload = webhookPayloadSchema.parse({- data,- event: trigger,- webhookId: webhook.id,- createdAt: new Date().toISOString(),- });-- const callbackUrl = `${APP_DOMAIN_WITH_NGROK}/api/webhooks/callback`;+ const callbackUrl = `${APP_DOMAIN_WITH_NGROK}/api/webhooks/callback?webhookId=${webhook.id}`;const signature = await createWebhookSignature(webhook.secret, payload);const response = await qstash.publishJSON({@@ -34,9 +25,7 @@ export const sendWebhookEventToQStash = async ({failureCallback: callbackUrl,});- if (response.messageId) {- console.log(- `Webhook event published to QStash with message ID: ${response.messageId}`,- );+ if (!response.messageId) {+ console.error("Failed to publish webhook event to QStash", response);}};diff --git a/apps/web/lib/zod/schemas/webhooks.ts b/apps/web/lib/zod/schemas/webhooks.tsindex cc0b6f9068..be037410ff 100644--- a/apps/web/lib/zod/schemas/webhooks.ts+++ b/apps/web/lib/zod/schemas/webhooks.ts@@ -3,6 +3,7 @@ import {WEBHOOK_TRIGGERS,} from "@/lib/webhook/constants";import { z } from "zod";+import { LinkSchema } from "./links";export const webhookSchema = z.object({id: z.string(),@@ -25,10 +26,16 @@ export const updateWebhookSchema = createWebhookSchema.partial();// Schema of the payload sent to the webhook endpoint by Dubexport const webhookPayloadSchema = z.object({- event: z.enum(WEBHOOK_TRIGGERS),- webhookId: z.string(),- createdAt: z.string(),- data: z.any(),+ id: z.string().describe("Unique identifier for the event."),+ event: z+ .enum(WEBHOOK_TRIGGERS)+ .describe("The type of event that triggered the webhook."),+ createdAt: z+ .string()+ .describe("The date and time when the event was created."),+ data: z+ .union([LinkSchema, z.any()])+ .describe("The data associated with the event."),});// Schema of response sent to the webhook callback URL by QStash@@ -43,13 +50,13 @@ export const webhookCallbackSchema = z.object({// Webhook event schema for the webhook logsexport const webhookEventSchemaTB = z.object({- timestamp: z.string().default(new Date(Date.now()).toISOString()),event_id: z.string(),webhook_id: z.string(),message_id: z.string(), // QStash message ID- url: z.string(),event: z.enum(WEBHOOK_TRIGGERS),+ url: z.string(),http_status: z.number(),request_body: z.string(),response_body: z.string(),+ timestamp: z.string(),});