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.

extract setting primary domain into it's own endpoint

Steven Tey46eb359f2a25
diff --git a/apps/web/app/api/domains/[domain]/archive/route.ts b/apps/web/app/api/domains/[domain]/archive/route.ts
index 2b44773cbb..d75e14db60 100644
--- a/apps/web/app/api/domains/[domain]/archive/route.ts
+++ b/apps/web/app/api/domains/[domain]/archive/route.ts
@@ -3,15 +3,25 @@ import { withAuth } from "@/lib/auth";
import { NextResponse } from "next/server";
// POST /api/domains/[domain]/archive – archive a domain
-export const POST = withAuth(async ({ headers, domain }) => {
- console.log("archiving domain", domain);
- const response = await archiveDomain({ domain, archived: true });
- return NextResponse.json(response, { headers });
-});
+export const POST = withAuth(
+ async ({ headers, domain }) => {
+ const response = await archiveDomain({ domain, archived: true });
+ return NextResponse.json(response, { headers });
+ },
+ {
+ domainChecks: true,
+ requiredRole: ["owner"],
+ },
+);
// DELETE /api/domains/[domain]/archive – unarchive a domain
-export const DELETE = withAuth(async ({ headers, domain }) => {
- console.log("unarchiving domain", domain);
- const response = await archiveDomain({ domain, archived: false });
- return NextResponse.json(response, { headers });
-});
+export const DELETE = withAuth(
+ async ({ headers, domain }) => {
+ const response = await archiveDomain({ domain, archived: false });
+ return NextResponse.json(response, { headers });
+ },
+ {
+ domainChecks: true,
+ requiredRole: ["owner"],
+ },
+);
diff --git a/apps/web/app/api/domains/[domain]/primary/route.ts b/apps/web/app/api/domains/[domain]/primary/route.ts
new file mode 100644
index 0000000000..0b88c8db11
--- /dev/null
+++ b/apps/web/app/api/domains/[domain]/primary/route.ts
@@ -0,0 +1,35 @@
+import { withAuth } from "@/lib/auth";
+import { NextResponse } from "next/server";
+import prisma from "@/lib/prisma";
+
+// POST /api/domains/[domain]/primary – set a domain as primary
+export const POST = withAuth(
+ async ({ headers, workspace, domain }) => {
+ const response = await Promise.all([
+ prisma.domain.update({
+ where: {
+ slug: domain,
+ },
+ data: {
+ primary: true,
+ },
+ }),
+ // Set all other domains as not primary
+ prisma.domain.updateMany({
+ where: {
+ projectId: workspace.id,
+ primary: true,
+ },
+ data: {
+ primary: false,
+ },
+ }),
+ ]);
+ console.log({ response });
+ return NextResponse.json(response, { headers });
+ },
+ {
+ domainChecks: true,
+ requiredRole: ["owner"],
+ },
+);
diff --git a/apps/web/app/api/domains/[domain]/route.ts b/apps/web/app/api/domains/[domain]/route.ts
index cbb138b173..232512c2b1 100644
--- a/apps/web/app/api/domains/[domain]/route.ts
+++ b/apps/web/app/api/domains/[domain]/route.ts
@@ -11,126 +11,108 @@ import { DUB_WORKSPACE_ID, isDubDomain } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/domains/[domain] – get a workspace's domain
-export const GET = withAuth(async ({ domain, workspace }) => {
- if (isDubDomain(domain) && workspace.id !== DUB_WORKSPACE_ID) {
- return new Response("Domain does not belong to workspace.", {
- status: 403,
+export const GET = withAuth(
+ async ({ domain }) => {
+ const data = await prisma.domain.findUnique({
+ where: {
+ slug: domain,
+ },
+ select: {
+ slug: true,
+ verified: true,
+ primary: true,
+ target: true,
+ type: true,
+ placeholder: true,
+ clicks: true,
+ },
});
- }
-
- const data = await prisma.domain.findUnique({
- where: {
- slug: domain,
- },
- select: {
- slug: true,
- verified: true,
- primary: true,
- target: true,
- type: true,
- placeholder: true,
- clicks: true,
- },
- });
- if (!data) {
- return new Response("Domain not found", { status: 404 });
- }
- return NextResponse.json({
- ...data,
- url: data.target,
- });
-});
+ if (!data) {
+ return new Response("Domain not found", { status: 404 });
+ }
+ return NextResponse.json({
+ ...data,
+ url: data.target,
+ });
+ },
+ {
+ domainChecks: true,
+ },
+);
// PUT /api/domains/[domain] – edit a workspace's domain
-export const PUT = withAuth(async ({ req, workspace, domain }) => {
- const {
- slug: newDomain,
- target,
- type,
- placeholder,
- primary,
- archived,
- expiredUrl,
- } = await req.json();
+export const PUT = withAuth(
+ async ({ req, workspace, domain }) => {
+ const {
+ slug: newDomain,
+ target,
+ type,
+ placeholder,
+ expiredUrl,
+ } = await req.json();
- if (isDubDomain(domain) && workspace.id !== DUB_WORKSPACE_ID) {
- return new Response("Domain does not belong to workspace.", {
- status: 403,
- });
- }
-
- if (newDomain !== domain) {
- const validDomain = await validateDomain(newDomain);
- if (validDomain !== true) {
- return new Response(validDomain, { status: 422 });
- }
- const vercelResponse = await addDomainToVercel(newDomain);
- if (vercelResponse.error) {
- return new Response(vercelResponse.error.message, { status: 422 });
+ if (newDomain !== domain) {
+ const validDomain = await validateDomain(newDomain);
+ if (validDomain !== true) {
+ return new Response(validDomain, { status: 422 });
+ }
+ const vercelResponse = await addDomainToVercel(newDomain);
+ if (vercelResponse.error) {
+ return new Response(vercelResponse.error.message, { status: 422 });
+ }
}
- }
- const response = await Promise.all([
- // Update the domain in the database along with its primary status
- prisma.domain.update({
- where: {
- slug: domain,
- },
- data: {
- ...(newDomain !== domain && {
- slug: newDomain,
- }),
- // only set target and expiredUrl if the workspace is not free
- ...(workspace.plan !== "free" && {
- target: target || null,
- expiredUrl: expiredUrl || null,
- }),
- type,
- placeholder,
- primary,
- archived,
- },
- }),
- // if the domain is being set as the primary domain, set the current primary domain to false
- primary &&
- prisma.domain.updateMany({
+ const response = await Promise.all([
+ prisma.domain.update({
where: {
- projectId: workspace.id,
- primary: true,
+ slug: domain,
},
data: {
- primary: false,
+ ...(newDomain !== domain && {
+ slug: newDomain,
+ }),
+ type,
+ placeholder,
+ // only set target and expiredUrl if the workspace is not free
+ ...(workspace.plan !== "free" && {
+ target: target || null,
+ expiredUrl: expiredUrl || null,
+ }),
},
}),
- // remove old domain from Vercel
- newDomain !== domain && removeDomainFromVercel(domain),
- ]);
-
- await setRootDomain({
- id: response[0].id,
- domain,
- ...(workspace.plan !== "free" && {
- url: target,
- }),
- rewrite: type === "rewrite",
- ...(newDomain !== domain && {
- newDomain,
- }),
- projectId: workspace.id,
- });
+ // remove old domain from Vercel
+ newDomain !== domain && removeDomainFromVercel(domain),
+ ]);
- return NextResponse.json(response);
-});
-
-// DELETE /api/domains/[domain] - delete a workspace's domain
-export const DELETE = withAuth(async ({ domain, workspace }) => {
- if (isDubDomain(domain) && workspace.id !== DUB_WORKSPACE_ID) {
- return new Response("Domain does not belong to workspace.", {
- status: 403,
+ await setRootDomain({
+ id: response[0].id,
+ domain,
+ ...(workspace.plan !== "free" && {
+ url: target,
+ }),
+ rewrite: type === "rewrite",
+ ...(newDomain !== domain && {
+ newDomain,
+ }),
+ projectId: workspace.id,
});
- }
- const response = await deleteDomainAndLinks(domain);
+ return NextResponse.json(response);
+ },
+ {
+ domainChecks: true,
+ requiredRole: ["owner"],
+ },
+);
- return NextResponse.json(response);
-});
+// DELETE /api/domains/[domain] - delete a workspace's domain
+export const DELETE = withAuth(
+ async ({ domain }) => {
+ const response = await deleteDomainAndLinks(domain);
+ return NextResponse.json(response);
+ },
+ {
+ domainChecks: true,
+ requiredRole: ["owner"],
+ },
+);
diff --git a/apps/web/app/api/domains/route.ts b/apps/web/app/api/domains/route.ts
index 96fc20ef61..1a724a95b4 100644
--- a/apps/web/app/api/domains/route.ts
+++ b/apps/web/app/api/domains/route.ts
@@ -30,7 +30,7 @@ export const GET = withAuth(async ({ workspace }) => {
// POST /api/domains - add a domain
export const POST = withAuth(async ({ req, workspace }) => {
- const { slug: domain, primary, archived, target, type } = await req.json();
+ const { slug: domain, target, type } = await req.json();
if (workspace.domains.length >= workspace.domainsLimit) {
return new Response(
@@ -57,8 +57,7 @@ export const POST = withAuth(async ({ req, workspace }) => {
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
+ 3. If the workspace has no domains (meaning this is the first domain added), set it as primary
*/
const response = await Promise.all([
prisma.domain.create({
@@ -67,20 +66,9 @@ export const POST = withAuth(async ({ req, workspace }) => {
target,
type,
projectId: workspace.id,
- primary: primary || workspace.domains.length === 0,
- archived,
+ primary: workspace.domains.length === 0,
},
}),
- primary &&
- prisma.domain.updateMany({
- where: {
- projectId: workspace.id,
- primary: true,
- },
- data: {
- primary: false,
- },
- }),
]);
await setRootDomain({
diff --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.ts
index ca3ff0b535..b4362624b9 100644
--- a/apps/web/lib/auth/index.ts
+++ b/apps/web/lib/auth/index.ts
@@ -80,6 +80,7 @@ export const withAuth = (
allowAnonymous, // special case for /api/links (POST /api/links) – allow no session
allowSelf, // special case for removing yourself from a workspace
skipLinkChecks, // special case for /api/links/exists – skip link checks
+ domainChecks,
}: {
requiredPlan?: Array<PlanProps>;
requiredRole?: Array<"owner" | "member">;
@@ -88,6 +89,7 @@ export const withAuth = (
allowAnonymous?: boolean;
allowSelf?: boolean;
skipLinkChecks?: boolean;
+ domainChecks?: boolean;
} = {},
) => {
return async (
@@ -293,16 +295,23 @@ export const withAuth = (
});
}
- // prevent unauthorized access to domains that don't belong to the workspace
- if (
- domain &&
- !isDubDomain(domain) &&
- !workspace.domains.find((d) => d.slug === domain)
- ) {
- throw new DubApiError({
- code: "forbidden",
- message: "Domain does not belong to workspace.",
- });
+ // if domain is defined, check if:
+ // it's a dub domain and domainChecks is required, check if the user is part of the dub workspace
+ // it's a custom domain, check if the domain belongs to the workspace
+ if (domain) {
+ if (isDubDomain(domain)) {
+ if (domainChecks && workspace.id !== DUB_WORKSPACE_ID) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Domain does not belong to workspace.",
+ });
+ }
+ } else if (!workspace.domains.find((d) => d.slug === domain)) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Domain does not belong to workspace.",
+ });
+ }
}
// workspace exists but user is not part of it
diff --git a/apps/web/ui/domains/domain-card-placeholder.tsx b/apps/web/ui/domains/domain-card-placeholder.tsx
index 80b820591d..8b330c3eb3 100644
--- a/apps/web/ui/domains/domain-card-placeholder.tsx
+++ b/apps/web/ui/domains/domain-card-placeholder.tsx
@@ -8,7 +8,7 @@ export default function DomainCardPlaceholder() {
</div>
<div className="flex space-x-3">
<div className="h-9 w-24 animate-pulse rounded-md bg-gray-200" />
- <div className="h-9 w-24 animate-pulse rounded-md bg-gray-200" />
+ <div className="h-9 w-9 animate-pulse rounded-md bg-gray-200" />
</div>
</div>
<div className="flex h-10 flex-col space-y-2 sm:flex-row sm:items-center sm:space-x-5 sm:space-y-0">
diff --git a/apps/web/ui/domains/domain-card.tsx b/apps/web/ui/domains/domain-card.tsx
index 9af9deb332..096111d81c 100644
--- a/apps/web/ui/domains/domain-card.tsx
+++ b/apps/web/ui/domains/domain-card.tsx
@@ -18,7 +18,7 @@ import {
useIntersectionObserver,
} from "@dub/ui";
import { capitalize, fetcher, nFormatter, truncate } from "@dub/utils";
-import { Archive, Edit3, QrCode } from "lucide-react";
+import { Archive, Edit3, FileCog, QrCode } from "lucide-react";
import Link from "next/link";
import punycode from "punycode/";
import useSWR, { mutate } from "swr";
@@ -28,9 +28,10 @@ import DomainConfiguration from "./domain-configuration";
import { useRef, useState } from "react";
import { useDeleteDomainModal } from "../modals/delete-domain-modal";
import { useArchiveDomainModal } from "../modals/archive-domain-modal";
+import { toast } from "sonner";
export default function DomainCard({ props }: { props: DomainProps }) {
- const { id, slug } = useWorkspace();
+ const { id: workspaceId, slug } = useWorkspace();
const { slug: domain, primary, target, type, archived } = props || {};
@@ -49,10 +50,10 @@ export default function DomainCard({ props }: { props: DomainProps }) {
status: DomainVerificationStatusProps;
response: any;
}>(
- id &&
+ workspaceId &&
isVisible &&
!showLinkQRModal && // Don't fetch if QR modal is open – it'll cause it to re-render
- `/api/domains/${domain}/verify?workspaceId=${id}`,
+ `/api/domains/${domain}/verify?workspaceId=${workspaceId}`,
fetcher,
{
revalidateOnFocus: true,
@@ -65,7 +66,8 @@ export default function DomainCard({ props }: { props: DomainProps }) {
);
const { data: clicks } = useSWR<number>(
- id && `/api/analytics/clicks?workspaceId=${id}&domain=${domain}&key=_root`,
+ workspaceId &&
+ `/api/analytics/clicks?workspaceId=${workspaceId}&domain=${domain}&key=_root`,
fetcher,
{
fallbackData: props.clicks,
@@ -89,6 +91,21 @@ export default function DomainCard({ props }: { props: DomainProps }) {
props,
});
+ const setPrimary = async () => {
+ const response = await fetch(
+ `/api/domains/${domain}/primary?workspaceId=${workspaceId}`,
+ {
+ method: "POST",
+ },
+ );
+ if (response.ok) {
+ await mutate(`/api/domains?workspaceId=${workspaceId}`);
+ } else {
+ const { error } = await response.json();
+ throw new Error(error.message);
+ }
+ };
+
return (
<>
<AddEditDomainModal />
@@ -140,12 +157,14 @@ export default function DomainCard({ props }: { props: DomainProps }) {
variant="secondary"
loading={isValidating}
onClick={() => {
- mutate(`/api/domains/${domain}/verify?workspaceId=${id}`);
+ mutate(
+ `/api/domains/${domain}/verify?workspaceId=${workspaceId}`,
+ );
}}
/>
<Popover
content={
- <div className="grid w-full gap-px p-2 sm:w-48">
+ <div className="grid w-full gap-px p-2 sm:w-44">
<Button
text="Edit"
variant="outline"
@@ -154,8 +173,7 @@ export default function DomainCard({ props }: { props: DomainProps }) {
setShowAddEditDomainModal(true);
}}
icon={<Edit3 className="h-4 w-4" />}
- shortcut="E"
- className="h-9 px-2 font-medium"
+ className="h-9 justify-start px-2 font-medium"
/>
<Button
text="QR Code"
@@ -165,8 +183,29 @@ export default function DomainCard({ props }: { props: DomainProps }) {
setShowLinkQRModal(true);
}}
icon={<QrCode className="h-4 w-4" />}
- shortcut="Q"
- className="h-9 px-2 font-medium"
+ className="h-9 justify-start px-2 font-medium"
+ />
+ <Button
+ text="Set as Primary"
+ variant="outline"
+ onClick={() => {
+ if (
+ window.confirm(
+ "Setting this domain as primary will make it the default domain in the link creation modal, as well as via the API. Are you sure you want to proceed?",
+ )
+ ) {
+ setOpenPopover(false);
+ toast.promise(setPrimary(), {
+ loading: `Setting ${domain} as the primary domain...`,
+ success: `Successfully set ${domain} as the primary domain!`,
+ error: (error) => {
+ return error.message;
+ },
+ });
+ }
+ }}
+ icon={<FileCog className="h-4 w-4" />}
+ className="h-9 justify-start px-2 font-medium"
/>
<Button
text={archived ? "Unarchive" : "Archive"}
@@ -176,8 +215,7 @@ export default function DomainCard({ props }: { props: DomainProps }) {
setShowArchiveDomainModal(true);
}}
icon={<Archive className="h-4 w-4" />}
- shortcut="A"
- className="h-9 px-2 font-medium"
+ className="h-9 justify-start px-2 font-medium"
/>
<Button
text="Delete"
@@ -187,8 +225,7 @@ export default function DomainCard({ props }: { props: DomainProps }) {
setShowDeleteDomainModal(true);
}}
icon={<Delete className="h-4 w-4" />}
- shortcut="X"
- className="h-9 px-2 font-medium"
+ className="h-9 justify-start px-2 font-medium"
/>
</div>
}
diff --git a/apps/web/ui/modals/add-edit-domain-modal/index.tsx b/apps/web/ui/modals/add-edit-domain-modal/index.tsx
index 7b5ac2d81b..40f32d832e 100644
--- a/apps/web/ui/modals/add-edit-domain-modal/index.tsx
+++ b/apps/web/ui/modals/add-edit-domain-modal/index.tsx
@@ -63,21 +63,18 @@ function AddEditDomainModal({
const [lockDomain, setLockDomain] = useState(true);
const [saving, setSaving] = useState(false);
const [domainError, setDomainError] = useState<string | null>(null);
- const [deleting, setDeleting] = useState(false);
const saveDisabled = useMemo(() => {
/*
Disable save if:
- modal is not open
- saving is in progress
- - deleting is in progress
- domain is invalid
- for an existing domain, there's no changes
*/
if (
!showAddEditDomainModal ||
saving ||
- deleting ||
domainError ||
(props &&
Object.entries(props).every(([key, value]) => data[key] === value))
@@ -273,45 +270,6 @@ function AddEditDomainModal({
{...FADE_IN_ANIMATION_SETTINGS}
className="flex flex-col space-y-6"
>
- <div className="flex items-center justify-between bg-gray-50">
- <div className="flex items-center space-x-2">
- <h2 className="text-sm font-medium text-gray-900">
- Primary Domain
- </h2>
- <InfoTooltip content="The default domain used in the link creation modal. You can only have one primary domain at a time." />
- </div>
- <Switch
- fn={() => setData((prev) => ({ ...prev, primary: !primary }))}
- checked={primary}
- disabled={props?.primary}
- />
- </div>
-
- <div>
- <label
- htmlFor="placeholder"
- className="flex items-center space-x-2"
- >
- <h2 className="text-sm font-medium text-gray-900">
- Input Placeholder URL
- </h2>
- <InfoTooltip content="Provide context to your teammates in the link creation modal by showing them an example of a link to be shortened." />
- </label>
- <div className="relative mt-2 rounded-md shadow-sm">
- <input
- type="url"
- name="placeholder"
- id="placeholder"
- className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"
- placeholder="https://dub.co/help/article/what-is-dub"
- value={placeholder}
- onChange={(e) =>
- setData({ ...data, placeholder: e.target.value })
- }
- />
- </div>
- </div>
-
<div>
<label
htmlFor="expiredUrl"
@@ -361,6 +319,31 @@ function AddEditDomainModal({
)}
</div>
</div>
+
+ <div>
+ <label
+ htmlFor="placeholder"
+ className="flex items-center space-x-2"
+ >
+ <h2 className="text-sm font-medium text-gray-900">
+ Input Placeholder URL
+ </h2>
+ <InfoTooltip content="Provide context to your teammates in the link creation modal by showing them an example of a link to be shortened." />
+ </label>
+ <div className="relative mt-2 rounded-md shadow-sm">
+ <input
+ type="url"
+ name="placeholder"
+ id="placeholder"
+ className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"
+ placeholder="https://dub.co/help/article/what-is-dub"
+ value={placeholder}
+ onChange={(e) =>
+ setData({ ...data, placeholder: e.target.value })
+ }
+ />
+ </div>
+ </div>
</motion.div>
)}
diff --git a/apps/web/ui/modals/archive-domain-modal.tsx b/apps/web/ui/modals/archive-domain-modal.tsx
index 89e68477e5..8bd90bbb72 100644
--- a/apps/web/ui/modals/archive-domain-modal.tsx
+++ b/apps/web/ui/modals/archive-domain-modal.tsx
@@ -32,14 +32,6 @@ const sendArchiveRequest = ({
});
};
-const revalidateDomains = () => {
- return mutate(
- (key) => typeof key === "string" && key.startsWith("/api/domains"),
- undefined,
- { revalidate: true },
- );
-};
-
function ArchiveDomainModal({
showArchiveDomainModal,
setShowArchiveDomainModal,
@@ -73,7 +65,7 @@ function ArchiveDomainModal({
return;
}
- revalidateDomains();
+ mutate(`/api/domains?workspaceId=${workspaceId}`);
setShowArchiveDomainModal(false);
toastWithUndo({
id: "domain-archive-undo-toast",
@@ -94,7 +86,7 @@ function ArchiveDomainModal({
loading: "Undo in progress...",
error: "Failed to roll back changes. An error occurred.",
success: () => {
- revalidateDomains();
+ mutate(`/api/domains?workspaceId=${workspaceId}`);
return "Undo successful! Changes reverted.";
},
},