The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
log webhook events
Kiran K3fd8b278f2df
diff --git a/apps/web/app/api/webhooks/callback/route.ts b/apps/web/app/api/webhooks/callback/route.tsindex 111519dad1..bd19663ba6 100644--- a/apps/web/app/api/webhooks/callback/route.ts+++ b/apps/web/app/api/webhooks/callback/route.ts@@ -1,5 +1,7 @@import { verifyQstashSignature } from "@/lib/cron/verify-qstash";import z from "@/lib/zod";+import { nanoid } from "@dub/utils";+import { recordWebhookEvent } from "../../../../lib/tinybird/record-webhook-event";const schema = z.object({status: z.number(),@@ -12,16 +14,31 @@ const schema = z.object({// POST /api/webhooks/callback – listen to webhooks status from QStashexport const POST = async (req: Request) => {- const body = await req.json();+ const rawBody = await req.json();- await verifyQstashSignature(req, body);+ await verifyQstashSignature(req, rawBody);- const parsedPayload = schema.parse(body);+ const { url, status, body, sourceBody, createdAt, sourceMessageId } =+ schema.parse(rawBody);- console.log("Webhook callback", parsedPayload);+ const request = Buffer.from(sourceBody, "base64").toString("utf-8");+ const response = Buffer.from(body, "base64").toString("utf-8");// TODO:- // Store the logs in TB+ // Use createdAt as timestamp+ // Replace with webhook.id from DB++ const tb = await recordWebhookEvent({+ event_id: nanoid(16),+ event_type: "link.clicked",+ status_code: status,+ webhook_id: sourceMessageId,+ url,+ request,+ response,+ });++ console.log("Webhook event recorded in Tinybird", tb);return new Response("OK");};diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.tsindex cb438658fb..872f53f443 100644--- a/apps/web/lib/tinybird/record-click.ts+++ b/apps/web/lib/tinybird/record-click.ts@@ -115,8 +115,9 @@ export async function recordClick({// send the click event to the webhook endpointsendToWebhook({- webhookUrl: "some-webhook-url",+ webhookUrl: "https://webhook.site/3264bb14-82cf-4d79-b368-50491b2b9a8a",data: clickEvent,+ trigger: "link.clicked",}),]);}diff --git a/apps/web/lib/tinybird/record-webhook-event.ts b/apps/web/lib/tinybird/record-webhook-event.tsnew file mode 100644index 0000000000..10790fc06a--- /dev/null+++ b/apps/web/lib/tinybird/record-webhook-event.ts@@ -0,0 +1,7 @@+import { webhookEventSchemaTB } from "../zod/schemas/webhooks";+import { tb } from "./client";++export const recordWebhookEvent = tb.buildIngestEndpoint({+ datasource: "dub_webhook_events",+ event: webhookEventSchemaTB,+});diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex 0e39fb4abf..b30a798605 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -2,6 +2,7 @@ import z from "@/lib/zod";import { metaTagsSchema } from "@/lib/zod/schemas/metatags";import { DirectorySyncProviders } from "@boxyhq/saml-jackson";import { Link, Project } from "@prisma/client";+import { webhookTriggers } from "./webhook/constants";import { integrationSchema } from "./zod/schemas/integration";import { createLinkBodySchema } from "./zod/schemas/links";import { oAuthAppSchema } from "./zod/schemas/oauth";@@ -237,7 +238,7 @@ export type InstalledIntegrationInfoProps = Pick<} | null;};-export type WebhookTrigger = (typeof webhookTrigger)[number];+export type WebhookTrigger = (typeof webhookTriggers)[number];export type WebhookEventPayload = {id: string;diff --git a/apps/web/lib/webhook/publish.ts b/apps/web/lib/webhook/publish.tsindex 65088890f1..c85252d923 100644--- a/apps/web/lib/webhook/publish.ts+++ b/apps/web/lib/webhook/publish.ts@@ -1,15 +1,15 @@import { qstash } from "@/lib/cron";-import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";+import { APP_DOMAIN_WITH_NGROK, nanoid } from "@dub/utils";import { Webhook } from "@prisma/client";import { WebhookTrigger } from "../types";-import { clickEventSchemaTB } from "../zod/schemas/clicks";-import { LinkSchema } from "../zod/schemas/links";+import { webhookPayloadSchema } from "../zod/schemas/webhooks";import { createWebhookSignature } from "./utils";interface SendToWebhookArgs {webhookUrl?: string;webhook?: Webhook;data: any;+ trigger: WebhookTrigger;}// Publish webhook event to the webhook endpoint@@ -17,23 +17,31 @@ export const sendToWebhook = async ({webhookUrl,webhook,data,+ trigger,}: SendToWebhookArgs) => {const url = webhookUrl || webhook?.url;- const secret = webhook?.secret || ""; // TODO: A signature is must+ 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(),+ data,+ });++ console.log("Webhook payload", payload);+const callbackUrl = `${APP_DOMAIN_WITH_NGROK}/api/webhooks/callback`;- const signature = createWebhookSignature(secret, data);+ const signature = await createWebhookSignature(secret, payload);const response = await qstash.publishJSON({url,- body: {- data,- },+ body: payload,headers: {"Dub-Signature": signature,},@@ -47,14 +55,3 @@ export const sendToWebhook = async ({);}};--// Transform payload to match the webhook event schema-export const transformPayload = (payload: any, event: WebhookTrigger) => {- if (event === "link.created") {- return LinkSchema.parse(payload);- }-- if (event === "link.clicked") {- return clickEventSchemaTB.parse(payload);- }-};diff --git a/apps/web/lib/zod/schemas/webhooks.ts b/apps/web/lib/zod/schemas/webhooks.tsindex 3508a2288f..6038dd1a6d 100644--- a/apps/web/lib/zod/schemas/webhooks.ts+++ b/apps/web/lib/zod/schemas/webhooks.ts@@ -1,7 +1,5 @@-import { webhookTrigger } from "@/lib/webhook/constants";+import { webhookTriggers } from "@/lib/webhook/constants";import { z } from "zod";-import { clickEventSchemaTB } from "./clicks";-import { LinkSchema } from "./links";export const webhookSchema = z.object({id: z.string(),@@ -10,7 +8,7 @@ export const webhookSchema = z.object({url: z.string(),secret: z.string(),active: z.boolean().default(true),- triggers: z.array(z.enum(webhookTrigger)),+ triggers: z.array(z.enum(webhookTriggers)),createdAt: z.string(),updatedAt: z.string(),});@@ -19,14 +17,25 @@ export const createWebhookSchema = z.object({name: z.string().min(3).max(50),url: z.string().url().max(190),secret: z.string().length(40),- triggers: z.array(z.enum(webhookTrigger)),+ triggers: z.array(z.enum(webhookTriggers)),});export const updateWebhookSchema = createWebhookSchema.partial();-export const webhookEventSchema = z.object({- id: z.string(),- event: z.string(),+export const webhookEventSchemaTB = z.object({+ event_id: z.string(),+ webhook_id: z.string(),+ url: z.string(),+ event_type: z.enum(webhookTriggers),+ status_code: z.number(),+ request: z.string(),+ response: z.string(),+});++// Represents the schema of the payload sent to the webhook endpoint+export const webhookPayloadSchema = z.object({+ event: z.enum(webhookTriggers),+ webhookId: z.string(),createdAt: z.string(),- data: z.union([LinkSchema, clickEventSchemaTB]),+ data: z.any(),});diff --git a/packages/tinybird/datasources/dub_webhook_events.datasource b/packages/tinybird/datasources/dub_webhook_events.datasourcenew file mode 100644index 0000000000..f909ea1a11--- /dev/null+++ b/packages/tinybird/datasources/dub_webhook_events.datasource@@ -0,0 +1,13 @@+SCHEMA >+ `timestamp` DateTime64(3) `json:$.timestamp` DEFAULT now(),+ `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`++ENGINE "MergeTree"+ENGINE_PARTITION_KEY "toYYYYMM(timestamp)"+ENGINE_SORTING_KEY "timestamp, webhook_id, event_id"