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.

Add support for setting UTM params via API

Steven Tey386773f2b589
diff --git a/apps/web/lib/api/links/process-link.ts b/apps/web/lib/api/links/process-link.ts
index 028abe1c2c..a32a701012 100644
--- a/apps/web/lib/api/links/process-link.ts
+++ b/apps/web/lib/api/links/process-link.ts
@@ -10,7 +10,9 @@ import { isStored } from "@/lib/storage";
import { NewLinkProps, ProcessedLinkProps, WorkspaceProps } from "@/lib/types";
import {
DUB_DOMAINS,
+ UTMTags,
combineWords,
+ constructURLFromUTMParams,
getApexDomain,
getDomainWithoutWWW,
getUrlFromString,
@@ -78,6 +80,15 @@ export async function processLink<T extends Record<string, any>>({
code: "unprocessable_entity",
};
}
+ if (UTMTags.some((tag) => payload[tag])) {
+ const utmParams = UTMTags.reduce((acc, tag) => {
+ if (payload[tag]) {
+ acc[tag] = payload[tag];
+ }
+ return acc;
+ }, {});
+ url = constructURLFromUTMParams(url, utmParams);
+ }
// only root domain links can have empty desintation URL
} else if (key !== "_root") {
return {
@@ -350,6 +361,9 @@ export async function processLink<T extends Record<string, any>>({
delete payload["shortLink"];
delete payload["qrCode"];
delete payload["prefix"];
+ UTMTags.forEach((tag) => {
+ delete payload[tag];
+ });
return {
link: {
diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.ts
index ea82450dc3..3deb4a1ee1 100644
--- a/apps/web/lib/zod/schemas/links.ts
+++ b/apps/web/lib/zod/schemas/links.ts
@@ -273,6 +273,23 @@ export const createLinkBodySchema = z.object({
.describe(
"Allow search engines to index your short link. Defaults to `false` if not provided. Learn more: https://d.to/noindex",
),
+ utm_source: z
+ .string()
+ .nullish()
+ .describe("The UTM source of the short link."),
+ utm_medium: z
+ .string()
+ .nullish()
+ .describe("The UTM medium of the short link."),
+ utm_campaign: z
+ .string()
+ .nullish()
+ .describe("The UTM campaign of the short link."),
+ utm_term: z.string().nullish().describe("The UTM term of the short link."),
+ utm_content: z
+ .string()
+ .nullish()
+ .describe("The UTM content of the short link."),
});
export const updateLinkBodySchema = createLinkBodySchema.partial().optional();
diff --git a/packages/utils/src/functions/urls.ts b/packages/utils/src/functions/urls.ts
index 4e495eb9ff..85f579375d 100644
--- a/packages/utils/src/functions/urls.ts
+++ b/packages/utils/src/functions/urls.ts
@@ -59,6 +59,14 @@ export const getParamsFromURL = (url: string) => {
}
};
+export const UTMTags = [
+ "utm_source",
+ "utm_medium",
+ "utm_campaign",
+ "utm_term",
+ "utm_content",
+];
+
export const constructURLFromUTMParams = (
url: string,
utmParams: Record<string, string>,