The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
add track/lead track/sale, track/customer, datasources etc.
Steven Tey37dd8e6e9cbb
diff --git a/apps/web/app/api/track/customer/route.ts b/apps/web/app/api/track/customer/route.tsnew file mode 100644index 0000000000..94d9df9e62--- /dev/null+++ b/apps/web/app/api/track/customer/route.ts@@ -0,0 +1,27 @@+import { parseRequestBody } from "@/lib/api/utils";+import { withSessionEdge } from "@/lib/auth/session-edge";+import { recordCustomer } from "@/lib/tinybird";+import { trackCustomerRequestSchema } from "@/lib/zod/schemas/customers";+import { waitUntil } from "@vercel/functions";+import { NextResponse } from "next/server";++export const runtime = "edge";++// POST /api/track/customer – Track a customer object+export const POST = withSessionEdge(async ({ req }) => {+ const { customerId, customerName, customerEmail, customerAvatar } =+ trackCustomerRequestSchema.parse(await parseRequestBody(req));++ waitUntil(+ recordCustomer({+ timestamp: new Date(Date.now()).toISOString(),+ customer_id: customerId,+ name: customerName,+ email: customerEmail,+ avatar: customerAvatar,+ project_id: "",+ }),+ );++ return NextResponse.json({ success: true });+});diff --git a/apps/web/app/api/track/lead/route.ts b/apps/web/app/api/track/lead/route.tsnew file mode 100644index 0000000000..f43f8e62e0--- /dev/null+++ b/apps/web/app/api/track/lead/route.ts@@ -0,0 +1,57 @@+import { parseRequestBody } from "@/lib/api/utils";+import { withSessionEdge } from "@/lib/auth/session-edge";+import { getClickEvent, recordCustomer, recordLead } from "@/lib/tinybird";+import { trackLeadRequestSchema } from "@/lib/zod/schemas";+import { nanoid } from "@dub/utils";+import { waitUntil } from "@vercel/functions";+import { NextResponse } from "next/server";++export const runtime = "edge";++// POST /api/track/lead – Track a lead conversion event+export const POST = withSessionEdge(async ({ req }) => {+ const {+ clickId,+ eventName,+ metadata,+ customerId,+ customerName,+ customerEmail,+ customerAvatar,+ } = trackLeadRequestSchema.parse(await parseRequestBody(req));++ waitUntil(+ (async () => {+ const clickEvent = await getClickEvent({ clickId });++ if (!clickEvent || clickEvent.data.length === 0) {+ return;+ }++ await Promise.all([+ recordLead({+ ...clickEvent.data[0],+ timestamp: new Date(Date.now()).toISOString(),+ event_name: eventName,+ event_id: nanoid(16),+ customer_id: customerId,+ metadata,+ }),+ ...(customerName || customerEmail || customerAvatar+ ? [+ recordCustomer({+ timestamp: new Date(Date.now()).toISOString(),+ customer_id: customerId,+ name: customerName,+ email: customerEmail,+ avatar: customerAvatar,+ project_id: "",+ }),+ ]+ : []),+ ]);+ })(),+ );++ return NextResponse.json({ success: true });+});diff --git a/apps/web/app/api/track/route.ts b/apps/web/app/api/track/route.tsdeleted file mode 100644index 8f2ab27c47..0000000000--- a/apps/web/app/api/track/route.ts+++ /dev/null@@ -1,63 +0,0 @@-import { parseRequestBody } from "@/lib/api/utils";-import { withSessionEdge } from "@/lib/auth/session-edge";-import { getClickEvent, recordLead, recordSale } from "@/lib/tinybird";-import { conversionRequestSchema } from "@/lib/zod/schemas/conversions";-import { log, nanoid } from "@dub/utils";-import { waitUntil } from "@vercel/functions";-import { NextResponse } from "next/server";--export const runtime = "edge";--// POST /api/track – Track a click conversion event-export const POST = withSessionEdge(async ({ req }) => {- const body = conversionRequestSchema.parse(await parseRequestBody(req));- const { clickId, eventName, eventType, metadata, customerId } = body;-- waitUntil(- (async () => {- const clickEvent = await getClickEvent({ clickId });-- if (!clickEvent || clickEvent.data.length === 0) {- return;- }-- const conversionEvent = {- ...clickEvent.data[0],- timestamp: new Date(Date.now()).toISOString(),- event_id: nanoid(16),- customer_id: customerId,- metadata,- };-- await Promise.all([- eventType === "lead"- ? recordLead({- ...conversionEvent,- event_name: eventName,- })- : recordSale({- ...conversionEvent,-- // TODO: Fix this- payment_processor: "stripe",- stripe_customer_id: "",- product_id: "",- amount: 1000,- currency: "usd",- recurring: true,- recurring_interval: "month",- recurring_interval_count: 1,- refunded: false,- }),-- // TODO: Remove this before launch- log({- message: `*Conversion event recorded*: Customer *${customerId}* converted on click *${clickId}* with event *${eventName}*.`,- type: "alerts",- }),- ]);- })(),- );-- return NextResponse.json({ success: true });-});diff --git a/apps/web/app/api/track/sale/route.ts b/apps/web/app/api/track/sale/route.tsnew file mode 100644index 0000000000..2651a6125b--- /dev/null+++ b/apps/web/app/api/track/sale/route.ts@@ -0,0 +1,49 @@+import { parseRequestBody } from "@/lib/api/utils";+import { withSessionEdge } from "@/lib/auth/session-edge";+import { getLeadEvent, recordSale } from "@/lib/tinybird";+import { trackSaleEventSchema } from "@/lib/zod/schemas";+import { waitUntil } from "@vercel/functions";+import { NextResponse } from "next/server";++export const runtime = "edge";++// POST /api/track/sale – Track a sale conversion event+export const POST = withSessionEdge(async ({ req }) => {+ const {+ customerId,+ paymentProcessor,+ productId,+ amount,+ currency,+ recurring,+ recurringInterval,+ recurringIntervalCount,+ refunded,+ metadata,+ } = trackSaleEventSchema.parse(await parseRequestBody(req));++ waitUntil(+ (async () => {+ const leadEvent = await getLeadEvent({ customerId });++ if (!leadEvent || leadEvent.data.length === 0) {+ return;+ }++ await recordSale({+ ...leadEvent.data[0],+ payment_processor: paymentProcessor,+ product_id: productId,+ amount,+ currency,+ recurring,+ recurring_interval: recurringInterval,+ recurring_interval_count: recurringIntervalCount,+ refunded,+ metadata,+ });+ })(),+ );++ return NextResponse.json({ success: true });+});diff --git a/apps/web/lib/tinybird/get-click-event.ts b/apps/web/lib/tinybird/get-click-event.tsindex 1c14dad198..714462b65e 100644--- a/apps/web/lib/tinybird/get-click-event.ts+++ b/apps/web/lib/tinybird/get-click-event.ts@@ -1,5 +1,5 @@import z from "../zod";-import { clickEventSchemaTB } from "../zod/schemas/conversions";+import { clickEventSchemaTB } from "../zod/schemas/clicks";import { tb } from "./client";export const getClickEvent = tb.buildPipe({diff --git a/apps/web/lib/tinybird/get-lead-event.ts b/apps/web/lib/tinybird/get-lead-event.tsnew file mode 100644index 0000000000..a32a4d8283--- /dev/null+++ b/apps/web/lib/tinybird/get-lead-event.ts@@ -0,0 +1,11 @@+import z from "../zod";+import { leadEventSchemaTB } from "../zod/schemas";+import { tb } from "./client";++export const getLeadEvent = tb.buildPipe({+ pipe: "get_lead_event",+ parameters: z.object({+ customerId: z.string(),+ }),+ data: leadEventSchemaTB,+});diff --git a/apps/web/lib/tinybird/index.ts b/apps/web/lib/tinybird/index.tsindex 62663c8805..5d04cc3b9d 100644--- a/apps/web/lib/tinybird/index.ts+++ b/apps/web/lib/tinybird/index.ts@@ -1,5 +1,7 @@export * from "./get-click-event";+export * from "./get-lead-event";export * from "./record-click";+export * from "./record-customer";export * from "./record-lead";export * from "./record-link";export * from "./record-sale";diff --git a/apps/web/lib/tinybird/record-customer.ts b/apps/web/lib/tinybird/record-customer.tsnew file mode 100644index 0000000000..6614218a11--- /dev/null+++ b/apps/web/lib/tinybird/record-customer.ts@@ -0,0 +1,7 @@+import { customersMetadataSchema } from "../zod/schemas/customers";+import { tb } from "./client";++export const recordCustomer = tb.buildIngestEndpoint({+ datasource: "dub_customers_metadata",+ event: customersMetadataSchema,+});diff --git a/apps/web/lib/tinybird/record-lead.ts b/apps/web/lib/tinybird/record-lead.tsindex cd0ac1376e..6b9c80fdf5 100644--- a/apps/web/lib/tinybird/record-lead.ts+++ b/apps/web/lib/tinybird/record-lead.ts@@ -1,4 +1,4 @@-import { leadEventSchemaTB } from "../zod/schemas/conversions";+import { leadEventSchemaTB } from "../zod/schemas";import { tb } from "./client";export const recordLead = tb.buildIngestEndpoint({diff --git a/apps/web/lib/tinybird/record-sale.ts b/apps/web/lib/tinybird/record-sale.tsindex f306e137d4..fa89a012af 100644--- a/apps/web/lib/tinybird/record-sale.ts+++ b/apps/web/lib/tinybird/record-sale.ts@@ -1,4 +1,4 @@-import { saleEventSchemaTB } from "../zod/schemas/conversions";+import { saleEventSchemaTB } from "../zod/schemas";import { tb } from "./client";export const recordSale = tb.buildIngestEndpoint({diff --git a/apps/web/lib/zod/schemas/clicks.ts b/apps/web/lib/zod/schemas/clicks.tsnew file mode 100644index 0000000000..1a50868e33--- /dev/null+++ b/apps/web/lib/zod/schemas/clicks.ts@@ -0,0 +1,27 @@+import z from "@/lib/zod";++export const clickEventSchemaTB = z.object({+ timestamp: z.string(),+ click_id: z.string(),+ link_id: z.string(),+ url: z.string(),+ country: z.string().nullable(),+ city: z.string().nullable(),+ region: z.string().nullable(),+ latitude: z.string().nullable(),+ longitude: z.string().nullable(),+ device: z.string().nullable(),+ device_model: z.string().nullable(),+ device_vendor: z.string().nullable(),+ browser: z.string().nullable(),+ browser_version: z.string().nullable(),+ os: z.string().nullable(),+ os_version: z.string().nullable(),+ engine: z.string().nullable(),+ engine_version: z.string().nullable(),+ cpu_architecture: z.string().nullable(),+ ua: z.string().nullable(),+ bot: z.number().nullable(),+ referer: z.string().nullable(),+ referer_url: z.string().nullable(),+});diff --git a/apps/web/lib/zod/schemas/conversions.ts b/apps/web/lib/zod/schemas/conversions.tsdeleted file mode 100644index 863c60bbe3..0000000000--- a/apps/web/lib/zod/schemas/conversions.ts+++ /dev/null@@ -1,81 +0,0 @@-import z from "@/lib/zod";--export const eventType = z- .enum(["lead", "sale"], {- errorMap: () => ({- message: "Must be either 'lead' or 'sale'",- }),- })- .default("lead");--export const clickEventSchemaTB = z.object({- timestamp: z.string(),- click_id: z.string(),- link_id: z.string(),- url: z.string(),- country: z.string().nullable(),- city: z.string().nullable(),- region: z.string().nullable(),- latitude: z.string().nullable(),- longitude: z.string().nullable(),- device: z.string().nullable(),- device_model: z.string().nullable(),- device_vendor: z.string().nullable(),- browser: z.string().nullable(),- browser_version: z.string().nullable(),- os: z.string().nullable(),- os_version: z.string().nullable(),- engine: z.string().nullable(),- engine_version: z.string().nullable(),- cpu_architecture: z.string().nullable(),- ua: z.string().nullable(),- bot: z.number().nullable(),- referer: z.string().nullable(),- referer_url: z.string().nullable(),-});--export const leadEventSchemaTB = clickEventSchemaTB.omit({ url: true }).and(- z.object({- event_id: z.string(),- event_name: z.string(),- metadata: z.string(), // TODO: Fix the type- customer_id: z.string(),- }),-);--export const saleEventSchemaTB = clickEventSchemaTB.omit({ url: true }).and(- z.object({- event_id: z.string(),- metadata: z.string(), // TODO: Fix the type- customer_id: z.string(),- payment_processor: z.string().default("stripe"),- stripe_customer_id: z.string(),- product_id: z.string(),- amount: z.number().int().positive().default(0),- currency: z.string().default("usd"),- recurring: z.boolean().default(false),- recurring_interval: z.enum(["month", "year"]).default("month"),- recurring_interval_count: z.number().int().positive().default(1),- refunded: z.boolean().default(false),- }),-);--export const conversionRequestSchema = z.object({- clickId: z.string({ required_error: "clickId is required" }),- eventName: z- .string({ required_error: "eventName is required" })- .min(1)- .max(50),- eventType,- metadata: z- .record(z.unknown())- .nullish()- .transform((val) => (val ? JSON.stringify(val) : "")),- customerId: z- .string()- .max(100)- .default("")- .describe(- "This is the identifier for the customer in the client's app. This is used to track the customer's journey.",- ),-});diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.tsnew file mode 100644index 0000000000..2fb8957a7e--- /dev/null+++ b/apps/web/lib/zod/schemas/customers.ts@@ -0,0 +1,18 @@+import z from "@/lib/zod";++export const trackCustomerRequestSchema = z.object({+ customerId: z.string({ required_error: "customerId is required" }),+ customerName: z.string().nullish().default(""),+ customerEmail: z.string().email().nullish().default(""),+ customerAvatar: z.string().url().nullish().default(""),+});++export const customersMetadataSchema = z.object({+ timestamp: z.string(),+ customer_id: z.string(),+ name: z.string().nullish().default(""),+ email: z.string().email().nullish().default(""),+ avatar: z.string().url().nullish().default(""),+ project_id: z.string(),+ deleted: z.boolean().default(false),+});diff --git a/apps/web/lib/zod/schemas/index.ts b/apps/web/lib/zod/schemas/index.tsindex 6ca1a9ed66..1763cb69d6 100644--- a/apps/web/lib/zod/schemas/index.ts+++ b/apps/web/lib/zod/schemas/index.ts@@ -1,7 +1,9 @@export * from "./analytics";-export * from "./domains";+export * from "./clicks";+export * from "./leads";export * from "./links";export * from "./misc";export * from "./qr";+export * from "./sales";export * from "./tags";export * from "./workspaces";diff --git a/apps/web/lib/zod/schemas/leads.ts b/apps/web/lib/zod/schemas/leads.tsnew file mode 100644index 0000000000..69e2935131--- /dev/null+++ b/apps/web/lib/zod/schemas/leads.ts@@ -0,0 +1,51 @@+import z from "@/lib/zod";+import { clickEventSchemaTB } from "./clicks";++export const trackLeadRequestSchema = z.object({+ clickId: z.string({ required_error: "clickId is required" }),+ eventName: z+ .string({ required_error: "eventName is required" })+ .min(1)+ .max(50),+ metadata: z+ .record(z.unknown())+ .nullish()+ .transform((val) => (val ? JSON.stringify(val) : "")),+ customerId: z+ .string()+ .max(100)+ .describe(+ "This is the unique identifier for the customer in the client's app. This is used to track the customer's journey.",+ ),+ customerName: z+ .string()+ .max(100)+ .optional()+ .describe(+ "This is the name of the customer in the client's app. This is used to track the customer's journey.",+ ),+ customerEmail: z+ .string()+ .email()+ .max(100)+ .optional()+ .describe(+ "This is the email of the customer in the client's app. This is used to track the customer's journey.",+ ),+ customerAvatar: z+ .string()+ .max(100)+ .optional()+ .describe(+ "This is the avatar of the customer in the client's app. This is used to track the customer's journey.",+ ),+});++export const leadEventSchemaTB = clickEventSchemaTB.omit({ url: true }).and(+ z.object({+ event_id: z.string(),+ event_name: z.string(),+ metadata: z.string(), // TODO: Fix the type+ customer_id: z.string(),+ }),+);diff --git a/apps/web/lib/zod/schemas/sales.ts b/apps/web/lib/zod/schemas/sales.tsnew file mode 100644index 0000000000..dd0c067896--- /dev/null+++ b/apps/web/lib/zod/schemas/sales.ts@@ -0,0 +1,34 @@+import z from "@/lib/zod";+import { clickEventSchemaTB } from "./clicks";++export const trackSaleEventSchema = z.object({+ customerId: z.string(),+ paymentProcessor: z.enum(["stripe", "shopify", "paddle"]).default("stripe"),+ productId: z.string(),+ amount: z.number().int().positive().default(0),+ currency: z.string().default("usd"),+ recurring: z.boolean().default(false),+ recurringInterval: z.enum(["month", "year"]).default("month"),+ recurringIntervalCount: z.number().int().positive().default(1),+ refunded: z.boolean().default(false),+ metadata: z+ .record(z.unknown())+ .nullish()+ .transform((val) => (val ? JSON.stringify(val) : "")),+});++export const saleEventSchemaTB = clickEventSchemaTB.omit({ url: true }).and(+ z.object({+ event_id: z.string(),+ customer_id: z.string(),+ payment_processor: z.string().default("stripe"),+ product_id: z.string(),+ amount: z.number().int().positive().default(0),+ currency: z.string().default("usd"),+ recurring: z.boolean().default(false),+ recurring_interval: z.enum(["month", "year"]).default("month"),+ recurring_interval_count: z.number().int().positive().default(1),+ refunded: z.boolean().default(false),+ metadata: z.string(), // TODO: Fix the type+ }),+);diff --git a/packages/tinybird/datasources/dub_customers_metadata.datasource b/packages/tinybird/datasources/dub_customers_metadata.datasourcenew file mode 100644index 0000000000..fdb66367b5--- /dev/null+++ b/packages/tinybird/datasources/dub_customers_metadata.datasource@@ -0,0 +1,11 @@+SCHEMA >+ `timestamp` DateTime `json:$.timestamp`,+ `customer_id` String `json:$.customer_id`,+ `name` String `json:$.name`,+ `email` String `json:$.email`,+ `avatar` String `json:$.avatar`,+ `project_id` String `json:$.project_id`,+ `deleted` UInt8 `json:$.deleted`++ENGINE "MergeTree"+ENGINE_SORTING_KEY "timestamp, customer_id, project_id, deleted"\ No newline at end of filediff --git a/packages/tinybird/datasources/dub_sale_events.datasource b/packages/tinybird/datasources/dub_sale_events.datasourceindex 109d838d9d..a1aa48810a 100644--- a/packages/tinybird/datasources/dub_sale_events.datasource+++ b/packages/tinybird/datasources/dub_sale_events.datasource@@ -5,7 +5,6 @@ SCHEMA >`metadata` String `json:$.metadata`,`customer_id` String `json:$.customer_id`,`payment_processor` LowCardinality(String) `json:$.payment_processor`,- `stripe_customer_id` String `json:$.stripe_customer_id`,`product_id` String `json:$.product_id`,`amount` UInt32 `json:$.amount`,`currency` LowCardinality(String) `json:$.currency`,