The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Made domain a unique field
Steven Tey26d4a433ebb9
diff --git a/components/app/add-project-modal.tsx b/components/app/add-project-modal.tsxindex 906c3c5e00..f22281b8b8 100644--- a/components/app/add-project-modal.tsx+++ b/components/app/add-project-modal.tsx@@ -5,6 +5,7 @@ import {useMemo,useState,Dispatch,+ FormEvent,SetStateAction,} from "react";import { useRouter } from "next/router";@@ -24,6 +25,7 @@ function AddProjectModalHelper({const router = useRouter();const [slugExistsError, setSlugExistsError] = useState(false);+ const [domainExistsError, setDomainExistsError] = useState(false);const [saving, setSaving] = useState(false);const [data, setData] = useState<{@@ -49,6 +51,20 @@ function AddProjectModalHelper({}}, [debouncedSlug]);+ const [debouncedDomain] = useDebounce(domain, 500);+ useEffect(() => {+ if (debouncedDomain.length > 0) {+ fetch(`/api/projects/${slug}/domains/${debouncedDomain}/exists`).then(+ async (res) => {+ if (res.status === 200) {+ const exists = await res.json();+ setDomainExistsError(exists === 1);+ }+ }+ );+ }+ }, [debouncedDomain]);+useEffect(() => {setData((prev) => ({...prev,@@ -75,7 +91,7 @@ function AddProjectModalHelper({</div><form- onSubmit={async (e) => {+ onSubmit={async (e: FormEvent<HTMLFormElement>) => {e.preventDefault();setSaving(true);fetch(`/api/projects`, {@@ -84,18 +100,15 @@ function AddProjectModalHelper({"Content-Type": "application/json",},body: JSON.stringify(data),- })- .then((res) => {- setSaving(false);- if (res.status === 200) {- mutate(`/api/projects`);- router.push(`/${slug}`);- }- })- .catch(() => {- setSaving(false);- setSlugExistsError(true);- });+ }).then(async (res) => {+ setSaving(false);+ if (res.status === 200) {+ mutate(`/api/projects`);+ router.push(`/${slug}`);+ } else {+ console.log(domain, slug); // console log to trigger debounce rerender+ }+ });}}className="flex flex-col space-y-6 text-left bg-gray-50 sm:px-16 px-4 py-8">@@ -131,6 +144,9 @@ function AddProjectModalHelper({Project Slug</label><div className="relative flex mt-1 rounded-md shadow-sm">+ <span className="inline-flex items-center rounded-l-md border border-r-0 border-gray-300 bg-gray-50 px-5 text-gray-500 sm:text-sm">+ app.dub.sh+ </span><inputname="slug"id="slug"@@ -140,7 +156,7 @@ function AddProjectModalHelper({slugExistsError? "border-red-300 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500": "border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:ring-gray-500"- } pr-10 block w-full rounded-md focus:outline-none sm:text-sm`}+ } pr-10 block w-full rounded-r-md focus:outline-none sm:text-sm`}placeholder="dub"value={slug}onChange={(e) => {@@ -172,27 +188,52 @@ function AddProjectModalHelper({>Domain</label>- <div className="flex mt-1 rounded-md shadow-sm">+ <div className="relative flex mt-1 rounded-md shadow-sm"><inputname="domain"id="domain"type="text"required- className="border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:ring-gray-500 block w-full rounded-md focus:outline-none sm:text-sm"+ className={`${+ domainExistsError+ ? "border-red-300 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500"+ : "border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:ring-gray-500"+ } pr-10 block w-full rounded-md focus:outline-none sm:text-sm`}placeholder="dub.sh"value={domain}onChange={(e) => {+ setDomainExistsError(false);setData({ ...data, domain: e.target.value });}}aria-invalid="true"/>+ {domainExistsError && (+ <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">+ <AlertCircleFill+ className="h-5 w-5 text-red-500"+ aria-hidden="true"+ />+ </div>+ )}</div>+ {domainExistsError && (+ <p className="mt-2 text-sm text-red-600" id="domain-error">+ Domain is already in use.{" "}+ <a+ className="underline"+ href="mailto:[email protected]?subject=My Domain Is Already In Use"+ >+ Contact us+ </a>{" "}+ if you'd like to use this domain for your project.+ </p>+ )}</div><button- disabled={saving || slugExistsError}+ disabled={saving || slugExistsError || domainExistsError}className={`${- saving || slugExistsError+ saving || slugExistsError || domainExistsError? "cursor-not-allowed bg-gray-100 border-gray-200 text-gray-400": "bg-black hover:bg-white hover:text-black border-black text-white"} flex justify-center items-center w-full text-sm h-10 rounded-md border transition-all focus:outline-none`}diff --git a/components/app/custom-domain/edit-domain-modal.tsx b/components/app/custom-domain/edit-domain-modal.tsxindex 85582ba340..593d4e3b7e 100644--- a/components/app/custom-domain/edit-domain-modal.tsx+++ b/components/app/custom-domain/edit-domain-modal.tsx@@ -26,19 +26,22 @@ function EditDomainModalHelper({const router = useRouter();const { slug } = router.query;const [saving, setSaving] = useState(false);- const [domainExistsError, setdomainExistsError] = useState(false);+ const [domainExistsError, setDomainExistsError] = useState(false);const [data, setData] = useState(domain);- const [debouncedDomain] = useDebounce(domain, 1000);+ const [debouncedDomain] = useDebounce(data, 500);useEffect(() => {if (debouncedDomain.length > 0 && debouncedDomain !== domain) {- fetch(`/api/domains/${debouncedDomain}/exists`).then(async (res) => {- if (res.status === 200) {- const exists = await res.json();- setdomainExistsError(exists === 1);+ console.log("checking domain");+ fetch(`/api/projects/${slug}/domains/${debouncedDomain}/exists`).then(+ async (res) => {+ if (res.status === 200) {+ const exists = await res.json();+ setDomainExistsError(exists === 1);+ }}- });+ );}}, [debouncedDomain]);@@ -78,6 +81,8 @@ function EditDomainModalHelper({if (res.status === 200) {mutate(`/api/projects/${slug}`);setShowEditDomainModal(false);+ } else if (res.status === 400) {+ setDomainExistsError(true);}});}}@@ -105,7 +110,7 @@ function EditDomainModalHelper({placeholder="github"value={data}onChange={(e) => {- setdomainExistsError(false);+ setDomainExistsError(false);setData(e.target.value);}}aria-invalid="true"@@ -121,8 +126,15 @@ function EditDomainModalHelper({)}</div>{domainExistsError && (- <p className="mt-2 text-sm text-red-600" id="key-error">- Domain is already in use.+ <p className="mt-2 text-sm text-red-600" id="domain-error">+ Domain is already in use.{" "}+ <a+ className="underline"+ href="mailto:[email protected]?subject=My Domain Is Already In Use"+ >+ Contact us+ </a>{" "}+ if you'd like to use this domain for your project.</p>)}</div>diff --git a/pages/api/projects/[slug]/domains/[domain]/exists.ts b/pages/api/projects/[slug]/domains/[domain]/exists.tsnew file mode 100644index 0000000000..04ca90bca0--- /dev/null+++ b/pages/api/projects/[slug]/domains/[domain]/exists.ts@@ -0,0 +1,33 @@+import { NextApiRequest, NextApiResponse } from "next";+import { getSession } from "@/lib/auth";+import prisma from "@/lib/prisma";++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse+) {+ const session = await getSession(req, res);+ if (!session?.user.id) return res.status(401).end("Unauthorized");++ const { domain } = req.query as { domain: string };++ // GET /api/projects/dub/domains/[domain]/exists – check if a domain exists (using `dub` as the default project slug)+ if (req.method === "GET") {+ const project = await prisma.project.findUnique({+ where: {+ domain,+ },+ select: {+ domain: true,+ },+ });+ if (project) {+ return res.status(200).json(1);+ } else {+ return res.status(200).json(0);+ }+ } else {+ res.setHeader("Allow", ["GET"]);+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });+ }+}diff --git a/pages/api/projects/[slug]/domains/[domain]/index.ts b/pages/api/projects/[slug]/domains/[domain]/index.tsindex 31771ba015..95387fd97d 100644--- a/pages/api/projects/[slug]/domains/[domain]/index.ts+++ b/pages/api/projects/[slug]/domains/[domain]/index.ts@@ -9,6 +9,16 @@ export default withProjectAuth(const newDomain = req.body;if (domain !== newDomain) {+ // make sure domain doesn't exist+ const project = await prisma.project.findUnique({+ where: {+ domain: newDomain,+ },+ select: { slug: true },+ });+ if (project?.slug !== slug) {+ return res.status(400).json({ error: "Domain already exists" });+ }const [removeResponse, addResponse] = await Promise.all([fetch(`https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${domain}?teamId=${process.env.VERCEL_TEAM_ID}`,diff --git a/pages/api/projects/[slug]/exists.ts b/pages/api/projects/[slug]/exists.tsindex 74e1d6ab4d..e2c252c550 100644--- a/pages/api/projects/[slug]/exists.ts+++ b/pages/api/projects/[slug]/exists.ts@@ -17,6 +17,9 @@ export default async function handler(where: {slug,},+ select: {+ slug: true,+ },});if (project) {return res.status(200).json(1);diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex 9df66933e2..71e127c4b0 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -62,7 +62,7 @@ model Project {id String @id @default(cuid())name Stringslug String @unique- domain String+ domain String @uniquedomainVerified Boolean @default(false)plan String @default("free")usageLimit Int @default(1000)