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.

FEAT: Conversion Tracking

Steven Tey62d8f4ad45be
diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.ts
index 11e0adc669..1bc3a35758 100644
--- a/apps/web/lib/middleware/link.ts
+++ b/apps/web/lib/middleware/link.ts
@@ -6,6 +6,7 @@ import {
DUB_HEADERS,
LEGAL_WORKSPACE_ID,
LOCALHOST_GEO_DATA,
+ nanoid,
punyEncode,
} from "@dub/utils";
import {
@@ -76,9 +77,10 @@ export default async function LinkMiddleware(
}
const {
- id,
+ id: linkId,
url,
password,
+ trackConversion = true,
proxy,
rewrite,
iframeable,
@@ -132,6 +134,7 @@ export default async function LinkMiddleware(
);
}
}
+ const clickId = nanoid(16);
const searchParams = req.nextUrl.searchParams;
// only track the click when there is no `dub-no-track` header or query param
@@ -141,7 +144,9 @@ export default async function LinkMiddleware(
searchParams.get("dub-no-track") === "1"
)
) {
- ev.waitUntil(recordClick({ req, id, url: getFinalUrl(url, { req }) }));
+ ev.waitUntil(
+ recordClick({ req, linkId, clickId, url: getFinalUrl(url, { req }) }),
+ );
}
const isBot = detectBot(req);
@@ -170,30 +175,54 @@ export default async function LinkMiddleware(
// redirect to iOS link if it is specified and the user is on an iOS device
} else if (ios && userAgent(req).os?.name === "iOS") {
- return NextResponse.redirect(getFinalUrl(ios, { req }), {
- ...DUB_HEADERS,
- status: 302,
- });
+ return NextResponse.redirect(
+ getFinalUrl(ios, {
+ req,
+ clickId: trackConversion ? clickId : undefined,
+ }),
+ {
+ ...DUB_HEADERS,
+ status: 302,
+ },
+ );
// redirect to Android link if it is specified and the user is on an Android device
} else if (android && userAgent(req).os?.name === "Android") {
- return NextResponse.redirect(getFinalUrl(android, { req }), {
- ...DUB_HEADERS,
- status: 302,
- });
+ return NextResponse.redirect(
+ getFinalUrl(android, {
+ req,
+ clickId: trackConversion ? clickId : undefined,
+ }),
+ {
+ ...DUB_HEADERS,
+ status: 302,
+ },
+ );
// redirect to geo-specific link if it is specified and the user is in the specified country
} else if (geo && country && country in geo) {
- return NextResponse.redirect(getFinalUrl(geo[country], { req }), {
- ...DUB_HEADERS,
- status: 302,
- });
+ return NextResponse.redirect(
+ getFinalUrl(geo[country], {
+ req,
+ clickId: trackConversion ? clickId : undefined,
+ }),
+ {
+ ...DUB_HEADERS,
+ status: 302,
+ },
+ );
// regular redirect
} else {
- return NextResponse.redirect(getFinalUrl(url, { req }), {
- ...DUB_HEADERS,
- status: 302,
- });
+ return NextResponse.redirect(
+ getFinalUrl(url, {
+ req,
+ clickId: trackConversion ? clickId : undefined,
+ }),
+ {
+ ...DUB_HEADERS,
+ status: 302,
+ },
+ );
}
}
diff --git a/apps/web/lib/middleware/utils/get-final-url.ts b/apps/web/lib/middleware/utils/get-final-url.ts
index 5573f811e1..9b56879a6f 100644
--- a/apps/web/lib/middleware/utils/get-final-url.ts
+++ b/apps/web/lib/middleware/utils/get-final-url.ts
@@ -1,15 +1,23 @@
import { NextRequest } from "next/server";
-export const getFinalUrl = (url: string, { req }: { req: NextRequest }) => {
+export const getFinalUrl = (
+ url: string,
+ { req, clickId }: { req: NextRequest; clickId?: string },
+) => {
// query is the query string (e.g. d.to/github?utm_source=twitter -> ?utm_source=twitter)
const searchParams = req.nextUrl.searchParams;
// get the query params of the target url
const urlObj = new URL(url);
+ if (clickId) {
+ // add clickId to the final url if it exists
+ urlObj.searchParams.set("dclid", clickId);
+ }
+
// if there are no query params, then return the target url as is (no need to parse it)
// @ts-ignore – until https://github.com/microsoft/TypeScript/issues/54466 is fixed
- if (searchParams.size === 0) return url;
+ if (searchParams.size === 0) return urlObj.toString();
// if searchParams (type: `URLSearchParams`) has the same key as target url, then overwrite it
for (const [key, value] of searchParams) {
diff --git a/apps/web/lib/tinybird.ts b/apps/web/lib/tinybird.ts
index 7f6233228f..ddcb3001da 100644
--- a/apps/web/lib/tinybird.ts
+++ b/apps/web/lib/tinybird.ts
@@ -4,7 +4,6 @@ import {
LOCALHOST_IP,
capitalize,
getDomainWithoutWWW,
- nanoid,
} from "@dub/utils";
import { ipAddress } from "@vercel/edge";
import { NextRequest, userAgent } from "next/server";
@@ -18,12 +17,14 @@ import { ratelimit } from "./upstash";
**/
export async function recordClick({
req,
- id,
+ linkId,
+ clickId,
url,
root,
}: {
req: NextRequest;
- id: string;
+ linkId: string;
+ clickId: string;
url?: string;
root?: boolean;
}) {
@@ -40,7 +41,7 @@ export async function recordClick({
// if in production / preview env, deduplicate clicks from the same IP address + link ID – only record 1 click per hour
if (process.env.VERCEL === "1") {
const { success } = await ratelimit(2, "1 h").limit(
- `recordClick:${ip}:${id}`,
+ `recordClick:${ip}:${linkId}`,
);
if (!success) {
return null;
@@ -58,8 +59,8 @@ export async function recordClick({
body: JSON.stringify({
timestamp: new Date(Date.now()).toISOString(),
identity_hash,
- click_id: nanoid(16),
- link_id: id,
+ click_id: clickId,
+ link_id: linkId,
alias_link_id: "",
url: url || "",
ip:
@@ -103,23 +104,23 @@ export async function recordClick({
? [
conn.execute(
"UPDATE Domain SET clicks = clicks + 1, lastClicked = NOW() WHERE id = ?",
- [id],
+ [linkId],
),
// only increment workspace clicks if there is a destination URL configured (not placeholder landing page)
url &&
conn.execute(
"UPDATE Project p JOIN Domain d ON p.id = d.projectId SET p.usage = p.usage + 1 WHERE d.id = ?",
- [id],
+ [linkId],
),
]
: [
conn.execute(
"UPDATE Link SET clicks = clicks + 1, lastClicked = NOW() WHERE id = ?",
- [id],
+ [linkId],
),
conn.execute(
"UPDATE Project p JOIN Link l ON p.id = l.projectId SET p.usage = p.usage + 1 WHERE l.id = ?",
- [id],
+ [linkId],
),
],
]);
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 47157cfbc8..aaea523caa 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -25,6 +25,7 @@ export interface QRLinkProps {
export interface RedisLinkProps {
id: string;
url: string;
+ trackConversion?: boolean;
password?: boolean;
proxy?: boolean;
rewrite?: boolean;
diff --git a/apps/web/lib/upstash.ts b/apps/web/lib/upstash.ts
index 67701c4054..d04c76abae 100644
--- a/apps/web/lib/upstash.ts
+++ b/apps/web/lib/upstash.ts
@@ -68,6 +68,7 @@ export async function formatRedisLink(
id,
domain,
url,
+ trackConversion,
password,
proxy,
rewrite,
@@ -83,6 +84,7 @@ export async function formatRedisLink(
return {
id,
url,
+ ...(trackConversion && { trackConversion: true }),
...(hasPassword && { password: true }),
...(proxy && { proxy: true }),
...(rewrite && {
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index 9ddd8a2019..33d324b2de 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -213,6 +213,8 @@ model Link {
password String? // password to access the link
externalId String?
+ trackConversion Boolean?
+
proxy Boolean @default(false) // Proxy to use custom OG tags (stored on redis) – if false, will use OG tags from target url
title String? // OG title for the link (e.g. Dub.co - Open-Source Link Management Infrastructure)
description String? @db.VarChar(280) // OG description for the link (e.g. An open-source link management tool for modern marketing teams to create, share, and track short links.)