The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Finish up domain registration
Tim Wilsona78f5f87d13f
diff --git a/apps/web/app/api/domains/register/route.ts b/apps/web/app/api/domains/register/route.tsindex b6e85cff45..3fae35a933 100644--- a/apps/web/app/api/domains/register/route.ts+++ b/apps/web/app/api/domains/register/route.ts@@ -1,6 +1,11 @@+import { createLink } from "@/lib/api/links";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({@@ -13,14 +18,52 @@ const schema = z.object({// GET /api/domains/register - register a domainexport const POST = withWorkspace(- async ({ searchParams }) => {+ async ({ searchParams, workspace, session }) => {const { domain } = schema.parse(searchParams);const response = await registerDomain({ domain });+ const slug = response.RegisterResponse.DomainName;- // TODO:- // Add domain to the workspace if registration is successful- // Add DNS records to the domain if registration is successful (in the background)+ const registeredDomain = await prisma.registeredDomain.create({+ data: {+ projectId: workspace.id,+ slug,+ expiresAt: new Date(response.RegisterResponse.Expiration),+ },+ });++ const totalDomains = await prisma.domain.count({+ where: {+ projectId: workspace.id,+ },+ });++ await Promise.all([+ // Create the workspace domain+ prisma.domain.create({+ data: {+ projectId: workspace.id,+ slug,+ verified: true,+ lastChecked: new Date(),+ registeredDomainId: registeredDomain.id,+ primary: totalDomains === 0,+ },+ }),+ // 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/search-availability/route.ts b/apps/web/app/api/domains/search-availability/route.tsindex 27beacb985..b754b0cda3 100644--- a/apps/web/app/api/domains/search-availability/route.ts+++ b/apps/web/app/api/domains/search-availability/route.ts@@ -13,7 +13,7 @@ const schema = z.object({// GET /api/domains/search-availability - search the domainexport const GET = withWorkspace(- async ({ workspace, searchParams }) => {+ async ({ searchParams }) => {const { domain } = schema.parse(searchParams);return NextResponse.json(await searchDomainsAvailability({ domain }));diff --git a/apps/web/lib/dynadot/configure-dns.ts b/apps/web/lib/dynadot/configure-dns.tsindex cbff29fb8c..d00fe07243 100644--- a/apps/web/lib/dynadot/configure-dns.ts+++ b/apps/web/lib/dynadot/configure-dns.ts@@ -2,11 +2,9 @@ import z from "@/lib/zod";import { DYNADOT_API_KEY, DYNADOT_BASE_URL } from "./constants";const schema = z.object({- RegisterResponse: z.object({- // ResponseCode: z.enum(["0", "-1", ""]),- Status: z.enum(["success", "insufficient_funds"]),- DomainName: z.string(),- // Expiration: z.number(),+ SetDnsResponse: z.object({+ ResponseCode: z.number(),+ Status: z.string(),}),});@@ -15,7 +13,7 @@ export const configureDNS = async ({ domain }: { domain: string }) => {key: DYNADOT_API_KEY,domain: domain,command: "set_dns2",- main_record_type0: "aaaa",+ main_record_type0: "a",main_record0: "76.76.21.21",});@@ -32,13 +30,7 @@ export const configureDNS = async ({ domain }: { domain: string }) => {throw new Error(`Failed to register domain: ${response.statusText}`);}- const json = await response.json();+ const data = schema.parse(await response.json());- console.log("registerDomain", json);-- return json;-- // const data = schema.parse(json);-- // return data;+ return data;};diff --git a/apps/web/lib/dynadot/register-domain.ts b/apps/web/lib/dynadot/register-domain.tsindex efc7600b34..5707a77d53 100644--- a/apps/web/lib/dynadot/register-domain.ts+++ b/apps/web/lib/dynadot/register-domain.ts@@ -3,10 +3,9 @@ import { DYNADOT_API_KEY, DYNADOT_BASE_URL } from "./constants";const schema = z.object({RegisterResponse: z.object({- // ResponseCode: z.enum(["0", "-1", ""]),- Status: z.enum(["success", "insufficient_funds"]),+ Status: z.string(),DomainName: z.string(),- // Expiration: z.number(),+ Expiration: z.number(),}),});@@ -17,6 +16,7 @@ export const registerDomain = async ({ domain }: { domain: string }) => {command: "register",duration: "1", // TODO: Is this month or year?currency: "USD",+ coupon: "DUBCOLINK",});const response = await fetch(@@ -32,13 +32,12 @@ export const registerDomain = async ({ domain }: { domain: string }) => {throw new Error(`Failed to register domain: ${response.statusText}`);}- const json = await response.json();+ const data = schema.parse(await response.json());- console.log("registerDomain", json);+ if (data.RegisterResponse.Status !== "success")+ throw new Error(+ `Failed to register domain: ${data.RegisterResponse.Status}`,+ );- return json;-- // const data = schema.parse(json);-- // return data;+ return data;};diff --git a/apps/web/ui/modals/register-domain.tsx b/apps/web/ui/modals/register-domain.tsxindex 455fb58561..262aeaa0bc 100644--- a/apps/web/ui/modals/register-domain.tsx+++ b/apps/web/ui/modals/register-domain.tsx@@ -28,6 +28,7 @@ const RegisterDomain = ({ showModal, setShowModal }: RegisterDomainProps) => {const workspace = useWorkspace();const { isMobile } = useMediaQuery();const [isSearching, setIsSearching] = useState(false);+ const [isRegistering, setIsRegistering] = useState(false);const [slug, setSlug] = useState<string | undefined>(undefined);const [searchedDomains, setSearchedDomains] = useState<DomainSearchResult[]>([],@@ -57,6 +58,7 @@ const RegisterDomain = ({ showModal, setShowModal }: RegisterDomainProps) => {// Register domainconst registerDomain = async (domain: string) => {+ setIsRegistering(true);const response = await fetch(`/api/domains/register?domain=${domain}&workspaceId=${workspace.id}`,{@@ -66,14 +68,13 @@ const RegisterDomain = ({ showModal, setShowModal }: RegisterDomainProps) => {if (!response.ok) {toast.error("Failed to register domain.");+ setIsRegistering(false);return;}- const data = await response.json();-- console.log(data);-toast.success("Domain registered successfully!");+ setShowModal(false);+ setIsRegistering(false);};const searchedDomain = searchedDomains.find(@@ -90,148 +91,158 @@ const RegisterDomain = ({ showModal, setShowModal }: RegisterDomainProps) => {Claim .link domain</h3><form- className="flex flex-col space-y-6 bg-white px-4 pb-8 pt-6 text-left sm:px-6"onSubmit={async (e: FormEvent<HTMLFormElement>) => {e.preventDefault();+ if (searchedDomain && searchedDomain.available)+ await registerDomain(searchedDomain.domain);}}>- <div>- <div className="flex items-center gap-2">- <p className="block text-sm font-medium text-gray-800">- Search domains- </p>-- {workspace.plan != "free" && (- <ProBadgeTooltip- content={- <SimpleTooltipContent- title="Search for a free .link domain to use for your short links."- cta="Learn more."- href="https://dub.co/help/article/how-to-add-custom-domain" // TODO: Update this link- />- }- />- )}- </div>+ <div className="flex flex-col space-y-6 bg-white px-4 pb-8 pt-6 text-left sm:px-6">+ <div>+ <div className="flex items-center gap-2">+ <p className="block text-sm font-medium text-gray-800">+ Search domains+ </p>- <div className="mt-2">- <div- className={cn(- "-m-1 rounded-[0.625rem] p-1",- searchedDomain &&- (searchedDomain.available ? "bg-[#def5c6]" : "bg-orange-100"),- )}- >- <div className="flex rounded-md border border-gray-300 bg-white">- <input- name="domain"- id="domain"- type="text"- required- autoComplete="off"- className="block w-full rounded-md rounded-r-none border-0 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-0 sm:text-sm"- aria-invalid="true"- autoFocus={!isMobile}- placeholder={workspace.slug}- value={slug}- onChange={(e) => {- setSlug(e.target.value);- }}+ {workspace.plan != "free" && (+ <ProBadgeTooltip+ content={+ <SimpleTooltipContent+ title="Search for a free .link domain to use for your short links."+ cta="Learn more."+ href="https://dub.co/help/article/how-to-add-custom-domain" // TODO: Update this link+ />+ }/>- <span className="inline-flex items-center rounded-md rounded-l-none bg-white px-3 font-medium text-gray-500 sm:text-sm">- .link- </span>- <div className="p-0.5">- <Button- className="h-8 w-fit border-gray-300 px-2"- icon={<Search className="mx-0.5 size-4" />}- onClick={searchDomainAvailability}- disabled={!slug || isSearching}- loading={isSearching}+ )}+ </div>++ <div className="mt-2">+ <div+ className={cn(+ "-m-1 rounded-[0.625rem] p-1",+ searchedDomain &&+ (searchedDomain.available+ ? "bg-[#def5c6]"+ : "bg-orange-100"),+ )}+ >+ <div className="flex rounded-md border border-gray-300 bg-white">+ <input+ name="domain"+ id="domain"+ type="text"+ required+ autoComplete="off"+ className="block w-full rounded-md rounded-r-none border-0 text-gray-900 placeholder-gray-400 focus:outline-none focus:ring-0 sm:text-sm"+ aria-invalid="true"+ autoFocus={!isMobile}+ placeholder={workspace.slug}+ value={slug}+ onChange={(e) => {+ setSlug(e.target.value);+ }}/>+ <span className="inline-flex items-center rounded-md rounded-l-none bg-white px-3 font-medium text-gray-500 sm:text-sm">+ .link+ </span>+ <div className="p-0.5">+ <Button+ className="h-8 w-fit border-gray-300 px-2"+ icon={<Search className="mx-0.5 size-4" />}+ onClick={searchDomainAvailability}+ disabled={!slug || isSearching}+ loading={isSearching}+ />+ </div></div>- </div>- <AnimatedSizeContainer- height- transition={{ ease: "easeInOut", duration: 0.1 }}- >- {searchedDomain && (- <div className="flex justify-between gap-3 px-2 pb-2 pt-3 text-sm text-gray-700">- <p>+ <AnimatedSizeContainer+ height+ transition={{ ease: "easeInOut", duration: 0.1 }}+ >+ {searchedDomain && (+ <div className="flex justify-between gap-3 px-2 pb-2 pt-3 text-sm text-gray-700">+ <p>+ {searchedDomain.available ? (+ <>+ <span className="font-semibold text-gray-800">+ {searchedDomain.domain}+ </span>{" "}+ is available. Claim your free domain before it's+ gone!+ </>+ ) : (+ <>+ <span className="font-semibold text-gray-800">+ {searchedDomain?.domain}+ </span>{" "}+ is not available.+ </>+ )}+ </p>{searchedDomain.available ? (- <>- <span className="font-semibold text-gray-800">- {searchedDomain.domain}- </span>{" "}- is available. Claim your free domain before it's gone!- </>+ <CheckCircleFill className="size-5 shrink-0 text-green-500" />) : (- <>- <span className="font-semibold text-gray-800">- {searchedDomain?.domain}- </span>{" "}- is not available.- </>+ <AlertCircleFill className="size-5 shrink-0 text-amber-500" />)}- </p>- {searchedDomain.available ? (- <CheckCircleFill className="size-5 shrink-0 text-green-500" />- ) : (- <AlertCircleFill className="size-5 shrink-0 text-amber-500" />- )}- </div>- )}- </AnimatedSizeContainer>+ </div>+ )}+ </AnimatedSizeContainer>+ </div></div></div>- </div>- {searchedDomain &&- !searchedDomain.available &&- availableDomains.length > 0 && (- <div>- <h2 className="text-sm font-medium text-gray-800">- Available alternatives- </h2>- <div className="mt-2 overflow-hidden rounded-lg border border-gray-200">- <div className="flex flex-col divide-y divide-gray-200">- {availableDomains.map((alternative) => (- <div- key={alternative.domain}- className="flex items-center justify-between p-1.5 pl-3 focus:outline-none"- >- <div className="flex items-center gap-2">- <CircleCheck className="size-5 fill-green-500 text-white" />- <span className="text-sm font-medium">- {alternative.domain}- </span>+ {searchedDomain &&+ !searchedDomain.available &&+ availableDomains.length > 0 && (+ <div>+ <h2 className="text-sm font-medium text-gray-800">+ Available alternatives+ </h2>+ <div className="mt-2 overflow-hidden rounded-lg border border-gray-200">+ <div className="flex flex-col divide-y divide-gray-200">+ {availableDomains.map((alternative) => (+ <div+ key={alternative.domain}+ className="flex items-center justify-between p-1.5 pl-3 focus:outline-none"+ >+ <div className="flex items-center gap-2">+ <CircleCheck className="size-5 fill-green-500 text-white" />+ <span className="text-sm font-medium">+ {alternative.domain}+ </span>+ </div>+ <Button+ text="Claim domain"+ className="h-8 w-fit"+ onClick={() => registerDomain(alternative.domain)}+ disabled={isRegistering}+ /></div>- <Button- text="Claim domain"- className="h-8 w-fit"- onClick={() => registerDomain(alternative.domain)}- />- </div>- ))}+ ))}+ </div></div></div>- </div>- )}+ )}+ </div>+ <div className="flex justify-end gap-2 border-t border-gray-200 px-4 py-4 sm:px-6">+ <Button+ type="button"+ variant="secondary"+ text="Cancel"+ className="h-9 w-fit"+ onClick={() => setShowModal(false)}+ />+ <Button+ type="submit"+ text="Claim domain"+ className="h-9 w-fit"+ disabled={!searchedDomain?.available}+ loading={isRegistering}+ />+ </div></form>- <div className="flex justify-end gap-2 border-t border-gray-200 px-4 py-4 sm:px-6">- <Button- variant="secondary"- text="Cancel"- className="h-9 w-fit"- onClick={() => setShowModal(false)}- />- <Button- text="Claim domain"- className="h-9 w-fit"- disabled={!searchedDomain?.available}- />- </div></Modal>);};