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 link cloaking feature

Steven Teyeeded80d75d3
diff --git a/app/ui/switch.tsx b/app/ui/switch.tsx
index 6bb6b8292a..f7c651f752 100644
--- a/app/ui/switch.tsx
+++ b/app/ui/switch.tsx
@@ -3,6 +3,7 @@
import { Dispatch, SetStateAction } from "react";
import * as SwitchPrimitive from "@radix-ui/react-switch";
import { cn } from "#/lib/utils";
+import Tooltip from "./tooltip";
const Switch = ({
fn,
@@ -11,6 +12,7 @@ const Switch = ({
thumbTranslate,
checked = true,
disabled = false,
+ disabledTooltip,
}: {
fn: Dispatch<SetStateAction<boolean>> | (() => void);
trackDimensions?: string;
@@ -18,7 +20,23 @@ const Switch = ({
thumbTranslate?: string;
checked?: boolean;
disabled?: boolean;
+ disabledTooltip?: string;
}) => {
+ if (disabledTooltip) {
+ return (
+ <Tooltip content={disabledTooltip}>
+ <SwitchPrimitive.Root
+ checked={checked}
+ name="switch"
+ disabled={true}
+ className="relative inline-flex h-4 w-8 flex-shrink-0 cursor-not-allowed rounded-full border-2 border-transparent bg-gray-200 radix-state-checked:bg-gray-300"
+ >
+ <SwitchPrimitive.Thumb className="h-3 w-3 transform rounded-full bg-white shadow-lg" />
+ </SwitchPrimitive.Root>
+ </Tooltip>
+ );
+ }
+
return (
<SwitchPrimitive.Root
checked={checked}
@@ -27,7 +45,7 @@ const Switch = ({
disabled={disabled}
className={cn(
disabled
- ? "cursor-not-allowed bg-gray-300"
+ ? "cursor-not-allowed radix-state-checked:bg-gray-300"
: "cursor-pointer focus:outline-none focus-visible:ring focus-visible:ring-blue-500 focus-visible:ring-opacity-75 radix-state-checked:bg-blue-500 radix-state-unchecked:bg-gray-200",
`relative inline-flex h-4 w-8 flex-shrink-0 rounded-full border-2 border-transparent transition-colors duration-200 ease-in-out`,
trackDimensions,
diff --git a/components/app/modals/add-edit-domain-modal.tsx b/components/app/modals/add-edit-domain-modal.tsx
index 1a53593686..1ea0e023c5 100644
--- a/components/app/modals/add-edit-domain-modal.tsx
+++ b/components/app/modals/add-edit-domain-modal.tsx
@@ -170,8 +170,8 @@ function AddEditDomainModal({
toast.error(domainErrorResponse);
}
} else {
- setDomainError("Something went wrong. Please try again.");
- toast.error("Something went wrong. Please try again.");
+ const error = await res.text();
+ toast.error(error);
}
});
}}
diff --git a/components/app/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsx
index 85625d74ff..7cfeb1988c 100644
--- a/components/app/modals/add-edit-link-modal/index.tsx
+++ b/components/app/modals/add-edit-link-modal/index.tsx
@@ -46,6 +46,7 @@ import va from "@vercel/analytics";
import punycode from "punycode/";
import Button from "#/ui/button";
import { ModalContext } from "#/ui/modal-provider";
+import RewriteSection from "./rewrite-section";
function AddEditLinkModal({
showAddEditLinkModal,
@@ -545,6 +546,7 @@ function AddEditLinkModal({
generatingMetatags={generatingMetatags}
/>
<UTMSection {...{ props, data, setData }} />
+ <RewriteSection {...{ data, setData }} />
<PasswordSection {...{ props, data, setData }} />
<ExpirationSection {...{ props, data, setData }} />
<IOSSection {...{ props, data, setData }} />
diff --git a/components/app/modals/add-edit-link-modal/rewrite-section.tsx b/components/app/modals/add-edit-link-modal/rewrite-section.tsx
new file mode 100644
index 0000000000..89012bdeef
--- /dev/null
+++ b/components/app/modals/add-edit-link-modal/rewrite-section.tsx
@@ -0,0 +1,59 @@
+import { Dispatch, SetStateAction, useEffect, useState } from "react";
+import { LinkProps } from "#/lib/types";
+import Switch from "#/ui/switch";
+import { HOME_DOMAIN } from "#/lib/constants";
+import { InfoTooltip, SimpleTooltipContent } from "#/ui/tooltip";
+import useProject from "#/lib/swr/use-project";
+
+export default function RewriteSection({
+ data,
+ setData,
+}: {
+ data: LinkProps;
+ setData: Dispatch<SetStateAction<LinkProps>>;
+}) {
+ const { plan } = useProject();
+ const { rewrite } = data;
+ const [enabled, setEnabled] = useState(rewrite);
+ useEffect(() => {
+ if (enabled) {
+ // if enabling, set rewrite to true or props.rewrite
+ setData({
+ ...data,
+ rewrite: true,
+ });
+ } else {
+ // if disabling, set rewrite to false
+ setData({ ...data, rewrite: false });
+ }
+ }, [enabled]);
+
+ return (
+ <div className="border-b border-gray-200 pb-5">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center justify-between space-x-2">
+ <h2 className="text-sm font-medium text-gray-900">Link Cloaking</h2>
+ <InfoTooltip
+ content={
+ <SimpleTooltipContent
+ title="Mask your destination URL so your users only see the short link in the browser address bar."
+ cta="Learn more."
+ href={`${HOME_DOMAIN}/help/article/how-to-create-link#expiration-date`}
+ />
+ }
+ />
+ </div>
+ <Switch
+ fn={() => setEnabled(!enabled)}
+ checked={enabled}
+ {...(!plan || plan === "free"
+ ? {
+ disabledTooltip:
+ "Link cloaking is only available on paid plans.",
+ }
+ : {})}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/lib/api/links.ts b/lib/api/links.ts
index 729b6b9e5b..771a32df19 100644
--- a/lib/api/links.ts
+++ b/lib/api/links.ts
@@ -5,7 +5,7 @@ import { LinkProps } from "#/lib/types";
import { redis } from "#/lib/upstash";
import { getParamsFromURL, nanoid, truncate, validKeyRegex } from "#/lib/utils";
import { isReservedKey } from "#/lib/edge-config";
-import { NextApiRequest } from "next";
+import { NextApiRequest, NextApiResponse } from "next";
export async function getLinksForProject({
projectId,
@@ -190,6 +190,7 @@ export async function addLink(link: LinkProps) {
description,
image,
proxy,
+ rewrite,
ios,
android,
} = link;
@@ -224,6 +225,7 @@ export async function addLink(link: LinkProps) {
url: encodeURIComponent(url),
password: hasPassword,
proxy,
+ ...(rewrite && { rewrite: true }),
ios,
android,
},
@@ -274,6 +276,7 @@ export async function editLink(
description,
image,
proxy,
+ rewrite,
ios,
android,
} = link;
@@ -325,6 +328,7 @@ export async function editLink(
url: encodeURIComponent(url),
password: hasPassword,
proxy,
+ ...(rewrite && { rewrite: true }),
ios,
android,
},
diff --git a/lib/constants/index.ts b/lib/constants/index.ts
index 63f5637dac..a9b9fe72f1 100644
--- a/lib/constants/index.ts
+++ b/lib/constants/index.ts
@@ -137,6 +137,7 @@ export const DEFAULT_LINK_PROPS = {
title: null,
description: null,
image: null,
+ rewrite: false,
ios: null,
android: null,
diff --git a/lib/middleware/link.ts b/lib/middleware/link.ts
index 970bd5ff5c..1a8fa618af 100644
--- a/lib/middleware/link.ts
+++ b/lib/middleware/link.ts
@@ -23,10 +23,18 @@ export default async function LinkMiddleware(
url: string;
password?: boolean;
proxy?: boolean;
+ rewrite?: boolean;
ios?: string;
android?: string;
}>(`${domain}:${key}`);
- const { url: target, password, proxy, ios, android } = response || {};
+ const {
+ url: target,
+ password,
+ proxy,
+ rewrite,
+ ios,
+ android,
+ } = response || {};
if (target) {
// special case for link health monitoring with planetfall.io :)
@@ -56,10 +64,9 @@ export default async function LinkMiddleware(
);
} else {
// regular redirect
- return NextResponse.redirect(
- getFinalUrl(target, { req }),
- REDIRECT_HEADERS,
- );
+ return rewrite
+ ? NextResponse.rewrite(getFinalUrl(target, { req }))
+ : NextResponse.redirect(getFinalUrl(target, { req }), REDIRECT_HEADERS);
}
} else {
// short link not found, redirect to root
diff --git a/lib/types.ts b/lib/types.ts
index 3a6aa7ff25..a228d1f4cb 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -18,6 +18,8 @@ export interface LinkProps {
description: string | null;
image: string | null;
+ rewrite: boolean;
+
ios: string | null;
android: string | null;
diff --git a/pages/api/links/[key]/index.ts b/pages/api/links/[key]/index.ts
index 1693391c11..1d9b9b3926 100644
--- a/pages/api/links/[key]/index.ts
+++ b/pages/api/links/[key]/index.ts
@@ -25,7 +25,7 @@ export default withLinksAuth(
// PUT /api/links/:key – edit a link
} else if (req.method === "PUT") {
- let { domain, key, url } = req.body;
+ let { domain, key, url, rewrite } = req.body;
if (!domain || !key || !url) {
return res.status(400).end("Missing domain or key or url.");
}
@@ -44,6 +44,15 @@ export default withLinksAuth(
}
}
+ // free plan limitations
+ if (!project || project.plan === "free") {
+ if (rewrite) {
+ return res
+ .status(403)
+ .end("Link cloaking is only available for Pro users.");
+ }
+ }
+
key = processKey(key);
if (!key) {
return res.status(422).end("Invalid key.");
diff --git a/pages/api/links/index.ts b/pages/api/links/index.ts
index b518967b55..13a19880a0 100644
--- a/pages/api/links/index.ts
+++ b/pages/api/links/index.ts
@@ -39,7 +39,7 @@ export default withLinksAuth(
// POST /api/links – create a new link
} else if (req.method === "POST") {
- let { domain, key, url } = req.body;
+ let { domain, key, url, rewrite } = req.body;
if (!domain || !key || !url) {
return res.status(400).end("Missing domain or key or url.");
}
@@ -59,6 +59,15 @@ export default withLinksAuth(
}
}
+ // free plan limitations
+ if (!project || project.plan === "free") {
+ if (rewrite) {
+ return res
+ .status(403)
+ .end("Link cloaking is only available for Pro users.");
+ }
+ }
+
key = processKey(key);
if (!key) {
return res.status(422).end("Invalid key.");
diff --git a/pages/api/projects/[slug]/domains/[domain]/index.ts b/pages/api/projects/[slug]/domains/[domain]/index.ts
index fbb066253b..4194e5d2c9 100644
--- a/pages/api/projects/[slug]/domains/[domain]/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/index.ts
@@ -24,7 +24,7 @@ export default withProjectAuth(async (req, res, project) => {
) {
return res
.status(400)
- .json({ error: "Missing or misconfigured project slug or domain" });
+ .end("Missing or misconfigured project slug or domain");
}
// prevent unauthorized access to domains that don't belong to the project
@@ -35,7 +35,7 @@ export default withProjectAuth(async (req, res, project) => {
},
});
if (!domainBelongsToProject) {
- return res.status(404).json({ error: "Domain not found" });
+ return res.status(404).end("Domain not found");
}
// PUT /api/projects/[slug]/domains/[domain] edit a project's domain
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index b98f4c04a3..42108bf9c4 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -174,6 +174,9 @@ model Link {
utm_term String? // UTM term for the link (e.g. dub)
utm_content String? // UTM content for the link (e.g. description)
+ // Link cloaking/masking via rewrite
+ rewrite Boolean @default(false) // whether to rewrite the link or not
+
// Custom device targeting
ios String? @db.LongText // custom link for iOS devices
android String? @db.LongText // custom link for Android devices