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.

improve /track/click and /track/visit

Steven Tey6a98e09a4bc9
diff --git a/apps/web/app/api/track/click/route.ts b/apps/web/app/api/track/click/route.ts
index 015d49fead..e1d3b08147 100644
--- a/apps/web/app/api/track/click/route.ts
+++ b/apps/web/app/api/track/click/route.ts
@@ -3,7 +3,7 @@ import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
import { getLinkWithAllowedHostnames } from "@/lib/planetscale/get-link-with-allowed-hostnames";
import { recordClick } from "@/lib/tinybird";
-import { ratelimit, redis } from "@/lib/upstash";
+import { redis } from "@/lib/upstash";
import { isValidUrl, LOCALHOST_IP, nanoid } from "@dub/utils";
import { ipAddress, waitUntil } from "@vercel/functions";
import { AxiomRequest, withAxiom } from "next-axiom";
@@ -21,7 +21,7 @@ const CORS_HEADERS = {
export const POST = withAxiom(
async (req: AxiomRequest) => {
try {
- const { domain, key, url } = await parseRequestBody(req);
+ const { domain, key, url, referrer } = await parseRequestBody(req);
if (!domain || !key) {
throw new DubApiError({
@@ -32,34 +32,25 @@ export const POST = withAxiom(
const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;
- const { success } = await ratelimit().limit(
- `track-click:${domain}-${key}:${ip}`,
- );
-
- if (!success) {
- throw new DubApiError({
- code: "rate_limit_exceeded",
- message: "Don't DDoS me pls 🥺",
- });
- }
+ const cacheKey = `recordClick:${domain}:${key}:${ip}`;
+ let clickId = await redis.get<string>(cacheKey);
- const link = await getLinkWithAllowedHostnames(domain, key);
+ // only generate + record a new click ID if it's not already cached in Redis
+ if (!clickId) {
+ clickId = nanoid(16);
- if (!link) {
- throw new DubApiError({
- code: "not_found",
- message: `Link not found for domain: ${domain} and key: ${key}.`,
- });
- }
+ const link = await getLinkWithAllowedHostnames(domain, key);
- const allowedHostnames = link.allowedHostnames;
- verifyAnalyticsAllowedHostnames({ allowedHostnames, req });
+ if (!link) {
+ throw new DubApiError({
+ code: "not_found",
+ message: `Link not found for domain: ${domain} and key: ${key}.`,
+ });
+ }
- const cacheKey = `recordClick:${link.id}:${ip}`;
- let clickId = await redis.get<string>(cacheKey);
+ const allowedHostnames = link.allowedHostnames;
+ verifyAnalyticsAllowedHostnames({ allowedHostnames, req });
- if (!clickId) {
- clickId = nanoid(16);
const finalUrl = isValidUrl(url) ? url : link.url;
waitUntil(
@@ -68,8 +59,8 @@ export const POST = withAxiom(
clickId,
linkId: link.id,
url: finalUrl,
- skipRatelimit: true,
workspaceId: link.projectId,
+ ...(referrer && { referrer }),
}),
);
}
diff --git a/apps/web/app/api/track/visit/route.ts b/apps/web/app/api/track/visit/route.ts
new file mode 100644
index 0000000000..0b64075adc
--- /dev/null
+++ b/apps/web/app/api/track/visit/route.ts
@@ -0,0 +1,101 @@
+import { verifyAnalyticsAllowedHostnames } from "@/lib/analytics/verify-analytics-allowed-hostnames";
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
+import { parseRequestBody } from "@/lib/api/utils";
+import { getLinkWithAllowedHostnames } from "@/lib/planetscale/get-link-with-allowed-hostnames";
+import { recordClick } from "@/lib/tinybird";
+import { redis } from "@/lib/upstash";
+import { isValidUrl, LOCALHOST_IP, nanoid } from "@dub/utils";
+import { ipAddress, waitUntil } from "@vercel/functions";
+import { AxiomRequest, withAxiom } from "next-axiom";
+import { NextResponse } from "next/server";
+
+export const runtime = "edge";
+
+const CORS_HEADERS = {
+ "Access-Control-Allow-Origin": "*",
+ "Access-Control-Allow-Methods": "POST, OPTIONS",
+ "Access-Control-Allow-Headers": "Content-Type, Authorization",
+};
+
+// POST /api/track/visit – Track a visit event from the client-side
+export const POST = withAxiom(
+ async (req: AxiomRequest) => {
+ try {
+ const { domain, url, referrer } = await parseRequestBody(req);
+
+ if (!domain || !url) {
+ throw new DubApiError({
+ code: "bad_request",
+ message: "Missing domain or url",
+ });
+ }
+
+ const urlObj = new URL(url);
+
+ let linkKey = urlObj.pathname.slice(1);
+ if (linkKey === "") {
+ linkKey = "_root";
+ }
+
+ const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;
+ const cacheKey = `recordClick:${domain}:${linkKey}:${ip}`;
+
+ let clickId = await redis.get<string>(cacheKey);
+
+ // only generate + record a new click ID if it's not already cached in Redis
+ if (!clickId) {
+ clickId = nanoid(16);
+
+ let link = await getLinkWithAllowedHostnames(domain, linkKey);
+
+ if (!link) {
+ return NextResponse.json(
+ {
+ clickId: null,
+ },
+ {
+ headers: CORS_HEADERS,
+ },
+ );
+ }
+
+ const allowedHostnames = link.allowedHostnames;
+ verifyAnalyticsAllowedHostnames({ allowedHostnames, req });
+
+ const finalUrl = isValidUrl(url) ? url : link.url;
+
+ waitUntil(
+ recordClick({
+ req,
+ clickId,
+ linkId: link.id,
+ url: finalUrl,
+ workspaceId: link.projectId,
+ ...(referrer && { referrer }),
+ }),
+ );
+ }
+
+ return NextResponse.json(
+ {
+ clickId,
+ },
+ {
+ headers: CORS_HEADERS,
+ },
+ );
+ } catch (error) {
+ return handleAndReturnErrorResponse(error, CORS_HEADERS);
+ }
+ },
+ {
+ logRequestDetails: ["body", "nextUrl"],
+ },
+);
+
+export const OPTIONS = () => {
+ return new Response(null, {
+ status: 204,
+ headers: CORS_HEADERS,
+ });
+};
diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.ts
index bc384fb1ea..a102091ba5 100644
--- a/apps/web/lib/middleware/link.ts
+++ b/apps/web/lib/middleware/link.ts
@@ -196,8 +196,10 @@ export default async function LinkMiddleware(
ev.waitUntil(
recordClick({
req,
- linkId,
clickId,
+ linkId,
+ domain,
+ key,
url,
webhookIds,
workspaceId,
@@ -241,8 +243,10 @@ export default async function LinkMiddleware(
ev.waitUntil(
recordClick({
req,
- linkId,
clickId,
+ linkId,
+ domain,
+ key,
url,
webhookIds,
workspaceId,
@@ -275,8 +279,10 @@ export default async function LinkMiddleware(
ev.waitUntil(
recordClick({
req,
- linkId,
clickId,
+ linkId,
+ domain,
+ key,
url,
webhookIds,
workspaceId,
@@ -311,8 +317,10 @@ export default async function LinkMiddleware(
ev.waitUntil(
recordClick({
req,
- linkId,
clickId,
+ linkId,
+ domain,
+ key,
url: ios,
webhookIds,
workspaceId,
@@ -341,8 +349,10 @@ export default async function LinkMiddleware(
ev.waitUntil(
recordClick({
req,
- linkId,
clickId,
+ linkId,
+ domain,
+ key,
url: android,
webhookIds,
workspaceId,
@@ -371,8 +381,10 @@ export default async function LinkMiddleware(
ev.waitUntil(
recordClick({
req,
- linkId,
clickId,
+ linkId,
+ domain,
+ key,
url: geo[country],
webhookIds,
workspaceId,
@@ -401,8 +413,10 @@ export default async function LinkMiddleware(
ev.waitUntil(
recordClick({
req,
- linkId,
clickId,
+ linkId,
+ domain,
+ key,
url,
webhookIds,
workspaceId,
diff --git a/apps/web/lib/rewardful/import-referrals.ts b/apps/web/lib/rewardful/import-referrals.ts
index e8416a49d0..6bd2ebc226 100644
--- a/apps/web/lib/rewardful/import-referrals.ts
+++ b/apps/web/lib/rewardful/import-referrals.ts
@@ -172,7 +172,6 @@ async function createReferral({
url: link.url,
workspaceId: workspace.id,
timestamp: new Date(referral.created_at).toISOString(),
- skipRatelimit: true,
});
const clickEvent = clickEventSchemaTB.parse({
diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.ts
index 7833e4816f..d0ed96c4ac 100644
--- a/apps/web/lib/tinybird/record-click.ts
+++ b/apps/web/lib/tinybird/record-click.ts
@@ -26,21 +26,23 @@ import { transformClickEventData } from "../webhook/transform";
**/
export async function recordClick({
req,
- linkId,
clickId,
+ linkId,
+ domain,
+ key,
url,
webhookIds,
- skipRatelimit,
workspaceId,
timestamp,
referrer,
}: {
req: Request;
- linkId: string;
clickId: string;
+ linkId: string;
+ domain?: string;
+ key?: string;
url?: string;
webhookIds?: string[];
- skipRatelimit?: boolean;
workspaceId: string | undefined;
timestamp?: string;
referrer?: string;
@@ -61,10 +63,11 @@ export async function recordClick({
const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;
- const cacheKey = `recordClick:${linkId}:${ip}`;
+ const cacheKey = `recordClick:${domain}:${key}:${ip}`;
- if (!skipRatelimit) {
- // by default, we deduplicate clicks from the same IP address + link ID – only record 1 click per hour
+ // by default, we deduplicate clicks for a domain + key pair from the same IP address – only record 1 click per hour
+ // we only need to do these if domain + key are defined (only in middleware/link and not /api/track/:path endpoints)
+ if (domain && key) {
// here, we check if the clickId is cached in Redis within the last hour
const cachedClickId = await redis.get<string>(cacheKey);
if (cachedClickId) {