The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Clear a link's partner when an update removes it
Cursor Agentb6a837965b3a
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.tsindex 7ea389b30d..56956be034 100644--- a/apps/web/app/api/links/[linkId]/route.ts+++ b/apps/web/app/api/links/[linkId]/route.ts@@ -6,6 +6,7 @@ import {updateLink,} from "@/lib/api/links";import { getLinkOrThrow } from "@/lib/api/links/get-link-or-throw";+import { partnerRemovalOverrides } from "@/lib/api/links/partner-removal";import { isRootDomainLinkKey } from "@/lib/api/links/utils/is-root-domain-link-key";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";@@ -116,6 +117,7 @@ export const PATCH = withWorkspace(: link.expiresAt,geo: link.geo as NewLinkProps["geo"],...body,+ ...(partnerRemovalOverrides(body) ?? {}),// Only pass UTM tags to processLink when explicitly provided in body (preserves existing values otherwise)...Object.fromEntries(UTMTags.filter((tag) => tag in body).map((tag) => [tag, body[tag]]),diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.tsindex 0822bce742..3feecee9d1 100644--- a/apps/web/app/api/links/bulk/route.ts+++ b/apps/web/app/api/links/bulk/route.ts@@ -10,6 +10,7 @@ import { bulkUpdateLinks } from "@/lib/api/links/bulk-update-links";import { getOwnedLinkImageKey } from "@/lib/api/links/get-owned-link-image-key";import { includeProgramEnrollment } from "@/lib/api/links/include-program-enrollment";import { includeTags } from "@/lib/api/links/include-tags";+import { partnerRemovalOverrides } from "@/lib/api/links/partner-removal";import { throwIfLinksUsageExceeded } from "@/lib/api/links/usage-checks";import { checkIfLinksHaveFolders } from "@/lib/api/links/utils/check-if-links-have-folders";import { checkIfLinksHaveProgramPartners } from "@/lib/api/links/utils/check-if-links-have-program-partners";@@ -507,6 +508,8 @@ export const PATCH = withWorkspace(}}+ const removal = partnerRemovalOverrides(data) ?? {};+const processedLinks = await Promise.all(links.map(async (link) =>processLink({@@ -527,6 +530,7 @@ export const PATCH = withWorkspace(? link.testStartedAt.toISOString(): link.testStartedAt,...data,+ ...removal,},workspace,userId: link.userId ?? undefined,@@ -557,6 +561,7 @@ export const PATCH = withWorkspace(linkIds: validLinkIds,data: {...data,+ ...removal,tagIds,expiresAt,},diff --git a/apps/web/app/api/links/upsert/route.ts b/apps/web/app/api/links/upsert/route.tsindex 22f0a9b406..2e9b4e4b0f 100644--- a/apps/web/app/api/links/upsert/route.ts+++ b/apps/web/app/api/links/upsert/route.ts@@ -5,6 +5,7 @@ import {transformLink,updateLink,} from "@/lib/api/links";+import { partnerRemovalOverrides } from "@/lib/api/links/partner-removal";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";import { verifyFolderAccess } from "@/lib/folder/permissions";@@ -75,6 +76,7 @@ export const PUT = withWorkspace(? link.testStartedAt.toISOString(): link.testStartedAt,...body,+ ...(partnerRemovalOverrides(body) ?? {}),};// if link and updatedLink are identical, return the linkdiff --git a/apps/web/lib/api/links/bulk-update-links.ts b/apps/web/lib/api/links/bulk-update-links.tsindex af4227e88e..5672083684 100644--- a/apps/web/lib/api/links/bulk-update-links.ts+++ b/apps/web/lib/api/links/bulk-update-links.ts@@ -112,6 +112,11 @@ export async function bulkUpdateLinks(},}),+ // Removing the partner also detaches the group default-link template.+ ...(rest.partnerId === null && {+ partnerGroupDefaultLinkId: null,+ }),+// Associate webhooks...(webhookIds && {webhooks: {diff --git a/apps/web/lib/api/links/partner-removal.ts b/apps/web/lib/api/links/partner-removal.tsnew file mode 100644index 0000000000..4a12bc5271--- /dev/null+++ b/apps/web/lib/api/links/partner-removal.ts@@ -0,0 +1,20 @@+/**+ * Overrides applied when an update explicitly removes a link's partner.+ *+ * PATCH, upsert, and bulk update merge the body onto the stored link, so an+ * omitted `partnerId` keeps the current partner. An explicit `null` has to+ * clear `programId` too: `processLink` treats a stored program id plus+ * `tenantId` as "resolve the partner" and would put the same partner back.+ * A program id sent in the same request is left alone so `tenantId` can still+ * enroll a different partner.+ */+export function partnerRemovalOverrides(patch: {+ partnerId?: string | null;+ programId?: string | null;+}): { partnerId: null; programId: null } | null {+ if (patch.partnerId !== null || patch.programId) {+ return null;+ }++ return { partnerId: null, programId: null };+}diff --git a/apps/web/lib/api/links/process-link.ts b/apps/web/lib/api/links/process-link.tsindex 6589be02c0..19d21fb58c 100644--- a/apps/web/lib/api/links/process-link.ts+++ b/apps/web/lib/api/links/process-link.ts@@ -437,6 +437,9 @@ export async function processLink<T extends Record<string, any>>({}// only perform program validity checks if not bulk creation (we do that check separately in the route itself)+ // A stored programId resolves the partner from partnerId or tenantId.+ // Removing a partner has to clear programId first (see partnerRemovalOverrides),+ // otherwise the stored tenantId puts that partner back.if (programId && !skipProgramChecks) {if (!partnerId && !tenantId) {return {diff --git a/apps/web/lib/api/links/update-link.ts b/apps/web/lib/api/links/update-link.tsindex 096d5b2b99..5732398d3a 100644--- a/apps/web/lib/api/links/update-link.ts+++ b/apps/web/lib/api/links/update-link.ts@@ -192,6 +192,11 @@ export async function updateLink({}: {}),+ // A link with no partner is no longer a partner-group default link.+ ...(partnerId === null && {+ partnerGroupDefaultLinkId: null,+ }),+// Shared dashboard...(publicStats && {dashboard: {diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.tsindex 784fd3ae3c..9b81281aff 100644--- a/apps/web/lib/zod/schemas/links.ts+++ b/apps/web/lib/zod/schemas/links.ts@@ -358,8 +358,11 @@ export const createLinkBodySchema = z.object({.describe("The ID of the program the short link is associated with."),partnerId: z.string()+ .transform((v) => (v === "" ? null : v)).nullish()- .describe("The ID of the partner the short link is associated with."),+ .describe(+ "The ID of the partner the short link is associated with. Pass `null` or an empty string to remove the partner. Removing the partner also removes the program association.",+ ),prefix: z.string().optional()diff --git a/apps/web/tests/links/partner-removal.test.ts b/apps/web/tests/links/partner-removal.test.tsnew file mode 100644index 0000000000..eaaad12830--- /dev/null+++ b/apps/web/tests/links/partner-removal.test.ts@@ -0,0 +1,90 @@+import { partnerRemovalOverrides } from "@/lib/api/links/partner-removal";+import { updateLinkBodySchema } from "@/lib/zod/schemas/links";+import { buildLinkBody } from "@/ui/links/link-builder/build-link-body";+import { describe, expect, test } from "vitest";++describe("partnerRemovalOverrides", () => {+ test("leaves an update that does not clear the partner unchanged", () => {+ expect(partnerRemovalOverrides({})).toBeNull();+ expect(partnerRemovalOverrides({ partnerId: "pn_1" })).toBeNull();+ expect(+ partnerRemovalOverrides({ partnerId: "pn_1", programId: "prog_1" }),+ ).toBeNull();+ });++ test("clears the program when the partner is removed and no new program is sent", () => {+ expect(partnerRemovalOverrides({ partnerId: null })).toEqual({+ partnerId: null,+ programId: null,+ });+ expect(+ partnerRemovalOverrides({ partnerId: null, programId: null }),+ ).toEqual({+ partnerId: null,+ programId: null,+ });+ });++ test("keeps an explicit program so a tenant can still enroll a partner", () => {+ expect(+ partnerRemovalOverrides({ partnerId: null, programId: "prog_1" }),+ ).toBeNull();+ });+});++describe("buildLinkBody", () => {+ const link = {+ url: "https://example.com",+ domain: "dub.sh",+ key: "hello",+ tags: [{ id: "tag_1" }],+ folderId: "fold_1",+ expiredUrl: "",+ ios: "",+ android: "",+ externalId: "",+ tenantId: "tenant_1",+ programId: "prog_1",+ partnerId: "pn_1",+ } as any;++ test("assigns the workspace program when a partner is set", () => {+ expect(+ buildLinkBody({+ data: link,+ defaultProgramId: "prog_default",+ }),+ ).toMatchObject({+ programId: "prog_default",+ partnerId: "pn_1",+ tenantId: "tenant_1",+ });+ });++ test("clears the stored program and partner when the partner is removed", () => {+ const body = buildLinkBody({+ data: { ...link, partnerId: null },+ defaultProgramId: "prog_default",+ });++ expect(body.partnerId).toBeNull();+ expect(body.programId).toBeNull();+ expect(body.tenantId).toBe("tenant_1");+ expect(body.folderId).toBe("fold_1");+ expect(body.tagIds).toEqual(["tag_1"]);+ });+});++describe("updateLinkBodySchema partner removal", () => {+ test("keeps null and treats an empty string as a removal", () => {+ expect(updateLinkBodySchema.parse({ partnerId: null })).toMatchObject({+ partnerId: null,+ });+ expect(updateLinkBodySchema.parse({ partnerId: "" })).toMatchObject({+ partnerId: null,+ });+ expect(+ updateLinkBodySchema.parse({ url: "https://example.com" }),+ ).not.toHaveProperty("partnerId");+ });+});diff --git a/apps/web/ui/links/link-builder/build-link-body.ts b/apps/web/ui/links/link-builder/build-link-body.tsnew file mode 100644index 0000000000..c50c3e1d12--- /dev/null+++ b/apps/web/ui/links/link-builder/build-link-body.ts@@ -0,0 +1,36 @@+import { LinkFormData } from "./link-builder-provider";++export function buildLinkBody({+ data,+ defaultProgramId,+}: {+ data: LinkFormData;+ defaultProgramId?: string | null;+}) {+ // @ts-ignore – exclude extra attributes from `data` object before sending to API+ const { user, tags, tagId, folderId, partnerId, ...rest } = data;++ return {+ ...rest,++ // Map tags to tagIds+ tagIds: tags.map(({ id }) => id),++ // Replace "unsorted" folder ID w/ null+ folderId: folderId === "unsorted" ? null : folderId,++ // Manually reset empty strings to null+ expiredUrl: rest.expiredUrl || null,+ ios: rest.ios || null,+ android: rest.android || null,+ externalId: rest.externalId || null,+ tenantId: rest.tenantId || null,++ // An omitted partnerId is ignored by PATCH (the route merges onto the+ // stored link). Removal has to send null, and programId has to be cleared+ // in the same request, otherwise the stored program reattaches the partner.+ ...(partnerId+ ? { programId: defaultProgramId, partnerId }+ : { programId: null, partnerId: null }),+ };+}diff --git a/apps/web/ui/links/link-builder/use-link-builder-submit.tsx b/apps/web/ui/links/link-builder/use-link-builder-submit.tsxindex 7fb337d95b..271276fc5f 100644--- a/apps/web/ui/links/link-builder/use-link-builder-submit.tsx+++ b/apps/web/ui/links/link-builder/use-link-builder-submit.tsx@@ -7,6 +7,7 @@ import { useCallback } from "react";import { useFormContext } from "react-hook-form";import { toast } from "sonner";import { mutate } from "swr";+import { buildLinkBody } from "./build-link-body";import { LinkFormData, useLinkBuilderContext } from "./link-builder-provider";export function useLinkBuilderSubmit({@@ -22,29 +23,10 @@ export function useLinkBuilderSubmit({return useCallback(async (data: LinkFormData) => {- // @ts-ignore – exclude extra attributes from `data` object before sending to API- const { user, tags, tagId, folderId, partnerId, ...rest } = data;- const bodyData = {- ...rest,-- // Map tags to tagIds- tagIds: tags.map(({ id }) => id),-- // Replace "unsorted" folder ID w/ null- folderId: folderId === "unsorted" ? null : folderId,-- // Manually reset empty strings to null- expiredUrl: rest.expiredUrl || null,- ios: rest.ios || null,- android: rest.android || null,- externalId: rest.externalId || null,- tenantId: rest.tenantId || null,-- // Create partner links- ...(partnerId- ? { programId: workspace.defaultProgramId, partnerId }- : {}),- };+ const bodyData = buildLinkBody({+ data,+ defaultProgramId: workspace.defaultProgramId,+ });const endpoint = props?.id? {@@ -164,6 +146,7 @@ export function useLinkBuilderSubmit({[workspace.id,workspace.slug,+ workspace.defaultProgramId,workspace.nextPlan,props,copyToClipboard,