The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
record the webhook events
Kiran Kba9d8e6fd70a
diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.tsindex 1a41392b10..94d5c6f53e 100644--- a/apps/web/app/api/links/route.ts+++ b/apps/web/app/api/links/route.ts@@ -4,12 +4,15 @@ import { createLink, getLinksForWorkspace, processLink } from "@/lib/api/links";import { throwIfLinksUsageExceeded } from "@/lib/api/links/usage-checks";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";+import { prisma } from "@/lib/prisma";import { ratelimit } from "@/lib/upstash";+import { sendToWebhook } from "@/lib/webhook/publish";import {createLinkBodySchema,getLinksQuerySchemaExtended,} from "@/lib/zod/schemas/links";import { LOCALHOST_IP, getSearchParamsWithArray } from "@dub/utils";+import { waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";// GET /api/links – get all links for a workspace@@ -97,6 +100,36 @@ export const POST = withWorkspace(try {const response = await createLink(link);+ waitUntil(+ (async () => {+ if (workspace.webhookEnabled) {+ const webhooks = await prisma.webhook.findMany({+ where: {+ projectId: workspace.id,+ triggers: {+ array_contains: ["link.created"],+ },+ },+ select: {+ id: true,+ url: true,+ secret: true,+ },+ });++ await Promise.all(+ webhooks.map((webhook) =>+ sendToWebhook({+ event: "link.created",+ data: response,+ webhook,+ }),+ ),+ );+ }+ })(),+ );+return NextResponse.json(response, { headers });} catch (error) {if (error.code === "P2002") {diff --git a/apps/web/app/api/webhooks/[webhookId]/events/route.ts b/apps/web/app/api/webhooks/[webhookId]/events/route.tsnew file mode 100644index 0000000000..1da2d3e04a--- /dev/null+++ b/apps/web/app/api/webhooks/[webhookId]/events/route.ts@@ -0,0 +1,29 @@+import { withWorkspace } from "@/lib/auth";+import { prisma } from "@/lib/prisma";+import { getWebhookEvents } from "@/lib/tinybird/get-webhook-events";+import { NextResponse } from "next/server";++// GET /api/webhooks/[webhookId]/events - get events occurred for a webhook+export const GET = withWorkspace(+ async ({ workspace, params }) => {+ const { webhookId } = params;++ await prisma.webhook.findUniqueOrThrow({+ where: {+ id: webhookId,+ projectId: workspace.id,+ },+ });++ const events = await getWebhookEvents({+ webhookId,+ });++ console.log(events);++ return NextResponse.json(events);+ },+ {+ requiredPermissions: ["webhooks.read"],+ },+);diff --git a/apps/web/app/api/webhooks/callback/route.ts b/apps/web/app/api/webhooks/callback/route.tsindex bd19663ba6..6921860c4d 100644--- a/apps/web/app/api/webhooks/callback/route.ts+++ b/apps/web/app/api/webhooks/callback/route.ts@@ -1,16 +1,10 @@import { verifyQstashSignature } from "@/lib/cron/verify-qstash";-import z from "@/lib/zod";+import { recordWebhookEvent } from "@/lib/tinybird/record-webhook-event";+import {+ webhookCallbackSchema,+ webhookPayloadSchema,+} from "@/lib/zod/schemas/webhooks";import { nanoid } from "@dub/utils";-import { recordWebhookEvent } from "../../../../lib/tinybird/record-webhook-event";--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 QStashexport const POST = async (req: Request) => {@@ -19,26 +13,31 @@ export const POST = async (req: Request) => {await verifyQstashSignature(req, rawBody);const { url, status, body, sourceBody, createdAt, sourceMessageId } =- schema.parse(rawBody);+ webhookCallbackSchema.parse(rawBody);const request = Buffer.from(sourceBody, "base64").toString("utf-8");const response = Buffer.from(body, "base64").toString("utf-8");- // TODO:- // Use createdAt as timestamp- // Replace with webhook.id from DB+ const { event, webhookId } = webhookPayloadSchema.parse(JSON.parse(request));- const tb = await recordWebhookEvent({+ await recordWebhookEvent({+ url,+ event,event_id: nanoid(16),- event_type: "link.clicked",- status_code: status,- webhook_id: sourceMessageId,+ http_status: status,+ webhook_id: webhookId,+ request_body: request,+ response_body: response,+ message_id: sourceMessageId,+ });++ console.log("Webhook event recorded", {url,- request,+ event,+ webhookId,+ status,response,});- console.log("Webhook event recorded in Tinybird", tb);-return new Response("OK");};diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/[webhookId]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/[webhookId]/page-client.tsxindex c295a2c74d..f37cb78af0 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/[webhookId]/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/settings/webhooks/[webhookId]/page-client.tsx@@ -25,7 +25,7 @@ export default function WebhookLogsPageClient({}const { data, isLoading, error } = useSWR<any[]>(- `/api/webhooks/${webhookId}/logs?workspaceId=${workspaceId}`,+ `/api/webhooks/${webhookId}/events?workspaceId=${workspaceId}`,fetcher,{keepPreviousData: true,diff --git a/apps/web/lib/tinybird/get-webhook-events.ts b/apps/web/lib/tinybird/get-webhook-events.tsnew file mode 100644index 0000000000..6e34c04b18--- /dev/null+++ b/apps/web/lib/tinybird/get-webhook-events.ts@@ -0,0 +1,11 @@+import z from "../zod";+import { webhookEventSchemaTB } from "../zod/schemas/webhooks";+import { tb } from "./client";++export const getWebhookEvents = tb.buildPipe({+ pipe: "get_webhook_events",+ parameters: z.object({+ webhookId: z.string(),+ }),+ data: webhookEventSchemaTB,+});diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex 8d194b4111..a9cfc21e45 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -7,7 +7,11 @@ import { integrationSchema } from "./zod/schemas/integration";import { createLinkBodySchema } from "./zod/schemas/links";import { oAuthAppSchema } from "./zod/schemas/oauth";import { tokenSchema } from "./zod/schemas/token";-import { createWebhookSchema, webhookSchema } from "./zod/schemas/webhooks";+import {+ createWebhookSchema,+ webhookPayloadSchema,+ webhookSchema,+} from "./zod/schemas/webhooks";export type LinkProps = Link;@@ -248,3 +252,5 @@ export type WebhookTrigger = (typeof WEBHOOK_TRIGGERS)[number];export type WebhookProps = z.infer<typeof webhookSchema>;export type NewWebhook = z.infer<typeof createWebhookSchema>;++export type WebhookPayloadSchema = z.infer<typeof webhookPayloadSchema>;diff --git a/apps/web/lib/webhook/publish.ts b/apps/web/lib/webhook/publish.tsindex 8c4a10fa49..a382f98473 100644--- a/apps/web/lib/webhook/publish.ts+++ b/apps/web/lib/webhook/publish.ts@@ -1,46 +1,33 @@import { qstash } from "@/lib/cron";-import { APP_DOMAIN_WITH_NGROK, nanoid } from "@dub/utils";+import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";import { Webhook } from "@prisma/client";import { WebhookTrigger } from "../types";import { webhookPayloadSchema } from "../zod/schemas/webhooks";import { createWebhookSignature } from "./signature";interface SendToWebhookArgs {- webhookUrl?: string;- webhook?: Webhook;+ webhook: Pick<Webhook, "id" | "url" | "secret">;+ event: WebhookTrigger;data: any;- trigger: WebhookTrigger;}-// Publish webhook event to the webhook endpointexport const sendToWebhook = async ({- webhookUrl,webhook,+ event,data,- trigger,}: SendToWebhookArgs) => {- const url = webhookUrl || webhook?.url;- const secret = webhook?.secret || "random-secret";-- if (!url) {- console.error("No webhook URL provided. Skipping webhook event.");- return;- }-const payload = webhookPayloadSchema.parse({- event: trigger,- webhookId: nanoid(16),- createdAt: new Date().toISOString(),+ event,data,+ webhookId: webhook.id,+ createdAt: new Date().toISOString(),});- console.log("Webhook payload", payload);-const callbackUrl = `${APP_DOMAIN_WITH_NGROK}/api/webhooks/callback`;- const signature = await createWebhookSignature(secret, payload);+ const signature = await createWebhookSignature(webhook.secret, payload);const response = await qstash.publishJSON({- url,+ url: webhook.url,body: payload,headers: {"Dub-Signature": signature,@@ -51,7 +38,7 @@ export const sendToWebhook = async ({if (response.messageId) {console.log(- `Webhook event sent to ${url} with messageId: ${response.messageId}`,+ `Webhook event published to QStash with message ID: ${response.messageId}`,);}};diff --git a/apps/web/lib/webhook/samples.ts b/apps/web/lib/webhook/samples.tsdeleted file mode 100644index b892c5202d..0000000000--- a/apps/web/lib/webhook/samples.ts+++ /dev/null@@ -1,22 +0,0 @@-import { WebhookTrigger } from "../types";--const linkCreatedEventSample = {- id: "1",- event: "link.created",- createdAt: "2021-09-01T00:00:00Z",-};--const linkClickedEventSample = {- id: "1",- event: "link.clicked",- createdAt: "2021-09-01T00:00:00Z",-};--export const getWebhookEventSample = <T extends WebhookTrigger>(event: T) => {- switch (event) {- case "link.created":- return linkCreatedEventSample;- case "link.clicked":- return linkClickedEventSample;- }-};diff --git a/apps/web/lib/webhook/send-test.ts b/apps/web/lib/webhook/send-test.tsdeleted file mode 100644index 5c117b9320..0000000000--- a/apps/web/lib/webhook/send-test.ts+++ /dev/null@@ -1,29 +0,0 @@-import { Webhook } from "@prisma/client";-import { WebhookTrigger } from "../types";-import { getWebhookEventSample } from "./samples";--const sendTestWebhook = async ({- webhook,- event,-}: {- webhook: Pick<Webhook, "url" | "secret">;- event: WebhookTrigger;-}) => {- const payload = getWebhookEventSample(event);-- // Send webhook- const response = await fetch(webhook.url, {- method: "POST",- headers: {- "Content-Type": "application/json",- "X-Webhook-Secret": webhook.secret,- },- body: JSON.stringify(payload),- });-- if (!response.ok) {- throw new Error(`Failed to send webhook: ${response.statusText}`);- }-- return response.json();-};diff --git a/apps/web/lib/webhook/signature.ts b/apps/web/lib/webhook/signature.tsindex 1446e8cb56..bae93260ca 100644--- a/apps/web/lib/webhook/signature.ts+++ b/apps/web/lib/webhook/signature.ts@@ -1,5 +1,4 @@// Create a signature for a webhook request-// Edge friendlyexport const createWebhookSignature = async (secret: string, rawBody: any) => {if (!secret) {throw new Error("A secret must be provided to create a webhook signature.");@@ -22,12 +21,5 @@ export const createWebhookSignature = async (secret: string, rawBody: any) => {.map((byte) => byte.toString(16).padStart(2, "0")).join("");- console.log("Webhook signature", hexSignature);-return hexSignature;-- // return crypto- // .createHmac("sha256", secret)- // .update(JSON.stringify(rawBody))- // .digest("hex");};diff --git a/apps/web/lib/zod/schemas/webhooks.ts b/apps/web/lib/zod/schemas/webhooks.tsindex ec2e81875c..804c4ad59e 100644--- a/apps/web/lib/zod/schemas/webhooks.ts+++ b/apps/web/lib/zod/schemas/webhooks.ts@@ -4,8 +4,6 @@ import {} from "@/lib/webhook/constants";import { z } from "zod";-//whsec_646072a9e9c28e22c8170ec50eba8e0f5dda32a21ac663771d9e901fe6bb25c1-export const webhookSchema = z.object({id: z.string(),linkId: z.string().optional(),@@ -30,17 +28,28 @@ export const updateWebhookSchema = createWebhookSchema.partial();export const webhookEventSchemaTB = z.object({event_id: z.string(),webhook_id: z.string(),+ message_id: z.string(), // QStash message IDurl: z.string(),- event_type: z.enum(WEBHOOK_TRIGGERS),- status_code: z.number(),- request: z.string(),- response: z.string(),+ event: z.enum(WEBHOOK_TRIGGERS),+ http_status: z.number(),+ request_body: z.string(),+ response_body: z.string(),});-// Represents the schema of the payload sent to the webhook endpoint+// Schema of the payload sent to the webhook endpointexport const webhookPayloadSchema = z.object({event: z.enum(WEBHOOK_TRIGGERS),webhookId: z.string(),createdAt: z.string(),data: z.any(),});++// Schema of the payload sent to /webhooks/callback endpoint from QStash+export const webhookCallbackSchema = z.object({+ status: z.number(),+ url: z.string(),+ createdAt: z.number(),+ sourceMessageId: z.string(),+ body: z.string().optional().default(""), // Response from the users webhook URL+ sourceBody: z.string(), // Original request payload from Dub+});diff --git a/packages/tinybird/datasources/dub_webhook_events.datasource b/packages/tinybird/datasources/dub_webhook_events.datasourceindex f909ea1a11..88f5fc5731 100644--- a/packages/tinybird/datasources/dub_webhook_events.datasource+++ b/packages/tinybird/datasources/dub_webhook_events.datasource@@ -3,10 +3,11 @@ SCHEMA >`event_id` String `json:$.event_id`,`webhook_id` String `json:$.webhook_id`,`url` String `json:$.url`,- `event_type` LowCardinality(String) `json:$.event_type`,- `status_code` UInt16 `json:$.status_code`,- `request` String `json:$.request`,- `response` String `json:$.response`+ `event` LowCardinality(String) `json:$.event`,+ `http_status` UInt16 `json:$.http_status`,+ `request_body` String `json:$.request_body`,+ `response_body` String `json:$.response_body`,+ `message_id` String `json:$.message_id`ENGINE "MergeTree"ENGINE_PARTITION_KEY "toYYYYMM(timestamp)"