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.

Include full link details in link webhook events

Steven Teyb39247648937
diff --git a/apps/web/app/api/stripe/connect/webhook/customer-created.ts b/apps/web/app/api/stripe/connect/webhook/customer-created.ts
index 4833f200f3..014596a792 100644
--- a/apps/web/app/api/stripe/connect/webhook/customer-created.ts
+++ b/apps/web/app/api/stripe/connect/webhook/customer-created.ts
@@ -110,7 +110,7 @@ export async function customerCreated(event: Stripe.Event) {
linkId,
data: transformLeadEventData({
...leadData,
- ...link,
+ link,
customerId: customer.id,
customerName: customer.name,
customerEmail: customer.email,
diff --git a/apps/web/app/api/track/lead/route.ts b/apps/web/app/api/track/lead/route.ts
index 2330172544..e1b78b9596 100644
--- a/apps/web/app/api/track/lead/route.ts
+++ b/apps/web/app/api/track/lead/route.ts
@@ -53,20 +53,6 @@ export const POST = withWorkspaceEdge(
});
}
- const linkId = clickEvent.data[0].link_id;
- const link = await prismaEdge.link.findUnique({
- where: {
- id: linkId,
- },
- });
-
- if (!link) {
- throw new DubApiError({
- code: "not_found",
- message: `Link not found for linkId: ${linkId}`,
- });
- }
-
const clickData = clickEventSchemaTB
.omit({ timestamp: true })
.parse(clickEvent.data[0]);
@@ -104,7 +90,7 @@ export const POST = withWorkspaceEdge(
});
}
- await Promise.all([
+ const [_lead, _customer, link, _project] = await Promise.all([
recordLead({
...clickData,
event_id: nanoid(16),
@@ -158,11 +144,11 @@ export const POST = withWorkspaceEdge(
(async () => {
sendLinkWebhookOnEdge({
trigger: "lead.created",
- linkId,
+ linkId: link.id,
data: transformLeadEventData({
...response,
...clickData,
- ...link,
+ link,
}),
});
})(),
diff --git a/apps/web/app/api/track/sale/route.ts b/apps/web/app/api/track/sale/route.ts
index cfcd78fdef..0034739e36 100644
--- a/apps/web/app/api/track/sale/route.ts
+++ b/apps/web/app/api/track/sale/route.ts
@@ -60,22 +60,7 @@ export const POST = withWorkspaceEdge(
.omit({ timestamp: true })
.parse(leadEvent.data[0]);
- // Find link
- const linkId = clickData.link_id;
- const link = await prismaEdge.link.findUnique({
- where: {
- id: linkId,
- },
- });
-
- if (!link) {
- throw new DubApiError({
- code: "not_found",
- message: `Link with ID ${linkId} not found, skipping...`,
- });
- }
-
- await Promise.all([
+ const [_sale, link, _project] = await Promise.all([
recordSale({
...clickData,
event_id: nanoid(16),
@@ -90,7 +75,7 @@ export const POST = withWorkspaceEdge(
// update link sales count
prismaEdge.link.update({
where: {
- id: linkId,
+ id: clickData.link_id,
},
data: {
sales: {
@@ -130,11 +115,11 @@ export const POST = withWorkspaceEdge(
waitUntil(
sendLinkWebhookOnEdge({
trigger: "sale.created",
- linkId,
+ linkId: link.id,
data: transformSaleEventData({
...response,
...clickData,
- ...link,
+ link,
customerId: customer.id,
customerName: customer.name,
customerEmail: customer.email,
diff --git a/apps/web/lib/api/links/utils/combine-tag-ids.ts b/apps/web/lib/api/links/utils/combine-tag-ids.ts
new file mode 100644
index 0000000000..1fb3889665
--- /dev/null
+++ b/apps/web/lib/api/links/utils/combine-tag-ids.ts
@@ -0,0 +1,16 @@
+/**
+ * Combines tagIds into a single string array or undefined from tagId and tagIds arguments
+ */
+export function combineTagIds({
+ tagId,
+ tagIds,
+}: {
+ tagId?: string | null;
+ tagIds?: string[];
+}): string[] | undefined {
+ // Use tagIds if present, fall back to tagId
+ if (tagIds && Array.isArray(tagIds)) {
+ return tagIds;
+ }
+ return tagId === null ? [] : tagId !== undefined ? [tagId] : undefined;
+}
diff --git a/apps/web/lib/api/links/utils/index.ts b/apps/web/lib/api/links/utils/index.ts
new file mode 100644
index 0000000000..91e60a6e11
--- /dev/null
+++ b/apps/web/lib/api/links/utils/index.ts
@@ -0,0 +1,4 @@
+export * from "./combine-tag-ids";
+export * from "./key-checks";
+export * from "./process-key";
+export * from "./transform-link";
diff --git a/apps/web/lib/api/links/utils.ts b/apps/web/lib/api/links/utils/key-checks.ts
similarity index 51%
rename from apps/web/lib/api/links/utils.ts
rename to apps/web/lib/api/links/utils/key-checks.ts
index 4ca785c5d3..aa66d2dc1e 100644
--- a/apps/web/lib/api/links/utils.ts
+++ b/apps/web/lib/api/links/utils/key-checks.ts
@@ -1,3 +1,4 @@
+import { DubApiError } from "@/lib/api/errors";
import {
isBlacklistedKey,
isReservedKey,
@@ -5,36 +6,7 @@ import {
} from "@/lib/edge-config";
import { checkIfKeyExists } from "@/lib/planetscale";
import { WorkspaceProps } from "@/lib/types";
-import {
- DEFAULT_REDIRECTS,
- isDubDomain,
- linkConstructor,
- punyEncode,
- validKeyRegex,
-} from "@dub/utils";
-import { Link, Tag } from "@prisma/client";
-import { DubApiError } from "../errors";
-
-export type LinkWithTags = Link & {
- tags?: { tag: Pick<Tag, "id" | "name" | "color"> }[];
-};
-
-/**
- * Combines tagIds into a single string array or undefined from tagId and tagIds arguments
- */
-export function combineTagIds({
- tagId,
- tagIds,
-}: {
- tagId?: string | null;
- tagIds?: string[];
-}): string[] | undefined {
- // Use tagIds if present, fall back to tagId
- if (tagIds && Array.isArray(tagIds)) {
- return tagIds;
- }
- return tagId === null ? [] : tagId !== undefined ? [tagId] : undefined;
-}
+import { DEFAULT_REDIRECTS, isDubDomain } from "@dub/utils";
export async function keyChecks({
domain,
@@ -108,60 +80,3 @@ export async function keyChecks({
error: null,
};
}
-
-export function processKey({ domain, key }: { domain: string; key: string }) {
- // Skip if root domain
- if (key === "_root") {
- return key;
- }
-
- if (!validKeyRegex.test(key)) {
- return null;
- }
- // if key starts with _, return null (reserved route for Dub internals)
- if (key.startsWith("_")) {
- return null;
- }
-
- // remove all leading and trailing slashes from key
- key = key.replace(/^\/+|\/+$/g, "");
- /*
- for default dub domains, remove all special characters + unicode normalization
- to remove accents / diacritical marks. this is to prevent phishing/typo squatting
- for custom domains this is fine, since only the workspace can set the key
- */
- if (isDubDomain(domain)) {
- key = key.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
- }
- // encode the key to ascii
- key = punyEncode(key);
-
- return key;
-}
-
-// Transform link with additional properties
-export const transformLink = (link: LinkWithTags) => {
- const tags = (link.tags || []).map(({ tag }) => tag);
-
- const shortLink = linkConstructor({
- domain: link.domain,
- key: link.key,
- });
-
- const qrLink = linkConstructor({
- domain: link.domain,
- key: link.key,
- searchParams: {
- qr: "1",
- },
- });
-
- return {
- ...link,
- shortLink,
- tagId: tags?.[0]?.id ?? null, // backwards compatibility
- tags,
- qrCode: `https://api.dub.co/qr?url=${qrLink}`,
- workspaceId: link.projectId ? `ws_${link.projectId}` : null,
- };
-};
diff --git a/apps/web/lib/api/links/utils/process-key.ts b/apps/web/lib/api/links/utils/process-key.ts
new file mode 100644
index 0000000000..a2a40a8881
--- /dev/null
+++ b/apps/web/lib/api/links/utils/process-key.ts
@@ -0,0 +1,31 @@
+import { isDubDomain, punyEncode, validKeyRegex } from "@dub/utils";
+
+export function processKey({ domain, key }: { domain: string; key: string }) {
+ // Skip if root domain
+ if (key === "_root") {
+ return key;
+ }
+
+ if (!validKeyRegex.test(key)) {
+ return null;
+ }
+ // if key starts with _, return null (reserved route for Dub internals)
+ if (key.startsWith("_")) {
+ return null;
+ }
+
+ // remove all leading and trailing slashes from key
+ key = key.replace(/^\/+|\/+$/g, "");
+ /*
+ for default dub domains, remove all special characters + unicode normalization
+ to remove accents / diacritical marks. this is to prevent phishing/typo squatting
+ for custom domains this is fine, since only the workspace can set the key
+ */
+ if (isDubDomain(domain)) {
+ key = key.normalize("NFD").replace(/[\u0300-\u036f]/g, "");
+ }
+ // encode the key to ascii
+ key = punyEncode(key);
+
+ return key;
+}
diff --git a/apps/web/lib/api/links/utils/transform-link.ts b/apps/web/lib/api/links/utils/transform-link.ts
new file mode 100644
index 0000000000..c9eb0c9c34
--- /dev/null
+++ b/apps/web/lib/api/links/utils/transform-link.ts
@@ -0,0 +1,33 @@
+import { linkConstructor } from "@dub/utils";
+import { Link, Tag } from "@prisma/client";
+
+export type LinkWithTags = Link & {
+ tags?: { tag: Pick<Tag, "id" | "name" | "color"> }[];
+};
+
+// Transform link with additional properties
+export const transformLink = (link: LinkWithTags) => {
+ const tags = (link.tags || []).map(({ tag }) => tag);
+
+ const shortLink = linkConstructor({
+ domain: link.domain,
+ key: link.key,
+ });
+
+ const qrLink = linkConstructor({
+ domain: link.domain,
+ key: link.key,
+ searchParams: {
+ qr: "1",
+ },
+ });
+
+ return {
+ ...link,
+ shortLink,
+ tagId: tags?.[0]?.id ?? null, // backwards compatibility
+ tags,
+ qrCode: `https://api.dub.co/qr?url=${qrLink}`,
+ workspaceId: link.projectId ? `ws_${link.projectId}` : null,
+ };
+};
diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.ts
index 2ac021d69b..e0cae5077b 100644
--- a/apps/web/lib/tinybird/record-click.ts
+++ b/apps/web/lib/tinybird/record-click.ts
@@ -15,6 +15,7 @@ import {
getIdentityHash,
} from "../middleware/utils";
import { conn } from "../planetscale";
+import { prismaEdge } from "../prisma/edge";
import { ratelimit } from "../upstash";
import { webhookCache } from "../webhook/cache";
import { sendWebhooks } from "../webhook/qstash";
@@ -114,7 +115,7 @@ export async function recordClick({
referer_url: referer || "(direct)",
};
- await Promise.allSettled([
+ const [_tb, link, _project] = await Promise.allSettled([
fetch(
`${process.env.TINYBIRD_API_URL}/v0/events?name=dub_click_events&wait=true`,
{
@@ -127,10 +128,10 @@ export async function recordClick({
).then((res) => res.json()),
// increment the click count for the link (based on their ID)
- conn.execute(
- "UPDATE Link SET clicks = clicks + 1, lastClicked = NOW() WHERE id = ?",
- [linkId],
- ),
+ prismaEdge.link.update({
+ where: { id: linkId },
+ data: { clicks: { increment: 1 } },
+ }),
// if the link has a destination URL, increment the usage count for the workspace
// and then we have a cron that will reset it at the start of new billing cycle
url &&
@@ -156,7 +157,16 @@ export async function recordClick({
trigger: "link.clicked",
webhooks: linkWebhooks,
// @ts-ignore
- data: transformClickEventData(clickData),
+ data: transformClickEventData({
+ ...clickData,
+ // on the super rare case that the link failed to fetch, we'll use the link ID as a fallback
+ link:
+ link.status === "fulfilled"
+ ? link.value
+ : {
+ id: linkId,
+ },
+ }),
});
}
}
diff --git a/apps/web/lib/webhook/schemas.ts b/apps/web/lib/webhook/schemas.ts
index 712f2dc8a4..200e8ca987 100644
--- a/apps/web/lib/webhook/schemas.ts
+++ b/apps/web/lib/webhook/schemas.ts
@@ -32,7 +32,7 @@ export const clickEventSchema = z.object({
refererUrl: z.string(),
timestamp: z.string(),
identityHash: z.string(),
- link: z.object({ id: z.string() }),
+ link: LinkSchema,
});
export const leadEventSchema = z.object({
@@ -42,12 +42,7 @@ export const leadEventSchema = z.object({
customerEmail: z.string().nullable(),
customerAvatar: z.string().nullable(),
click: clickEventSchema.partial(),
- link: z.object({
- id: z.string(),
- externalId: z.string().nullable(),
- domain: z.string(),
- key: z.string(),
- }),
+ link: LinkSchema,
});
export const saleEventSchema = z.object({
@@ -61,12 +56,7 @@ export const saleEventSchema = z.object({
invoiceId: z.string().nullable(),
currency: z.string(),
click: clickEventSchema.partial(),
- link: z.object({
- id: z.string(),
- externalId: z.string().nullable(),
- domain: z.string(),
- key: z.string(),
- }),
+ link: LinkSchema,
});
// Schema of the payload sent to the webhook endpoint by Dub
diff --git a/apps/web/lib/webhook/transform.ts b/apps/web/lib/webhook/transform.ts
index 9e194edb46..7361d5e0c0 100644
--- a/apps/web/lib/webhook/transform.ts
+++ b/apps/web/lib/webhook/transform.ts
@@ -1,6 +1,7 @@
import { webhookPayloadSchema } from "@/lib/webhook/schemas";
import { nanoid, toCamelCase } from "@dub/utils";
import type { Link, Webhook } from "@prisma/client";
+import { LinkWithTags, transformLink } from "../api/links/utils/transform-link";
import { WebhookTrigger } from "../types";
import z from "../zod";
import { clickEventSchemaTB } from "../zod/schemas/clicks";
@@ -37,7 +38,9 @@ export const transformLinkEventData = (data: Link) => {
};
export const transformClickEventData = (
- data: z.infer<typeof clickEventSchemaTB>,
+ data: z.infer<typeof clickEventSchemaTB> & {
+ link: any;
+ },
) => {
const click = Object.fromEntries(
Object.entries(data).map(([key, value]) => [toCamelCase(key), value]),
@@ -45,9 +48,7 @@ export const transformClickEventData = (
return clickEventSchema.parse({
...click,
- link: {
- id: click.linkId,
- },
+ link: transformLinkEventData(transformLink(data.link as LinkWithTags)),
});
};
@@ -63,12 +64,9 @@ export const transformLeadEventData = (data: any) => {
qr: lead.qr === 1,
bot: lead.bot === 1,
},
- link: {
- id: lead.linkId,
- externalId: lead.externalId,
- domain: lead.domain,
- key: lead.key,
- },
+ // transformLinkEventData -> normalize date to string
+ // transformLink -> add shortLink, qrCode, workspaceId, etc.
+ link: transformLinkEventData(transformLink(lead.link as LinkWithTags)),
});
};
@@ -84,12 +82,9 @@ export const transformSaleEventData = (data: any) => {
qr: sale.qr === 1,
bot: sale.bot === 1,
},
- link: {
- id: sale.linkId,
- externalId: sale.externalId,
- domain: sale.domain,
- key: sale.key,
- },
+ // transformLinkEventData -> normalize date to string
+ // transformLink -> add shortLink, qrCode, workspaceId, etc.
+ link: transformLinkEventData(transformLink(sale.link as LinkWithTags)),
});
};