The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
move logic into `LinkMiddleware` directly
Steven Tey0322833bf29d
diff --git a/apps/web/lib/middleware/link.ts b/apps/web/lib/middleware/link.tsindex 5ebc4ec699..57824e9573 100644--- a/apps/web/lib/middleware/link.ts+++ b/apps/web/lib/middleware/link.ts@@ -5,7 +5,10 @@ import {DUB_HEADERS,LEGAL_WORKSPACE_ID,LOCALHOST_GEO_DATA,+ REDIRECTION_QUERY_PARAM,+ getUrlFromStringIfValid,isDubDomain,+ isGoogleClickTrackerDomain,isUnsupportedKey,nanoid,punyEncode,@@ -38,7 +41,7 @@ import { parse } from "./utils/parse";import { resolveABTestURL } from "./utils/resolve-ab-test-url";export async function LinkMiddleware(req: NextRequest, ev: NextFetchEvent) {- let { domain, fullKey: originalKey, fullPath } = parse(req);+ let { domain, fullKey: originalKey, fullPath, searchParamsObj } = parse(req);if (!domain) {return NextResponse.next();@@ -174,6 +177,70 @@ export async function LinkMiddleware(req: NextRequest, ev: NextFetchEvent) {// everything else is not indexed by default, unless the user has explicitly set it to be indexedconst shouldIndex = isDubDomain(domain) || doIndex === true;+ const dubIdCookieName = `dub_id_${domain}_${key}`;++ const cookieStore = await cookies();+ let clickId = cookieStore.get(dubIdCookieName)?.value;+ if (!clickId) {+ // if we need to pass the clickId, check if clickId is cached in Redis+ if (shouldCacheClickId) {+ const identityHash = await getIdentityHash(req);+ clickId =+ (await recordClickCache+ .get({ domain, key, identityHash })+ .catch(() => undefined)) || undefined;+ }++ // if there's still no clickId, generate a new one+ if (!clickId) {+ clickId = nanoid(16);+ }+ }++ const cookieData = {+ path: `/${encodeURI(originalKey)}`,+ dubIdCookieName,+ dubIdCookieValue: clickId,+ dubTestUrlValue: testUrl,+ };++ // for Google click tracker domains (dub.sh, dub.link):+ // if there is a redirection url set, then use it instead of the target+ if (isGoogleClickTrackerDomain(domain)) {+ const redirectionUrl = getUrlFromStringIfValid(+ searchParamsObj[REDIRECTION_QUERY_PARAM] ?? "",+ );++ // if redirectionUrl is present, return it immediately+ if (redirectionUrl) {+ ev.waitUntil(+ recordClick({+ req,+ clickId,+ workspaceId,+ linkId,+ domain,+ key,+ url: redirectionUrl,+ programId: cachedLink.programId,+ partnerId: cachedLink.partnerId,+ shouldCacheClickId,+ }),+ );++ return createResponseWithCookies(+ NextResponse.redirect(redirectionUrl, {+ headers: {+ ...DUB_HEADERS,+ ...(!shouldIndex && { "X-Robots-Tag": "googlebot: noindex" }),+ },+ status: key === "_root" ? 301 : 302,+ }),+ cookieData,+ );+ }+ }+// only show inspect modal if the link is not password protectedif (inspectMode && !password) {return NextResponse.rewrite(@@ -254,33 +321,6 @@ export async function LinkMiddleware(req: NextRequest, ev: NextFetchEvent) {}}- const dubIdCookieName = `dub_id_${domain}_${key}`;-- const cookieStore = await cookies();- let clickId = cookieStore.get(dubIdCookieName)?.value;- if (!clickId) {- // if we need to pass the clickId, check if clickId is cached in Redis- if (shouldCacheClickId) {- const identityHash = await getIdentityHash(req);- clickId =- (await recordClickCache- .get({ domain, key, identityHash })- .catch(() => undefined)) || undefined;- }-- // if there's still no clickId, generate a new one- if (!clickId) {- clickId = nanoid(16);- }- }-- const cookieData = {- path: `/${encodeURI(originalKey)}`,- dubIdCookieName,- dubIdCookieValue: clickId,- dubTestUrlValue: testUrl,- };-// for root domain links, if there's no destination URL, rewrite to placeholder pageif (!url) {ev.waitUntil(diff --git a/apps/web/lib/middleware/utils/get-final-url.ts b/apps/web/lib/middleware/utils/get-final-url.tsindex f49b41b9cc..0d44950768 100644--- a/apps/web/lib/middleware/utils/get-final-url.ts+++ b/apps/web/lib/middleware/utils/get-final-url.ts@@ -2,7 +2,6 @@ import {LOCALHOST_IP,REDIRECTION_QUERY_PARAM,} from "@dub/utils/src/constants";-import { getUrlFromStringIfValid } from "@dub/utils/src/functions";import { ipAddress } from "@vercel/functions";import { NextRequest, userAgent } from "next/server";import { isAppsFlyerTrackingUrl } from "./is-appsflyer-tracking-url";@@ -25,19 +24,6 @@ export const getFinalUrl = (// query is the query string (e.g. d.to/github?utm_source=twitter -> ?utm_source=twitter)const searchParams = req.nextUrl.searchParams;- // for Google-certified click tracker domains (dub.sh, dub.link):- // if there is a redirection url set, then use it instead of the target- if (["dub.sh", "dub.link"].includes(parse(req).domain)) {- const redirectionUrl = getUrlFromStringIfValid(- searchParams.get(REDIRECTION_QUERY_PARAM) ?? "",- );-- // if redirectionUrl is present, return it immediately- if (redirectionUrl) {- return redirectionUrl;- }- }-const urlObj = new URL(url);if (via) {diff --git a/packages/utils/src/functions/domains.ts b/packages/utils/src/functions/domains.tsindex fb6fc9cb48..180fe27947 100644--- a/packages/utils/src/functions/domains.ts+++ b/packages/utils/src/functions/domains.ts@@ -85,3 +85,10 @@ export const getDomainWithoutWWW = (url: string) => {export const isDubDomain = (domain: string) => {return DUB_DOMAINS.some((d) => d.slug === domain);};++export const isGoogleClickTrackerDomain = (domain: string) => {+ // accepts both the full domain and the subdomain+ return ["dub.sh", "dub.link"].some(+ (d) => d === domain || domain.endsWith(`.${d}`),+ );+};