The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add API endpoint for tracking conversions
Kiran K3b77aabdb977
diff --git a/apps/web/app/api/track/conversions/route.ts b/apps/web/app/api/track/conversions/route.tsnew file mode 100644index 0000000000..6ae8879c4d--- /dev/null+++ b/apps/web/app/api/track/conversions/route.ts@@ -0,0 +1,34 @@+import { parseRequestBody } from "@/lib/api/utils";+import { withWorkspace } from "@/lib/auth";+import { getClickEvent, recordConversion } from "@/lib/tinybird";+import { conversionRequestSchema } from "@/lib/zod/schemas/conversions";+import { NextResponse } from "next/server";++// export const runtime = "edge";++// TODO:+// Support Edge and waitUntil+// Replace withWorkspace++// POST /api/track/conversions – post conversion event+export const POST = withWorkspace(async ({ req }) => {+ const body = await parseRequestBody(req);+ const { clickId, eventName, eventType, metadata, customerId } =+ conversionRequestSchema.parse(body);++ const clickEvent = await getClickEvent(clickId);++ if (!clickEvent) {+ return NextResponse.json({ success: false }, { status: 404 });+ }++ await recordConversion({+ ...clickEvent,+ eventName,+ eventType,+ metadata,+ customerId,+ });++ return NextResponse.json({ success: true });+});diff --git a/apps/web/lib/tinybird.ts b/apps/web/lib/tinybird.tsindex c691382312..11eba45adb 100644--- a/apps/web/lib/tinybird.ts+++ b/apps/web/lib/tinybird.ts@@ -12,6 +12,7 @@ import { detectBot, detectQr, getIdentityHash } from "./middleware/utils";import { conn } from "./planetscale";import { LinkProps } from "./types";import { ratelimit } from "./upstash";+import { ConversionEvent, clickEventSchema } from "./zod/schemas/conversions";/*** Recording clicks with geo, ua, referer and timestamp data@@ -156,3 +157,38 @@ export async function recordLink({},).then((res) => res.json());}++// TODO:+// Review this is the right way to fetch+export async function getClickEvent(clickId: string) {+ const url = new URL(+ `${process.env.TINYBIRD_API_URL}/v0/pipes/click_by_id.json`,+ );++ url.searchParams.append("clickId", clickId);++ const response = await fetch(url.toString(), {+ headers: {+ Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,+ },+ });++ if (!response.ok) {+ console.error("Error fetching click event from Tinybird", response);+ return null;+ }++ const { rows, data } = await response.json();++ if (rows === 0) {+ console.error("No click event found in Tinybird", clickId);+ return null;+ }++ return clickEventSchema.parse(data[0]);+}++// Record conversion event in Tinybird+export async function recordConversion(event: ConversionEvent) {+ console.log("event", event);+}diff --git a/apps/web/lib/zod/schemas/conversions.ts b/apps/web/lib/zod/schemas/conversions.tsnew file mode 100644index 0000000000..f643bada57--- /dev/null+++ b/apps/web/lib/zod/schemas/conversions.ts@@ -0,0 +1,42 @@+import z from "@/lib/zod";++export const clickEventSchema = z.object({+ timestamp: z.string(),+ click_id: z.string(),+ link_id: z.string(),+ url: z.string(),+ country: z.string().nullable(),+ city: z.string().nullable(),+ device: z.string().nullable(),+ browser: z.string().nullable(),+ os: z.string().nullable(),+ referer: z.string().nullable(),+});++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: z+ .union([z.literal("lead"), z.literal("sale")], {+ errorMap: () => ({+ message: "Must be either 'lead' or 'sale'",+ }),+ })+ .default("lead"),+ metadata: z.record(z.unknown()).nullish(),+ customerId: z.string().max(100).nullish(),+});++export const conversionEventSchema = clickEventSchema.merge(+ conversionRequestSchema.pick({+ eventName: true,+ eventType: true,+ metadata: true,+ customerId: true,+ }),+);++export type ConversionEvent = z.infer<typeof conversionEventSchema>;diff --git a/packages/tinybird/endpoints/click_by_id.pipe b/packages/tinybird/endpoints/click_by_id.pipenew file mode 100644index 0000000000..05e17f7199--- /dev/null+++ b/packages/tinybird/endpoints/click_by_id.pipe@@ -0,0 +1,11 @@+DESCRIPTION >+ Get click event by id++TOKEN "browser_endpoint_read_5885" READ++NODE endpoint+DESCRIPTION >+ undefined++SQL >+ % SELECT * FROM dub_click_events_mv WHERE click_id = {{ clickId }} LIMIT 1\ No newline at end of file