Skip to content

Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.

Improve domain add modal UX

Marc Seitz89dff729a76b
diff --git a/components/domains/add-domain-modal.tsx b/components/domains/add-domain-modal.tsx
index 1713e562..729e37f3 100644
--- a/components/domains/add-domain-modal.tsx
+++ b/components/domains/add-domain-modal.tsx
@@ -1,14 +1,20 @@
-import { useState } from "react";
+import { useEffect, useState, type ElementType } from "react";
import { useTeam } from "@/context/team-context";
import { PlanEnum } from "@/ee/stripe/constants";
import { LinkType } from "@prisma/client";
+import {
+ AlertTriangleIcon,
+ CircleCheckIcon,
+ InfoIcon,
+} from "lucide-react";
import { toast } from "sonner";
-import { z } from "zod";
+import { useDebounce } from "use-debounce";
import { useAnalytics } from "@/lib/analytics";
import { usePlan } from "@/lib/swr/use-billing";
import useLimits from "@/lib/swr/use-limits";
+import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";
import {
@@ -22,10 +28,81 @@ import {
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
+import LoadingSpinner from "@/components/ui/loading-spinner";
import { UpgradePlanModal } from "../billing/upgrade-plan-modal";
import { UpgradeButton } from "../ui/upgrade-button";
+const validDomainRegex = new RegExp(
+ /^([a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,
+);
+
+const sanitizeDomain = (value: string) =>
+ value
+ .trim()
+ .toLowerCase()
+ .replace(/^(?:https?:\/\/)?(?:www\.)?/i, "")
+ .split("/")[0];
+
+type DomainStatus =
+ | "checking"
+ | "conflict"
+ | "has site"
+ | "available"
+ | "idle"
+ | "invalid"
+ | "error";
+
+const STATUS_CONFIG: Record<
+ DomainStatus,
+ {
+ prefix?: string;
+ useStrong?: boolean;
+ suffix?: string;
+ icon?: ElementType;
+ className?: string;
+ message?: string;
+ }
+> = {
+ checking: {
+ prefix: "Checking availability for",
+ useStrong: true,
+ suffix: "...",
+ icon: LoadingSpinner,
+ className: "bg-neutral-100 text-neutral-500",
+ },
+ conflict: {
+ suffix: "is already in use.",
+ icon: AlertTriangleIcon,
+ className: "bg-rose-100 text-rose-600",
+ },
+ "has site": {
+ suffix:
+ "is currently pointing to an existing website. Only proceed if you're sure you want to use this domain for Papermark links.",
+ icon: InfoIcon,
+ className: "bg-blue-100 text-blue-800",
+ },
+ available: {
+ suffix: "is ready to connect.",
+ icon: CircleCheckIcon,
+ className: "bg-emerald-100 text-emerald-600",
+ },
+ invalid: {
+ message: "Enter a valid domain to check availability.",
+ icon: AlertTriangleIcon,
+ className: "bg-rose-100 text-rose-600",
+ },
+ idle: {
+ message: "Enter a valid domain to check availability.",
+ className: "bg-neutral-100 text-neutral-500",
+ },
+ error: {
+ message: "We couldn't check this domain right now. Try again.",
+ icon: AlertTriangleIcon,
+ className: "bg-rose-100 text-rose-600",
+ },
+};
+
export function AddDomainModal({
open,
setOpen,
@@ -39,59 +116,132 @@ export function AddDomainModal({
linkType?: Omit<LinkType, "WORKFLOW_LINK">;
children?: React.ReactNode;
}) {
- const [domain, setDomain] = useState<string>("");
- const [loading, setLoading] = useState<boolean>(false);
+ const [domainInput, setDomainInput] = useState<string>("");
+ const [submitting, setSubmitting] = useState<boolean>(false);
+ const [domainStatus, setDomainStatus] = useState<DomainStatus>("idle");
+ const [statusMessageOverride, setStatusMessageOverride] = useState<
+ string | null
+ >(null);
const teamInfo = useTeam();
+ const teamId = teamInfo?.currentTeam?.id;
const { isFree, isPro, isBusiness } = usePlan();
const { limits } = useLimits();
const analytics = useAnalytics();
- const addDomainSchema = z.object({
- name: z
- .string()
- .min(3, {
- message: "Please provide a domain name with at least 3 characters.",
+
+ useEffect(() => {
+ if (!open) {
+ setDomainInput("");
+ setSubmitting(false);
+ setDomainStatus("idle");
+ setStatusMessageOverride(null);
+ }
+ }, [open]);
+
+ const sanitizedDomain = sanitizeDomain(domainInput);
+ const [debouncedDomain] = useDebounce(sanitizedDomain, 500);
+
+ useEffect(() => {
+ if (!open) return;
+ if (!teamId) return;
+
+ if (!debouncedDomain) {
+ setDomainStatus("idle");
+ setStatusMessageOverride(null);
+ return;
+ }
+
+ if (debouncedDomain.includes("papermark")) {
+ setDomainStatus("invalid");
+ setStatusMessageOverride("Domain cannot contain 'papermark'.");
+ return;
+ }
+
+ if (!validDomainRegex.test(debouncedDomain)) {
+ setDomainStatus("idle");
+ setStatusMessageOverride(null);
+ return;
+ }
+
+ let active = true;
+ setDomainStatus("checking");
+ setStatusMessageOverride(null);
+
+ fetch(
+ `/api/teams/${teamId}/domains/${encodeURIComponent(
+ debouncedDomain,
+ )}/validate`,
+ )
+ .then(async (res) => res.json())
+ .then((data) => {
+ if (!active) return;
+ const nextStatus = data?.status as DomainStatus | undefined;
+ if (
+ nextStatus &&
+ ["invalid", "conflict", "has site", "available"].includes(nextStatus)
+ ) {
+ setDomainStatus(nextStatus);
+ } else {
+ setDomainStatus("error");
+ }
})
- // Add validation for papermark
- .refine((name) => !name.toLowerCase().includes("papermark"), {
- message: "Domain cannot contain 'papermark'",
- }),
- });
+ .catch(() => {
+ if (!active) return;
+ setDomainStatus("error");
+ });
+
+ return () => {
+ active = false;
+ };
+ }, [debouncedDomain, open, teamId]);
+
+ const saveDisabled =
+ !["available", "has site"].includes(domainStatus) || submitting;
const handleSubmit = async (event: any) => {
event.preventDefault();
event.stopPropagation();
- const validation = addDomainSchema.safeParse({ name: domain });
- if (!validation.success) {
- return toast.error(validation.error.errors[0].message);
+ const normalizedDomain = sanitizeDomain(domainInput);
+ if (!normalizedDomain || !validDomainRegex.test(normalizedDomain)) {
+ return toast.error("Please enter a valid domain (e.g., example.com).");
+ }
+
+ if (normalizedDomain.includes("papermark")) {
+ return toast.error("Domain cannot contain 'papermark'.");
}
- setLoading(true);
+ if (saveDisabled) {
+ return toast.error(
+ statusMessageOverride ??
+ "Please enter a valid domain before adding.",
+ );
+ }
+
+ setSubmitting(true);
const response = await fetch(
- `/api/teams/${teamInfo?.currentTeam?.id}/domains`,
+ `/api/teams/${teamId}/domains`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
- domain: domain,
+ domain: normalizedDomain,
}),
},
);
if (!response.ok) {
const { message } = await response.json();
- setLoading(false);
- setOpen(false);
+ setSubmitting(false);
toast.error(message);
return;
}
const newDomain = await response.json();
- analytics.capture("Domain Added", { slug: domain });
+ analytics.capture("Domain Added", { slug: normalizedDomain });
toast.success("Domain added successfully! 🎉");
// Update local data with the new link
@@ -99,7 +249,7 @@ export function AddDomainModal({
setOpen(false);
- setLoading(false);
+ setSubmitting(false);
!onAddition && window.open("/settings/domains", "_blank");
};
@@ -149,26 +299,80 @@ export function AddDomainModal({
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild>{children}</DialogTrigger>
- <DialogContent className="sm:max-w-[425px]">
+ <DialogContent className="sm:max-w-[520px]">
<DialogHeader className="text-start">
<DialogTitle>Add Domain</DialogTitle>
<DialogDescription>
- You can easily add a custom domain.
+ Add a custom domain and verify it with DNS.
</DialogDescription>
</DialogHeader>
<form onSubmit={handleSubmit}>
<Label htmlFor="domain" className="opacity-80">
- Domain
+ Your domain
</Label>
- <Input
- id="domain"
- placeholder="docs.yourdomain.com"
- className="mb-8 mt-1 w-full"
- onChange={(e) => setDomain(e.target.value)}
- />
- <DialogFooter>
- <Button type="submit" className="h-9 w-full">
- Add domain
+ <div
+ className={cn(
+ "-m-1 mt-2 rounded-[0.625rem] p-1",
+ STATUS_CONFIG[domainStatus].className ||
+ "bg-neutral-100 text-neutral-500",
+ )}
+ >
+ <div className="flex rounded-md border border-neutral-300 bg-white">
+ <Input
+ id="domain"
+ placeholder="docs.yourdomain.com"
+ className="border-0 bg-transparent shadow-none focus-visible:ring-0 focus-visible:ring-offset-0"
+ value={domainInput}
+ onBlur={() => {
+ const normalized = sanitizeDomain(domainInput);
+ if (normalized && normalized !== domainInput) {
+ setDomainInput(normalized);
+ }
+ }}
+ onChange={(e) => {
+ setDomainStatus("idle");
+ setStatusMessageOverride(null);
+ setDomainInput(e.target.value);
+ }}
+ />
+ </div>
+ <div className="flex items-center justify-between gap-4 p-2 text-sm">
+ <p>
+ {["checking", "conflict", "has site", "available"].includes(
+ domainStatus,
+ ) ? (
+ <>
+ {STATUS_CONFIG[domainStatus].prefix || "The domain"}{" "}
+ {STATUS_CONFIG[domainStatus].useStrong ? (
+ <strong className="font-semibold underline underline-offset-2">
+ {sanitizedDomain || "this domain"}
+ </strong>
+ ) : (
+ <span className="font-semibold underline underline-offset-2">
+ {sanitizedDomain || "this domain"}
+ </span>
+ )}{" "}
+ {STATUS_CONFIG[domainStatus].suffix}
+ </>
+ ) : (
+ statusMessageOverride ||
+ STATUS_CONFIG[domainStatus].message ||
+ "Enter a valid domain to check availability."
+ )}
+ </p>
+ {STATUS_CONFIG[domainStatus].icon && (
+ <STATUS_CONFIG[domainStatus].icon className="h-5 w-5 shrink-0" />
+ )}
+ </div>
+ </div>
+
+ <DialogFooter className="mt-6">
+ <Button
+ type="submit"
+ className="h-9 w-full"
+ disabled={saveDisabled}
+ >
+ {submitting ? "Adding domain..." : "Add domain"}
</Button>
</DialogFooter>
</form>
diff --git a/components/domains/use-domain-status.ts b/components/domains/use-domain-status.ts
index 0a5586da..97043821 100644
--- a/components/domains/use-domain-status.ts
+++ b/components/domains/use-domain-status.ts
@@ -9,19 +9,27 @@ import {
} from "@/lib/types";
import { fetcher } from "@/lib/utils";
-export function useDomainStatus({ domain }: { domain: string }) {
+export function useDomainStatus({
+ domain,
+ enabled = true,
+}: {
+ domain: string;
+ enabled?: boolean;
+}) {
const teamInfo = useTeam();
+ const key =
+ enabled && domain
+ ? `/api/teams/${teamInfo?.currentTeam?.id}/domains/${domain}/verify`
+ : null;
+
const { data, isValidating, mutate } = useSWR<{
status: DomainVerificationStatusProps;
response: {
domainJson: DomainResponse & { error: { code: string; message: string } };
configJson: DomainConfigResponse;
};
- }>(
- `/api/teams/${teamInfo?.currentTeam?.id}/domains/${domain}/verify`,
- fetcher,
- );
+ }>(key, fetcher);
return {
status: data?.status,
diff --git a/pages/api/teams/[teamId]/domains/[domain]/validate.ts b/pages/api/teams/[teamId]/domains/[domain]/validate.ts
new file mode 100644
index 00000000..8c68be2c
--- /dev/null
+++ b/pages/api/teams/[teamId]/domains/[domain]/validate.ts
@@ -0,0 +1,136 @@
+import { NextApiRequest, NextApiResponse } from "next";
+
+import dns from "dns/promises";
+import { getServerSession } from "next-auth/next";
+
+import { validDomainRegex } from "@/lib/domains";
+import { errorhandler } from "@/lib/errorHandler";
+import prisma from "@/lib/prisma";
+import { getTeamWithDomain } from "@/lib/team/helper";
+import { CustomUser } from "@/lib/types";
+
+import { authOptions } from "../../../../auth/[...nextauth]";
+
+type DomainValidationStatus =
+ | "invalid"
+ | "conflict"
+ | "has site"
+ | "available";
+
+const sanitizeDomain = (value: string) =>
+ value
+ .trim()
+ .toLowerCase()
+ .replace(/^(?:https?:\/\/)?(?:www\.)?/i, "")
+ .split("/")[0];
+
+export default async function handle(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method !== "GET") {
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).end(`Method ${req.method} Not Allowed`);
+ }
+
+ const session = await getServerSession(req, res, authOptions);
+ if (!session) {
+ return res.status(401).end("Unauthorized");
+ }
+
+ const { teamId } = req.query as { teamId: string };
+ const rawDomain = Array.isArray(req.query.domain)
+ ? req.query.domain[0]
+ : req.query.domain;
+
+ if (!teamId || !rawDomain) {
+ return res.status(400).json({ status: "invalid" });
+ }
+
+ const userId = (session.user as CustomUser).id;
+
+ try {
+ await getTeamWithDomain({ teamId, userId });
+
+ const sanitizedDomain = sanitizeDomain(rawDomain);
+
+ if (
+ !sanitizedDomain ||
+ !validDomainRegex.test(sanitizedDomain) ||
+ sanitizedDomain.includes("papermark")
+ ) {
+ return res.status(200).json({
+ status: "invalid" as DomainValidationStatus,
+ });
+ }
+
+ const existingDomain = await prisma.domain.findFirst({
+ where: {
+ slug: sanitizedDomain,
+ },
+ select: {
+ id: true,
+ },
+ });
+
+ if (existingDomain) {
+ return res.status(200).json({
+ status: "conflict" as DomainValidationStatus,
+ });
+ }
+
+ const hasSite = await hasSiteConfigured(sanitizedDomain);
+ if (hasSite) {
+ return res.status(200).json({
+ status: "has site" as DomainValidationStatus,
+ });
+ }
+
+ return res.status(200).json({
+ status: "available" as DomainValidationStatus,
+ });
+ } catch (error) {
+ errorhandler(error, res);
+ }
+}
+
+async function hasSiteConfigured(domain: string): Promise<boolean> {
+ try {
+ const urls = [`https://${domain}`, `http://${domain}`];
+
+ for (const url of urls) {
+ try {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 3000);
+ const response = await fetch(url, {
+ method: "HEAD",
+ signal: controller.signal,
+ });
+ clearTimeout(timeoutId);
+ if (response.ok) return true;
+ } catch (error) {
+ if (error instanceof DOMException && error.name === "AbortError") {
+ continue;
+ }
+ continue;
+ }
+ }
+
+ const dnsPromise = dns.resolve(domain);
+ const timeoutPromise = new Promise((_, reject) =>
+ setTimeout(() => reject(new Error("DNS Timeout")), 3000),
+ );
+
+ try {
+ const records = (await Promise.race([
+ dnsPromise,
+ timeoutPromise,
+ ])) as string[];
+ return records.length > 0;
+ } catch (error) {
+ return false;
+ }
+ } catch (error) {
+ return false;
+ }
+}