The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
upate the api
Kiran K7b960e334058
diff --git a/apps/web/app/api/track/click/route.ts b/apps/web/app/api/track/click/route.tsindex c85bdcfa98..a65448af21 100644--- a/apps/web/app/api/track/click/route.ts+++ b/apps/web/app/api/track/click/route.ts@@ -1,6 +1,6 @@-import { DubApiError } from "@/lib/api/errors";-import { parseRequestBody } from "@/lib/api/utils";-import { getLinkViaEdge } from "@/lib/planetscale";+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";+import { extractPublishableKey, parseRequestBody } from "@/lib/api/utils";+import { getLink, getProjectByPublishableKey } from "@/lib/planetscale";import { recordClick } from "@/lib/tinybird";import { redis } from "@/lib/upstash";import { nanoid } from "@dub/utils";@@ -10,44 +10,56 @@ import { NextResponse } from "next/server";export const runtime = "edge";-// POST /api/track/click – Track a click event+// POST /api/track/click – Track a click event from client sideexport const POST = async (req: Request) => {- const { domain, identifier } = await parseRequestBody(req);+ try {+ const publishableKey = extractPublishableKey(req);+ const workspace = await getProjectByPublishableKey(publishableKey);- const link = await getLinkViaEdge(domain, identifier);+ if (!workspace) {+ throw new DubApiError({+ code: "unauthorized",+ message: `Workspace not found for publishable key: ${publishableKey}`,+ });+ }- if (- !link- // || link.projectId !== workspace.id- ) {- throw new DubApiError({- code: "not_found",- message: `Link not found for identifier: ${identifier}`,- });- }+ const { identifier } = await parseRequestBody(req);- const redisKey = `trackClick:${link.id}:${ipAddress(req)}`;- let clickId = await redis.get<string>(redisKey);- if (!clickId) {- clickId = nanoid(16);-- waitUntil(- Promise.allSettled([- redis.set(redisKey, clickId, {- ex: 60 * 60,- }), // 1 hour- recordClick({- req,- clickId,- linkId: link.id,- url: link.url,- skipRatelimit: true,- }),- ]),- );- }+ const link = await getLink(workspace.id, identifier);++ if (!link) {+ throw new DubApiError({+ code: "not_found",+ message: `Link not found for identifier: ${identifier}`,+ });+ }++ const redisKey = `trackClick:${link.id}:${ipAddress(req)}`;+ let clickId = await redis.get<string>(redisKey);- return NextResponse.json({- clickId,- });+ if (!clickId) {+ clickId = nanoid(16);++ waitUntil(+ Promise.allSettled([+ redis.set(redisKey, clickId, {+ ex: 60 * 60,+ }), // 1 hour+ recordClick({+ req,+ clickId,+ linkId: link.id,+ url: link.url,+ skipRatelimit: true,+ }),+ ]),+ );+ }++ return NextResponse.json({+ clickId,+ });+ } catch (error) {+ return handleAndReturnErrorResponse(error);+ }};diff --git a/apps/web/lib/actions/create-publishable-key.ts b/apps/web/lib/actions/create-publishable-key.tsindex b519743d1b..0bc061a850 100644--- a/apps/web/lib/actions/create-publishable-key.ts+++ b/apps/web/lib/actions/create-publishable-key.ts@@ -23,7 +23,7 @@ export const createPublishableKey = authActionClientthrow new Error("Publishable key already exists.");}- const publishableKey = `dub_pk_${nanoid(24)}`;+ const publishableKey = `dub_publishable_${nanoid(24)}`;await prisma.project.update({where: {diff --git a/apps/web/lib/api/utils.ts b/apps/web/lib/api/utils.tsindex caca93bd44..2bb67b9b34 100644--- a/apps/web/lib/api/utils.ts+++ b/apps/web/lib/api/utils.ts@@ -50,3 +50,16 @@ export const getIP = () => {return headers().get("x-real-ip") ?? FALLBACK_IP_ADDRESS;};++export const extractPublishableKey = (req: Request) => {+ const authorizationHeader = req.headers.get("Authorization");++ if (!authorizationHeader) {+ throw new DubApiError({+ code: "bad_request",+ message: "Missing authorization header",+ });+ }++ return authorizationHeader.replace("Bearer ", "");+};diff --git a/apps/web/lib/planetscale.ts b/apps/web/lib/planetscale.tsindex 1912c9c610..a7dd1172b3 100644--- a/apps/web/lib/planetscale.ts+++ b/apps/web/lib/planetscale.ts@@ -1,5 +1,6 @@import { nanoid, punyEncode } from "@dub/utils";import { connect } from "@planetscale/database";+import { Link, Project } from "@prisma/client";import { WorkspaceProps } from "./types";export const DATABASE_URL =@@ -101,3 +102,32 @@ export async function getRandomKey({return key;}}++// Get project by publishable key+export const getProjectByPublishableKey = async (publishableKey: string) => {+ if (!DATABASE_URL) return null;++ const { rows } =+ (await conn.execute(+ "SELECT * FROM Project WHERE publishableKey = ? LIMIT 1",+ [publishableKey],+ )) || {};++ return rows && Array.isArray(rows) && rows.length > 0+ ? (rows[0] as Project)+ : null;+};++export const getLink = async (projectId: string, identifier: string) => {+ if (!DATABASE_URL) return null;++ const { rows } =+ (await conn.execute(+ "SELECT * FROM Link WHERE projectId = ? AND identifier = ? LIMIT 1",+ [projectId, identifier],+ )) || {};++ return rows && Array.isArray(rows) && rows.length > 0+ ? (rows[0] as Link)+ : null;+};