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 UTM templates

Tim Wilson7484324f2efe
diff --git a/apps/web/app/api/utm-templates/[id]/route.ts b/apps/web/app/api/utm-templates/[id]/route.ts
new file mode 100644
index 0000000000..9ba9af5cdb
--- /dev/null
+++ b/apps/web/app/api/utm-templates/[id]/route.ts
@@ -0,0 +1,40 @@
+import { DubApiError } from "@/lib/api/errors";
+import { withWorkspace } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import { NextResponse } from "next/server";
+
+// DELETE /api/utm-templates/[id] – delete a UTM template for a workspace
+export const DELETE = withWorkspace(
+ async ({ params, workspace }) => {
+ const { id } = params;
+ try {
+ const response = await prisma.utmTemplate.delete({
+ where: {
+ id,
+ projectId: workspace.id,
+ },
+ });
+
+ if (!response) {
+ throw new DubApiError({
+ code: "not_found",
+ message: "UTM template not found.",
+ });
+ }
+
+ return NextResponse.json({ id });
+ } catch (error) {
+ if (error.code === "P2025") {
+ throw new DubApiError({
+ code: "not_found",
+ message: "UTM template not found.",
+ });
+ }
+
+ throw error;
+ }
+ },
+ {
+ requiredPermissions: ["links.write"],
+ },
+);
diff --git a/apps/web/app/api/utm-templates/route.ts b/apps/web/app/api/utm-templates/route.ts
new file mode 100644
index 0000000000..a414ef8b8b
--- /dev/null
+++ b/apps/web/app/api/utm-templates/route.ts
@@ -0,0 +1,56 @@
+import { withWorkspace } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import { createUTMTemplateBodySchema } from "@/lib/zod/schemas/utm-templates";
+import { NextResponse } from "next/server";
+
+// GET /api/utm-templates - get all UTM templates for a workspace
+export const GET = withWorkspace(
+ async ({ workspace, headers }) => {
+ const templates = await prisma.utmTemplate.findMany({
+ where: {
+ projectId: workspace.id,
+ },
+ orderBy: {
+ updatedAt: "desc",
+ },
+ take: 50,
+ });
+
+ return NextResponse.json(templates, { headers });
+ },
+ {
+ requiredPermissions: ["links.read"],
+ },
+);
+
+// POST /api/utm-templates - create or update a UTM template for a workspace
+export const POST = withWorkspace(
+ async ({ req, workspace, session, headers }) => {
+ const props = createUTMTemplateBodySchema.parse(await req.json());
+
+ const response = await prisma.utmTemplate.upsert({
+ where: {
+ projectId_name: {
+ projectId: workspace.id,
+ name: props.name,
+ },
+ },
+ create: {
+ projectId: workspace.id,
+ userId: session?.user.id,
+ ...props,
+ },
+ update: {
+ ...props,
+ },
+ });
+
+ return NextResponse.json(response, {
+ headers,
+ status: 201,
+ });
+ },
+ {
+ requiredPermissions: ["links.write"],
+ },
+);
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 75c5dc638a..eb63907600 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -1,7 +1,7 @@
import z from "@/lib/zod";
import { metaTagsSchema } from "@/lib/zod/schemas/metatags";
import { DirectorySyncProviders } from "@boxyhq/saml-jackson";
-import { Link, Project, Webhook } from "@prisma/client";
+import { Link, Project, UTMTemplate, Webhook } from "@prisma/client";
import { WEBHOOK_TRIGGER_DESCRIPTIONS } from "./webhook/constants";
import { trackCustomerResponseSchema } from "./zod/schemas/customers";
import { integrationSchema } from "./zod/schemas/integration";
@@ -60,6 +60,8 @@ export interface TagProps {
export type TagColorProps = (typeof tagColors)[number];
+export type UTMTemplateProps = UTMTemplate;
+
export type PlanProps = (typeof plans)[number];
export type RoleProps = (typeof roles)[number];
diff --git a/apps/web/lib/zod/schemas/utm-templates.ts b/apps/web/lib/zod/schemas/utm-templates.ts
new file mode 100644
index 0000000000..3956fadfbb
--- /dev/null
+++ b/apps/web/lib/zod/schemas/utm-templates.ts
@@ -0,0 +1,35 @@
+import z from "@/lib/zod";
+
+export const createUTMTemplateBodySchema = z.object({
+ name: z.string(),
+ utm_source: z
+ .string()
+ .nullish()
+ .transform((v) => v ?? null)
+ .describe("The UTM source of the short link."),
+ utm_medium: z
+ .string()
+ .nullish()
+ .transform((v) => v ?? null)
+ .describe("The UTM medium of the short link."),
+ utm_campaign: z
+ .string()
+ .nullish()
+ .transform((v) => v ?? null)
+ .describe("The UTM campaign of the short link."),
+ utm_term: z
+ .string()
+ .nullish()
+ .transform((v) => v ?? null)
+ .describe("The UTM term of the short link."),
+ utm_content: z
+ .string()
+ .nullish()
+ .transform((v) => v ?? null)
+ .describe("The UTM content of the short link."),
+ ref: z
+ .string()
+ .nullish()
+ .transform((v) => v ?? null)
+ .describe("The ref of the short link."),
+});
diff --git a/apps/web/prisma/schema/link.prisma b/apps/web/prisma/schema/link.prisma
index e69056aeff..04123138a5 100644
--- a/apps/web/prisma/schema/link.prisma
+++ b/apps/web/prisma/schema/link.prisma
@@ -78,3 +78,32 @@ model Link {
@@index(userId)
@@fulltext([key, url])
}
+
+model UtmTemplate {
+ id String @id @default(cuid())
+ name String
+
+ // Parameters
+ utm_source String?
+ utm_medium String?
+ utm_campaign String?
+ utm_term String?
+ utm_content String?
+ ref String?
+
+ // User who created the template
+ user User? @relation(fields: [userId], references: [id])
+ userId String?
+
+ // Project that the template belongs to
+ project Project? @relation(fields: [projectId], references: [id], onUpdate: Cascade, onDelete: Cascade)
+ projectId String?
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index(userId)
+ @@index(projectId)
+ @@unique([projectId, name])
+ @@index(updatedAt(sort: Desc))
+}
diff --git a/apps/web/prisma/schema/schema.prisma b/apps/web/prisma/schema/schema.prisma
index f5c5a804a5..d2633e1976 100644
--- a/apps/web/prisma/schema/schema.prisma
+++ b/apps/web/prisma/schema/schema.prisma
@@ -39,6 +39,7 @@ model User {
oAuthCodes OAuthCode[]
integrations Integration[] // Integrations user created in their workspace
installedIntegrations InstalledIntegration[] // Integrations user installed in their workspace
+ utmTemplates UtmTemplate[]
@@index(source)
@@index(defaultWorkspace)
diff --git a/apps/web/prisma/schema/workspace.prisma b/apps/web/prisma/schema/workspace.prisma
index b7c8734c94..99d6e18892 100644
--- a/apps/web/prisma/schema/workspace.prisma
+++ b/apps/web/prisma/schema/workspace.prisma
@@ -50,6 +50,7 @@ model Project {
installedIntegrations InstalledIntegration[] // Integrations workspace installed
webhooks Webhook[]
registeredDomains RegisteredDomain[]
+ utmTemplates UtmTemplate[]
@@index(usageLastChecked(sort: Asc))
}
diff --git a/apps/web/ui/modals/link-builder/utm-modal.tsx b/apps/web/ui/modals/link-builder/utm-modal.tsx
index 2e84556373..1ee9bd7d7f 100644
--- a/apps/web/ui/modals/link-builder/utm-modal.tsx
+++ b/apps/web/ui/modals/link-builder/utm-modal.tsx
@@ -24,9 +24,10 @@ import {
useRef,
useState,
} from "react";
-import { useForm, useFormContext } from "react-hook-form";
+import { FormProvider, useForm, useFormContext } from "react-hook-form";
import { LinkFormData } from ".";
import { UTM_PARAMETERS } from "./constants";
+import { UTMTemplatesButton } from "./utm-templates-button";
type UTMModalProps = {
showUTMModal: boolean;
@@ -52,13 +53,7 @@ function UTMModalInner({ setShowUTMModal }: UTMModalProps) {
const { getValues: getValuesParent, setValue: setValueParent } =
useFormContext<LinkFormData>();
- const {
- watch,
- setValue,
- reset,
- formState: { isDirty },
- handleSubmit,
- } = useForm<
+ const form = useForm<
Pick<
LinkFormData,
| "url"
@@ -79,6 +74,14 @@ function UTMModalInner({ setShowUTMModal }: UTMModalProps) {
},
});
+ const {
+ watch,
+ setValue,
+ reset,
+ formState: { isDirty },
+ handleSubmit,
+ } = form;
+
const url = watch("url");
const enabledParams = useMemo(() => getParamsFromURL(url), [url]);
@@ -290,24 +293,39 @@ function UTMModalInner({ setShowUTMModal }: UTMModalProps) {
</div>
)}
- <div className="mt-6 flex items-center justify-end gap-2">
- <Button
- type="button"
- variant="secondary"
- text="Cancel"
- className="h-9 w-fit"
- onClick={() => {
- reset();
- setShowUTMModal(false);
- }}
- />
- <Button
- type="submit"
- variant="primary"
- text="Save"
- className="h-9 w-fit"
- disabled={!isDirty}
- />
+ <div className="mt-6 flex items-center justify-between gap-2">
+ {isValidUrl(url) ? (
+ <FormProvider {...form}>
+ <UTMTemplatesButton
+ onLoad={(params) => {
+ setValue("url", constructURLFromUTMParams(url, params), {
+ shouldDirty: true,
+ });
+ }}
+ />
+ </FormProvider>
+ ) : (
+ <div />
+ )}
+ <div className="flex items-center gap-2">
+ <Button
+ type="button"
+ variant="secondary"
+ text="Cancel"
+ className="h-9 w-fit"
+ onClick={() => {
+ reset();
+ setShowUTMModal(false);
+ }}
+ />
+ <Button
+ type="submit"
+ variant="primary"
+ text="Save"
+ className="h-9 w-fit"
+ disabled={!isDirty}
+ />
+ </div>
</div>
</form>
);
diff --git a/apps/web/ui/modals/link-builder/utm-templates-button.tsx b/apps/web/ui/modals/link-builder/utm-templates-button.tsx
new file mode 100644
index 0000000000..380b5fb5b7
--- /dev/null
+++ b/apps/web/ui/modals/link-builder/utm-templates-button.tsx
@@ -0,0 +1,313 @@
+"use client";
+
+import useWorkspace from "@/lib/swr/use-workspace";
+import { UTMTemplateProps } from "@/lib/types";
+import { AnimatedSizeContainer, Button, Popover, Xmark } from "@dub/ui";
+import {
+ Book2,
+ Download,
+ LoadingSpinner,
+ SquareLayoutGrid6,
+ useMediaQuery,
+} from "@dub/ui/src";
+import { fetcher, getParamsFromURL, timeAgo } from "@dub/utils";
+import { ChevronUp } from "lucide-react";
+import { useEffect, useMemo, useRef, useState } from "react";
+import { useFormContext } from "react-hook-form";
+import { toast } from "sonner";
+import useSWR, { mutate } from "swr";
+
+export function UTMTemplatesButton({
+ onLoad,
+}: {
+ onLoad: (params: Record<string, string>) => void;
+}) {
+ const { isMobile } = useMediaQuery();
+ const { id: workspaceId } = useWorkspace();
+
+ let { data, isLoading } = useSWR<UTMTemplateProps[]>(
+ workspaceId && `/api/utm-templates?workspaceId=${workspaceId}`,
+ fetcher,
+ {
+ dedupingInterval: 60000,
+ },
+ );
+
+ const [openPopover, setOpenPopover] = useState(false);
+ const [state, setState] = useState<"default" | "load" | "save">("default");
+ useEffect(() => {
+ if (!openPopover) setState("default");
+ }, [openPopover]);
+
+ return (
+ <Popover
+ openPopover={openPopover}
+ setOpenPopover={setOpenPopover}
+ side="top"
+ align="start"
+ onWheel={(e) => {
+ // Allows scrolling to work when the popover's in a modal
+ e.stopPropagation();
+ }}
+ content={
+ <AnimatedSizeContainer width={!isMobile} height>
+ {data ? (
+ <div className="text-sm">
+ {state === "default" && (
+ <div className="grid p-1">
+ {data.length > 0 && (
+ <button
+ onClick={() => setState("load")}
+ className="flex w-full items-center gap-2 rounded-md p-2 text-gray-700 outline-none hover:bg-gray-100 focus-visible:ring-2 focus-visible:ring-gray-500 active:bg-gray-200"
+ >
+ <Download className="size-4 text-gray-900" />
+ Load template
+ </button>
+ )}
+ <button
+ onClick={() => setState("save")}
+ className="flex w-full items-center gap-2 rounded-md p-2 text-gray-700 outline-none hover:bg-gray-100 focus-visible:ring-2 focus-visible:ring-gray-500 active:bg-gray-200"
+ >
+ <Book2 className="size-4 text-gray-900" />
+ Save template
+ </button>
+ </div>
+ )}
+ {state === "save" && (
+ <div className="max-w-64 p-2">
+ <SaveUTMTemplateForm
+ onSuccess={() => setOpenPopover(false)}
+ />
+ </div>
+ )}
+ {state === "load" && (
+ <div className="max-w-64">
+ <UTMTemplateList
+ data={data}
+ onLoad={(params) => {
+ setOpenPopover(false);
+ onLoad(params);
+ }}
+ onDelete={() => setOpenPopover(false)}
+ />
+ </div>
+ )}
+ </div>
+ ) : isLoading ? (
+ <div className="flex w-full items-center justify-center py-4 md:w-32">
+ <LoadingSpinner className="size-4" />
+ </div>
+ ) : (
+ <div className="flex w-full items-center justify-center p-2 text-center text-xs text-gray-500 md:w-32">
+ Failed to load templates
+ </div>
+ )}
+ </AnimatedSizeContainer>
+ }
+ >
+ <Button
+ type="button"
+ variant="secondary"
+ className="h-10 w-fit px-3"
+ textWrapperClassName="flex items-center justify-start"
+ text={
+ <>
+ Templates
+ <ChevronUp
+ className={`ml-1 size-4 shrink-0 text-gray-400 transition-transform duration-75 group-data-[state=open]:rotate-180`}
+ />
+ </>
+ }
+ />
+ </Popover>
+ );
+}
+
+function SaveUTMTemplateForm({ onSuccess }: { onSuccess: () => void }) {
+ const { isMobile } = useMediaQuery();
+ const { id: workspaceId } = useWorkspace();
+
+ const { getValues } = useFormContext();
+
+ const [name, setName] = useState("");
+ const [saving, setSaving] = useState(false);
+
+ // Manual name input autofocus to prevent scroll (which screws up the AnimatedSizeContainer)
+ const inputRef = useRef<HTMLInputElement>(null);
+ useEffect(() => {
+ if (!isMobile && inputRef.current)
+ inputRef.current.focus({ preventScroll: true });
+ }, [isMobile]);
+
+ return (
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setSaving(true);
+ try {
+ const res = await fetch(
+ `/api/utm-templates?workspaceId=${workspaceId}`,
+ {
+ method: "POST",
+ body: JSON.stringify({
+ name,
+ ...getParamsFromURL(getValues("url")),
+ }),
+ },
+ );
+ if (!res.ok) throw new Error("UTM template save request failed");
+
+ mutate(`/api/utm-templates?workspaceId=${workspaceId}`);
+ toast.success("Template saved successfully");
+ onSuccess();
+ } catch (e) {
+ console.error(e);
+ toast.error("Failed to save UTM template");
+ } finally {
+ setSaving(false);
+ }
+ }}
+ >
+ <div className="flex items-center gap-2">
+ <input
+ ref={inputRef}
+ type="text"
+ className="h-9 min-w-0 grow rounded-md border border-gray-300 placeholder-gray-400 focus:border-gray-500 focus:ring-gray-500 sm:text-sm"
+ placeholder="Template name"
+ value={name}
+ onChange={(e) => setName(e.target.value)}
+ />
+ <Button
+ type="submit"
+ variant="primary"
+ text="Save"
+ className="h-9 w-fit"
+ onClick={() => {}}
+ disabled={!name}
+ loading={saving}
+ />
+ </div>
+ <p className="mt-2 text-xs text-gray-500">
+ Your saved template will be available to all users in this workspace.
+ </p>
+ </form>
+ );
+}
+
+function UTMTemplateList({
+ data,
+ onLoad,
+ onDelete,
+}: {
+ data: UTMTemplateProps[];
+ onLoad: (params: Record<string, string>) => void;
+ onDelete: () => void;
+}) {
+ const { id: workspaceId } = useWorkspace();
+ const { setValue } = useFormContext();
+
+ const handleDelete = async (id: string) => {
+ try {
+ const res = await fetch(
+ `/api/utm-templates/${id}?workspaceId=${workspaceId}`,
+ {
+ method: "DELETE",
+ },
+ );
+ if (!res.ok) throw new Error("UTM template delete failed");
+
+ mutate(`/api/utm-templates?workspaceId=${workspaceId}`);
+ toast.success("Template deleted successfully");
+ onDelete();
+ } catch (e) {
+ console.error(e);
+ toast.error("Failed to delete template");
+ }
+ };
+
+ return data.length ? (
+ <div className="scrollbar-hide grid max-h-64 overflow-y-auto p-1 md:min-w-48">
+ <span className="block pb-2 pl-2.5 pt-2 text-xs font-medium text-gray-500">
+ Templates
+ </span>
+ {data.map((template) => (
+ <UTMTemplateOption
+ key={template.id}
+ template={template}
+ onClick={() => {
+ const paramEntries = Object.entries(template)
+ .filter(([key]) => key === "ref" || key.startsWith("utm_"))
+ .map(([key, value]) => [key, (value || "").toString()]);
+
+ paramEntries.forEach(([key, value]) =>
+ setValue(key, value, { shouldDirty: true }),
+ );
+
+ onLoad(Object.fromEntries(paramEntries));
+ }}
+ onDelete={async () => await handleDelete(template.id)}
+ />
+ ))}
+ </div>
+ ) : (
+ <div className="flex items-center justify-center p-3 text-center text-xs text-gray-500">
+ No templates found
+ </div>
+ );
+}
+
+function UTMTemplateOption({
+ template,
+ onClick,
+ onDelete,
+}: {
+ template: UTMTemplateProps;
+ onClick: () => void;
+ onDelete: () => Promise<void>;
+}) {
+ const time = useMemo(
+ () => timeAgo(new Date(template.updatedAt)),
+ [template.updatedAt],
+ );
+
+ const [deleting, setDeleting] = useState(false);
+
+ return (
+ <div className="group relative">
+ <button
+ onClick={onClick}
+ className="flex w-full items-center justify-between gap-2 rounded-md p-2 text-gray-700 outline-none hover:bg-gray-100 focus-visible:ring-2 focus-visible:ring-gray-500 active:bg-gray-200 group-hover:bg-gray-100"
+ >
+ <span className="flex items-center gap-1.5">
+ <SquareLayoutGrid6 className="text-gray-500" />
+ {template.name}
+ </span>
+ <div className="flex items-center gap-1">
+ <span className="text-xs text-gray-500">{time}</span>
+ <div className="size-[1.375rem]"></div>
+ </div>
+ </button>
+ <button
+ type="button"
+ onClick={async (e) => {
+ e.stopPropagation();
+ if (!window.confirm("Are you sure you want to delete this template?"))
+ return;
+
+ setDeleting(true);
+ await onDelete();
+ setDeleting(false);
+ }}
+ className="absolute right-1.5 top-2 rounded-md p-1 text-gray-400 outline-none transition-colors hover:text-gray-500 focus-visible:ring-2 focus-visible:ring-gray-500"
+ title="Delete template"
+ >
+ {deleting ? (
+ <LoadingSpinner className="size-3.5" />
+ ) : (
+ <Xmark className="size-3.5" />
+ )}
+ </button>
+ </div>
+ );
+}