The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
improved error messaging
Steven Tey5a7a892ac174
diff --git a/components/app/add-project-modal.tsx b/components/app/add-project-modal.tsxindex f22281b8b8..db038414fe 100644--- a/components/app/add-project-modal.tsx+++ b/components/app/add-project-modal.tsx@@ -24,8 +24,8 @@ function AddProjectModalHelper({}) {const router = useRouter();- const [slugExistsError, setSlugExistsError] = useState(false);- const [domainExistsError, setDomainExistsError] = useState(false);+ const [slugError, setSlugError] = useState(null);+ const [domainError, setDomainError] = useState(null);const [saving, setSaving] = useState(false);const [data, setData] = useState<{@@ -45,7 +45,7 @@ function AddProjectModalHelper({fetch(`/api/projects/${slug}/exists`).then(async (res) => {if (res.status === 200) {const exists = await res.json();- setSlugExistsError(exists === 1);+ setSlugError(exists === 1 ? "Slug is already in use." : null);}});}@@ -54,11 +54,11 @@ function AddProjectModalHelper({const [debouncedDomain] = useDebounce(domain, 500);useEffect(() => {if (debouncedDomain.length > 0) {- fetch(`/api/projects/${slug}/domains/${debouncedDomain}/exists`).then(+ fetch(`/api/projects/dub.sh/domains/${debouncedDomain}/exists`).then(async (res) => {if (res.status === 200) {const exists = await res.json();- setDomainExistsError(exists === 1);+ setDomainError(exists === 1 ? "Domain is already in use." : null);}});@@ -105,6 +105,17 @@ function AddProjectModalHelper({if (res.status === 200) {mutate(`/api/projects`);router.push(`/${slug}`);+ } else if (res.status === 422) {+ const {+ slugError: slugErrorResponse,+ domainError: domainErrorResponse,+ } = await res.json();+ if (slugErrorResponse) {+ setSlugError(slugErrorResponse);+ }+ if (domainErrorResponse) {+ setDomainError(domainErrorResponse);+ }} else {console.log(domain, slug); // console log to trigger debounce rerender}@@ -114,7 +125,7 @@ function AddProjectModalHelper({><div><label- htmlFor="key"+ htmlFor="name"className="block text-sm font-medium text-gray-700">Project Name@@ -153,19 +164,19 @@ function AddProjectModalHelper({type="text"requiredclassName={`${- slugExistsError+ slugError? "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-r-md focus:outline-none sm:text-sm`}placeholder="dub"value={slug}onChange={(e) => {- setSlugExistsError(false);+ setSlugError(null);setData({ ...data, slug: e.target.value });}}aria-invalid="true"/>- {slugExistsError && (+ {slugError && (<div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3"><AlertCircleFillclassName="h-5 w-5 text-red-500"@@ -174,9 +185,9 @@ function AddProjectModalHelper({</div>)}</div>- {slugExistsError && (+ {slugError && (<p className="mt-2 text-sm text-red-600" id="slug-error">- Slug is already in use.+ {slugError}</p>)}</div>@@ -195,19 +206,19 @@ function AddProjectModalHelper({type="text"requiredclassName={`${- domainExistsError+ domainError? "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);+ setDomainError(null);setData({ ...data, domain: e.target.value });}}aria-invalid="true"/>- {domainExistsError && (+ {domainError && (<div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3"><AlertCircleFillclassName="h-5 w-5 text-red-500"@@ -216,24 +227,29 @@ function AddProjectModalHelper({</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>- )}+ {domainError &&+ (domainError === "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>+ ) : (+ <p className="mt-2 text-sm text-red-600" id="domain-error">+ {domainError}+ </p>+ ))}</div><button- disabled={saving || slugExistsError || domainExistsError}+ disabled={saving || slugError || domainError}className={`${- saving || slugExistsError || domainExistsError+ saving || slugError || domainError? "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 04ace29c69..f42775378d 100644--- a/components/app/custom-domain/edit-domain-modal.tsx+++ b/components/app/custom-domain/edit-domain-modal.tsx@@ -26,19 +26,18 @@ function EditDomainModalHelper({const router = useRouter();const { slug } = router.query;const [saving, setSaving] = useState(false);- const [domainExistsError, setDomainExistsError] = useState(false);+ const [domainError, setDomainError] = useState(null);const [data, setData] = useState(domain);const [debouncedDomain] = useDebounce(data, 500);useEffect(() => {if (debouncedDomain.length > 0 && debouncedDomain !== domain) {- 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);+ setDomainError(exists === 1 ? "Domain is already in use." : null);}});@@ -76,13 +75,19 @@ function EditDomainModalHelper({"Content-Type": "application/json",},body: JSON.stringify(data),- }).then((res) => {+ }).then(async (res) => {setSaving(false);+ console.log("status is ", res.status);if (res.status === 200) {mutate(`/api/projects/${slug}`);setShowEditDomainModal(false);+ } else if (res.status === 422) {+ const { domainError: domainErrorResponse } = await res.json();+ if (domainErrorResponse) {+ setDomainError(domainErrorResponse);+ }} else if (res.status === 400) {- setDomainExistsError(true);+ setDomainError("Domain is already in use.");}});}}@@ -103,20 +108,20 @@ function EditDomainModalHelper({requiredautoFocus={false}className={`${- domainExistsError+ domainError? "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="github"value={data}onChange={(e) => {- setDomainExistsError(false);+ setDomainError(null);setData(e.target.value);}}aria-invalid="true"aria-describedby="key-error"/>- {domainExistsError && (+ {domainError && (<div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3"><AlertCircleFillclassName="h-5 w-5 text-red-500"@@ -125,18 +130,23 @@ function EditDomainModalHelper({</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>- )}+ {domainError &&+ (domainError === "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>+ ) : (+ <p className="mt-2 text-sm text-red-600" id="domain-error">+ {domainError}+ </p>+ ))}</div><div>@@ -161,9 +171,9 @@ function EditDomainModalHelper({</div><button- disabled={saving || domainExistsError}+ disabled={saving || domainError}className={`${- saving || domainExistsError+ saving || domainError? "cursor-not-allowed bg-gray-100 border-gray-200 text-gray-400": "bg-red-600 hover:bg-white hover:text-red-600 border-red-600 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/plan-usage.tsx b/components/app/plan-usage.tsxindex 971d7eafc5..4b640aca7e 100644--- a/components/app/plan-usage.tsx+++ b/components/app/plan-usage.tsx@@ -55,7 +55,7 @@ export default function PlanUsage({ project }: { project: ProjectProps }) {{typeof usage === "number" ? (<p className="text-sm text-gray-600">{nFormatter(usage)} / {nFormatter(project.usageLimit)} clicks (- {(usage / project.usageLimit) * 100}%)+ {((usage / project.usageLimit) * 100).toFixed(1)}%)</p>) : (<div className="h-5 w-32 bg-gray-200 rounded-md animate-pulse" />diff --git a/lib/upstash.ts b/lib/upstash.tsindex 8eb62d6a2b..858b453c2d 100644--- a/lib/upstash.ts+++ b/lib/upstash.ts@@ -255,5 +255,9 @@ export async function changeDomain(hostname: string, newHostname: string) {`${newHostname}:clicks:${key}`);});- return await pipeline.exec();+ try {+ return await pipeline.exec();+ } catch (e) {+ return null;+ }}diff --git a/pages/api/projects/[slug]/domains/[domain]/index.ts b/pages/api/projects/[slug]/domains/[domain]/index.tsindex 5edb9113bf..92ecfa5d77 100644--- a/pages/api/projects/[slug]/domains/[domain]/index.ts+++ b/pages/api/projects/[slug]/domains/[domain]/index.ts@@ -9,6 +9,15 @@ export default withProjectAuth(const { slug, domain } = req.query as { slug: string; domain: string }; // slug is the domainconst newDomain = req.body;+ const domainError = newDomain.includes(" ")+ ? "Domain cannot contain spaces"+ : null;+ if (domainError) {+ return res.status(422).json({+ domainError,+ });+ }+if (domain !== newDomain) {// make sure domain doesn't existconst project = await prisma.project.findUnique({@@ -17,45 +26,49 @@ export default withProjectAuth(},select: { slug: true },});- if (project?.slug !== slug) {+ if (project && 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}`,- {- headers: {- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,+ const [removeResponse, addResponse, upstashResponse, prismaResponse] =+ await Promise.all([+ fetch(+ `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${domain}?teamId=${process.env.VERCEL_TEAM_ID}`,+ {+ headers: {+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,+ },+ method: "DELETE",+ }+ ),+ fetch(+ `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains?teamId=${process.env.VERCEL_TEAM_ID}`,+ {+ body: `{\n "name": "${newDomain}"\n}`,+ headers: {+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,+ "Content-Type": "application/json",+ },+ method: "POST",+ }+ ),+ changeDomain(domain, newDomain),+ prisma.project.update({+ where: {+ slug,},- method: "DELETE",- }- ),- fetch(- `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains?teamId=${process.env.VERCEL_TEAM_ID}`,- {- body: `{\n "name": "${newDomain}"\n}`,- headers: {- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,- "Content-Type": "application/json",+ data: {+ domain: newDomain,+ domainVerified: false,},- method: "POST",- }- ),- ]);+ }),+ ]);- const upstashResponse = await changeDomain(domain, newDomain);-- const response = await prisma.project.update({- where: {- slug,- },- data: {- domain: newDomain,- domainVerified: false,- },+ return res.status(200).json({+ removeResponse,+ addResponse,+ upstashResponse,+ prismaResponse,});-- return res.status(200).json({ removeResponse, addResponse, response });}return res.status(200).json({ message: "Domains are the same" });} else {diff --git a/pages/api/projects/index.ts b/pages/api/projects/index.tsindex db471e1d1f..d271d1f04d 100644--- a/pages/api/projects/index.ts+++ b/pages/api/projects/index.ts@@ -1,7 +1,6 @@import { NextApiRequest, NextApiResponse } from "next";import { getSession } from "@/lib/auth";import prisma from "@/lib/prisma";-import { stripe } from "@/lib/stripe";export default async function handler(req: NextApiRequest,@@ -27,9 +26,21 @@ export default async function handler(} else if (req.method === "POST") {const { name, slug, domain } = req.body;if (!name || !slug || !domain) {- return res.status(400).json({ error: "Missing name or slug or domain" });+ return res.status(422).json({ error: "Missing name or slug or domain" });+ }+ const slugError =+ slug.includes(" ") || slug.includes(".")+ ? "Slug cannot contain spaces or periods"+ : null;+ const domainError = domain.includes(" ")+ ? "Domain cannot contain spaces"+ : null;+ if (slugError || domainError) {+ return res.status(422).json({+ slugError,+ domainError,+ });}-try {const project = await prisma.project.create({data: {@@ -45,31 +56,17 @@ export default async function handler(},});if (project) {- const [domainResponse, stripeResponse] = await Promise.all([- fetch(- `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains?teamId=${process.env.VERCEL_TEAM_ID}`,- {- body: `{\n "name": "${project.domain}"\n}`,- headers: {- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,- "Content-Type": "application/json",- },- method: "POST",- }- ).then((res) => res.json()),- stripe.customers.create({- name,- email: session.user.email,- }),- ]);- await prisma.project.update({- where: {- id: project.id,- },- data: {- stripeId: stripeResponse.id,- },- });+ const domainResponse = await fetch(+ `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains?teamId=${process.env.VERCEL_TEAM_ID}`,+ {+ body: `{\n "name": "${project.domain}"\n}`,+ headers: {+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,+ "Content-Type": "application/json",+ },+ method: "POST",+ }+ ).then((res) => res.json());return res.status(200).json({ project, domain: domainResponse });}return res.status(400).json({ error: "Project not created" });