The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add support for redir_url
Steven Teyc34a14e19161
diff --git a/apps/web/lib/middleware/utils/get-final-url.ts b/apps/web/lib/middleware/utils/get-final-url.tsindex 37b071b366..f9b1f5ae7e 100644--- a/apps/web/lib/middleware/utils/get-final-url.ts+++ b/apps/web/lib/middleware/utils/get-final-url.ts@@ -1,5 +1,8 @@+import { getUrlFromString } from "@dub/utils/src/functions";import { NextRequest } from "next/server";+const REDIRECTION_QUERY_PARAM = "redir_url";+export const getFinalUrl = (url: string,{ req, clickId }: { req: NextRequest; clickId?: string },@@ -7,12 +10,17 @@ export const getFinalUrl = (// query is the query string (e.g. d.to/github?utm_source=twitter -> ?utm_source=twitter)const searchParams = req.nextUrl.searchParams;+ // if there is a redirection url set, then use it instead of the target url+ const redirectionUrl = getUrlFromString(+ searchParams.get(REDIRECTION_QUERY_PARAM) ?? "",+ );+// get the query params of the target url- const urlObj = new URL(url);+ const urlObj = redirectionUrl ? new URL(redirectionUrl) : new URL(url);- // if there's no dub-no-track search param, then add clickId to the final url if it exists+ // if there's a clickId and no dub-no-track search param, then add clickId to the final url// reasoning: if you're skipping tracking, there's no point in passing the clickId anyway- if (!searchParams.has("dub-no-track") && clickId) {+ if (clickId && !searchParams.has("dub-no-track")) {// add clickId to the final url if it existsurlObj.searchParams.set("dub_id", clickId);}@@ -23,10 +31,9 @@ export const getFinalUrl = (// if searchParams (type: `URLSearchParams`) has the same key as target url, then overwrite itfor (const [key, value] of searchParams) {- // we will pass everything except dub-no-track (used for skipping tracking)- if (key !== "dub-no-track") {- urlObj.searchParams.set(key, value);- }+ // we will pass everything except internal query params (dub-no-track and redir_url)+ if (["dub-no-track", REDIRECTION_QUERY_PARAM].includes(key)) continue;+ urlObj.searchParams.set(key, value);}// remove qr param from the final url if the value is "1" (only used for detectQr function)@@ -56,7 +63,14 @@ export const getFinalUrlForRecordClick = ({url: string;}) => {const searchParams = new URL(req.url).searchParams;- const urlObj = new URL(url);++ // if there is a redirection url set, then use it instead of the target url+ const redirectionUrl = getUrlFromString(+ searchParams.get(REDIRECTION_QUERY_PARAM) ?? "",+ );++ // get the query params of the target url+ const urlObj = redirectionUrl ? new URL(redirectionUrl) : new URL(url);// Filter out query params that are not in the allowed listif (searchParams.size > 0) {