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.

Use identityHash for recordClickCache

Steven Tey0d5737b77516
diff --git a/apps/web/app/(ee)/api/track/click/route.ts b/apps/web/app/(ee)/api/track/click/route.ts
index 95ee801267..9b905ca378 100644
--- a/apps/web/app/(ee)/api/track/click/route.ts
+++ b/apps/web/app/(ee)/api/track/click/route.ts
@@ -8,6 +8,7 @@ import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { linkCache } from "@/lib/api/links/cache";
import { recordClickCache } from "@/lib/api/links/record-click-cache";
import { parseRequestBody } from "@/lib/api/utils";
+import { getIdentityHash } from "@/lib/middleware/utils/get-identity-hash";
import { getWorkspaceViaEdge } from "@/lib/planetscale";
import { getLinkWithPartner } from "@/lib/planetscale/get-link-with-partner";
import { recordClick } from "@/lib/tinybird";
@@ -15,8 +16,8 @@ import { RedisLinkProps } from "@/lib/types";
import { formatRedisLink, redis } from "@/lib/upstash";
import { DiscountSchema } from "@/lib/zod/schemas/discount";
import { PartnerSchema } from "@/lib/zod/schemas/partners";
-import { isValidUrl, LOCALHOST_IP, nanoid } from "@dub/utils";
-import { ipAddress, waitUntil } from "@vercel/functions";
+import { isValidUrl, nanoid } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
import { AxiomRequest, withAxiom } from "next-axiom";
import { NextResponse } from "next/server";
import { z } from "zod";
@@ -52,12 +53,12 @@ export const POST = withAxiom(async (req: AxiomRequest) => {
await parseRequestBody(req),
);
- const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;
+ const identityHash = await getIdentityHash(req);
let [cachedClickId, cachedLink, cachedAllowedHostnames] = await redis.mget<
[string, RedisLinkProps, string[]]
>([
- recordClickCache._createKey({ domain, key, ip }),
+ recordClickCache._createKey({ domain, key, identityHash }),
linkCache._createKey({ domain, key }),
allowedHostnamesCache._createKey({ domain }),
]);
diff --git a/apps/web/app/(ee)/api/track/open/route.ts b/apps/web/app/(ee)/api/track/open/route.ts
index 085f16d5f3..78aaddf6e3 100644
--- a/apps/web/app/(ee)/api/track/open/route.ts
+++ b/apps/web/app/(ee)/api/track/open/route.ts
@@ -3,6 +3,7 @@ import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { linkCache } from "@/lib/api/links/cache";
import { recordClickCache } from "@/lib/api/links/record-click-cache";
import { parseRequestBody } from "@/lib/api/utils";
+import { getIdentityHash } from "@/lib/middleware/utils";
import { DeepLinkClickData } from "@/lib/middleware/utils/cache-deeplink-click-data";
import { getLinkViaEdge } from "@/lib/planetscale";
import { recordClick } from "@/lib/tinybird";
@@ -25,6 +26,7 @@ export const POST = withAxiom(async (req: AxiomRequest) => {
);
const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;
+ const identityHash = await getIdentityHash(req);
if (!deepLinkUrl) {
if (ip) {
@@ -70,7 +72,7 @@ export const POST = withAxiom(async (req: AxiomRequest) => {
let [cachedClickId, cachedLink] = await redis.mget<
[string, RedisLinkProps, string[]]
>([
- recordClickCache._createKey({ domain, key, ip }),
+ recordClickCache._createKey({ domain, key, identityHash }),
linkCache._createKey({ domain, key }),
]);
diff --git a/apps/web/app/(ee)/api/track/visit/route.ts b/apps/web/app/(ee)/api/track/visit/route.ts
index 148e7f84f7..17bf96b014 100644
--- a/apps/web/app/(ee)/api/track/visit/route.ts
+++ b/apps/web/app/(ee)/api/track/visit/route.ts
@@ -4,12 +4,13 @@ import { DubApiError, handleAndReturnErrorResponse } from "@/lib/api/errors";
import { linkCache } from "@/lib/api/links/cache";
import { recordClickCache } from "@/lib/api/links/record-click-cache";
import { parseRequestBody } from "@/lib/api/utils";
+import { getIdentityHash } from "@/lib/middleware/utils";
import { getLinkViaEdge, getWorkspaceViaEdge } from "@/lib/planetscale";
import { recordClick } from "@/lib/tinybird";
import { RedisLinkProps } from "@/lib/types";
import { formatRedisLink, redis } from "@/lib/upstash";
-import { isValidUrl, LOCALHOST_IP, nanoid } from "@dub/utils";
-import { ipAddress, waitUntil } from "@vercel/functions";
+import { isValidUrl, nanoid } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
import { AxiomRequest, withAxiom } from "next-axiom";
import { NextResponse } from "next/server";
@@ -33,10 +34,10 @@ export const POST = withAxiom(async (req: AxiomRequest) => {
key = "_root";
}
- const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;
+ const identityHash = await getIdentityHash(req);
let [clickId, cachedLink] = await redis.mget<[string, RedisLinkProps]>([
- recordClickCache._createKey({ domain, key, ip }),
+ recordClickCache._createKey({ domain, key, identityHash }),
linkCache._createKey({ domain, key }),
]);
diff --git a/apps/web/lib/api/links/record-click-cache.ts b/apps/web/lib/api/links/record-click-cache.ts
index 43992aca1f..142a319487 100644
--- a/apps/web/lib/api/links/record-click-cache.ts
+++ b/apps/web/lib/api/links/record-click-cache.ts
@@ -6,22 +6,33 @@ const CACHE_EXPIRATION = 60 * 60;
interface KeyProps {
domain: string;
key: string;
- ip: string | undefined;
+ identityHash: string | undefined;
}
class RecordClickCache {
- async set({ domain, key, ip, clickId }: KeyProps & { clickId: string }) {
- return await redis.set(this._createKey({ domain, key, ip }), clickId, {
- ex: CACHE_EXPIRATION,
- });
+ async set({
+ domain,
+ key,
+ identityHash,
+ clickId,
+ }: KeyProps & { clickId: string }) {
+ return await redis.set(
+ this._createKey({ domain, key, identityHash }),
+ clickId,
+ {
+ ex: CACHE_EXPIRATION,
+ },
+ );
}
- async get({ domain, key, ip }: KeyProps) {
- return await redis.get<string>(this._createKey({ domain, key, ip }));
+ async get({ domain, key, identityHash }: KeyProps) {
+ return await redis.get<string>(
+ this._createKey({ domain, key, identityHash }),
+ );
}
- _createKey({ domain, key, ip }: KeyProps) {
- return `recordClick:${domain}:${key}:${ip}`;
+ _createKey({ domain, key, identityHash }: KeyProps) {
+ return `recordClick:${domain}:${key}:${identityHash}`;
}
}
diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.ts
index b996b90c9a..6e03d1d67c 100644
--- a/apps/web/lib/middleware/link.ts
+++ b/apps/web/lib/middleware/link.ts
@@ -2,6 +2,7 @@ import {
createResponseWithCookies,
detectBot,
getFinalUrl,
+ getIdentityHash,
isSupportedCustomURIScheme,
parse,
} from "@/lib/middleware/utils";
@@ -12,13 +13,12 @@ import {
DUB_HEADERS,
LEGAL_WORKSPACE_ID,
LOCALHOST_GEO_DATA,
- LOCALHOST_IP,
isDubDomain,
isUnsupportedKey,
nanoid,
punyEncode,
} from "@dub/utils";
-import { geolocation, ipAddress } from "@vercel/functions";
+import { geolocation } from "@vercel/functions";
import { cookies } from "next/headers";
import {
NextFetchEvent,
@@ -250,9 +250,10 @@ export default async function LinkMiddleware(
if (!clickId) {
// if we need to pass the clickId, check if clickId is cached in Redis
if (shouldCacheClickId) {
- const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;
-
- clickId = (await recordClickCache.get({ domain, key, ip })) || undefined;
+ const identityHash = await getIdentityHash(req);
+ clickId =
+ (await recordClickCache.get({ domain, key, identityHash })) ||
+ undefined;
}
// if there's still no clickId, generate a new one
diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.ts
index bb2f0e7292..be6373f9c7 100644
--- a/apps/web/lib/tinybird/record-click.ts
+++ b/apps/web/lib/tinybird/record-click.ts
@@ -84,13 +84,17 @@ export async function recordClick({
return null;
}
- const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;
+ const identityHash = await getIdentityHash(req);
// 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 skipRatelimit is not true (we skip it in /api/track/:path endpoints)
if (!skipRatelimit) {
// here, we check if the clickId is cached in Redis within the last hour
- const cachedClickId = await recordClickCache.get({ domain, key, ip });
+ const cachedClickId = await recordClickCache.get({
+ domain,
+ key,
+ identityHash,
+ });
if (cachedClickId) {
return null;
}
@@ -115,12 +119,11 @@ export async function recordClick({
const geo =
process.env.VERCEL === "1" ? geolocation(req) : LOCALHOST_GEO_DATA;
+ const ip = process.env.VERCEL === "1" ? ipAddress(req) : LOCALHOST_IP;
const isEuCountry = geo.country && EU_COUNTRY_CODES.includes(geo.country);
const referer = referrer || req.headers.get("referer");
- const identityHash = await getIdentityHash(req);
-
const finalUrl = url ? getFinalUrlForRecordClick({ req, url }) : "";
const clickData = {
@@ -180,7 +183,7 @@ export async function recordClick({
).then((res) => res.json()),
// cache the recorded click for the corresponding IP address in Redis for 1 hour
- recordClickCache.set({ domain, key, ip, clickId }),
+ recordClickCache.set({ domain, key, identityHash, clickId }),
// increment the click count for the link (based on their ID)
// we have to use planetscale connection directly (not prismaEdge) because of connection pooling