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.

refactored API structure + started work on adding domains

Steven Teye3d1fda219d6
diff --git a/.gitignore b/.gitignore
index 4a7ab0cc67..bd89748b03 100644
--- a/.gitignore
+++ b/.gitignore
@@ -36,4 +36,4 @@ yarn-error.log*
*.tsbuildinfo
next-env.d.ts
-/pages/api/test.ts
\ No newline at end of file
+/pages/api/scripts*
\ No newline at end of file
diff --git a/components/app/add-modal.tsx b/components/app/add-link-modal.tsx
similarity index 81%
rename from components/app/add-modal.tsx
rename to components/app/add-link-modal.tsx
index d487415313..cf75cfdd6f 100644
--- a/components/app/add-modal.tsx
+++ b/components/app/add-link-modal.tsx
@@ -7,6 +7,7 @@ import {
Dispatch,
SetStateAction,
} from "react";
+import { useRouter } from "next/router";
import BlurImage from "@/components/shared/blur-image";
import { LinkProps } from "@/lib/types";
import {
@@ -18,19 +19,22 @@ import { useDebounce } from "use-debounce";
import TextareaAutosize from "react-textarea-autosize";
import { mutate } from "swr";
-function AddModalHelper({
- showAddModal,
- setShowAddModal,
- slug, // project domain
+function AddLinkModalHelper({
+ showAddLinkModal,
+ setShowAddLinkModal,
+ domain,
}: {
- showAddModal: boolean;
- setShowAddModal: Dispatch<SetStateAction<boolean>>;
- slug?: string;
+ showAddLinkModal: boolean;
+ setShowAddLinkModal: Dispatch<SetStateAction<boolean>>;
+ domain?: string;
}) {
+ const router = useRouter();
+ const { slug } = router.query as { slug: string };
+
const [keyExistsError, setKeyExistsError] = useState(false);
const [generatingSlug, setGeneratingSlug] = useState(false);
const [generatingTitle, setGeneratingTitle] = useState(false);
- const [buttonText, setButtonText] = useState("Save changes");
+ const [buttonText, setButtonText] = useState("Add link");
const [saving, setSaving] = useState(false);
const [data, setData] = useState<LinkProps>({
@@ -45,8 +49,8 @@ function AddModalHelper({
useEffect(() => {
if (debouncedKey.length > 0) {
fetch(
- slug
- ? `/api/projects/${slug}/links/${debouncedKey}/exists`
+ domain
+ ? `/api/projects/${slug}/domains/${domain}/links/${debouncedKey}/exists`
: `/api/edge/links/${debouncedKey}/exists`
).then(async (res) => {
if (res.status === 200) {
@@ -60,7 +64,9 @@ function AddModalHelper({
const generateRandomSlug = useCallback(async () => {
setGeneratingSlug(true);
const res = await fetch(
- slug ? `/api/projects/${slug}/links/random` : `/api/edge/links/random`
+ domain
+ ? `/api/projects/${slug}/domains/${domain}/links/random`
+ : `/api/edge/links/random`
);
const key = await res.json();
setData((prev) => ({ ...prev, key }));
@@ -90,7 +96,7 @@ function AddModalHelper({
);
return (
- <Modal showModal={showAddModal} setShowModal={setShowAddModal}>
+ <Modal showModal={showAddLinkModal} setShowModal={setShowAddLinkModal}>
<div className="inline-block w-full max-w-md overflow-hidden align-middle transition-all transform bg-white shadow-xl rounded-2xl">
<div className="flex flex-col justify-center items-center space-y-3 sm:px-16 px-4 pt-8 py-4 border-b border-gray-200">
<BlurImage
@@ -107,27 +113,32 @@ function AddModalHelper({
onSubmit={async (e) => {
e.preventDefault();
setSaving(true);
- fetch(slug ? `/api/projects/${slug}/links` : `/api/links`, {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(data),
- })
+ fetch(
+ domain
+ ? `/api/projects/${slug}/domains/${domain}/links`
+ : `/api/links`,
+ {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(data),
+ }
+ )
.then((res) => {
setSaving(false);
if (res.status === 200) {
setButtonText("Saved!");
- mutate(slug ? `/api/projects/${slug}` : `/api/links`);
+ mutate(domain ? `/api/projects/${slug}` : `/api/links`);
setTimeout(() => {
- setButtonText("Save changes");
+ setButtonText("Add link");
});
- setShowAddModal(false);
+ setShowAddLinkModal(false);
}
})
.catch(() => {
setSaving(false);
- setButtonText("Save changes");
+ setButtonText("Add link");
setKeyExistsError(true);
});
}}
@@ -142,7 +153,7 @@ function AddModalHelper({
Short Link
</label>
<button
- className="hover:text-black active:scale-95 flex items-center text-gray-500 text-sm transition-all duration-75"
+ className="hover:text-black active:scale-95 flex items-center space-x-2 text-gray-500 text-sm transition-all duration-75"
onClick={generateRandomSlug}
disabled={generatingSlug}
type="button"
@@ -153,7 +164,7 @@ function AddModalHelper({
</div>
<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">
- {slug || "dub.sh"}
+ {domain || "dub.sh"}/
</span>
<input
type="text"
@@ -228,7 +239,7 @@ function AddModalHelper({
url.length === 0
? "cursor-not-allowed text-gray-300"
: "hover:text-black active:scale-95"
- } flex items-center text-gray-500 text-sm transition-all duration-75`}
+ } flex items-center space-x-2 text-gray-500 text-sm transition-all duration-75`}
onClick={() => generateTitleFromUrl(url)}
disabled={url.length === 0 || generatingTitle}
type="button"
@@ -270,21 +281,21 @@ function AddModalHelper({
);
}
-export function useAddModal({ slug }: { slug?: string }) {
- const [showAddModal, setShowAddModal] = useState(false);
+export function useAddLinkModal({ domain }: { domain?: string }) {
+ const [showAddLinkModal, setShowAddLinkModal] = useState(false);
- const AddModal = useCallback(() => {
+ const AddLinkModal = useCallback(() => {
return (
- <AddModalHelper
- showAddModal={showAddModal}
- setShowAddModal={setShowAddModal}
- slug={slug}
+ <AddLinkModalHelper
+ showAddLinkModal={showAddLinkModal}
+ setShowAddLinkModal={setShowAddLinkModal}
+ domain={domain}
/>
);
- }, [showAddModal, setShowAddModal, slug]);
+ }, [showAddLinkModal, setShowAddLinkModal, domain]);
return useMemo(
- () => ({ setShowAddModal, AddModal }),
- [setShowAddModal, AddModal]
+ () => ({ setShowAddLinkModal, AddLinkModal }),
+ [setShowAddLinkModal, AddLinkModal]
);
}
diff --git a/components/app/custom-domain/configurations-placeholder.tsx b/components/app/custom-domain/configurations-placeholder.tsx
new file mode 100644
index 0000000000..c8cc7aef9a
--- /dev/null
+++ b/components/app/custom-domain/configurations-placeholder.tsx
@@ -0,0 +1,10 @@
+const ConfigurationsPlaceholder = () => {
+ return (
+ <div className="flex items-center space-x-3 mt-3 px-2 sm:px-10">
+ <div className="w-6 h-6 rounded-full bg-gray-300 animate-pulse" />
+ <p className="text-gray-500 font-normal text-sm">Loading Configuration</p>
+ </div>
+ );
+};
+
+export default ConfigurationsPlaceholder;
diff --git a/components/app/custom-domain/configurations.tsx b/components/app/custom-domain/configurations.tsx
new file mode 100644
index 0000000000..e95ffd2000
--- /dev/null
+++ b/components/app/custom-domain/configurations.tsx
@@ -0,0 +1,202 @@
+import { useState } from "react";
+import ConfigurationsPlaceholder from "./configurations-placeholder";
+
+function getVerificationError(verificationResponse) {
+ try {
+ const error = verificationResponse.error;
+ if (error.code === "missing_txt_record") {
+ return null;
+ }
+ return error.message;
+ } catch {
+ return null;
+ }
+}
+
+const Configurations = ({ data }) => {
+ const [recordType, setRecordType] = useState("CNAME");
+ if (!data) {
+ return <ConfigurationsPlaceholder />;
+ }
+
+ if (!data.verified) {
+ const txtVerification = data.verification.find((x) => x.type === "TXT");
+ return (
+ <>
+ <div className="flex items-center space-x-3 my-3 px-2 sm:px-10">
+ <svg
+ viewBox="0 0 24 24"
+ width="24"
+ height="24"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ shapeRendering="geometricPrecision"
+ >
+ <circle cx="12" cy="12" r="10" fill="#d32f2f" />
+ <>
+ <path d="M15 9l-6 6" stroke="white" />
+ <path d="M9 9l6 6" stroke="white" />
+ </>
+ </svg>
+ <p className={`text-red-700 font-medium text-sm`}>
+ Domain is pending verification
+ </p>
+ </div>
+
+ <div className="w-full border-t border-gray-100 mt-5 mb-8" />
+
+ <div className="px-2 sm:px-10">
+ <div className="flex justify-start space-x-4">
+ <div
+ onClick={() => setRecordType("CNAME")}
+ className={`${
+ recordType == "CNAME"
+ ? "text-black border-black"
+ : "text-gray-400 border-white"
+ } text-sm border-b-2 pb-1 transition-all ease duration-150`}
+ >
+ Verify Domain Ownership
+ </div>
+ </div>
+ <div className="my-3 text-left">
+ <p className="my-5 text-sm">
+ Please set the following TXT record on {data.apexName} to prove
+ ownership of {data.name}:
+ </p>
+ <div className="flex justify-start items-start space-x-10 bg-gray-50 p-2 rounded-md">
+ <div>
+ <p className="text-sm font-bold">Type</p>
+ <p className="text-sm font-mono mt-2">{txtVerification.type}</p>
+ </div>
+ <div>
+ <p className="text-sm font-bold">Name</p>
+ <p className="text-sm font-mono mt-2">
+ {txtVerification.domain.slice(
+ 0,
+ txtVerification.domain.length - data.apexName.length - 1
+ )}
+ </p>
+ </div>
+ <div>
+ <p className="text-sm font-bold">Value</p>
+ <p className="text-sm font-mono mt-2">
+ <span className="text-ellipsis">{txtVerification.value}</span>
+ </p>
+ </div>
+ </div>
+ {getVerificationError(data.verificationResponse) && (
+ <p className="my-5 text-sm text-red-700">
+ {getVerificationError(data.verificationResponse)}
+ </p>
+ )}
+ </div>
+ </div>
+ </>
+ );
+ }
+
+ return (
+ <>
+ <div className="flex items-center space-x-3">
+ <svg
+ viewBox="0 0 24 24"
+ width="24"
+ height="24"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ shapeRendering="geometricPrecision"
+ >
+ <circle
+ cx="12"
+ cy="12"
+ r="10"
+ fill={data.configured ? "#1976d2" : "#d32f2f"}
+ />
+ {data.configured ? (
+ <>
+ <path
+ d="M8 11.8571L10.5 14.3572L15.8572 9"
+ fill="none"
+ stroke="white"
+ />
+ </>
+ ) : (
+ <>
+ <path d="M15 9l-6 6" stroke="white" />
+ <path d="M9 9l6 6" stroke="white" />
+ </>
+ )}
+ </svg>
+ <p
+ className={`${
+ data.configured
+ ? "text-black font-normal"
+ : "text-red-700 font-medium"
+ } text-sm`}
+ >
+ {data.configured ? "Valid" : "Invalid"} Configuration
+ </p>
+ </div>
+
+ {!data.configured && (
+ <>
+ <div className="w-full border-t border-gray-100 mt-5 mb-8" />
+
+ <div className="px-2 sm:px-10">
+ <div className="flex justify-start space-x-4">
+ <button
+ onClick={() => setRecordType("CNAME")}
+ className={`${
+ recordType == "CNAME"
+ ? "text-black border-black"
+ : "text-gray-400 border-white"
+ } text-sm border-b-2 pb-1 transition-all ease duration-150`}
+ >
+ CNAME Record (subdomains)
+ </button>
+ <button
+ onClick={() => setRecordType("A")}
+ className={`${
+ recordType == "A"
+ ? "text-black border-black"
+ : "text-gray-400 border-white"
+ } text-sm border-b-2 pb-1 transition-all ease duration-150`}
+ >
+ A Record (apex domain)
+ </button>
+ </div>
+ <div className="my-3 text-left">
+ <p className="my-5 text-sm">
+ Set the following record on your DNS provider to continue:
+ </p>
+ <div className="flex justify-start items-center space-x-10 bg-gray-50 p-2 rounded-md">
+ <div>
+ <p className="text-sm font-bold">Type</p>
+ <p className="text-sm font-mono mt-2">{recordType}</p>
+ </div>
+ <div>
+ <p className="text-sm font-bold">Name</p>
+ <p className="text-sm font-mono mt-2">
+ {recordType == "CNAME" ? "www" : "@"}
+ </p>
+ </div>
+ <div>
+ <p className="text-sm font-bold">Value</p>
+ <p className="text-sm font-mono mt-2">
+ {recordType == "CNAME"
+ ? `cname.platformize.co`
+ : `76.76.21.21`}
+ </p>
+ </div>
+ </div>
+ </div>
+ </div>
+ </>
+ )}
+ </>
+ );
+};
+
+export default Configurations;
diff --git a/components/app/custom-domain/edit-domain-modal.tsx b/components/app/custom-domain/edit-domain-modal.tsx
new file mode 100644
index 0000000000..e0b03d116e
--- /dev/null
+++ b/components/app/custom-domain/edit-domain-modal.tsx
@@ -0,0 +1,167 @@
+import Modal from "@/components/shared/modal";
+import {
+ useCallback,
+ useEffect,
+ useMemo,
+ useState,
+ Dispatch,
+ SetStateAction,
+} from "react";
+import { useRouter } from "next/router";
+import BlurImage from "@/components/shared/blur-image";
+import LoadingDots from "@/components/shared/icons/loading-dots";
+import { AlertCircleFill } from "@/components/shared/icons";
+import { useDebounce } from "use-debounce";
+import { mutate } from "swr";
+
+function EditDomainModalHelper({
+ showEditDomainModal,
+ setShowEditDomainModal,
+ domain,
+}: {
+ showEditDomainModal: boolean;
+ setShowEditDomainModal: Dispatch<SetStateAction<boolean>>;
+ domain: string;
+}) {
+ const router = useRouter();
+ const { slug } = router.query;
+ const [saving, setSaving] = useState(false);
+ const [buttonText, setButtonText] = useState("Confirm domain change");
+ const [domainExistsError, setdomainExistsError] = useState(false);
+
+ const [data, setData] = useState(domain);
+ const [debouncedDomain] = useDebounce(domain, 1000);
+
+ 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);
+ }
+ });
+ }
+ }, [debouncedDomain]);
+
+ return (
+ <Modal
+ showModal={showEditDomainModal}
+ setShowModal={setShowEditDomainModal}
+ >
+ <div className="inline-block w-full max-w-md overflow-hidden align-middle transition-all transform bg-white shadow-xl rounded-2xl">
+ <div className="flex flex-col justify-center items-center space-y-3 sm:px-16 px-4 pt-8 py-4 border-b border-gray-200">
+ <BlurImage
+ src={`https://logo.clearbit.com/${domain}`}
+ alt={domain}
+ className="w-10 h-10 rounded-full border border-gray-200 dark:border-gray-600"
+ width={20}
+ height={20}
+ />
+ <h3 className="font-medium text-lg">Change Domain</h3>
+ <p className="text-sm text-gray-500">
+ Warning: Changing your project's domain will break all existing
+ short links.
+ </p>
+ </div>
+
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ setSaving(true);
+ fetch(`/api/projects/${slug}/domains`, {
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(data),
+ }).then((res) => {
+ setSaving(false);
+ if (res.status === 200) {
+ setButtonText("Saved!");
+ mutate(`/api/projects/${slug}`);
+ setTimeout(() => {
+ setButtonText("Save changes");
+ });
+ }
+ });
+ }}
+ className="flex flex-col space-y-6 text-left bg-gray-50 sm:px-16 px-4 py-8"
+ >
+ <div>
+ <label
+ htmlFor="key"
+ className="block text-sm font-medium text-gray-700"
+ >
+ Domain
+ </label>
+ <div className="relative mt-1 rounded-md shadow-sm">
+ <input
+ type="text"
+ name="key"
+ id="key"
+ required
+ autoFocus={false}
+ 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="github"
+ value={data}
+ onChange={(e) => {
+ setdomainExistsError(false);
+ setData(e.target.value);
+ }}
+ aria-invalid="true"
+ aria-describedby="key-error"
+ />
+ {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="key-error">
+ Domain is already in use.
+ </p>
+ )}
+ </div>
+
+ <button
+ disabled={saving || domainExistsError}
+ className={`${
+ saving || domainExistsError
+ ? "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`}
+ >
+ {saving ? <LoadingDots color="#808080" /> : <p>{buttonText}</p>}
+ </button>
+ </form>
+ </div>
+ </Modal>
+ );
+}
+
+export function useEditDomainModal({ domain }: { domain: string }) {
+ const [showEditDomainModal, setShowEditDomainModal] = useState(false);
+
+ const EditDomainModal = useCallback(() => {
+ return (
+ <EditDomainModalHelper
+ showEditDomainModal={showEditDomainModal}
+ setShowEditDomainModal={setShowEditDomainModal}
+ domain={domain}
+ />
+ );
+ }, [showEditDomainModal, setShowEditDomainModal, domain]);
+
+ return useMemo(
+ () => ({ setShowEditDomainModal, EditDomainModal }),
+ [setShowEditDomainModal, EditDomainModal]
+ );
+}
diff --git a/components/app/custom-domain/index.tsx b/components/app/custom-domain/index.tsx
new file mode 100644
index 0000000000..2b2b1a036f
--- /dev/null
+++ b/components/app/custom-domain/index.tsx
@@ -0,0 +1,112 @@
+import useSWR, { mutate } from "swr";
+import { fetcher } from "@/lib/utils";
+import { useRouter } from "next/router";
+import {
+ AlertCircleFill,
+ CheckCircleFill,
+ ExternalLink,
+ LoadingCircle,
+ LoadingDots,
+ XCircleFill,
+} from "@/components/shared/icons";
+import { useEditDomainModal } from "./edit-domain-modal";
+
+interface DomainResponse {
+ status:
+ | "Valid Configuration"
+ | "Invalid Configuration"
+ | "Pending Verification"
+ | "Domain Not Found";
+}
+
+export default function CustomDomain({ domain }: { domain: string }) {
+ const router = useRouter();
+ const { slug } = router.query as { slug: string };
+
+ const { data, isValidating } = useSWR<DomainResponse>(
+ `/api/projects/${slug}/domains/${domain}/verify`,
+ fetcher,
+ { revalidateOnMount: true, refreshInterval: 5000 }
+ );
+
+ const { setShowEditDomainModal, EditDomainModal } = useEditDomainModal({
+ domain,
+ });
+
+ return (
+ <div className="bg-white rounded-lg border border-gray-200 py-10">
+ {domain && <EditDomainModal />}
+ <div className="flex flex-col space-y-3 px-10">
+ <h2 className="text-xl font-medium">Custom Domain</h2>
+ <p className="text-gray-500 text-sm">
+ This is the custom domain associated with your project.
+ </p>
+ </div>
+ <div className="border-b border-gray-200 my-8" />
+ <div className="flex flex-col space-y-3 px-10">
+ <div className="flex justify-between space-x-4">
+ {domain ? (
+ <a
+ href={`http://${domain}`}
+ target="_blank"
+ rel="noreferrer"
+ className="flex items-center space-x-2"
+ >
+ <p className="text-xl font-semibold flex items-center">
+ {domain}
+ </p>
+ <ExternalLink className="w-5 h-5" />
+ </a>
+ ) : (
+ <div className="h-8 w-32 bg-gray-200 rounded-md animate-pulse" />
+ )}
+ <div className="flex space-x-3">
+ {domain ? (
+ <button
+ onClick={() => {
+ mutate(`/api/projects/${slug}/domains/${domain}/verify`);
+ }}
+ disabled={isValidating}
+ className={`${
+ isValidating
+ ? "cursor-not-allowed bg-gray-100"
+ : "bg-white hover:text-black hover:border-black"
+ } text-gray-500 border-gray-200 h-9 w-24 text-sm border-solid border rounded-md focus:outline-none transition-all ease-in-out duration-150`}
+ >
+ {isValidating ? <LoadingDots /> : "Refresh"}
+ </button>
+ ) : (
+ <div className="h-9 w-24 bg-gray-200 rounded-md animate-pulse" />
+ )}
+ {domain ? (
+ <button
+ onClick={() => setShowEditDomainModal(true)}
+ className="bg-black text-white border-black hover:text-black hover:bg-white h-9 w-24 text-sm border-solid border rounded-md focus:outline-none transition-all ease-in-out duration-150"
+ >
+ Change
+ </button>
+ ) : (
+ <div className="h-9 w-24 bg-gray-200 rounded-md animate-pulse" />
+ )}
+ </div>
+ </div>
+ <div className="flex items-center space-x-2 h-10">
+ {data ? (
+ data.status === "Valid Configuration" ? (
+ <CheckCircleFill className="w-6 h-6 text-blue-500" />
+ ) : data.status === "Pending Verification" ? (
+ <AlertCircleFill className="w-6 h-6 text-yellow-500" />
+ ) : (
+ <XCircleFill className="w-6 h-6 text-red-500" />
+ )
+ ) : (
+ <LoadingCircle dimensions="w-5 h-5 mr-1" />
+ )}
+ <p className="text-sm text-gray-500">
+ {data ? data.status : "Checking Domain Status"}
+ </p>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/components/app/edit-modal.tsx b/components/app/edit-link-modal.tsx
similarity index 84%
rename from components/app/edit-modal.tsx
rename to components/app/edit-link-modal.tsx
index 2024ba6918..b31f883d3a 100644
--- a/components/app/edit-modal.tsx
+++ b/components/app/edit-link-modal.tsx
@@ -7,6 +7,7 @@ import {
Dispatch,
SetStateAction,
} from "react";
+import { useRouter } from "next/router";
import BlurImage from "@/components/shared/blur-image";
import LoadingDots from "@/components/shared/icons/loading-dots";
import { LinkProps } from "@/lib/types";
@@ -16,21 +17,24 @@ import { useDebounce } from "use-debounce";
import TextareaAutosize from "react-textarea-autosize";
import { mutate } from "swr";
-function EditModalHelper({
- showEditModal,
- setShowEditModal,
+function EditLinkModalHelper({
+ showEditLinkModal,
+ setShowEditLinkModal,
props,
- slug,
+ domain,
}: {
- showEditModal: boolean;
- setShowEditModal: Dispatch<SetStateAction<boolean>>;
+ showEditLinkModal: boolean;
+ setShowEditLinkModal: Dispatch<SetStateAction<boolean>>;
props: LinkProps;
- slug?: string;
+ domain?: string;
}) {
+ const router = useRouter();
+ const { slug } = router.query as { slug: string };
+
const [saving, setSaving] = useState(false);
const [buttonText, setButtonText] = useState("Save changes");
const [keyExistsError, setKeyExistsError] = useState(false);
- const urlHostname = new URL(props.url).hostname;
+ const urlHostname = props.url ? new URL(props.url).hostname : "";
const [data, setData] = useState<LinkProps>(props);
const { key, url, title, timestamp } = data;
@@ -39,8 +43,8 @@ function EditModalHelper({
useEffect(() => {
if (debouncedKey.length > 0 && debouncedKey !== props.key) {
fetch(
- slug
- ? `/api/projects/${slug}/links/${debouncedKey}/exists`
+ domain
+ ? `/api/projects/${domain}/domain/${domain}/links/${debouncedKey}/exists`
: `/api/edge/links/${debouncedKey}/exists`
).then(async (res) => {
if (res.status === 200) {
@@ -52,7 +56,7 @@ function EditModalHelper({
}, [debouncedKey]);
return (
- <Modal showModal={showEditModal} setShowModal={setShowEditModal}>
+ <Modal showModal={showEditLinkModal} setShowModal={setShowEditLinkModal}>
<div className="inline-block w-full max-w-md overflow-hidden align-middle transition-all transform bg-white shadow-xl rounded-2xl">
<div className="flex flex-col justify-center items-center space-y-3 sm:px-16 px-4 pt-8 py-4 border-b border-gray-200">
<BlurImage
@@ -73,8 +77,8 @@ function EditModalHelper({
e.preventDefault();
setSaving(true);
fetch(
- slug
- ? `/api/projects/${slug}/links/${props.key}`
+ domain
+ ? `/api/projects/${slug}/domains/${domain}/links/${props.key}`
: `/api/links/${props.key}`,
{
method: "PUT",
@@ -87,7 +91,7 @@ function EditModalHelper({
setSaving(false);
if (res.status === 200) {
setButtonText("Saved!");
- mutate(slug ? `/api/projects/${slug}` : `/api/links`);
+ mutate(domain ? `/api/projects/${slug}` : `/api/links`);
setTimeout(() => {
setButtonText("Save changes");
});
@@ -105,7 +109,7 @@ function EditModalHelper({
</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">
- {slug || "dub.sh"}
+ {domain || "dub.sh"}
</span>
<input
type="text"
@@ -207,28 +211,28 @@ function EditModalHelper({
);
}
-export function useEditModal({
+export function useEditLinkModal({
props,
- slug,
+ domain,
}: {
props: LinkProps;
- slug?: string;
+ domain?: string;
}) {
- const [showEditModal, setShowEditModal] = useState(false);
+ const [showEditLinkModal, setShowEditLinkModal] = useState(false);
- const EditModal = useCallback(() => {
+ const EditLinkModal = useCallback(() => {
return (
- <EditModalHelper
- showEditModal={showEditModal}
- setShowEditModal={setShowEditModal}
+ <EditLinkModalHelper
+ showEditLinkModal={showEditLinkModal}
+ setShowEditLinkModal={setShowEditLinkModal}
props={props}
- slug={slug}
+ domain={domain}
/>
);
- }, [showEditModal, setShowEditModal, props, slug]);
+ }, [showEditLinkModal, setShowEditLinkModal, props, domain]);
return useMemo(
- () => ({ setShowEditModal, EditModal }),
- [setShowEditModal, EditModal]
+ () => ({ setShowEditLinkModal, EditLinkModal }),
+ [setShowEditLinkModal, EditLinkModal]
);
}
diff --git a/components/app/link-card.tsx b/components/app/link-card.tsx
index b4cb5b43ac..3237bdc547 100644
--- a/components/app/link-card.tsx
+++ b/components/app/link-card.tsx
@@ -6,33 +6,37 @@ import useSWR from "swr";
import { fetcher, nFormatter, linkConstructor, timeAgo } from "@/lib/utils";
import Link from "next/link";
import { LinkProps } from "@/lib/types";
-import { useEditModal } from "./edit-modal";
+import { useEditLinkModal } from "./edit-link-modal";
export default function LinkCard({
props,
- slug,
+ domain,
}: {
props: LinkProps;
- slug?: string;
+ domain?: string;
}) {
const { key, url, title, timestamp } = props;
- const urlHostname = new URL(url).hostname;
+ const urlHostname = url ? new URL(url).hostname : "";
const router = useRouter();
+ const { slug } = router.query as { slug: string };
const { data: clicks, isValidating } = useSWR<string>(
- slug
- ? `/api/projects/${slug}/links/${key}/clicks`
+ domain
+ ? `/api/projects/${slug}/domains/${domain}/links/${key}/clicks`
: `/api/edge/links/${key}/clicks`,
fetcher
);
- const { setShowEditModal, EditModal } = useEditModal({ props, slug });
+ const { setShowEditLinkModal, EditLinkModal } = useEditLinkModal({
+ props,
+ domain,
+ });
return (
<div className="flex justify-between items-center border border-gray-200 dark:border-gray-600 bg-white dark:bg-black p-4 rounded-md transition-all">
- <EditModal />
+ <EditLinkModal />
<div className="relative flex items-center space-x-4">
<BlurImage
src={`https://logo.clearbit.com/${urlHostname}`}
@@ -75,7 +79,7 @@ export default function LinkCard({
Added {timeAgo(timestamp)}
</p>
<button
- onClick={() => setShowEditModal(true)}
+ onClick={() => setShowEditLinkModal(true)}
className="font-medium text-sm text-gray-500 px-5 py-2 border rounded-md border-gray-200 dark:border-gray-600 hover:border-black dark:hover:border-white active:scale-95 transition-all duration-75"
>
Edit
diff --git a/components/shared/icons/check-circle-fill.tsx b/components/shared/icons/check-circle-fill.tsx
new file mode 100644
index 0000000000..6e70af50bf
--- /dev/null
+++ b/components/shared/icons/check-circle-fill.tsx
@@ -0,0 +1,18 @@
+export default function CheckCircleFill({ className }: { className?: string }) {
+ return (
+ <svg
+ className={className}
+ viewBox="0 0 24 24"
+ width="24"
+ height="24"
+ fill="none"
+ shapeRendering="geometricPrecision"
+ >
+ <path
+ d="M12 2C6.47715 2 2 6.47715 2 12C2 17.5228 6.47715 22 12 22C17.5228 22 22 17.5228 22 12C22 6.47715 17.5228 2 12 2Z"
+ fill="currentColor"
+ />
+ <path d="M8 11.8571L10.5 14.3572L15.8572 9" stroke="white" />
+ </svg>
+ );
+}
diff --git a/components/shared/icons/external-link.tsx b/components/shared/icons/external-link.tsx
new file mode 100644
index 0000000000..518430272b
--- /dev/null
+++ b/components/shared/icons/external-link.tsx
@@ -0,0 +1,20 @@
+export default function ExternalLink({ className }: { className?: string }) {
+ return (
+ <svg
+ className={className}
+ viewBox="0 0 24 24"
+ width="24"
+ height="24"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ fill="none"
+ shapeRendering="geometricPrecision"
+ >
+ <path d="M18 13v6a2 2 0 01-2 2H5a2 2 0 01-2-2V8a2 2 0 012-2h6" />
+ <path d="M15 3h6v6" />
+ <path d="M10 14L21 3" />
+ </svg>
+ );
+}
diff --git a/components/shared/icons/index.tsx b/components/shared/icons/index.tsx
index 03f6e099e4..5499fd3bd5 100644
--- a/components/shared/icons/index.tsx
+++ b/components/shared/icons/index.tsx
@@ -13,3 +13,6 @@ export { default as ChevronLeft } from "./chevron-left";
export { default as ChevronDown } from "./chevron-down";
export { default as ChevronUpDown } from "./chevron-up-down";
export { default as AlertCircleFill } from "./alert-circle-fill";
+export { default as ExternalLink } from "./external-link";
+export { default as XCircleFill } from "./x-circle-fill";
+export { default as CheckCircleFill } from "./check-circle-fill";
diff --git a/components/shared/icons/loading-circle.tsx b/components/shared/icons/loading-circle.tsx
index 8926f0eae8..7b13da2dc1 100644
--- a/components/shared/icons/loading-circle.tsx
+++ b/components/shared/icons/loading-circle.tsx
@@ -1,8 +1,10 @@
-export default function LoadingCircle({ className }: { className?: string }) {
+export default function LoadingCircle({ dimensions }: { dimensions?: string }) {
return (
<svg
aria-hidden="true"
- className="mr-2 w-4 h-4 text-gray-200 animate-spin dark:text-gray-600 fill-gray-600"
+ className={`${
+ dimensions || "w-4 h-4"
+ } text-gray-200 animate-spin dark:text-gray-600 fill-gray-600`}
viewBox="0 0 100 101"
fill="none"
xmlns="http://www.w3.org/2000/svg"
diff --git a/components/shared/icons/loading-dots.tsx b/components/shared/icons/loading-dots.tsx
index 629bf6f75b..23ebed0ef3 100644
--- a/components/shared/icons/loading-dots.tsx
+++ b/components/shared/icons/loading-dots.tsx
@@ -1,6 +1,6 @@
import styles from "./loading-dots.module.css";
-const LoadingDots = ({ color = "#000" }: { color: string }) => {
+const LoadingDots = ({ color = "#000" }: { color?: string }) => {
return (
<span className={styles.loading}>
<span style={{ backgroundColor: color }} />
diff --git a/components/shared/icons/x-circle-fill.tsx b/components/shared/icons/x-circle-fill.tsx
new file mode 100644
index 0000000000..0bd734c450
--- /dev/null
+++ b/components/shared/icons/x-circle-fill.tsx
@@ -0,0 +1,20 @@
+export default function XCircleFill({ className }: { className?: string }) {
+ return (
+ <svg
+ className={className}
+ viewBox="0 0 24 24"
+ width="24"
+ height="24"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ fill="none"
+ shapeRendering="geometricPrecision"
+ >
+ <circle cx="12" cy="12" r="10" fill="currentColor" />
+ <path d="M15 9l-6 6" stroke="white" />
+ <path d="M9 9l6 6" stroke="white" />
+ </svg>
+ );
+}
diff --git a/lib/auth.ts b/lib/auth.ts
index b3641a7964..a593ed61d2 100644
--- a/lib/auth.ts
+++ b/lib/auth.ts
@@ -2,6 +2,7 @@ import { NextApiRequest, NextApiResponse } from "next";
import { unstable_getServerSession } from "next-auth/next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import prisma from "@/lib/prisma";
+import { URLPattern } from "next/server";
interface Session {
user: {
@@ -21,8 +22,11 @@ export async function getSession(req: NextApiRequest, res: NextApiResponse) {
}
const withProjectAuth =
- // TODO - fix this type when we figure it out
- (handler: any) => async (req: NextApiRequest, res: NextApiResponse) => {
+ (handler: any, isWriteEditLink?: boolean) =>
+ // TODO - fix `handler` type when we figure it out
+ // `isWriteEditLink` is only true when it's a POST or PUT request for links
+ // (you can't add/edit a link when domain is not configured)
+ async (req: NextApiRequest, res: NextApiResponse) => {
const session = await getSession(req, res);
if (!session?.user.id) return res.status(401).end("Unauthorized");
@@ -33,7 +37,7 @@ const withProjectAuth =
.json({ error: "Missing or misconfigured project slug" });
}
- const isProjectOwner = await prisma.project.count({
+ const project = await prisma.project.findFirst({
where: {
slug,
users: {
@@ -44,7 +48,13 @@ const withProjectAuth =
},
});
- if (!isProjectOwner) return res.status(401).end("Unauthorized");
+ if (!project) return res.status(401).end("Unauthorized");
+
+ if (isWriteEditLink && !project.domainVerified) {
+ return res
+ .status(401)
+ .end("Unauthorized: Cannot add links when domain is not verified");
+ }
return handler(req, res);
};
diff --git a/lib/stats.ts b/lib/stats.ts
index a7edd8b002..4698dc41b7 100644
--- a/lib/stats.ts
+++ b/lib/stats.ts
@@ -4,6 +4,7 @@ import { COUNTRIES } from "@/lib/constants";
export interface RawStatsProps {
geo: NextRequest["geo"];
ua: any;
+ referer: string;
timestamp: number;
}
diff --git a/lib/types.ts b/lib/types.ts
index a7e2bc9290..f695512adc 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -8,6 +8,7 @@ export interface LinkProps {
export interface ProjectProps {
name: string;
slug: string;
- verified: boolean;
+ domain: string;
+ domainVerified: boolean;
links: LinkProps[];
}
diff --git a/lib/utils.ts b/lib/utils.ts
index 7e26284a3a..0fa784531f 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -79,5 +79,6 @@ export const getTitleFromUrl = async (url: string) => {
};
export const timeAgo = (timestamp: number): string => {
+ if (!timestamp) return "never";
return `${ms(Date.now() - timestamp)} ago`;
};
diff --git a/pages/api/projects/[slug]/links/[key]/clicks.ts b/pages/api/projects/[slug]/domains/[domain]/links/[key]/clicks.ts
similarity index 79%
rename from pages/api/projects/[slug]/links/[key]/clicks.ts
rename to pages/api/projects/[slug]/domains/[domain]/links/[key]/clicks.ts
index f79fa4fb22..df90e7c63d 100644
--- a/pages/api/projects/[slug]/links/[key]/clicks.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/links/[key]/clicks.ts
@@ -5,8 +5,8 @@ import { redis } from "@/lib/upstash";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === "GET") {
- const { slug, key } = req.query;
- const response = (await redis.zcard(`${slug}:clicks:${key}`)) || "0";
+ const { domain, key } = req.query;
+ const response = (await redis.zcard(`${domain}:clicks:${key}`)) || "0";
return res.status(200).json(response);
} else {
res.setHeader("Allow", ["GET"]);
diff --git a/pages/api/projects/[slug]/links/[key]/exists.ts b/pages/api/projects/[slug]/domains/[domain]/links/[key]/exists.ts
similarity index 71%
rename from pages/api/projects/[slug]/links/[key]/exists.ts
rename to pages/api/projects/[slug]/domains/[domain]/links/[key]/exists.ts
index 80a6f0134f..efb6ab316e 100644
--- a/pages/api/projects/[slug]/links/[key]/exists.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/links/[key]/exists.ts
@@ -5,10 +5,11 @@ import { withProjectAuth } from "@/lib/auth";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === "GET") {
- const { key } = req.query as { key: string };
- const response = await checkIfKeyExists("dub.sh", key);
+ const { domain, key } = req.query as { domain: string; key: string };
+ const response = await checkIfKeyExists(domain, key);
return res.status(200).json(response);
} else {
+ res.setHeader("Allow", ["GET"]);
return res
.status(405)
.json({ error: `Method ${req.method} Not Allowed` });
diff --git a/pages/api/projects/[slug]/links/[key]/index.ts b/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts
similarity index 71%
rename from pages/api/projects/[slug]/links/[key]/index.ts
rename to pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts
index e676ef45bb..7a217c092e 100644
--- a/pages/api/projects/[slug]/links/[key]/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts
@@ -5,7 +5,7 @@ import { withProjectAuth } from "@/lib/auth";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === "PUT") {
- const { slug, key } = req.query as { slug: string; key: string };
+ const { domain, key } = req.query as { domain: string; key: string };
let { key: newKey, url, title, timestamp } = req.body;
if (!newKey || !url || !title || !timestamp) {
@@ -13,13 +13,21 @@ export default withProjectAuth(
.status(400)
.json({ error: "Missing key or url or title or timestamp" });
}
- const response = await editLink(slug, key, newKey, url, title, timestamp);
+ const response = await editLink(
+ domain,
+ key,
+ newKey,
+ url,
+ title,
+ timestamp
+ );
return res.status(200).json(response);
} else {
- res.setHeader("Allow", ["GET", "POST"]);
+ res.setHeader("Allow", ["PUT"]);
return res
.status(405)
.json({ error: `Method ${req.method} Not Allowed` });
}
- }
+ },
+ true
);
diff --git a/pages/api/projects/[slug]/links/[key]/stats.ts b/pages/api/projects/[slug]/domains/[domain]/links/[key]/stats.ts
similarity index 88%
rename from pages/api/projects/[slug]/links/[key]/stats.ts
rename to pages/api/projects/[slug]/domains/[domain]/links/[key]/stats.ts
index c0176c2d1c..bb3b89c653 100644
--- a/pages/api/projects/[slug]/links/[key]/stats.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/links/[key]/stats.ts
@@ -6,15 +6,15 @@ import { IntervalProps, intervalData, RawStatsProps } from "@/lib/stats";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === "GET") {
- const { slug, key, interval } = req.query as {
- slug: string;
+ const { domain, key, interval } = req.query as {
+ domain: string;
key: string;
interval: IntervalProps;
};
const start = Date.now() - intervalData[interval || "7d"].milliseconds;
const end = Date.now();
const response = await redis.zrange<RawStatsProps[]>(
- `${slug}:clicks:${key}`,
+ `${domain}:clicks:${key}`,
start,
end,
{
diff --git a/pages/api/projects/[slug]/links/index.ts b/pages/api/projects/[slug]/domains/[domain]/links/index.ts
similarity index 74%
rename from pages/api/projects/[slug]/links/index.ts
rename to pages/api/projects/[slug]/domains/[domain]/links/index.ts
index bc5e1bb508..f9bbbadd6c 100644
--- a/pages/api/projects/[slug]/links/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/links/index.ts
@@ -6,12 +6,12 @@ export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
// POST /api/links – create a new link
if (req.method === "POST") {
- const { slug } = req.query as { slug: string };
+ const { domain } = req.query as { domain: string };
let { key, url, title } = req.body;
- if (!slug || !url) {
- return res.status(400).json({ error: "Missing hostname or url" });
+ if (!domain || !url) {
+ return res.status(400).json({ error: "Missing domain or url" });
}
- const response = await addLink(slug, url, key, title);
+ const response = await addLink(domain, url, key, title);
if (response === null) {
return res.status(400).json({ error: "Key already exists" });
}
@@ -22,5 +22,6 @@ export default withProjectAuth(
.status(405)
.json({ error: `Method ${req.method} Not Allowed` });
}
- }
+ },
+ true
);
diff --git a/pages/api/projects/[slug]/links/random.ts b/pages/api/projects/[slug]/domains/[domain]/links/random.ts
similarity index 82%
rename from pages/api/projects/[slug]/links/random.ts
rename to pages/api/projects/[slug]/domains/[domain]/links/random.ts
index 26269e4c82..816e167afa 100644
--- a/pages/api/projects/[slug]/links/random.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/links/random.ts
@@ -6,11 +6,11 @@ export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
// POST /api/links – create a new link
if (req.method === "GET") {
- const { slug } = req.query as { slug: string };
- if (!slug) {
+ const { domain } = req.query as { domain: string };
+ if (!domain) {
return res.status(400).json({ error: "Missing hostname" });
}
- const key = await getRandomKey(slug);
+ const key = await getRandomKey(domain);
return res.status(200).json(key);
} else {
res.setHeader("Allow", ["GET"]);
diff --git a/pages/api/projects/[slug]/domains/[domain]/verify.ts b/pages/api/projects/[slug]/domains/[domain]/verify.ts
new file mode 100644
index 0000000000..ed113d7986
--- /dev/null
+++ b/pages/api/projects/[slug]/domains/[domain]/verify.ts
@@ -0,0 +1,83 @@
+import { withProjectAuth } from "@/lib/auth";
+import { NextApiRequest, NextApiResponse } from "next";
+
+type StatusProps =
+ | "Valid Configuration"
+ | "Invalid Configuration"
+ | "Pending Verification"
+ | "Domain Not Found";
+
+export default withProjectAuth(
+ async (req: NextApiRequest, res: NextApiResponse) => {
+ const { domain } = req.query as { domain: string };
+ let status: StatusProps = "Valid Configuration";
+
+ const [domainResponse, configResponse] = await Promise.all([
+ fetch(
+ `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${domain}?teamId=${process.env.VERCEL_TEAM_ID}`,
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
+ "Content-Type": "application/json",
+ },
+ }
+ ),
+ fetch(
+ `https://api.vercel.com/v6/domains/${domain}/config?teamId=${process.env.VERCEL_TEAM_ID}`,
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
+ "Content-Type": "application/json",
+ },
+ }
+ ),
+ ]);
+
+ const domainJson = await domainResponse.json();
+ const configJson = await configResponse.json();
+ if (domainResponse.status !== 200) {
+ // domain not found on Vercel project
+ status = "Domain Not Found";
+ return res.status(200).json({ status });
+ }
+
+ /**
+ * If domain is not verified, we try to verify now
+ */
+ let verificationResponse = null;
+ if (!domainJson.verified) {
+ status = "Pending Verification";
+ const verificationRes = await fetch(
+ `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${domain}/verify?teamId=${process.env.VERCEL_TEAM_ID}`,
+ {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
+ "Content-Type": "application/json",
+ },
+ }
+ );
+ verificationResponse = await verificationRes.json();
+ }
+
+ if (verificationResponse && verificationResponse.verified) {
+ /**
+ * Domain was just verified
+ */
+ status = "Valid Configuration";
+ return res.status(200).json({
+ status,
+ });
+ }
+
+ status = configJson.misconfigured ? "Invalid Configuration" : status;
+
+ return res.status(200).json({
+ status,
+ ...domainJson,
+ ...(verificationResponse ? { verificationResponse } : {}),
+ });
+ }
+);
diff --git a/pages/api/projects/[slug]/domains/index.ts b/pages/api/projects/[slug]/domains/index.ts
new file mode 100644
index 0000000000..c25e14e0a9
--- /dev/null
+++ b/pages/api/projects/[slug]/domains/index.ts
@@ -0,0 +1,20 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { redis, editLink } from "@/lib/upstash";
+import { withProjectAuth } from "@/lib/auth";
+
+export default withProjectAuth(
+ async (req: NextApiRequest, res: NextApiResponse) => {
+ if (req.method === "PUT") {
+ const { slug } = req.query as { slug: string }; // slug is the domain
+
+ const response = slug;
+
+ return res.status(200).json(response);
+ } else {
+ res.setHeader("Allow", ["PUT"]);
+ return res
+ .status(405)
+ .json({ error: `Method ${req.method} Not Allowed` });
+ }
+ }
+);
diff --git a/pages/api/projects/[slug]/index.ts b/pages/api/projects/[slug]/index.ts
index d491d2d8db..a4aee00b37 100644
--- a/pages/api/projects/[slug]/index.ts
+++ b/pages/api/projects/[slug]/index.ts
@@ -30,9 +30,9 @@ export default async function handler(
},
});
if (project) {
- if (project.verified) {
+ if (project.domainVerified) {
// only fetch links if project domain has been verified
- const links = await getLinksForProject(slug);
+ const links = await getLinksForProject(project.domain);
return res.status(200).json({
...project,
links,
diff --git a/pages/api/projects/index.ts b/pages/api/projects/index.ts
index d35ac56c58..548fef69be 100644
--- a/pages/api/projects/index.ts
+++ b/pages/api/projects/index.ts
@@ -24,14 +24,16 @@ export default async function handler(
// POST /api/projects – create a new project
} else if (req.method === "POST") {
- const { name, slug } = req.body;
- if (!name || !slug)
- return res.status(400).json({ error: "Missing name or slug" });
+ const { name, slug, domain } = req.body;
+ if (!name || !slug || !domain) {
+ return res.status(400).json({ error: "Missing name or slug or domain" });
+ }
const project = await prisma.project.create({
data: {
name,
slug,
+ domain,
users: {
create: {
userId: session.user.id,
diff --git a/pages/app/[slug]/index.tsx b/pages/app/[slug]/index.tsx
index cf3faca70c..e173bd945f 100644
--- a/pages/app/[slug]/index.tsx
+++ b/pages/app/[slug]/index.tsx
@@ -7,7 +7,7 @@ import PlaceholderCard from "@/components/app/placeholder-card";
import { useEffect } from "react";
import { ProjectProps } from "@/lib/types";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
-import { useAddModal } from "@/components/app/add-modal";
+import { useAddLinkModal } from "@/components/app/add-link-modal";
import Tooltip from "@/components/shared/tooltip";
export default function ProjectLinks() {
@@ -27,31 +27,29 @@ export default function ProjectLinks() {
}
}, [error]);
- const { setShowAddModal, AddModal } = useAddModal({ slug });
+ const { setShowAddLinkModal, AddLinkModal } = useAddLinkModal({
+ domain: data?.domain,
+ });
return (
<AppLayout>
- <AddModal />
+ {data && <AddLinkModal />}
<div className="h-36 flex items-center bg-white border-b border-gray-200">
<MaxWidthWrapper>
<div className="flex justify-between items-center">
<h1 className="text-2xl text-gray-600">Links</h1>
- {data?.verified ? (
+ {data?.domainVerified ? (
<button
- onClick={() => setShowAddModal(true)}
+ onClick={() => setShowAddLinkModal(true)}
className="text-gray-500 hover:border-black dark:hover:border-white active:scale-95 font-medium text-sm px-5 py-2 border rounded-md border-gray-200 dark:border-gray-600 transition-all duration-75"
>
Add
</button>
) : (
<Tooltip content="You can only start adding links after your project domain is configured.">
- <button
- onClick={() => setShowAddModal(true)}
- disabled={true}
- className="text-gray-300 cursor-not-allowed font-medium text-sm px-5 py-2 border rounded-md border-gray-200 dark:border-gray-600 transition-all duration-75"
- >
+ <div className="text-gray-300 cursor-not-allowed font-medium text-sm px-5 py-2 border rounded-md border-gray-200 dark:border-gray-600 transition-all duration-75">
Add
- </button>
+ </div>
</Tooltip>
)}
</div>
@@ -61,7 +59,7 @@ export default function ProjectLinks() {
<div className="my-10 grid grid-cols-1 gap-3">
{data?.links && data.links.length > 0
? data.links.map((props) => (
- <LinkCard key={props.key} props={props} slug={slug} />
+ <LinkCard key={props.key} props={props} domain={data.domain} />
))
: Array.from({ length: 3 }).map((_, i) => (
<PlaceholderCard key={i} />
diff --git a/pages/app/[slug]/settings.tsx b/pages/app/[slug]/settings.tsx
index 18de3cb39c..c36cbdff53 100644
--- a/pages/app/[slug]/settings.tsx
+++ b/pages/app/[slug]/settings.tsx
@@ -1,13 +1,12 @@
import AppLayout from "components/layout/app";
import { useRouter } from "next/router";
+import Link from "next/link";
import useSWR from "swr";
import { fetcher } from "@/lib/utils";
-import LinkCard from "@/components/app/link-card";
-import PlaceholderCard from "@/components/app/placeholder-card";
import { useEffect } from "react";
import { ProjectProps } from "@/lib/types";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
-import { useAddModal } from "@/components/app/add-modal";
+import CustomDomain from "@/components/app/custom-domain";
export default function ProjectLinks() {
const router = useRouter();
@@ -26,11 +25,8 @@ export default function ProjectLinks() {
}
}, [error]);
- const { setShowAddModal, AddModal } = useAddModal({ slug });
-
return (
<AppLayout>
- <AddModal />
<div className="h-36 flex items-center bg-white border-b border-gray-200">
<MaxWidthWrapper>
<div className="flex justify-between items-center">
@@ -39,14 +35,9 @@ export default function ProjectLinks() {
</MaxWidthWrapper>
</div>
<MaxWidthWrapper>
- <div className="my-10 grid grid-cols-1 gap-3">
- {data?.links && data.links.length > 0
- ? data.links.map((props) => (
- <LinkCard key={props.key} props={props} slug={slug} />
- ))
- : Array.from({ length: 3 }).map((_, i) => (
- <PlaceholderCard key={i} />
- ))}
+ <div className="my-10 grid gap-5">
+ {/* Custom Domain Div */}
+ <CustomDomain domain={data?.domain || ""} />
</div>
</MaxWidthWrapper>
</AppLayout>
diff --git a/pages/app/links/index.tsx b/pages/app/links/index.tsx
index 6f768916bb..f861992f12 100644
--- a/pages/app/links/index.tsx
+++ b/pages/app/links/index.tsx
@@ -6,24 +6,24 @@ import { fetcher } from "@/lib/utils";
import LinkCard from "@/components/app/link-card";
import PlaceholderCard from "@/components/app/placeholder-card";
import { LinkProps } from "@/lib/types";
-import { useAddModal } from "@/components/app/add-modal";
+import { useAddLinkModal } from "@/components/app/add-link-modal";
export default function Links() {
const router = useRouter();
const { data } = useSWR<LinkProps[]>(router.isReady && `/api/links`, fetcher);
- const { setShowAddModal, AddModal } = useAddModal({});
+ const { setShowAddLinkModal, AddLinkModal } = useAddLinkModal({});
return (
<AppLayout>
- <AddModal />
+ <AddLinkModal />
<div className="h-36 flex items-center bg-white border-b border-gray-200">
<MaxWidthWrapper>
<div className="flex justify-between items-center">
<h1 className="text-2xl text-gray-600">Dub.sh Links</h1>
<button
- onClick={() => setShowAddModal(true)}
+ onClick={() => setShowAddLinkModal(true)}
className="font-medium text-sm text-gray-500 px-5 py-2 border rounded-md border-gray-200 dark:border-gray-600 hover:border-black dark:hover:border-white active:scale-95 transition-all duration-75"
>
Add
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 8e0c4049bf..b98131c063 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -59,13 +59,14 @@ model VerificationToken {
}
model Project {
- id String @id @default(cuid())
- name String
- slug String @unique // domain name
- verified Boolean @default(false)
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- users ProjectUsers[]
+ id String @id @default(cuid())
+ name String
+ slug String @unique
+ domain String
+ domainVerified Boolean @default(false)
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ users ProjectUsers[]
}
model ProjectUsers {