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.

Add publishableKey support + /track/lead/client

Steven Tey16e09d0cba4f
diff --git a/apps/web/app/(ee)/api/track/lead/client/route.ts b/apps/web/app/(ee)/api/track/lead/client/route.ts
new file mode 100644
index 0000000000..009a830ecd
--- /dev/null
+++ b/apps/web/app/(ee)/api/track/lead/client/route.ts
@@ -0,0 +1,44 @@
+import { trackLead } from "@/lib/api/conversions/track-lead";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withPublishableKey } from "@/lib/auth/publishable-key";
+import { trackLeadRequestSchema } from "@/lib/zod/schemas/leads";
+import { NextResponse } from "next/server";
+
+// POST /api/track/lead/client – Track a lead conversion event on the client side
+export const POST = withPublishableKey(
+ async ({ req, workspace }) => {
+ const body = await parseRequestBody(req);
+
+ const {
+ clickId,
+ eventName,
+ customerExternalId,
+ customerName,
+ customerEmail,
+ customerAvatar,
+ } = trackLeadRequestSchema.parse(body);
+
+ const response = await trackLead({
+ clickId,
+ eventName,
+ customerExternalId,
+ customerName,
+ customerEmail,
+ customerAvatar,
+ rawBody: body,
+ workspace,
+ });
+
+ return NextResponse.json(response);
+ },
+ {
+ requiredPlan: [
+ "business",
+ "business plus",
+ "business extra",
+ "business max",
+ "advanced",
+ "enterprise",
+ ],
+ },
+);
diff --git a/apps/web/lib/auth/publishable-key.ts b/apps/web/lib/auth/publishable-key.ts
new file mode 100644
index 0000000000..843ff0ed4f
--- /dev/null
+++ b/apps/web/lib/auth/publishable-key.ts
@@ -0,0 +1,103 @@
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { ratelimit } from "@/lib/upstash";
+import { prisma } from "@dub/prisma";
+import { getSearchParams } from "@dub/utils";
+import { Project } from "@prisma/client";
+import { AxiomRequest, withAxiom } from "next-axiom";
+
+interface WithPublishableKeyHandler {
+ ({
+ req,
+ params,
+ searchParams,
+ workspace,
+ }: {
+ req: Request;
+ params: Record<string, string>;
+ searchParams: Record<string, string>;
+ workspace: Project;
+ }): Promise<Response>;
+}
+
+export const withPublishableKey = (
+ handler: WithPublishableKeyHandler,
+ {
+ requiredPlan = [
+ "free",
+ "pro",
+ "business",
+ "business plus",
+ "business max",
+ "business extra",
+ "advanced",
+ "enterprise",
+ ],
+ },
+) =>
+ withAxiom(
+ async (
+ req: AxiomRequest,
+ { params = {} }: { params: Record<string, string> | undefined },
+ ) => {
+ try {
+ let headers = {};
+
+ const authorizationHeader = req.headers.get("Authorization");
+ if (authorizationHeader) {
+ if (!authorizationHeader.includes("Bearer ")) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "Misconfigured authorization header. Did you forget to add 'Bearer '? Learn more: https://d.to/auth",
+ });
+ }
+ const publishableKey = authorizationHeader.replace("Bearer ", "");
+
+ const { success, limit, reset, remaining } = await ratelimit(
+ 600,
+ "1 m",
+ ).limit(publishableKey);
+
+ headers = {
+ "Retry-After": reset.toString(),
+ "X-RateLimit-Limit": limit.toString(),
+ "X-RateLimit-Remaining": remaining.toString(),
+ "X-RateLimit-Reset": reset.toString(),
+ };
+
+ if (!success) {
+ return new Response("Too many requests.", {
+ status: 429,
+ headers,
+ });
+ }
+
+ const workspace = await prisma.project.findFirst({
+ where: {
+ publishableKey,
+ },
+ });
+
+ if (!workspace) {
+ throw new DubApiError({
+ code: "unauthorized",
+ message: "Unauthorized: Invalid Dub publishable key.",
+ });
+ }
+
+ if (!requiredPlan.includes(workspace.plan)) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Unauthorized: Need higher plan.",
+ });
+ }
+
+ const searchParams = getSearchParams(req.url);
+ return await handler({ req, params, searchParams, workspace });
+ }
+ } catch (error) {
+ req.log.error(error);
+ return handleAndReturnErrorResponse(error);
+ }
+ },
+ );
diff --git a/packages/prisma/schema/workspace.prisma b/packages/prisma/schema/workspace.prisma
index 78ae32bb7a..2035c29f19 100644
--- a/packages/prisma/schema/workspace.prisma
+++ b/packages/prisma/schema/workspace.prisma
@@ -39,11 +39,11 @@ model Project {
store Json? // General key-value store for things like persisting toggles, dismissing popups, etc.
allowedHostnames Json?
+ publishableKey String? @unique // for the client-side publishable key
conversionEnabled Boolean @default(false) // Whether to enable conversion tracking for links by default
webhookEnabled Boolean @default(false)
partnersEnabled Boolean @default(false)
- ssoEnabled Boolean @default(false)
dotLinkClaimed Boolean @default(false)
createdAt DateTime @default(now())