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.

auto-create link when creating a domain via dashboard

Steven Tey8f7b9419f89e
diff --git a/apps/web/app/api/domains/route.ts b/apps/web/app/api/domains/route.ts
index aacd65026a..cab868ff2b 100644
--- a/apps/web/app/api/domains/route.ts
+++ b/apps/web/app/api/domains/route.ts
@@ -1,5 +1,4 @@
import { addDomainToVercel, validateDomain } from "@/lib/api/domains";
-import { createDomain } from "@/lib/api/domains/create-domain";
import { DubApiError, exceededLimitError } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
@@ -23,11 +22,9 @@ export const GET = withWorkspace(async ({ workspace }) => {
});
// POST /api/domains - add a domain
-export const POST = withWorkspace(async ({ req, workspace, session }) => {
+export const POST = withWorkspace(async ({ req, workspace }) => {
const body = await parseRequestBody(req);
- const payload = createDomainBodySchema.parse(body);
-
- const { slug } = payload;
+ const { slug, placeholder, expiredUrl } = createDomainBodySchema.parse(body);
if (workspace.domains.length >= workspace.domainsLimit) {
return new Response(
@@ -58,16 +55,16 @@ export const POST = withWorkspace(async ({ req, workspace, session }) => {
return new Response(vercelResponse.error.message, { status: 422 });
}
- /*
- 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 workspace has no domains (meaning this is the first domain added), set it as primary
- */
- const domainRecord = await createDomain({
- ...payload,
- workspace,
- userId: session.user.id,
+ const domainRecord = await prisma.domain.create({
+ data: {
+ slug: slug,
+ projectId: workspace.id,
+ primary: workspace.domains.length === 0,
+ ...(placeholder && { placeholder }),
+ ...(workspace.plan !== "free" && {
+ expiredUrl,
+ }),
+ },
});
return NextResponse.json(DomainSchema.parse(domainRecord), {
diff --git a/apps/web/app/api/workspaces/route.ts b/apps/web/app/api/workspaces/route.ts
index 7212ba7ba4..4d6dfc3e32 100644
--- a/apps/web/app/api/workspaces/route.ts
+++ b/apps/web/app/api/workspaces/route.ts
@@ -1,11 +1,7 @@
-import { addDomainToVercel, validateDomain } from "@/lib/api/domains";
-import { createDomain } from "@/lib/api/domains/create-domain";
import { DubApiError } from "@/lib/api/errors";
import { withSession } from "@/lib/auth";
import { checkIfUserExists } from "@/lib/planetscale";
import { prisma } from "@/lib/prisma";
-import { WorkspaceProps } from "@/lib/types";
-import { createDomainBodySchema } from "@/lib/zod/schemas/domains";
import {
WorkspaceSchema,
createWorkspaceSchema,
@@ -16,7 +12,7 @@ import { NextResponse } from "next/server";
// GET /api/workspaces - get all projects for the current user
export const GET = withSession(async ({ session }) => {
- const projects = await prisma.project.findMany({
+ const workspaces = await prisma.project.findMany({
where: {
users: {
some: {
@@ -42,14 +38,14 @@ export const GET = withSession(async ({ session }) => {
},
});
return NextResponse.json(
- projects.map((project) =>
+ workspaces.map((project) =>
WorkspaceSchema.parse({ ...project, id: `ws_${project.id}` }),
),
);
});
export const POST = withSession(async ({ req, session }) => {
- const { name, slug, domain } = await createWorkspaceSchema.parseAsync(
+ const { name, slug } = await createWorkspaceSchema.parseAsync(
await req.json(),
);
@@ -81,17 +77,14 @@ export const POST = withSession(async ({ req, session }) => {
});
}
- const [slugExist, validDomain] = await Promise.all([
- prisma.project.findUnique({
- where: {
- slug,
- },
- select: {
- slug: true,
- },
- }),
- domain ? validateDomain(domain) : { error: null },
- ]);
+ const slugExist = await prisma.project.findUnique({
+ where: {
+ slug,
+ },
+ select: {
+ slug: true,
+ },
+ });
if (slugExist) {
throw new DubApiError({
@@ -100,14 +93,7 @@ export const POST = withSession(async ({ req, session }) => {
});
}
- if (validDomain.error && validDomain.code) {
- throw new DubApiError({
- code: validDomain.code,
- message: validDomain.error,
- });
- }
-
- const projectResponse = await prisma.project.create({
+ const workspaceResponse = await prisma.project.create({
data: {
name,
slug,
@@ -124,16 +110,18 @@ export const POST = withSession(async ({ req, session }) => {
},
},
include: {
- domains: {
+ users: {
+ where: {
+ userId: session.user.id,
+ },
select: {
- id: true,
- slug: true,
- primary: true,
+ role: true,
},
},
- users: {
+ domains: {
select: {
- role: true,
+ slug: true,
+ primary: true,
},
},
},
@@ -147,38 +135,17 @@ export const POST = withSession(async ({ req, session }) => {
id: session.user.id,
},
data: {
- defaultWorkspace: projectResponse.slug,
+ defaultWorkspace: workspaceResponse.slug,
},
});
}
- if (domain) {
- const domainRepsonse = await addDomainToVercel(domain);
- if (domainRepsonse.error) {
- await prisma.domain.delete({
- where: {
- slug: domain,
- projectId: projectResponse.id,
- },
- });
- } else {
- await createDomain({
- ...createDomainBodySchema.parse({ slug: domain }),
- workspace: projectResponse as WorkspaceProps,
- userId: session.user.id,
- });
- }
- }
})(),
);
- const response = {
- ...projectResponse,
- id: `ws_${projectResponse.id}`,
- domains: projectResponse.domains.map(({ slug, primary }) => ({
- slug,
- primary,
- })),
- };
-
- return NextResponse.json(response);
+ return NextResponse.json(
+ WorkspaceSchema.parse({
+ ...workspaceResponse,
+ id: `ws_${workspaceResponse.id}`,
+ }),
+ );
});
diff --git a/apps/web/lib/api/links/process-link.ts b/apps/web/lib/api/links/process-link.ts
index 8ea1fc289a..f34e2c2485 100644
--- a/apps/web/lib/api/links/process-link.ts
+++ b/apps/web/lib/api/links/process-link.ts
@@ -67,7 +67,7 @@ export async function processLink<T extends Record<string, any>>({
const tagIds = combineTagIds(payload);
// url checks
- if (!url) {
+ if (!url && key !== "_root") {
return {
link: payload,
error: "Missing destination url.",
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index c0b152a55c..d59856c4e1 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -127,10 +127,10 @@ export interface DomainProps {
primary: boolean;
archived: boolean;
placeholder?: string;
- projectId: string;
expiredUrl?: string;
- noindex?: boolean;
+ projectId: string;
}
+
export interface RedisDomainProps {
id: string;
url?: string;
diff --git a/apps/web/lib/zod/schemas/utils.ts b/apps/web/lib/zod/schemas/utils.ts
index e64c6fe830..8f6f2d24e7 100644
--- a/apps/web/lib/zod/schemas/utils.ts
+++ b/apps/web/lib/zod/schemas/utils.ts
@@ -4,7 +4,7 @@ import { getUrlFromString, isValidUrl, parseDateTime } from "@dub/utils";
export const parseUrlSchema = z
.string()
.transform((v) => getUrlFromString(v))
- .refine((v) => isValidUrl(v), { message: "Invalid URL" });
+ .refine((v) => isValidUrl(v) || v === "", { message: "Invalid URL" });
export const parseDateSchema = z
.string()
diff --git a/apps/web/scripts/migrate-domains.ts b/apps/web/scripts/migrate-domains.ts
index c89598f9ce..b01ad26ce1 100644
--- a/apps/web/scripts/migrate-domains.ts
+++ b/apps/web/scripts/migrate-domains.ts
@@ -30,6 +30,7 @@ async function main() {
id: domain.id,
domain: domain.slug,
key: "_root",
+ url: domain.target || "",
description: domain.description,
publicStats: domain.publicStats,
projectId: domain.projectId,
@@ -39,13 +40,11 @@ async function main() {
clicks: domain.clicks,
...(domain.project?.plan === "free"
? {
- url: "",
expiredUrl: null,
rewrite: false,
noindex: false,
}
: {
- url: domain.target || "",
expiredUrl: domain.expiredUrl || null,
rewrite: domain.type === "rewrite",
noindex: domain.noindex,
@@ -60,6 +59,15 @@ async function main() {
});
console.log(`Added ${result.count} links`);
+
+ // const links = await prisma.link.deleteMany({
+ // where: {
+ // projectId: "cl7wsy2836920mjrb352g5wfx",
+ // key: "_root",
+ // },
+ // });
+
+ // console.log(links);
}
main();
diff --git a/apps/web/ui/domains/domain-card.tsx b/apps/web/ui/domains/domain-card.tsx
index 746a3b8fa7..ffea7900c7 100644
--- a/apps/web/ui/domains/domain-card.tsx
+++ b/apps/web/ui/domains/domain-card.tsx
@@ -49,11 +49,11 @@ import DomainConfiguration from "./domain-configuration";
export default function DomainCard({ props }: { props: DomainProps }) {
const { slug: domain, primary, archived } = props || {};
- const { id: workspaceId, slug, plan } = useWorkspace();
+ const { id: workspaceId, slug } = useWorkspace();
const { activeWorkspaceDomains } = useDomains();
- const { data: linkProps } = useSWR<LinkProps>(
- workspaceId && domain && plan != "free"
+ const { data: linkProps } = useSWRImmutable<LinkProps>(
+ workspaceId
? `/api/links/info?${new URLSearchParams({ workspaceId, domain, key: "_root" }).toString()}`
: null,
fetcher,
@@ -76,6 +76,16 @@ export default function DomainCard({ props }: { props: DomainProps }) {
setTimeout(() => setCopiedLinkId(false), 3000);
};
+ const { data: totalEvents } = useSWR<{ clicks: number }>(
+ workspaceId &&
+ linkProps &&
+ `/api/analytics?event=clicks&workspaceId=${workspaceId}&domain=${domain}&key=_root&interval=all_unfiltered`,
+ fetcher,
+ {
+ dedupingInterval: 15000,
+ },
+ );
+
const domainRef = useRef<any>();
const entry = useIntersectionObserver(domainRef, {});
const isVisible = !!entry?.isIntersecting;
@@ -90,16 +100,6 @@ export default function DomainCard({ props }: { props: DomainProps }) {
fetcher,
);
- const { data: totalEvents } = useSWR<{ clicks: number }>(
- workspaceId &&
- linkProps &&
- `/api/analytics?event=clicks&workspaceId=${workspaceId}&domain=${domain}&key=_root&interval=all_unfiltered`,
- fetcher,
- {
- dedupingInterval: 15000,
- },
- );
-
const [openPopover, setOpenPopover] = useState(false);
const { setShowAddEditDomainModal, AddEditDomainModal } =
@@ -191,65 +191,41 @@ export default function DomainCard({ props }: { props: DomainProps }) {
/>
<Popover
content={
- <div className="w-full sm:w-44">
+ <div className="w-full sm:w-48">
<div className="grid gap-px p-2">
- {linkProps?.url ? (
- <>
- <Button
- text="Edit Link"
- variant="outline"
- onClick={() => {
- setOpenPopover(false);
- setShowAddEditLinkModal(true);
- }}
- icon={<Edit3 className="h-4 w-4" />}
- className="h-9 justify-start px-2 font-medium"
- />
- <Button
- text="QR Code"
- variant="outline"
- onClick={() => {
- setOpenPopover(false);
- setShowLinkQRModal(true);
- }}
- icon={<QrCode className="h-4 w-4" />}
- className="h-9 justify-start px-2 font-medium"
- />
- <Button
- text="Copy Link ID"
- variant="outline"
- onClick={() => copyLinkId()}
- icon={
- copiedLinkId ? (
- <CheckCircleFill className="h-4 w-4" />
- ) : (
- <Copy className="h-4 w-4" />
- )
- }
- className="h-9 justify-start px-2 font-medium"
- />
- </>
- ) : (
- <Button
- text="Create Link"
- variant="outline"
- icon={<Edit3 className="h-4 w-4" />}
- className="h-9 justify-start px-2 font-medium"
- onClick={() => {
- setOpenPopover(false);
- setShowAddEditLinkModal(true);
- }}
- {...(plan === "free" && {
- disabledTooltip: (
- <SimpleTooltipContent
- title="You can only create root links on a Pro plan and above. Upgrade to Pro to use this feature."
- cta="Learn more."
- href="https://dub.co/help/article/how-to-redirect-root-domain"
- />
- ),
- })}
- />
- )}
+ <Button
+ text="Edit Link"
+ variant="outline"
+ onClick={() => {
+ setOpenPopover(false);
+ setShowAddEditLinkModal(true);
+ }}
+ icon={<Edit3 className="h-4 w-4" />}
+ className="h-9 justify-start px-2 font-medium"
+ />
+ <Button
+ text="QR Code"
+ variant="outline"
+ onClick={() => {
+ setOpenPopover(false);
+ setShowLinkQRModal(true);
+ }}
+ icon={<QrCode className="h-4 w-4" />}
+ className="h-9 justify-start px-2 font-medium"
+ />
+ <Button
+ text="Copy Link ID"
+ variant="outline"
+ onClick={() => copyLinkId()}
+ icon={
+ copiedLinkId ? (
+ <CheckCircleFill className="h-4 w-4" />
+ ) : (
+ <Copy className="h-4 w-4" />
+ )
+ }
+ className="h-9 justify-start px-2 font-medium"
+ />
</div>
<div className="border-t border-gray-200" />
<div className="grid gap-px p-2">
@@ -352,15 +328,23 @@ export default function DomainCard({ props }: { props: DomainProps }) {
</div>
<div className="flex items-center space-x-2">
{linkProps ? (
- <CheckCircleFill className="h-6 w-6 text-blue-500" />
+ linkProps.url ? (
+ <CheckCircleFill className="h-6 w-6 text-blue-500" />
+ ) : (
+ <XCircleFill className="h-6 w-6 text-gray-400" />
+ )
) : (
- <XCircleFill className="h-6 w-6 text-gray-400" />
+ <LoadingCircle className="mr-1 h-5 w-5" />
)}
<div className="flex space-x-1">
<p className="text-sm text-gray-500">
- {linkProps ? `Redirects to` : `No redirect configured`}
+ {linkProps
+ ? linkProps.url
+ ? `Redirects to`
+ : `No redirect configured`
+ : `Checking link status`}
</p>
- {linkProps?.url && (
+ {linkProps && (
<a
href={linkProps.url}
target="_blank"
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 5bf0ea199c..d515ef7e20 100644
--- a/apps/web/ui/modals/add-edit-domain-modal/index.tsx
+++ b/apps/web/ui/modals/add-edit-domain-modal/index.tsx
@@ -39,7 +39,7 @@ function AddEditDomainModal({
}) {
const router = useRouter();
const { slug } = useParams() as { slug: string };
- const { id, logo, plan } = useWorkspace();
+ const { id: workspaceId, logo, plan } = useWorkspace();
const { queryParams } = useRouterStuff();
const [data, setData] = useState<DomainProps>(
@@ -49,7 +49,7 @@ function AddEditDomainModal({
verified: false,
primary: false,
archived: false,
- projectId: id || "",
+ projectId: workspaceId || "",
},
);
@@ -84,13 +84,13 @@ function AddEditDomainModal({
if (props) {
return {
method: "PATCH",
- url: `/api/domains/${domain}?workspaceId=${id}`,
+ url: `/api/domains/${domain}?workspaceId=${workspaceId}`,
successMessage: "Successfully updated domain!",
};
} else {
return {
method: "POST",
- url: `/api/domains?workspaceId=${id}`,
+ url: `/api/domains?workspaceId=${workspaceId}`,
successMessage: "Successfully added domain!",
};
}
@@ -128,16 +128,29 @@ function AddEditDomainModal({
headers: {
"Content-Type": "application/json",
},
- body: JSON.stringify({
- ...data,
- placeholder: placeholder || null,
- expiredUrl: expiredUrl || null,
- }),
+ body: JSON.stringify(data),
}).then(async (res) => {
if (res.ok) {
- await mutate(`/api/domains?workspaceId=${id}`);
+ if (endpoint.method === "POST") {
+ await fetch(`/api/links?workspaceId=${workspaceId}`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ domain: data.slug,
+ key: "_root",
+ url: "",
+ }),
+ });
+ }
+ await Promise.all([
+ mutate(`/api/domains?workspaceId=${workspaceId}`),
+ mutate(`/api/links?workspaceId=${workspaceId}`),
+ ]);
setShowAddEditDomainModal(false);
toast.success(endpoint.successMessage);
+ // TODO: Remove after links dashboard is refactored to use new filter UX
if (!props) {
router.push(`/${slug}/domains`);
}
diff --git a/apps/web/ui/modals/add-edit-link-modal/index.tsx b/apps/web/ui/modals/add-edit-link-modal/index.tsx
index 5c26d730f5..5dbc618113 100644
--- a/apps/web/ui/modals/add-edit-link-modal/index.tsx
+++ b/apps/web/ui/modals/add-edit-link-modal/index.tsx
@@ -36,12 +36,7 @@ import {
import va from "@vercel/analytics";
import { useCompletion } from "ai/react";
import { TriangleAlert } from "lucide-react";
-import {
- useParams,
- usePathname,
- useRouter,
- useSearchParams,
-} from "next/navigation";
+import { useParams, useSearchParams } from "next/navigation";
import {
Dispatch,
SetStateAction,
@@ -83,8 +78,6 @@ function AddEditLinkModal({
}) {
const params = useParams() as { slug?: string };
const { slug } = params;
- const router = useRouter();
- const pathname = usePathname();
const {
id: workspaceId,
aiUsage,