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 domain registration to onboarding

Tim Wilson9ece42e6c731
diff --git a/apps/web/app/api/domains/register/route.ts b/apps/web/app/api/domains/register/route.ts
index 07592439f0..658ab74c2f 100644
--- a/apps/web/app/api/domains/register/route.ts
+++ b/apps/web/app/api/domains/register/route.ts
@@ -1,12 +1,6 @@
-import { DubApiError } from "@/lib/api/errors";
-import { createLink } from "@/lib/api/links";
+import { claimDotLinkDomain } from "@/lib/api/domains/claim-dot-link-domain";
import { withWorkspace } from "@/lib/auth";
-import { configureDNS } from "@/lib/dynadot/configure-dns";
-import { registerDomain } from "@/lib/dynadot/register-domain";
-import { prisma } from "@/lib/prisma";
import z from "@/lib/zod";
-import { DEFAULT_LINK_PROPS } from "@dub/utils";
-import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
const schema = z.object({
@@ -18,83 +12,17 @@ const schema = z.object({
.describe("We only support .link domains for now."),
});
-// GET /api/domains/register - register a domain
+// POST /api/domains/register - register a domain
export const POST = withWorkspace(
async ({ searchParams, workspace, session }) => {
- if (workspace.plan === "free")
- throw new DubApiError({
- code: "forbidden",
- message: "Free workspaces cannot register .link domains.",
- });
-
const { domain } = schema.parse(searchParams);
- const existingRegisteredDotLinkDomain =
- await prisma.registeredDomain.findFirst({
- where: {
- projectId: workspace.id,
- slug: {
- endsWith: ".link",
- },
- },
- });
-
- if (existingRegisteredDotLinkDomain)
- throw new DubApiError({
- code: "forbidden",
- message: "Workspace is limited to one free .link domain.",
- });
-
- const response = await registerDomain({ domain });
- const slug = response.RegisterResponse.DomainName;
-
- const totalDomains = await prisma.domain.count({
- where: {
- projectId: workspace.id,
- },
+ const response = await claimDotLinkDomain({
+ domain,
+ workspace,
+ userId: session.user.id,
});
- // Delete any matching unverified domain
- await prisma.domain.delete({
- where: {
- slug,
- verified: false,
- },
- });
-
- await Promise.all([
- // Create the workspace domain
- prisma.domain.create({
- data: {
- projectId: workspace.id,
- slug,
- verified: true,
- lastChecked: new Date(),
- primary: totalDomains === 0,
- registeredDomain: {
- create: {
- slug,
- expiresAt: new Date(response.RegisterResponse.Expiration || ""),
- projectId: workspace.id,
- },
- },
- },
- }),
- // Create the root link
- createLink({
- ...DEFAULT_LINK_PROPS,
- domain: slug,
- key: "_root",
- url: "",
- tags: undefined,
- userId: session.user.id,
- projectId: workspace.id,
- }),
- ]);
-
- // Configure the DNS in the background
- waitUntil(configureDNS({ domain: slug }));
-
return NextResponse.json(response);
},
{
diff --git a/apps/web/app/api/domains/saved/route.ts b/apps/web/app/api/domains/saved/route.ts
new file mode 100644
index 0000000000..a5192985dd
--- /dev/null
+++ b/apps/web/app/api/domains/saved/route.ts
@@ -0,0 +1,33 @@
+import { withWorkspace } from "@/lib/auth";
+import { redis } from "@/lib/upstash";
+import z from "@/lib/zod";
+import { NextResponse } from "next/server";
+
+const schema = z.object({
+ domain: z
+ .string()
+ .min(1)
+ .endsWith(".link")
+ .transform((domain) => domain.toLowerCase())
+ .describe("We only support .link domains for now."),
+});
+
+// POST /api/domains/saved - save a domain for future registration (e.g. after onboarding)
+export const POST = withWorkspace(
+ async ({ searchParams, workspace, session }) => {
+ const { domain } = schema.parse(searchParams);
+
+ await redis.set(
+ `onboarding-domain:${workspace.id}`,
+ { domain, userId: session.user.id },
+ {
+ ex: 60 * 60 * 24 * 15, // 15 days
+ },
+ );
+
+ return NextResponse.json({ success: true });
+ },
+ {
+ requiredPermissions: ["domains.write"],
+ },
+);
diff --git a/apps/web/app/api/stripe/webhook/checkout-session-completed.ts b/apps/web/app/api/stripe/webhook/checkout-session-completed.ts
index 2114002463..a4fd1a8530 100644
--- a/apps/web/app/api/stripe/webhook/checkout-session-completed.ts
+++ b/apps/web/app/api/stripe/webhook/checkout-session-completed.ts
@@ -1,3 +1,4 @@
+import { claimDotLinkDomain } from "@/lib/api/domains/claim-dot-link-domain";
import { inviteUser } from "@/lib/api/users";
import { limiter } from "@/lib/cron/limiter";
import { prisma } from "@/lib/prisma";
@@ -124,6 +125,20 @@ async function completeOnboarding({
users: Pick<User, "id">[];
workspaceId: string;
}) {
+ const workspace = (await prisma.project.findUnique({
+ where: {
+ id: workspaceId,
+ },
+ include: {
+ users: true,
+ },
+ })) as unknown as WorkspaceProps | null;
+
+ if (!workspace) {
+ console.error("Failed to complete onboarding for workspace", workspaceId);
+ return;
+ }
+
await Promise.allSettled([
// Complete onboarding for workspace users
...users.map(({ id }) => redis.set(`onboarding-step:${id}`, "completed")),
@@ -134,15 +149,6 @@ async function completeOnboarding({
if (!invites?.length) return;
- const workspace = (await prisma.project.findUnique({
- where: {
- id: workspaceId,
- },
- include: {
- users: true,
- },
- })) as unknown as WorkspaceProps | null;
-
if (!workspace) return;
await Promise.allSettled(
@@ -157,5 +163,29 @@ async function completeOnboarding({
await redis.del(`invites:${workspaceId}`);
})(),
+
+ // Register saved domain
+ (async () => {
+ const data = await redis.get<{ domain: string; userId: string }>(
+ `onboarding-domain:${workspaceId}`,
+ );
+ if (!data || !data.domain || !data.userId) return;
+ const { domain, userId } = data;
+
+ try {
+ await claimDotLinkDomain({
+ domain,
+ userId,
+ workspace,
+ });
+ await redis.del(`onboarding-domain:${workspaceId}`);
+ } catch (e) {
+ console.error(
+ "Failed to register saved domain from onboarding",
+ { domain, userId, workspace },
+ e,
+ );
+ }
+ })(),
]);
}
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/domain-selector.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/domain-selector.tsx
index 6a539159da..64c777dafb 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/domain-selector.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/domain-selector.tsx
@@ -1,50 +1,86 @@
"use client";
import useLinks from "@/lib/swr/use-links";
+import useWorkspace from "@/lib/swr/use-workspace";
import { CheckCircleFill } from "@/ui/shared/icons";
import { Button } from "@dub/ui";
-import { Globe2 } from "@dub/ui/src/icons";
+import { Globe2, LoadingSpinner } from "@dub/ui/src/icons";
import { cn } from "@dub/utils";
-import { useEffect, useState } from "react";
+import { Crown } from "lucide-react";
+import { ReactNode, useEffect, useState } from "react";
import { LaterButton } from "../../later-button";
import { useOnboardingProgress } from "../../use-onboarding-progress";
export function DomainSelector() {
+ const { loading: isWorkspaceLoading, flags } = useWorkspace();
const { continueTo, isLoading, isSuccessful } = useOnboardingProgress();
- return (
- <div>
- <div className="mx-auto w-full max-w-[312px]">
+ const [selectedOption, setSelectedOption] = useState<"custom" | "register">(
+ "custom",
+ );
+
+ return isWorkspaceLoading ? (
+ <div className="mt-12 flex w-full justify-center">
+ <LoadingSpinner />
+ </div>
+ ) : (
+ <>
+ <div
+ className={cn(
+ "animate-fade-in mx-auto grid w-full max-w-[312px] gap-4",
+ flags?.dotlink && "sm:max-w-2xl sm:grid-cols-2",
+ )}
+ >
<DomainOption
title="Connect a custom domain"
example="acme.com"
- onClick={() => {}}
- isSelected={true}
+ onClick={() => setSelectedOption("custom")}
+ isSelected={selectedOption === "custom"}
/>
+ {flags?.dotlink && (
+ <DomainOption
+ title={
+ <>
+ Claim a free{" "}
+ <span className="rounded border border-green-800/10 bg-lime-100 p-1 font-mono text-xs">
+ .link
+ </span>{" "}
+ domain
+ </>
+ }
+ example="acme.link"
+ onClick={() => setSelectedOption("register")}
+ isSelected={selectedOption === "register"}
+ paidPlanRequired={true}
+ />
+ )}
</div>
- <div className="mt-8">
+ <div className="mx-auto mt-8 w-full max-w-sm">
<Button
type="button"
variant="primary"
- onClick={() => continueTo("domain/custom")}
+ onClick={() => continueTo(`domain/${selectedOption}`)}
loading={isLoading || isSuccessful}
text="Continue"
/>
<LaterButton next="invite" className="mt-4" />
</div>
- </div>
+ </>
);
}
function DomainOption({
+ title,
example,
onClick,
isSelected,
+ paidPlanRequired,
}: {
- title: string;
+ title: ReactNode;
example: string;
onClick: () => void;
isSelected: boolean;
+ paidPlanRequired?: boolean;
}) {
const { links } = useLinks({ sort: "createdAt", pageSize: 1 });
@@ -67,8 +103,8 @@ function DomainOption({
return (
<div
className={cn(
- "transition-border relative flex flex-col gap-2 rounded-lg border border-gray-300 px-10 py-9",
- isSelected && "border-2 border-black bg-black/[0.03]",
+ "relative flex flex-col gap-2 rounded-lg border border-gray-300 px-10 pb-4 pt-9 transition-all",
+ isSelected && "border-transparent bg-black/[0.03] ring-2 ring-black",
)}
role="button"
onClick={onClick}
@@ -95,8 +131,14 @@ function DomainOption({
</div>
</div>
<span className="text-center text-sm font-medium text-gray-800">
- Connect a custom domain
+ {title}
</span>
+ {paidPlanRequired && (
+ <span className="flex items-center justify-center gap-1 text-center text-xs font-normal text-gray-500/80">
+ <Crown className="size-4" />
+ Paid plan required
+ </span>
+ )}
</div>
);
}
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/page.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/page.tsx
index 5b14438b23..491a45ec47 100644
--- a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/page.tsx
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/page.tsx
@@ -8,6 +8,7 @@ export default function Domain() {
icon={Globe}
title="Add a custom domain"
description="Take your links to the next level with your own branding."
+ className="max-w-none"
>
<DomainSelector />
</StepPage>
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/register/form.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/register/form.tsx
new file mode 100644
index 0000000000..930cb58b09
--- /dev/null
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/register/form.tsx
@@ -0,0 +1,21 @@
+"use client";
+
+import { RegisterDomainForm } from "@/ui/domains/register-domain-form";
+import { LaterButton } from "../../../later-button";
+import { useOnboardingProgress } from "../../../use-onboarding-progress";
+
+export function Form() {
+ const { continueTo } = useOnboardingProgress();
+
+ return (
+ <div>
+ <RegisterDomainForm
+ saveOnly
+ onSuccess={() => {
+ continueTo("invite");
+ }}
+ />
+ <LaterButton next="invite" className="mt-4" />
+ </div>
+ );
+}
diff --git a/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/register/page.tsx b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/register/page.tsx
new file mode 100644
index 0000000000..1a66106ccc
--- /dev/null
+++ b/apps/web/app/app.dub.co/(onboarding)/onboarding/(steps)/domain/register/page.tsx
@@ -0,0 +1,16 @@
+import { Globe } from "@dub/ui/src/icons";
+import { StepPage } from "../../step-page";
+import { Form } from "./form";
+
+export default function Register() {
+ return (
+ <StepPage
+ icon={Globe}
+ title="Claim your free .link domain"
+ paidPlanRequired={true}
+ description="Exclusively free for a year"
+ >
+ <Form />
+ </StepPage>
+ );
+}
diff --git a/apps/web/lib/api/domains/claim-dot-link-domain.ts b/apps/web/lib/api/domains/claim-dot-link-domain.ts
new file mode 100644
index 0000000000..fa7f6a1309
--- /dev/null
+++ b/apps/web/lib/api/domains/claim-dot-link-domain.ts
@@ -0,0 +1,90 @@
+import { DubApiError } from "@/lib/api/errors";
+import { createLink } from "@/lib/api/links";
+import { configureDNS } from "@/lib/dynadot/configure-dns";
+import { registerDomain } from "@/lib/dynadot/register-domain";
+import { prisma } from "@/lib/prisma";
+import { WorkspaceWithUsers } from "@/lib/types";
+import { DEFAULT_LINK_PROPS } from "@dub/utils";
+import { waitUntil } from "@vercel/functions";
+
+export async function claimDotLinkDomain({
+ domain,
+ workspace,
+ userId,
+}: {
+ domain: string;
+ workspace: WorkspaceWithUsers;
+ userId: string;
+}) {
+ if (workspace.plan === "free")
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Free workspaces cannot register .link domains.",
+ });
+
+ const existingRegisteredDotLinkDomain =
+ await prisma.registeredDomain.findFirst({
+ where: {
+ projectId: workspace.id,
+ slug: {
+ endsWith: ".link",
+ },
+ },
+ });
+
+ if (existingRegisteredDotLinkDomain)
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Workspace is limited to one free .link domain.",
+ });
+
+ const response = await registerDomain({ domain });
+ const slug = response.RegisterResponse.DomainName;
+
+ const totalDomains = await prisma.domain.count({
+ where: {
+ projectId: workspace.id,
+ },
+ });
+
+ // Delete any matching unverified domain
+ await prisma.domain.delete({
+ where: {
+ slug,
+ verified: false,
+ },
+ });
+
+ await Promise.all([
+ // Create the workspace domain
+ prisma.domain.create({
+ data: {
+ projectId: workspace.id,
+ slug,
+ verified: true,
+ lastChecked: new Date(),
+ primary: totalDomains === 0,
+ registeredDomain: {
+ create: {
+ slug,
+ expiresAt: new Date(response.RegisterResponse.Expiration || ""),
+ projectId: workspace.id,
+ },
+ },
+ },
+ }),
+ // Create the root link
+ createLink({
+ ...DEFAULT_LINK_PROPS,
+ domain: slug,
+ key: "_root",
+ url: "",
+ tags: undefined,
+ userId: userId,
+ projectId: workspace.id,
+ }),
+ ]);
+
+ // Configure the DNS in the background
+ waitUntil(configureDNS({ domain: slug }));
+}
diff --git a/apps/web/lib/onboarding/types.ts b/apps/web/lib/onboarding/types.ts
index 7fb4527015..c0efb50831 100644
--- a/apps/web/lib/onboarding/types.ts
+++ b/apps/web/lib/onboarding/types.ts
@@ -3,6 +3,7 @@ export const ONBOARDING_STEPS = [
"link",
"domain",
"domain/custom",
+ "domain/register",
"invite",
"plan",
"completed",
diff --git a/apps/web/ui/domains/register-domain-form.tsx b/apps/web/ui/domains/register-domain-form.tsx
index 04d54f9154..d02507c3c6 100644
--- a/apps/web/ui/domains/register-domain-form.tsx
+++ b/apps/web/ui/domains/register-domain-form.tsx
@@ -23,9 +23,13 @@ interface DomainSearchResult {
}
export function RegisterDomainForm({
+ variant = "default",
+ saveOnly = false,
onSuccess,
onCancel,
}: {
+ variant?: "default" | "modal";
+ saveOnly?: boolean; // Whether to only save the data without actually sending invites
onSuccess: (domain: string) => void;
onCancel?: () => void;
}) {
@@ -58,7 +62,14 @@ export function RegisterDomainForm({
return;
}
- setSearchedDomains(await response.json());
+ const data = await response.json();
+
+ if (!Array.isArray(data)) {
+ toast.error("Failed to search for domain availability.");
+ return;
+ }
+
+ setSearchedDomains(data);
};
// Search automatically when the debounced slug changes
@@ -69,8 +80,11 @@ export function RegisterDomainForm({
// Register domain
const registerDomain = async (domain: string) => {
setIsRegistering(true);
+
+ const baseUrl = saveOnly ? "/api/domains/saved" : "/api/domains/register";
+
const response = await fetch(
- `/api/domains/register?domain=${domain}&workspaceId=${workspace.id}`,
+ `${baseUrl}?domain=${domain}&workspaceId=${workspace.id}`,
{
method: "POST",
},
@@ -83,24 +97,27 @@ export function RegisterDomainForm({
return;
}
- toast.success("Domain registered successfully!");
+ if (saveOnly) {
+ toast.custom(() => <DomainSavedToast />, { duration: 7000 });
+ } else {
+ toast.success("Domain registered successfully!");
- // Mutate domains and links
- await Promise.all([
- mutate(
- (key) =>
- typeof key === "string" &&
- key.startsWith(`/api/domains?workspaceId=${workspace.id}`),
- ),
- mutate(
- (key) => typeof key === "string" && key.startsWith("/api/links"),
- undefined,
- { revalidate: true },
- ),
- ]);
+ // Mutate domains and links
+ await Promise.all([
+ mutate(
+ (key) =>
+ typeof key === "string" &&
+ key.startsWith(`/api/domains?workspaceId=${workspace.id}`),
+ ),
+ mutate(
+ (key) => typeof key === "string" && key.startsWith("/api/links"),
+ undefined,
+ { revalidate: true },
+ ),
+ ]);
+ }
onSuccess(domain.toLowerCase());
- setIsRegistering(false);
};
const searchedDomain = searchedDomains.find(
@@ -119,14 +136,19 @@ export function RegisterDomainForm({
await registerDomain(searchedDomain.domain);
}}
>
- <div className="flex flex-col space-y-6 bg-white px-4 pb-8 pt-6 text-left sm:px-6">
+ <div
+ className={cn(
+ "flex flex-col gap-y-6 text-left",
+ variant === "modal" && "px-4 sm:px-6",
+ )}
+ >
<div>
<div className="flex items-center gap-2">
<p className="block text-sm font-medium text-gray-800">
Search domains
</p>
- {workspace.plan != "free" && (
+ {workspace.plan === "free" && variant === "modal" && (
<ProBadgeTooltip
content={
<SimpleTooltipContent
@@ -249,9 +271,12 @@ export function RegisterDomainForm({
text="Claim domain"
className="h-8 w-fit"
onClick={() => registerDomain(alternative.domain)}
- disabled={isRegistering || workspace.plan === "free"}
+ disabled={
+ isRegistering ||
+ (workspace.plan === "free" && !saveOnly)
+ }
disabledTooltip={
- workspace.plan === "free" ? (
+ workspace.plan === "free" && !saveOnly ? (
<UpgradeTooltipContent />
) : undefined
}
@@ -263,8 +288,13 @@ export function RegisterDomainForm({
</div>
)}
</div>
- <div className="flex justify-end gap-2 border-t border-gray-200 px-4 py-4 sm:px-6">
- {onCancel && (
+ <div
+ className={cn(
+ "mt-8 flex justify-end gap-2",
+ variant === "modal" && "border-t border-gray-200 px-4 py-4 sm:px-6",
+ )}
+ >
+ {onCancel && variant === "modal" && (
<Button
type="button"
variant="secondary"
@@ -276,11 +306,16 @@ export function RegisterDomainForm({
<Button
type="submit"
text="Claim domain"
- className="h-9 w-fit"
- disabled={!searchedDomain?.available || workspace.plan === "free"}
+ className={cn("h-9", variant === "modal" && "w-fit")}
+ disabled={
+ !searchedDomain?.available ||
+ (workspace.plan === "free" && !saveOnly)
+ }
loading={isRegistering}
disabledTooltip={
- workspace.plan === "free" ? <UpgradeTooltipContent /> : undefined
+ workspace.plan === "free" && !saveOnly ? (
+ <UpgradeTooltipContent />
+ ) : undefined
}
/>
</div>
@@ -303,3 +338,21 @@ function UpgradeTooltipContent() {
/>
);
}
+
+function DomainSavedToast() {
+ return (
+ <div className="flex items-center gap-1.5 rounded-lg bg-white p-4 text-sm shadow-[0_4px_12px_#0000001a]">
+ <CheckCircleFill className="size-5 shrink-0 text-black" />
+ <p className="text-[13px] font-medium text-gray-900">
+ Domain saved. You'll need a pro plan to complete the registration.{" "}
+ <a
+ href="https://dub.co/help/article/how-to-add-custom-domain" // TODO: Update this link
+ target="_blank"
+ className="text-gray-500 underline transition-colors hover:text-gray-800"
+ >
+ Learn more
+ </a>
+ </p>
+ </div>
+ );
+}
diff --git a/apps/web/ui/modals/register-domain-modal.tsx b/apps/web/ui/modals/register-domain-modal.tsx
index 472f88676b..b291d84b40 100644
--- a/apps/web/ui/modals/register-domain-modal.tsx
+++ b/apps/web/ui/modals/register-domain-modal.tsx
@@ -15,13 +15,16 @@ const RegisterDomain = ({ showModal, setShowModal }: RegisterDomainProps) => {
<h3 className="border-b border-gray-200 px-4 py-4 text-lg font-medium sm:px-6">
Claim .link domain
</h3>
- <RegisterDomainForm
- onSuccess={(domain) => {
- setShowModal(false);
- queryParams({ set: { registered: domain.toLowerCase() } });
- }}
- onCancel={() => setShowModal(false)}
- />
+ <div className="mt-6">
+ <RegisterDomainForm
+ variant="modal"
+ onSuccess={(domain) => {
+ setShowModal(false);
+ queryParams({ set: { registered: domain.toLowerCase() } });
+ }}
+ onCancel={() => setShowModal(false)}
+ />
+ </div>
</Modal>
);
};