The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Improve Lead Tracking
Steven Tey830b09874b17
diff --git a/apps/web/app/api/track/customer/route.ts b/apps/web/app/api/track/customer/route.tsindex 9178360d76..f0c8692e82 100644--- a/apps/web/app/api/track/customer/route.ts+++ b/apps/web/app/api/track/customer/route.ts@@ -1,13 +1,12 @@import { DubApiError } from "@/lib/api/errors";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspaceEdge } from "@/lib/auth/workspace-edge";+import { generateRandomName } from "@/lib/names";import { prismaEdge } from "@/lib/prisma/edge";import { recordCustomer } from "@/lib/tinybird";-import {- trackCustomerRequestSchema,- trackCustomerResponseSchema,-} from "@/lib/zod/schemas/customers";+import { trackCustomerRequestSchema } from "@/lib/zod/schemas/customers";import { nanoid } from "@dub/utils";+import { waitUntil } from "@vercel/functions";import { NextResponse } from "next/server";export const runtime = "edge";@@ -16,59 +15,62 @@ export const runtime = "edge";export const POST = withWorkspaceEdge(async ({ req, workspace }) => {const {+ customerId: externalId,customerName,customerEmail,customerAvatar,- customerId: externalId,} = trackCustomerRequestSchema.parse(await parseRequestBody(req));- // Find customer- const existingCustomer = await prismaEdge.customer.findUnique({- where: {- projectId_externalId: {- projectId: workspace.id,+ const randomId = `cus_${nanoid(16)}`;+ const randomName = generateRandomName();++ try {+ const customer = await prismaEdge.customer.upsert({+ where: {+ projectId_externalId: {+ projectId: workspace.id,+ externalId,+ },+ },+ create: {+ id: randomId,+ name: customerName || randomName,+ email: customerEmail,+ avatar: customerAvatar,externalId,+ projectId: workspace.id,+ projectConnectId: workspace.stripeConnectId,+ },+ update: {+ name: customerName,+ email: customerEmail,+ avatar: customerAvatar,},- },- });+ });++ waitUntil(+ recordCustomer({+ workspace_id: workspace.id,+ customer_id: customer.id,+ name: customer.name || "",+ email: customer.email || "",+ avatar: customer.avatar || "",+ }),+ );- if (existingCustomer) {+ return NextResponse.json(customer, { status: 201 });+ } catch (error) {+ if (error.code === "P2002") {+ throw new DubApiError({+ code: "conflict",+ message: `A customer with customerId: ${externalId} already exists`,+ });+ }throw new DubApiError({- code: "conflict",- message: `A customer with customerId: ${externalId} already exists`,+ code: "internal_server_error",+ message: "Failed to create customer",});}-- // Create a new customer- const customer = await prismaEdge.customer.create({- data: {- id: nanoid(16),- name: customerName, // TODO: Generate random name if not provided- email: customerEmail,- avatar: customerAvatar,- externalId,- projectId: workspace.id,- projectConnectId: "", // TODO: This can be null- },- });-- // Record customer- await recordCustomer({- workspace_id: workspace.id,- customer_id: customer.id,- name: customerName || "",- email: customerEmail || "",- avatar: customerAvatar || "",- });-- const response = trackCustomerResponseSchema.parse({- customerId: externalId,- customerName,- customerEmail,- customerAvatar,- });-- return NextResponse.json(response, { status: 201 });},{ betaFeature: true },);diff --git a/apps/web/app/api/track/lead/route.ts b/apps/web/app/api/track/lead/route.tsindex d7d26540b0..5244800e7b 100644--- a/apps/web/app/api/track/lead/route.ts+++ b/apps/web/app/api/track/lead/route.ts@@ -1,6 +1,7 @@import { DubApiError } from "@/lib/api/errors";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspaceEdge } from "@/lib/auth/workspace-edge";+import { generateRandomName } from "@/lib/names";import { prismaEdge } from "@/lib/prisma/edge";import { getClickEvent, recordCustomer, recordLead } from "@/lib/tinybird";import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";@@ -19,11 +20,11 @@ export const POST = withWorkspaceEdge(const {clickId,eventName,- metadata,+ customerId: externalId,customerName,customerEmail,customerAvatar,- customerId: externalId,+ metadata,} = trackLeadRequestSchema.parse(await parseRequestBody(req));// Find click event@@ -40,6 +41,9 @@ export const POST = withWorkspaceEdge(.omit({ timestamp: true }).parse(clickEvent.data[0]);+ const randomId = `cus_${nanoid(16)}`;+ const randomName = generateRandomName();+// Find customer or create if not existsconst customer = await prismaEdge.customer.upsert({where: {@@ -49,8 +53,8 @@ export const POST = withWorkspaceEdge(},},create: {- id: nanoid(16),- name: customerName, // TODO: Generate random name if not provided+ id: randomId,+ name: customerName || randomName,email: customerEmail,avatar: customerAvatar,externalId,@@ -72,14 +76,6 @@ export const POST = withWorkspaceEdge(}await Promise.all([- recordCustomer({- workspace_id: workspace.id,- customer_id: customer.id,- name: customerName || "",- email: customerEmail || "",- avatar: customerAvatar || "",- }),-recordLead({...clickData,event_id: nanoid(16),@@ -88,6 +84,14 @@ export const POST = withWorkspaceEdge(metadata: metadata ? JSON.stringify(metadata) : "",}),+ recordCustomer({+ workspace_id: workspace.id,+ customer_id: customer.id,+ name: customer.name || "",+ email: customer.email || "",+ avatar: customer.avatar || "",+ }),+// update link leads countprismaEdge.link.update({where: {@@ -104,10 +108,11 @@ export const POST = withWorkspaceEdge(const response = trackLeadResponseSchema.parse({clickId,eventName,- customerName,- customerEmail,- customerAvatar,- customerId: externalId,+ customerId: customer.id,+ customerName: customer.name,+ customerEmail: customer.email,+ customerAvatar: customer.avatar,+ externalId: customer.externalId,metadata,});diff --git a/apps/web/lib/names.ts b/apps/web/lib/names.tsnew file mode 100644index 0000000000..b1b2dc75b2--- /dev/null+++ b/apps/web/lib/names.ts@@ -0,0 +1,17 @@+import {+ Config,+ adjectives,+ animals,+ colors,+ uniqueNamesGenerator,+} from "unique-names-generator";++export const generateRandomName = () => {+ const config: Config = {+ dictionaries: [adjectives, colors, animals],+ separator: " ",+ style: "capital",+ };++ return uniqueNamesGenerator(config);+};diff --git a/apps/web/lib/zod/schemas/clicks.ts b/apps/web/lib/zod/schemas/clicks.tsindex 1a50868e33..88a97cf99c 100644--- a/apps/web/lib/zod/schemas/clicks.ts+++ b/apps/web/lib/zod/schemas/clicks.ts@@ -24,4 +24,6 @@ export const clickEventSchemaTB = z.object({bot: z.number().nullable(),referer: z.string().nullable(),referer_url: z.string().nullable(),+ ip: z.string().nullable(),+ qr: z.number().nullable(),});diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.tsindex 2181d1dbb9..5538e6f0b7 100644--- a/apps/web/lib/zod/schemas/customers.ts+++ b/apps/web/lib/zod/schemas/customers.ts@@ -15,21 +15,18 @@ export const trackCustomerRequestSchema = z.object({customerName: z.string().max(100)- .nullish()- .default(null)+ .optional().describe("Name of the customer in the client's app."),customerEmail: z.string().email().max(100)- .nullish()- .default(null)+ .optional().describe("Email of the customer in the client's app."),customerAvatar: z.string().max(100)- .nullish()- .default(null)+ .optional().describe("Avatar of the customer in the client's app."),});@@ -41,7 +38,13 @@ export const trackCustomerResponseSchema = z.object({});export const customersMetadataSchema = z.object({- workspace_id: z.string(),+ workspace_id: z.string().transform((v) => {+ if (!v.startsWith("ws_")) {+ return `ws_${v}`;+ } else {+ return v;+ }+ }),customer_id: z.string(),name: z.string().default(""),email: z.string().default(""),diff --git a/apps/web/lib/zod/schemas/leads.ts b/apps/web/lib/zod/schemas/leads.tsindex eccc3f4687..a2e7fb94c3 100644--- a/apps/web/lib/zod/schemas/leads.ts+++ b/apps/web/lib/zod/schemas/leads.ts@@ -30,26 +30,22 @@ export const trackLeadRequestSchema = z.object({customerName: z.string().max(100)- .nullish()- .default(null)+ .optional().describe("Name of the customer in the client's app."),customerEmail: z.string().email().max(100)- .nullish()- .default(null)+ .optional().describe("Email of the customer in the client's app."),customerAvatar: z.string().max(100)- .nullish()- .default(null)+ .optional().describe("Avatar of the customer in the client's app."),metadata: z.record(z.unknown())- .nullish()- .default(null)+ .optional().describe("Additional metadata to be stored with the lead event"),});@@ -60,7 +56,7 @@ export const trackLeadResponseSchema = z.object({customerName: z.string().nullable(),customerEmail: z.string().nullable(),customerAvatar: z.string().nullable(),- metadata: z.record(z.unknown()).nullable(),+ metadata: z.record(z.unknown()).optional(),});export const leadEventSchemaTB = clickEventSchemaTBdiff --git a/apps/web/package.json b/apps/web/package.jsonindex 17aa83022a..dab7c30735 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -95,6 +95,7 @@"stripe": "^12.12.0","swr": "^2.1.5","topojson-client": "^3.1.0",+ "unique-names-generator": "^4.7.1","unsplash-js": "^7.0.18","use-debounce": "^8.0.4","vaul": "^0.6.8",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 062a6814fa..c2971a43fe 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -283,6 +283,9 @@ importers:topojson-client:specifier: ^3.1.0version: 3.1.0+ unique-names-generator:+ specifier: ^4.7.1+ version: 4.7.1unsplash-js:specifier: ^7.0.18version: 7.0.18@@ -17098,6 +17101,7 @@ packages:resolution: {integrity: sha512-mwqeW5XsA2qAejG46gYdENaxXjx9onRNCfn7L0duuP4hCuTIi/QO7PDK07KJfp1d+izWPrzEJDcSqBa0OZQriA==}+ deprecated: Rimraf versions prior to v4 are no longer supportedhasBin: truedependencies:glob: 7.2.3@@ -18972,6 +18976,11 @@ packages:vfile: 5.3.7dev: false+ resolution: {integrity: sha512-lMx9dX+KRmG8sq6gulYYpKWZc9RlGsgBR6aoO8Qsm3qvkSJ+3rAymr+TnV8EDMrIrwuFJ4kruzMWM/OpYzPoow==}+ engines: {node: '>=8'}+ dev: false+resolution: {integrity: sha512-u9njyyfEh43npf1M+yGKDGVPbY/JWEemg5nH05ncKPfi+kBbKBJoTdsogMu33uhytuLlv9y0O7GH7fEdwLdLQw==}dependencies: