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.

Fix domain management

Steven Tey3ee8632be2ee
diff --git a/components/app/modals/add-edit-domain-modal.tsx b/components/app/modals/add-edit-domain-modal.tsx
index f13bf73e60..45a44a17c2 100644
--- a/components/app/modals/add-edit-domain-modal.tsx
+++ b/components/app/modals/add-edit-domain-modal.tsx
@@ -16,7 +16,11 @@ import Modal from "@/components/shared/modal";
import { DomainProps } from "@/lib/types";
import Tooltip, { TooltipContent } from "@/components/shared/tooltip";
import useProject from "@/lib/swr/use-project";
-import { getPlanFromUsageLimit } from "@/lib/stripe/constants";
+import useUsage from "@/lib/swr/use-usage";
+import { AnimatePresence, motion } from "framer-motion";
+import { SWIPE_REVEAL_ANIMATION_SETTINGS } from "@/lib/constants";
+import Switch from "@/components/shared/switch";
+import useDomains from "@/lib/swr/use-domains";
function AddEditDomainModal({
showAddEditDomainModal,
@@ -29,7 +33,9 @@ function AddEditDomainModal({
}) {
const router = useRouter();
const { slug } = router.query;
- const { project: { logo } = {} } = useProject();
+ const { project: { logo } = {}, isOwner } = useProject();
+ const { plan } = useUsage();
+ const { domains } = useDomains();
const [data, setData] = useState<DomainProps>(
props || {
@@ -245,39 +251,72 @@ function AddEditDomainModal({
>
Landing Page
</label>
- <div className="relative mt-1 rounded-md shadow-sm">
- <input
- type="url"
- name="target"
- id="target"
- className="block w-full rounded-md border-gray-300 pr-10 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500"
- placeholder="https://example.com"
- value={target}
- onChange={(e) => setData({ ...data, target: e.target.value })}
- />
- </div>
+ {plan !== "Free" ? (
+ <div className="relative mt-1 rounded-md shadow-sm">
+ <input
+ type="url"
+ name="target"
+ id="target"
+ className="block w-full rounded-md border-gray-300 pr-10 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500"
+ placeholder="https://example.com"
+ value={target}
+ onChange={(e) => setData({ ...data, target: e.target.value })}
+ />
+ </div>
+ ) : (
+ <Tooltip
+ content={
+ <TooltipContent
+ title={`You can't configure a custom landing page on a free plan. ${
+ isOwner
+ ? "Upgrade to a Pro plan to proceed."
+ : "Ask your project owner to upgrade to a Pro plan."
+ }`}
+ cta={isOwner && "Upgrade to Pro"}
+ ctaLink={isOwner && "/settings"}
+ />
+ }
+ fullWidth
+ >
+ <div className="mt-1 w-full cursor-not-allowed rounded-md border border-gray-300 px-3 py-2 text-left text-sm text-gray-300 sm:max-w-md">
+ https://yourdomain.com
+ </div>
+ </Tooltip>
+ )}
</div>
- <div>
- <label
- htmlFor="type"
- className="block text-sm font-medium text-gray-700"
- >
- Behavior
- </label>
- <select
- value={type}
- onChange={(e) =>
- setData({
- ...data,
- type: e.target.value as "redirect" | "rewrite",
- })
- }
- className="mt-1 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-gray-500 shadow-sm focus:border-gray-500 focus:outline-none focus:ring-gray-500"
- >
- <option value="redirect">Redirect</option>
- <option value="rewrite">Rewrite</option>
- </select>
+ <AnimatePresence initial={false}>
+ {target && (
+ <motion.div key="type" {...SWIPE_REVEAL_ANIMATION_SETTINGS}>
+ <label
+ htmlFor="type"
+ className="block text-sm font-medium text-gray-700"
+ >
+ Behavior
+ </label>
+ <select
+ value={type}
+ onChange={(e) =>
+ setData({
+ ...data,
+ type: e.target.value as "redirect" | "rewrite",
+ })
+ }
+ className="mt-1 w-full rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-gray-500 shadow-sm focus:border-gray-500 focus:outline-none focus:ring-gray-500"
+ >
+ <option value="redirect">Redirect</option>
+ <option value="rewrite">Rewrite</option>
+ </select>
+ </motion.div>
+ )}
+ </AnimatePresence>
+
+ <div className="flex items-center justify-between bg-gray-50">
+ <p className="text-sm font-medium text-gray-900">Primary Domain</p>
+ <Switch
+ fn={() => setData((prev) => ({ ...prev, primary: !primary }))}
+ checked={primary}
+ />
</div>
<div className="grid gap-2">
@@ -295,7 +334,7 @@ function AddEditDomainModal({
<p>{props ? "Save changes" : "Add domain"}</p>
)}
</button>
- {props && (
+ {props && domains.length > 1 && (
<button
type="button"
className={`${
@@ -331,15 +370,14 @@ function AddEditDomainButton({
const router = useRouter();
const { slug } = router.query as { slug?: string };
- const { project: { ownerUsageLimit } = {} } = useProject();
+ const { plan } = useUsage();
+ const { domains } = useDomains();
- return slug && ownerUsageLimit < 1000000 ? ( // only show exceeded usage tooltip if user is on a project page
+ return slug && plan === "Free" && domains?.length >= 1 ? (
<Tooltip
content={
<TooltipContent
- title={`You can only add 1 custom domain on the ${getPlanFromUsageLimit(
- ownerUsageLimit,
- )} plan. Upgrade to add more.`}
+ title={`You can only add 1 custom domain on the ${plan} plan. Upgrade to add more.`}
cta="Upgrade"
ctaLink="/settings"
/>
diff --git a/components/app/modals/add-project-modal.tsx b/components/app/modals/add-project-modal.tsx
index 16705d3b69..99c32c7917 100644
--- a/components/app/modals/add-project-modal.tsx
+++ b/components/app/modals/add-project-modal.tsx
@@ -111,7 +111,6 @@ function AddProjectModalHelper({
},
body: JSON.stringify(data),
}).then(async (res) => {
- setSaving(false);
if (res.status === 200) {
mutate(`/api/projects`);
router.push(`/${slug}`);
@@ -129,6 +128,7 @@ function AddProjectModalHelper({
} else {
setDomainError("Something went wrong.");
}
+ setSaving(false);
});
}}
className="flex flex-col space-y-6 bg-gray-50 px-4 py-8 text-left sm:px-16"
diff --git a/components/app/modals/delete-project-modal.tsx b/components/app/modals/delete-project-modal.tsx
index eca032b733..998f2ebacd 100644
--- a/components/app/modals/delete-project-modal.tsx
+++ b/components/app/modals/delete-project-modal.tsx
@@ -25,6 +25,27 @@ function DeleteProjectModal({
const { project: { logo } = {} } = useProject();
const [deleting, setDeleting] = useState(false);
+ async function deleteProject() {
+ setDeleting(true);
+ await fetch(`/api/projects/${slug}`, {
+ method: "DELETE",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }).catch((err) => {
+ setDeleting(false);
+ throw new Error(err);
+ });
+ router.push("/");
+ mutate("/api/projects");
+ // delay to allow for the route change to complete
+ await new Promise((resolve) =>
+ setTimeout(() => {
+ resolve(null);
+ }, 200),
+ );
+ }
+
return (
<Modal
showModal={showDeleteProjectModal}
@@ -42,30 +63,17 @@ function DeleteProjectModal({
<h3 className="text-lg font-medium">Delete Project</h3>
<p className="text-center text-sm text-gray-500">
Warning: This will permanently delete your project, custom domain,
- and all associated links + their stats.
+ and all associated links and their respective stats.
</p>
</div>
<form
onSubmit={async (e) => {
e.preventDefault();
- setDeleting(true);
- fetch(`/api/projects/${slug}`, {
- method: "DELETE",
- headers: {
- "Content-Type": "application/json",
- },
- }).then(async (res) => {
- setDeleting(false);
- if (res.status === 200) {
- router.push("/");
- mutate("/api/projects");
- setShowDeleteProjectModal(false);
- toast.success("Project deleted successfully.");
- } else {
- const error = await res.json();
- toast.error(JSON.stringify(error));
- }
+ toast.promise(deleteProject(), {
+ loading: "Deleting project...",
+ success: "Project deleted successfully!",
+ error: (err) => err,
});
}}
className="flex flex-col space-y-6 bg-gray-50 px-4 py-8 text-left sm:px-16"
diff --git a/lib/api/domains.ts b/lib/api/domains.ts
index 16209338e9..f2dfd26379 100644
--- a/lib/api/domains.ts
+++ b/lib/api/domains.ts
@@ -115,27 +115,6 @@ export async function setRootDomain(
}
}
-export async function deleteRootDomainAndLinks(domain: string) {
- const links = await prisma.link.findMany({
- where: {
- domain,
- },
- select: {
- key: true,
- },
- });
- const pipeline = redis.pipeline();
- links.forEach(({ key }) => {
- pipeline.del(`${domain}:${key}`);
- });
- pipeline.del(`root:${domain}`);
- try {
- return await pipeline.exec();
- } catch (e) {
- return null;
- }
-}
-
/* Change the domain for every link and its respective stats when the project domain is changed */
export async function changeDomainForLinks(domain: string, newDomain: string) {
const links = await prisma.link.findMany({
@@ -186,7 +165,7 @@ export async function changeDomainForImages(domain: string, newDomain: string) {
}
}
-/* Delete all links & stats associated with a domain when it's deleted */
+/* Delete all links & images associated with a domain when it's deleted */
export async function deleteDomainLinks(domain: string) {
const links = await prisma.link.findMany({
where: {
@@ -197,9 +176,10 @@ export async function deleteDomainLinks(domain: string) {
links.forEach(({ key }) => {
pipeline.del(`${domain}:${key}`);
});
- try {
- return await pipeline.exec();
- } catch (e) {
- return null;
- }
+ pipeline.del(`root:${domain}`);
+ return await Promise.allSettled([
+ pipeline.exec(), // delete all links from redis
+ // remove all images from cloudinary
+ cloudinary.v2.api.delete_resources_by_prefix(domain),
+ ]);
}
diff --git a/lib/swr/use-domains.ts b/lib/swr/use-domains.ts
index b6b5575a8b..7845fe4f38 100644
--- a/lib/swr/use-domains.ts
+++ b/lib/swr/use-domains.ts
@@ -11,7 +11,7 @@ export default function useDomains(domain?: string) {
slug: string;
};
- if (!slug) {
+ if (!slug && router.isReady) {
slug = "dub";
}
diff --git a/lib/utils.ts b/lib/utils.ts
index c8bd68e499..09aabfbf0f 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -291,6 +291,23 @@ export const getUrlWithoutUTMParams = (url: string) => {
}
};
+export async function generateMD5Hash(message) {
+ // Convert the message string to a Uint8Array
+ const encoder = new TextEncoder();
+ const data = encoder.encode(message);
+
+ // Generate the hash using the SubtleCrypto interface
+ const hashBuffer = await crypto.subtle.digest("MD5", data);
+
+ // Convert the hash to a hexadecimal string
+ const hashArray = Array.from(new Uint8Array(hashBuffer));
+ const hashHex = hashArray
+ .map((byte) => byte.toString(16).padStart(2, "0"))
+ .join("");
+
+ return hashHex;
+}
+
const logTypeToEnv = {
cron: process.env.DUB_SLACK_HOOK_CRON,
links: process.env.DUB_SLACK_HOOK_LINKS,
diff --git a/pages/api/projects/[slug]/domains/[domain]/index.ts b/pages/api/projects/[slug]/domains/[domain]/index.ts
index ac24d25ce5..fa4b35ada6 100644
--- a/pages/api/projects/[slug]/domains/[domain]/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/index.ts
@@ -5,7 +5,7 @@ import prisma from "@/lib/prisma";
import {
changeDomainForImages,
changeDomainForLinks,
- deleteRootDomainAndLinks,
+ deleteDomainLinks,
setRootDomain,
} from "@/lib/api/domains";
import { ProjectProps } from "@/lib/types";
@@ -29,10 +29,16 @@ export default withProjectAuth(
if (req.method === "PUT") {
const { slug: newDomain, target, type, primary } = req.body;
- if (project && project.slug !== slug) {
- return res.status(400).json({ error: "Invalid project slug" });
- }
-
+ /*
+ If the domain is being changed (and the new domain is valid), we need to:
+ 1. Remove the old domain from Vercel
+ 2. Add the new domain to Vercel
+ 3. If there's a landing page set, update the root domain in Redis
+ 4. Update all links in the project to point to the new domain
+ 5. Update all images in the project to point to the new domain
+ 6. If the domain is being set as the primary domain, set all other domains to not be the primary domain
+ 7. Update the domain in the database along with its primary status
+ */
if (newDomain !== domain) {
const validDomain = await validateDomain(newDomain);
@@ -44,27 +50,52 @@ export default withProjectAuth(
const response = await Promise.allSettled([
removeDomain(domain),
addDomain(newDomain),
- setRootDomain(domain, target, type === "rewrite", newDomain),
+ target &&
+ setRootDomain(domain, target, type === "rewrite", newDomain),
changeDomainForLinks(domain, newDomain),
changeDomainForImages(domain, newDomain),
+ primary &&
+ prisma.domain.updateMany({
+ where: {
+ projectId: project.id,
+ primary: true,
+ },
+ data: {
+ primary: false,
+ },
+ }),
+ prisma.domain.update({
+ where: {
+ slug: domain,
+ },
+ data: {
+ slug: newDomain,
+ target,
+ type,
+ primary,
+ },
+ }),
]);
- const updatedDomain = await prisma.domain.update({
- where: {
- slug: domain,
- },
- data: {
- slug: newDomain,
- target,
- type,
- primary,
- },
- });
- return res.status(200).json({
- ...response,
- updatedDomain,
- });
+ return res.status(200).json(response);
} else {
+ /*
+ If the domain is not being changed, we only need to:
+ 1. If there's a landing page set, update the root domain in Redis
+ 2. If the domain is being set as the primary domain, set all other domains to not be the primary domain
+ 3. Then, update the domain in the database along with its primary status
+ */
const response = await Promise.allSettled([
+ target && setRootDomain(domain, target, type === "rewrite"),
+ primary &&
+ prisma.domain.updateMany({
+ where: {
+ projectId: project.id,
+ primary: true,
+ },
+ data: {
+ primary: false,
+ },
+ }),
prisma.domain.update({
where: {
slug: domain,
@@ -75,14 +106,13 @@ export default withProjectAuth(
primary,
},
}),
- setRootDomain(domain, target, type === "rewrite"),
]);
return res.status(200).json(response);
}
} else if (req.method === "DELETE") {
const response = await Promise.allSettled([
removeDomain(domain),
- deleteRootDomainAndLinks(domain),
+ deleteDomainLinks(domain),
]);
const deletedDomain = await prisma.domain.delete({
where: {
diff --git a/pages/api/projects/[slug]/domains/index.ts b/pages/api/projects/[slug]/domains/index.ts
index 0190a5bb62..fe1613b24d 100644
--- a/pages/api/projects/[slug]/domains/index.ts
+++ b/pages/api/projects/[slug]/domains/index.ts
@@ -33,17 +33,14 @@ export default withProjectAuth(
domainError: validDomain,
});
}
-
+ /*
+ If the domain is being added, we need to:
+ 1. Add the domain to Vercel
+ 2. If there's a landing page set, update the root domain in Redis
+ 3. If the domain is being set as the primary domain, set all other domains to not be the primary domain
+ 4. Add the domain to the database along with its primary status
+ */
const response = await Promise.allSettled([
- await prisma.domain.create({
- data: {
- slug: domain,
- target,
- type,
- projectId: project.id,
- primary,
- },
- }),
addDomain(domain),
target &&
redis.set(`root:${domain}`, {
@@ -51,17 +48,24 @@ export default withProjectAuth(
rewrite: type === "rewrite",
}),
primary &&
- (await prisma.domain.updateMany({
+ prisma.domain.updateMany({
where: {
projectId: project.id,
- slug: {
- not: domain,
- },
+ primary: true,
},
data: {
primary: false,
},
- })),
+ }),
+ prisma.domain.create({
+ data: {
+ slug: domain,
+ target,
+ type,
+ projectId: project.id,
+ primary,
+ },
+ }),
]);
return res.status(200).json(response);
} else {
@@ -73,7 +77,6 @@ export default withProjectAuth(
},
{
excludeGet: true,
- needNotExceededUsage: true,
needProSubscription: true,
},
);
diff --git a/pages/api/projects/[slug]/index.ts b/pages/api/projects/[slug]/index.ts
index 3068445683..9070402659 100644
--- a/pages/api/projects/[slug]/index.ts
+++ b/pages/api/projects/[slug]/index.ts
@@ -1,9 +1,8 @@
import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
-import { removeDomain } from "@/lib/api/domains";
+import { removeDomain, deleteDomainLinks } from "@/lib/api/domains";
import prisma from "@/lib/prisma";
import { ProjectProps } from "@/lib/types";
-import { deleteProjectLinks } from "@/lib/api/links";
import cloudinary from "cloudinary";
export default withProjectAuth(
@@ -57,10 +56,7 @@ export default withProjectAuth(
},
}),
...domains.map((domain) => removeDomain(domain)),
- ...domains.map((domain) => deleteProjectLinks(domain)),
- ...domains.map((domain) =>
- cloudinary.v2.api.delete_resources_by_prefix(domain),
- ),
+ ...domains.map((domain) => deleteDomainLinks(domain)),
]);
return res.status(200).json(response);
diff --git a/pages/app/[slug]/domains.tsx b/pages/app/[slug]/domains.tsx
index 3671bef33b..a03c166059 100644
--- a/pages/app/[slug]/domains.tsx
+++ b/pages/app/[slug]/domains.tsx
@@ -1,21 +1,12 @@
import ErrorPage from "next/error";
-import LinksContainer from "@/components/app/links/links-container";
import { useAddEditDomainModal } from "@/components/app/modals/add-edit-domain-modal";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
import AppLayout from "components/layout/app";
import useProject from "@/lib/swr/use-project";
-import { DomainProps } from "@/lib/types";
-import useSWR from "swr";
-import { useRouter } from "next/router";
-import { fetcher } from "@/lib/utils";
import DomainCard from "@/components/app/domains/domain-card";
+import useDomains from "@/lib/swr/use-domains";
export default function ProjectDomains() {
- const router = useRouter();
- const { slug } = router.query as {
- slug: string;
- };
-
const { project, error } = useProject();
const { AddEditDomainModal, AddEditDomainButton } = useAddEditDomainModal({});
@@ -24,14 +15,7 @@ export default function ProjectDomains() {
return <ErrorPage statusCode={404} />;
}
- const { data: domains } = useSWR<DomainProps[]>(
- `/api/projects/${slug}/domains`,
- fetcher,
- {
- // disable this because it keeps refreshing the state of the modal when its open
- revalidateOnFocus: false,
- },
- );
+ const { domains } = useDomains();
return (
<AppLayout>