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.

Proxy updates

Tim Wilson486657f1c96d
diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.ts
index 32d77ca224..4f29507dd3 100644
--- a/apps/web/lib/middleware/link.ts
+++ b/apps/web/lib/middleware/link.ts
@@ -1,5 +1,5 @@
import {
- createResponseWithCookie,
+ createResponseWithCookies,
detectBot,
getFinalUrl,
isSupportedDeeplinkProtocol,
@@ -25,12 +25,11 @@ import {
NextResponse,
userAgent,
} from "next/server";
-import { z } from "zod";
import { linkCache } from "../api/links/cache";
import { isCaseSensitiveDomain } from "../api/links/case-sensitivity";
import { getLinkViaEdge } from "../planetscale";
import { getDomainViaEdge } from "../planetscale/get-domain-via-edge";
-import { LinkTestsSchema, MAX_TEST_COUNT } from "../zod/schemas/links";
+import { getTestDestinationURL } from "./utils/get-test-destination-url";
import { hasEmptySearchParams } from "./utils/has-empty-search-params";
export default async function LinkMiddleware(
@@ -152,10 +151,11 @@ export default async function LinkMiddleware(
projectId: workspaceId,
} = cachedLink;
- const url =
- tests && testsCompleteAt
- ? getTestDestinationURL({ url: cachedLink.url, tests, testsCompleteAt })
- : cachedLink.url;
+ const testUrl = getTestDestinationURL({
+ tests,
+ testsCompleteAt,
+ });
+ const url = testUrl || cachedLink.url;
// by default, we only index default dub domain links (e.g. dub.sh)
// everything else is not indexed by default, unless the user has explicitly set it to be indexed
@@ -260,7 +260,7 @@ export default async function LinkMiddleware(
}),
);
- return createResponseWithCookie(
+ return createResponseWithCookies(
NextResponse.rewrite(new URL(`/${domain}`, req.url), {
headers: {
...DUB_HEADERS,
@@ -279,7 +279,7 @@ export default async function LinkMiddleware(
// rewrite to proxy page (/proxy/[domain]/[key]) if it's a bot and proxy is enabled
if (isBot && proxy) {
- return createResponseWithCookie(
+ return createResponseWithCookies(
NextResponse.rewrite(
new URL(`/proxy/${domain}/${encodeURIComponent(key)}`, req.url),
{
@@ -308,7 +308,7 @@ export default async function LinkMiddleware(
}),
);
- return createResponseWithCookie(
+ return createResponseWithCookies(
NextResponse.rewrite(
new URL(
`/deeplink/${encodeURIComponent(
@@ -326,7 +326,7 @@ export default async function LinkMiddleware(
},
},
),
- { clickId, path: `/${originalKey}` },
+ { clickId, path: `/${originalKey}`, testUrl },
);
// rewrite to target URL if link cloaking is enabled
@@ -345,7 +345,7 @@ export default async function LinkMiddleware(
}),
);
- return createResponseWithCookie(
+ return createResponseWithCookies(
NextResponse.rewrite(
new URL(
`/cloaked/${encodeURIComponent(
@@ -365,7 +365,7 @@ export default async function LinkMiddleware(
},
},
),
- { clickId, path: `/${originalKey}` },
+ { clickId, path: `/${originalKey}`, testUrl },
);
// redirect to iOS link if it is specified and the user is on an iOS device
@@ -384,7 +384,7 @@ export default async function LinkMiddleware(
}),
);
- return createResponseWithCookie(
+ return createResponseWithCookies(
NextResponse.redirect(
getFinalUrl(ios, {
req,
@@ -417,7 +417,7 @@ export default async function LinkMiddleware(
}),
);
- return createResponseWithCookie(
+ return createResponseWithCookies(
NextResponse.redirect(
getFinalUrl(android, {
req,
@@ -450,7 +450,7 @@ export default async function LinkMiddleware(
}),
);
- return createResponseWithCookie(
+ return createResponseWithCookies(
NextResponse.redirect(
getFinalUrl(geo[country], {
req,
@@ -484,19 +484,22 @@ export default async function LinkMiddleware(
);
if (hasEmptySearchParams(url)) {
- return NextResponse.rewrite(new URL("/api/patch-redirect", req.url), {
- request: {
- headers: new Headers({
- destination: getFinalUrl(url, {
- req,
- clickId: trackConversion ? clickId : undefined,
+ return createResponseWithCookies(
+ NextResponse.rewrite(new URL("/api/patch-redirect", req.url), {
+ request: {
+ headers: new Headers({
+ destination: getFinalUrl(url, {
+ req,
+ clickId: trackConversion ? clickId : undefined,
+ }),
}),
- }),
- },
- });
+ },
+ }),
+ { path: `/${originalKey}`, testUrl },
+ );
}
- return createResponseWithCookie(
+ return createResponseWithCookies(
NextResponse.redirect(
getFinalUrl(url, {
req,
@@ -510,49 +513,7 @@ export default async function LinkMiddleware(
status: key === "_root" ? 301 : 302,
},
),
- { clickId, path: `/${originalKey}` },
+ { clickId, path: `/${originalKey}`, testUrl },
);
}
}
-
-/**
- * Determines the destination URL for a link with A/B tests using weighted random selection
- */
-const getTestDestinationURL = ({
- url,
- tests,
- testsCompleteAt,
-}: {
- url?: string;
- tests: z.infer<typeof LinkTestsSchema>;
- testsCompleteAt: Date;
-}) => {
- try {
- if (!tests || !testsCompleteAt || !(new Date(testsCompleteAt) > new Date()))
- return url;
-
- if (tests.length < 2 || tests.length > MAX_TEST_COUNT) {
- throw new Error("Invalid test count: " + tests.length);
- }
-
- let i = 0;
- const weights = [tests[0].percentage];
-
- // Calculate cumulative weights
- for (i = 1; i < tests.length; ++i)
- weights[i] = tests[i].percentage + weights[i - 1];
-
- // Generate a random number between 0 and the total cumulative weight
- const random = Math.random() * weights[weights.length - 1];
-
- // Loop through cumulative weights and stop when we've found the first one greater than `random`
- for (i = 0; i < weights.length; ++i) if (weights[i] > random) break;
-
- // Return the corresponding test URL
- return tests[i].url;
- } catch (e) {
- console.error("Error getting test destination URL", e);
- }
-
- return url;
-};
diff --git a/apps/web/lib/middleware/utils/create-response-with-cookie.ts b/apps/web/lib/middleware/utils/create-response-with-cookie.ts
deleted file mode 100644
index 55e90bf495..0000000000
--- a/apps/web/lib/middleware/utils/create-response-with-cookie.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { NextResponse } from "next/server";
-
-export function createResponseWithCookie(
- response: NextResponse,
- { clickId, path }: { clickId: string; path: string },
-): NextResponse {
- response.cookies.set("dub_id", clickId, {
- path,
- maxAge: 60 * 60, // 1 hour
- });
-
- return response;
-}
diff --git a/apps/web/lib/middleware/utils/create-response-with-cookies.ts b/apps/web/lib/middleware/utils/create-response-with-cookies.ts
new file mode 100644
index 0000000000..44eb93c310
--- /dev/null
+++ b/apps/web/lib/middleware/utils/create-response-with-cookies.ts
@@ -0,0 +1,26 @@
+import { NextResponse } from "next/server";
+
+export function createResponseWithCookies(
+ response: NextResponse,
+ {
+ path,
+ clickId,
+ testUrl,
+ }: { path: string; clickId?: string; testUrl?: string | null },
+): NextResponse {
+ if (clickId !== undefined) {
+ response.cookies.set("dub_id", clickId, {
+ path,
+ maxAge: 60 * 60, // 1 hour
+ });
+ }
+
+ if (testUrl) {
+ response.cookies.set("dub_test_url", testUrl, {
+ path,
+ maxAge: 60 * 60, // 1 hour
+ });
+ }
+
+ return response;
+}
diff --git a/apps/web/lib/middleware/utils/get-test-destination-url.ts b/apps/web/lib/middleware/utils/get-test-destination-url.ts
new file mode 100644
index 0000000000..bd89a74a87
--- /dev/null
+++ b/apps/web/lib/middleware/utils/get-test-destination-url.ts
@@ -0,0 +1,47 @@
+import { LinkTestsSchema, MAX_TEST_COUNT } from "@/lib/zod/schemas/links";
+import { cookies } from "next/headers";
+import { z } from "zod";
+
+/**
+ * Determines the destination URL for a link with A/B tests using weighted random selection
+ */
+export const getTestDestinationURL = ({
+ tests,
+ testsCompleteAt,
+}: {
+ tests?: z.infer<typeof LinkTestsSchema>;
+ testsCompleteAt?: Date;
+}) => {
+ try {
+ if (!tests || !testsCompleteAt || !(new Date(testsCompleteAt) > new Date()))
+ return null;
+
+ if (tests.length < 2 || tests.length > MAX_TEST_COUNT)
+ throw new Error("Invalid test count: " + tests.length);
+
+ const cookieStore = cookies();
+ const cookieUrl = cookieStore.get("dub_test_url")?.value;
+ if (cookieUrl && tests.map((t) => t.url).includes(cookieUrl))
+ return cookieUrl;
+
+ let i = 0;
+ const weights = [tests[0].percentage];
+
+ // Calculate cumulative weights
+ for (i = 1; i < tests.length; ++i)
+ weights[i] = tests[i].percentage + weights[i - 1];
+
+ // Generate a random number between 0 and the total cumulative weight
+ const random = Math.random() * weights[weights.length - 1];
+
+ // Loop through cumulative weights and stop when we've found the first one greater than `random`
+ for (i = 0; i < weights.length; ++i) if (weights[i] > random) break;
+
+ // Return the corresponding test URL
+ return tests[i].url;
+ } catch (e) {
+ console.error("Error getting test destination URL", e);
+ }
+
+ return null;
+};
diff --git a/apps/web/lib/middleware/utils/index.ts b/apps/web/lib/middleware/utils/index.ts
index a899312f8a..b8a763a6da 100644
--- a/apps/web/lib/middleware/utils/index.ts
+++ b/apps/web/lib/middleware/utils/index.ts
@@ -1,4 +1,4 @@
-export * from "./create-response-with-cookie";
+export * from "./create-response-with-cookies";
export * from "./detect-bot";
export * from "./detect-qr";
export * from "./get-final-url";