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.

Fixed a bunch of bugs

Steven Tey2cc3b60ecbb7
diff --git a/components/app/add-link-modal.tsx b/components/app/add-link-modal.tsx
index 2c673ceabe..11a2921ba8 100644
--- a/components/app/add-link-modal.tsx
+++ b/components/app/add-link-modal.tsx
@@ -10,6 +10,7 @@ import {
import { useRouter } from "next/router";
import BlurImage from "@/components/shared/blur-image";
import { LinkProps } from "@/lib/types";
+import { linkConstructor } from "@/lib/utils";
import {
LoadingDots,
LoadingCircle,
@@ -22,13 +23,16 @@ import TextareaAutosize from "react-textarea-autosize";
import { mutate } from "swr";
import Tooltip, { TooltipContent } from "@/components/shared/tooltip";
import useProject from "@/lib/swr/use-project";
+import useUsage from "@/lib/swr/use-usage";
-function AddLinkModal({
- showAddLinkModal,
- setShowAddLinkModal,
+function AddEditLinkModal({
+ showAddEditLinkModal,
+ setShowAddEditLinkModal,
+ props,
}: {
- showAddLinkModal: boolean;
- setShowAddLinkModal: Dispatch<SetStateAction<boolean>>;
+ showAddEditLinkModal: boolean;
+ setShowAddEditLinkModal: Dispatch<SetStateAction<boolean>>;
+ props?: LinkProps;
}) {
const router = useRouter();
const { slug } = router.query as { slug: string };
@@ -40,17 +44,37 @@ function AddLinkModal({
const [generatingTitle, setGeneratingTitle] = useState(false);
const [saving, setSaving] = useState(false);
- const [data, setData] = useState<LinkProps>({
- key: "",
- url: "",
- title: "",
- timestamp: Date.now(),
- });
+ const [data, setData] = useState<LinkProps>(
+ props || {
+ key: "",
+ url: "",
+ title: "",
+ }
+ );
const { key, url, title } = data;
+ const heroProps = useMemo(() => {
+ if (props?.url) {
+ const urlHostname = new URL(props.url).hostname;
+ return {
+ avatar: `https://logo.clearbit.com/${urlHostname}`,
+ copy: `Edit ${linkConstructor({
+ key: props.key,
+ domain,
+ pretty: true,
+ })}`,
+ };
+ } else {
+ return {
+ avatar: "/static/logo.png",
+ copy: "Add a new link",
+ };
+ }
+ }, [props]);
+
const [debouncedKey] = useDebounce(key, 500);
useEffect(() => {
- if (debouncedKey.length > 0) {
+ if (debouncedKey.length > 0 && debouncedKey !== props?.key) {
fetch(
domain
? `/api/projects/${slug}/domains/${domain}/links/${debouncedKey}/exists`
@@ -98,36 +122,52 @@ function AddLinkModal({
[debouncedUrl]
);
+ const endpoint = useMemo(() => {
+ if (props?.key) {
+ return {
+ method: "PUT",
+ url: domain
+ ? `/api/projects/${slug}/domains/${domain}/links/${props.key}`
+ : `/api/links/${props.key}`,
+ };
+ } else {
+ return {
+ method: "POST",
+ url: domain
+ ? `/api/projects/${slug}/domains/${domain}/links`
+ : `/api/links`,
+ };
+ }
+ }, [props]);
+
return (
- <Modal showModal={showAddLinkModal} setShowModal={setShowAddLinkModal}>
+ <Modal
+ showModal={showAddEditLinkModal}
+ setShowModal={setShowAddEditLinkModal}
+ >
<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={`/static/logo.png`}
- alt={"dub.sh"}
+ src={heroProps.avatar}
+ alt={heroProps.copy}
className="w-10 h-10 rounded-full border border-gray-200"
width={20}
height={20}
/>
- <h3 className="font-medium text-lg">Add a new link</h3>
+ <h3 className="font-medium text-lg">{heroProps.copy}</h3>
</div>
<form
onSubmit={async (e) => {
e.preventDefault();
setSaving(true);
- fetch(
- domain
- ? `/api/projects/${slug}/domains/${domain}/links`
- : `/api/links`,
- {
- method: "POST",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(data),
- }
- )
+ fetch(endpoint.url, {
+ method: endpoint.method,
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(data),
+ })
.then((res) => {
setSaving(false);
if (res.status === 200) {
@@ -136,7 +176,7 @@ function AddLinkModal({
? `/api/projects/${slug}/domains/${domain}/links`
: `/api/links`
);
- setShowAddLinkModal(false);
+ setShowAddEditLinkModal(false);
}
})
.catch(() => {
@@ -174,6 +214,7 @@ function AddLinkModal({
id="key"
required
autoFocus={false}
+ pattern="[a-zA-Z0-9\-]+"
className={`${
keyExistsError
? "border-red-300 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500"
@@ -283,7 +324,11 @@ function AddLinkModal({
: "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`}
>
- {saving ? <LoadingDots color="#808080" /> : <p>Add link</p>}
+ {saving ? (
+ <LoadingDots color="#808080" />
+ ) : (
+ <p>{props ? "Save changes" : "Add link"}</p>
+ )}
</button>
</form>
</div>
@@ -298,7 +343,7 @@ function AdvancedSettings({ data, setData, debouncedUrl }) {
const { url, description, image } = data;
useEffect(() => {
- if (debouncedUrl.length > 0 && description.length === 0) {
+ if (debouncedUrl.length > 0 && description?.length === 0) {
// only fetch title if user hasn't entered one
generateTitleFromUrl(debouncedUrl);
}
@@ -380,7 +425,11 @@ function AdvancedSettings({ data, setData, debouncedUrl }) {
placeholder="Dub is an open-source link shortener SaaS with built-in analytics + free custom domains."
value={description}
onChange={(e) => {
- setData({ ...data, description: e.target.value });
+ setData({
+ ...data,
+ description:
+ e.target.value.length > 0 ? e.target.value : undefined,
+ });
}}
aria-invalid="true"
/>
@@ -394,11 +443,21 @@ function AdvancedSettings({ data, setData, debouncedUrl }) {
className="group flex flex-col justify-center items-center mt-1 h-[10.5rem] cursor-pointer rounded-md border border-gray-300 bg-white hover:bg-gray-50 shadow-sm transition-all"
>
{image ? (
- <img
- src={image}
- alt="Preview"
- className="object-cover h-full w-full rounded-md hover:brightness-95 transition-all"
- />
+ image.startsWith("data:") ? (
+ <img
+ src={image}
+ alt="Preview"
+ className="object-cover h-full w-full rounded-md hover:brightness-95 transition-all"
+ />
+ ) : (
+ <BlurImage
+ src={image}
+ alt="Preview"
+ width={1200}
+ height={627}
+ className="object-cover h-full w-full rounded-md hover:brightness-95 transition-all"
+ />
+ )
) : (
<>
<UploadCloud className="h-7 w-7 text-gray-500 group-hover:scale-110 group-active:scale-95 transition-all duration-75" />
@@ -425,19 +484,18 @@ function AdvancedSettings({ data, setData, debouncedUrl }) {
);
}
-function AddLinkButton({
- domainVerified,
- exceededUsage,
- setShowAddLinkModal,
+function AddEditLinkButton({
+ setShowAddEditLinkModal,
}: {
- domainVerified: boolean;
- exceededUsage: boolean;
- setShowAddLinkModal: Dispatch<SetStateAction<boolean>>;
+ setShowAddEditLinkModal: Dispatch<SetStateAction<boolean>>;
}) {
const router = useRouter();
const { slug } = router.query as { slug?: string };
- return !domainVerified ? (
+ const { project } = useProject();
+ const { exceededUsage } = useUsage(project);
+
+ return project && !project.domainVerified ? (
<Tooltip
content={
<TooltipContent
@@ -468,7 +526,7 @@ start adding links."
</Tooltip>
) : (
<button
- onClick={() => setShowAddLinkModal(true)}
+ onClick={() => setShowAddEditLinkModal(true)}
className="text-white hover:text-black bg-black hover:bg-white active:scale-95 font-medium text-sm px-5 py-2 border rounded-md border-black transition-all duration-75"
>
Add
@@ -476,40 +534,35 @@ start adding links."
);
}
-export function useAddLinkModal({
- domainVerified,
- exceededUsage,
-}: {
- domainVerified: boolean;
- exceededUsage: boolean;
-}) {
- const [showAddLinkModal, setShowAddLinkModal] = useState(false);
+export function useAddEditLinkModal({ props }: { props?: LinkProps }) {
+ const [showAddEditLinkModal, setShowAddEditLinkModal] = useState(false);
- const AddLinkModalCallback = useCallback(() => {
+ const AddEditLinkModalCallback = useCallback(() => {
return (
- <AddLinkModal
- showAddLinkModal={showAddLinkModal}
- setShowAddLinkModal={setShowAddLinkModal}
+ <AddEditLinkModal
+ showAddEditLinkModal={showAddEditLinkModal}
+ setShowAddEditLinkModal={setShowAddEditLinkModal}
+ props={props}
/>
);
- }, [showAddLinkModal, setShowAddLinkModal]);
+ }, [showAddEditLinkModal, setShowAddEditLinkModal, props]);
- const AddLinkButtonCallback = useCallback(() => {
+ const AddEditLinkButtonCallback = useCallback(() => {
return (
- <AddLinkButton
- domainVerified={domainVerified}
- exceededUsage={exceededUsage}
- setShowAddLinkModal={setShowAddLinkModal}
- />
+ <AddEditLinkButton setShowAddEditLinkModal={setShowAddEditLinkModal} />
);
- }, [domainVerified, exceededUsage, setShowAddLinkModal]);
+ }, [setShowAddEditLinkModal]);
return useMemo(
() => ({
- setShowAddLinkModal,
- AddLinkModal: AddLinkModalCallback,
- AddLinkButton: AddLinkButtonCallback,
+ setShowAddEditLinkModal,
+ AddEditLinkModal: AddEditLinkModalCallback,
+ AddEditLinkButton: AddEditLinkButtonCallback,
}),
- [setShowAddLinkModal, AddLinkModalCallback, AddLinkButtonCallback]
+ [
+ setShowAddEditLinkModal,
+ AddEditLinkModalCallback,
+ AddEditLinkButtonCallback,
+ ]
);
}
diff --git a/components/app/custom-domain/edit-domain-modal.tsx b/components/app/custom-domain/edit-domain-modal.tsx
index 387054638d..595f73ec4f 100644
--- a/components/app/custom-domain/edit-domain-modal.tsx
+++ b/components/app/custom-domain/edit-domain-modal.tsx
@@ -13,20 +13,20 @@ import LoadingDots from "@/components/shared/icons/loading-dots";
import { AlertCircleFill } from "@/components/shared/icons";
import { useDebounce } from "use-debounce";
import { mutate } from "swr";
+import useProject from "@/lib/swr/use-project";
-function EditDomainModalHelper({
+function EditDomainModal({
showEditDomainModal,
setShowEditDomainModal,
- domain,
}: {
showEditDomainModal: boolean;
setShowEditDomainModal: Dispatch<SetStateAction<boolean>>;
- domain: string;
}) {
const router = useRouter();
const { slug } = router.query;
const [saving, setSaving] = useState(false);
const [domainError, setDomainError] = useState(null);
+ const { project: { domain } = {} } = useProject();
const [data, setData] = useState(domain);
@@ -189,21 +189,23 @@ function EditDomainModalHelper({
);
}
-export function useEditDomainModal({ domain }: { domain: string }) {
+export function useEditDomainModal() {
const [showEditDomainModal, setShowEditDomainModal] = useState(false);
- const EditDomainModal = useCallback(() => {
+ const EditDomainModalCallback = useCallback(() => {
return (
- <EditDomainModalHelper
+ <EditDomainModal
showEditDomainModal={showEditDomainModal}
setShowEditDomainModal={setShowEditDomainModal}
- domain={domain}
/>
);
- }, [showEditDomainModal, setShowEditDomainModal, domain]);
+ }, [showEditDomainModal, setShowEditDomainModal]);
return useMemo(
- () => ({ setShowEditDomainModal, EditDomainModal }),
- [setShowEditDomainModal, EditDomainModal]
+ () => ({
+ setShowEditDomainModal,
+ EditDomainModal: EditDomainModalCallback,
+ }),
+ [setShowEditDomainModal, EditDomainModalCallback]
);
}
diff --git a/components/app/delete-link-modal.tsx b/components/app/delete-link-modal.tsx
new file mode 100644
index 0000000000..62dcf6b2ce
--- /dev/null
+++ b/components/app/delete-link-modal.tsx
@@ -0,0 +1,148 @@
+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 { linkConstructor } from "@/lib/utils";
+import { mutate } from "swr";
+import useProject from "@/lib/swr/use-project";
+import { LinkProps } from "@/lib/types";
+
+function DeleteLinkModal({
+ showDeleteLinkModal,
+ setShowDeleteLinkModal,
+ props,
+}: {
+ showDeleteLinkModal: boolean;
+ setShowDeleteLinkModal: Dispatch<SetStateAction<boolean>>;
+ props: LinkProps;
+}) {
+ const router = useRouter();
+ const { slug } = router.query;
+ const [deleting, setDeleting] = useState(false);
+ const { project: { domain } = {} } = useProject();
+ const urlHostname = props?.url ? new URL(props.url).hostname : null;
+
+ const shortlink = useMemo(() => {
+ return linkConstructor({
+ key: props.key,
+ domain,
+ pretty: true,
+ });
+ }, [props, domain]);
+
+ return (
+ <Modal
+ showModal={showDeleteLinkModal}
+ setShowModal={setShowDeleteLinkModal}
+ >
+ <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/${urlHostname}`}
+ alt={urlHostname}
+ className="w-10 h-10 rounded-full border border-gray-200"
+ width={20}
+ height={20}
+ />
+ <h3 className="font-medium text-lg">Delete {shortlink}</h3>
+ <p className="text-sm text-gray-500">
+ Warning: Deleting this link will remove all of its stats. This
+ action cannot be undone.
+ </p>
+ </div>
+
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ setDeleting(true);
+ fetch(
+ domain
+ ? `/api/projects/${slug}/domains/${domain}/links/${props.key}`
+ : `/api/links/${props.key}`,
+ {
+ method: "DELETE",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ }
+ ).then(async (res) => {
+ setDeleting(false);
+ if (res.status === 200) {
+ mutate(
+ domain
+ ? `/api/projects/${slug}/domains/${domain}/links`
+ : `/api/links`
+ );
+ setShowDeleteLinkModal(false);
+ }
+ });
+ }}
+ className="flex flex-col space-y-6 text-left bg-gray-50 sm:px-16 px-4 py-8"
+ >
+ <div>
+ <label
+ htmlFor="verification"
+ className="block text-sm text-gray-700"
+ >
+ To verify, type <span className="font-semibold">{shortlink}</span>{" "}
+ below
+ </label>
+ <div className="relative mt-1 rounded-md shadow-sm">
+ <input
+ type="text"
+ name="verification"
+ id="verification"
+ pattern={shortlink}
+ required
+ autoFocus={false}
+ className="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"
+ />
+ </div>
+ </div>
+
+ <button
+ disabled={deleting}
+ className={`${
+ deleting
+ ? "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`}
+ >
+ {deleting ? <LoadingDots color="#808080" /> : <p>Confirm delete</p>}
+ </button>
+ </form>
+ </div>
+ </Modal>
+ );
+}
+
+export function useDeleteLinkModal({ props }: { props?: LinkProps }) {
+ const [showDeleteLinkModal, setShowDeleteLinkModal] = useState(false);
+
+ const DeleteLinkModalCallback = useCallback(() => {
+ return props ? (
+ <DeleteLinkModal
+ showDeleteLinkModal={showDeleteLinkModal}
+ setShowDeleteLinkModal={setShowDeleteLinkModal}
+ props={props}
+ />
+ ) : null;
+ }, [showDeleteLinkModal, setShowDeleteLinkModal]);
+
+ return useMemo(
+ () => ({
+ setShowDeleteLinkModal,
+ DeleteLinkModal: DeleteLinkModalCallback,
+ }),
+ [setShowDeleteLinkModal, DeleteLinkModalCallback]
+ );
+}
diff --git a/components/app/edit-link-modal.tsx b/components/app/edit-link-modal.tsx
deleted file mode 100644
index 097b9ca91a..0000000000
--- a/components/app/edit-link-modal.tsx
+++ /dev/null
@@ -1,243 +0,0 @@
-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 { LinkProps } from "@/lib/types";
-import { linkConstructor, timeAgo } from "@/lib/utils";
-import { AlertCircleFill } from "@/components/shared/icons";
-import { useDebounce } from "use-debounce";
-import TextareaAutosize from "react-textarea-autosize";
-import { mutate } from "swr";
-
-function EditLinkModalHelper({
- showEditLinkModal,
- setShowEditLinkModal,
- props,
- domain,
-}: {
- showEditLinkModal: boolean;
- setShowEditLinkModal: Dispatch<SetStateAction<boolean>>;
- props: LinkProps;
- domain?: string;
-}) {
- const router = useRouter();
- const { slug } = router.query as { slug: string };
-
- const [saving, setSaving] = useState(false);
- const [keyExistsError, setKeyExistsError] = useState(false);
- const urlHostname = props.url ? new URL(props.url).hostname : "";
-
- const [data, setData] = useState<LinkProps>(props);
- const { key, url, title, timestamp } = data;
- const [debouncedKey] = useDebounce(key, 1000);
-
- useEffect(() => {
- if (debouncedKey.length > 0 && debouncedKey !== props.key) {
- fetch(
- domain
- ? `/api/projects/${slug}/domains/${domain}/links/${debouncedKey}/exists`
- : `/api/edge/links/${debouncedKey}/exists`
- ).then(async (res) => {
- if (res.status === 200) {
- const exists = await res.json();
- setKeyExistsError(exists === 1);
- }
- });
- }
- }, [debouncedKey]);
-
- return (
- <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
- src={`https://logo.clearbit.com/${urlHostname}`}
- alt={urlHostname}
- className="w-10 h-10 rounded-full border border-gray-200"
- width={20}
- height={20}
- />
- <h3 className="font-medium text-lg">
- Edit {linkConstructor({ key: props.key, domain, pretty: true })}
- </h3>
- <p className="text-sm text-gray-500">Added {timeAgo(timestamp)}</p>
- </div>
-
- <form
- onSubmit={async (e) => {
- e.preventDefault();
- setSaving(true);
- fetch(
- domain
- ? `/api/projects/${slug}/domains/${domain}/links/${props.key}`
- : `/api/links/${props.key}`,
- {
- method: "PUT",
- headers: {
- "Content-Type": "application/json",
- },
- body: JSON.stringify(data),
- }
- )
- .then((res) => {
- setSaving(false);
- if (res.status === 200) {
- mutate(
- domain
- ? `/api/projects/${slug}/domains/${domain}/links`
- : `/api/links`
- );
- setShowEditLinkModal(false);
- }
- })
- .catch(() => {
- setSaving(false);
- setKeyExistsError(true);
- });
- }}
- 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"
- >
- Short Link
- </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">
- {domain || "dub.sh"}
- </span>
- <input
- type="text"
- name="key"
- id="key"
- required
- autoFocus={false}
- className={`${
- keyExistsError
- ? "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="github"
- value={key}
- onChange={(e) => {
- setKeyExistsError(false);
- setData({ ...data, key: e.target.value });
- }}
- aria-invalid="true"
- aria-describedby="key-error"
- />
- {keyExistsError && (
- <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>
- {keyExistsError && (
- <p className="mt-2 text-sm text-red-600" id="key-error">
- Short link is already in use.
- </p>
- )}
- </div>
-
- <div>
- <label
- htmlFor="url"
- className="block text-sm font-medium text-gray-700"
- >
- Destination URL
- </label>
- <div className="flex mt-1 rounded-md shadow-sm">
- <input
- name="url"
- id="url"
- type="url"
- 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"
- placeholder="https://github.com/steven-tey/dub"
- value={url}
- onChange={(e) => {
- setData({ ...data, url: e.target.value });
- }}
- aria-invalid="true"
- />
- </div>
- </div>
-
- <div>
- <label
- htmlFor="title"
- className="block text-sm font-medium text-gray-700"
- >
- Title
- </label>
- <div className="flex mt-1 rounded-md shadow-sm">
- <TextareaAutosize
- name="title"
- id="title"
- required
- minRows={3}
- className="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 - an open-source link shortener SaaS with built-in analytics + free custom domains."
- value={title}
- onChange={(e) => {
- setData({ ...data, title: e.target.value });
- }}
- aria-invalid="true"
- />
- </div>
- </div>
-
- <button
- disabled={saving || keyExistsError}
- className={`${
- saving || keyExistsError
- ? "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`}
- >
- {saving ? <LoadingDots color="#808080" /> : <p>Save changes</p>}
- </button>
- </form>
- </div>
- </Modal>
- );
-}
-
-export function useEditLinkModal({
- props,
- domain,
-}: {
- props: LinkProps;
- domain?: string;
-}) {
- const [showEditLinkModal, setShowEditLinkModal] = useState(false);
-
- const EditLinkModal = useCallback(() => {
- return (
- <EditLinkModalHelper
- showEditLinkModal={showEditLinkModal}
- setShowEditLinkModal={setShowEditLinkModal}
- props={props}
- domain={domain}
- />
- );
- }, [showEditLinkModal, setShowEditLinkModal, props, domain]);
-
- return useMemo(
- () => ({ setShowEditLinkModal, EditLinkModal }),
- [setShowEditLinkModal, EditLinkModal]
- );
-}
diff --git a/components/app/link-card.tsx b/components/app/link-card.tsx
index 9c94537004..70655d3241 100644
--- a/components/app/link-card.tsx
+++ b/components/app/link-card.tsx
@@ -6,18 +6,13 @@ import useSWR from "swr";
import { fetcher, nFormatter, linkConstructor, timeAgo } from "@/lib/utils";
import Link from "next/link";
import { LinkProps } from "@/lib/types";
-import { useEditLinkModal } from "./edit-link-modal";
import Tooltip, { TooltipContent } from "@/components/shared/tooltip";
+import useProject from "@/lib/swr/use-project";
+import useUsage from "@/lib/swr/use-usage";
+import { useAddEditLinkModal } from "./add-link-modal";
+import { useDeleteLinkModal } from "./delete-link-modal";
-export default function LinkCard({
- props,
- exceededUsage,
- domain,
-}: {
- props: LinkProps;
- exceededUsage: boolean;
- domain?: string;
-}) {
+export default function LinkCard({ props }: { props: LinkProps }) {
const { key, url, title, timestamp } = props;
const urlHostname = url ? new URL(url).hostname : "";
@@ -25,6 +20,10 @@ export default function LinkCard({
const router = useRouter();
const { slug } = router.query as { slug: string };
+ const { project } = useProject();
+ const { domain } = project || {};
+ const { exceededUsage } = useUsage(project);
+
const { data: clicks, isValidating } = useSWR<string>(
domain
? `/api/projects/${slug}/domains/${domain}/links/${key}/clicks`
@@ -32,14 +31,18 @@ export default function LinkCard({
fetcher
);
- const { setShowEditLinkModal, EditLinkModal } = useEditLinkModal({
+ const { setShowAddEditLinkModal, AddEditLinkModal } = useAddEditLinkModal({
+ props,
+ });
+
+ const { setShowDeleteLinkModal, DeleteLinkModal } = useDeleteLinkModal({
props,
- domain,
});
return (
<li className="flex flex-col sm:flex-row justify-between items-start sm:items-center space-y-5 sm:space-y-0 border border-gray-200 bg-white p-4 rounded-md transition-all">
- <EditLinkModal />
+ <AddEditLinkModal />
+ <DeleteLinkModal />
<div className="relative flex items-center space-x-4">
<BlurImage
src={`https://logo.clearbit.com/${urlHostname}`}
@@ -96,12 +99,18 @@ export default function LinkCard({
</Tooltip>
) : (
<button
- onClick={() => setShowEditLinkModal(true)}
+ onClick={() => setShowAddEditLinkModal(true)}
className="font-medium text-sm text-gray-500 px-5 py-2 border rounded-md border-gray-200 hover:border-black active:scale-95 transition-all duration-75"
>
Edit
</button>
)}
+ <button
+ onClick={() => setShowDeleteLinkModal(true)}
+ className="font-medium text-sm text-white bg-red-600 hover:bg-white hover:text-red-600 border-red-600 px-5 py-2 border rounded-md active:scale-95 transition-all duration-75"
+ >
+ Delete
+ </button>
</div>
</li>
);
diff --git a/components/app/links-container.tsx b/components/app/links-container.tsx
index 598fb7fdd3..e9d329fc11 100644
--- a/components/app/links-container.tsx
+++ b/components/app/links-container.tsx
@@ -6,20 +6,19 @@ import LinkCardPlaceholder from "@/components/app/link-card-placeholder";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
import NoLinksPlaceholder from "@/components/app/no-links-placeholder";
import { LinkProps } from "@/lib/types";
+import useProject from "@/lib/swr/use-project";
export default function LinksContainer({
- exceededUsage,
- AddLinkButton,
- domain,
+ AddEditLinkButton,
}: {
- exceededUsage: boolean;
- AddLinkButton: () => JSX.Element;
- domain?: string;
+ AddEditLinkButton: () => JSX.Element;
}) {
const router = useRouter();
const { slug } = router.query as {
slug: string;
};
+
+ const { project: { domain } = {} } = useProject();
const { data: links } = useSWR<LinkProps[]>(
domain ? `/api/projects/${slug}/domains/${domain}/links` : `/api/links`,
fetcher
@@ -30,16 +29,9 @@ export default function LinksContainer({
<ul className="py-10 grid grid-cols-1 gap-3">
{links ? (
links.length > 0 ? (
- links.map((props) => (
- <LinkCard
- key={props.key}
- props={props}
- domain={domain}
- exceededUsage={exceededUsage}
- />
- ))
+ links.map((props) => <LinkCard key={props.key} props={props} />)
) : (
- <NoLinksPlaceholder AddLinkButton={AddLinkButton} />
+ <NoLinksPlaceholder AddEditLinkButton={AddEditLinkButton} />
)
) : (
Array.from({ length: 3 }).map((_, i) => (
diff --git a/components/app/no-links-placeholder.tsx b/components/app/no-links-placeholder.tsx
index 7a0a443fa1..693ea907d7 100644
--- a/components/app/no-links-placeholder.tsx
+++ b/components/app/no-links-placeholder.tsx
@@ -1,9 +1,9 @@
import BlurImage from "@/components/shared/blur-image";
export default function NoLinksPlaceholder({
- AddLinkButton,
+ AddEditLinkButton,
}: {
- AddLinkButton: () => JSX.Element;
+ AddEditLinkButton: () => JSX.Element;
}) {
return (
<div className="border border-gray-200 rounded-md bg-white py-12 flex flex-col justify-center items-center">
@@ -18,7 +18,7 @@ export default function NoLinksPlaceholder({
className="-my-8"
/>
<div className="z-10">
- <AddLinkButton />
+ <AddEditLinkButton />
</div>
</div>
);
diff --git a/components/home/footer.tsx b/components/home/footer.tsx
deleted file mode 100644
index 54a43c01b8..0000000000
--- a/components/home/footer.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import { Github, Logo, Twitter } from "@/components/shared/icons";
-import Link from "next/link";
-
-const Footer = () => {
- return (
- <div className="border-t border-gray-200 h-20 flex items-center justify-center space-x-12">
- <a href="https://twitter.com/dubdotsh" target="_blank" rel="noreferrer">
- <span className="sr-only">Twitter</span>
- <Twitter className="w-6 h-6 text-gray-600" />
- </a>
- <Link href="/">
- <a>
- <span className="sr-only">Dub.sh Logo</span>
- <Logo className="w-7 h-7 text-gray-600" />
- </a>
- </Link>
- <a
- href="https://github.com/steven-tey/dub"
- target="_blank"
- rel="noreferrer"
- >
- <span className="sr-only">Github</span>
- <Github className="w-6 h-6 text-gray-600" />
- </a>
- </div>
- );
-};
-
-export default Footer;
diff --git a/components/layout/home/index.tsx b/components/layout/home/index.tsx
index 4eb203f448..fb52b0aeb9 100644
--- a/components/layout/home/index.tsx
+++ b/components/layout/home/index.tsx
@@ -3,9 +3,15 @@ import { useSession } from "next-auth/react";
import Link from "next/link";
import Meta from "../meta";
import Image from "next/future/image";
-import Footer from "@/components/home/footer";
+import { Github, Logo, Twitter } from "@/components/shared/icons";
-export default function HomeLayout({ children }: { children: ReactNode }) {
+export default function HomeLayout({
+ children,
+ domain,
+}: {
+ children: ReactNode;
+ domain?: string;
+}) {
const { data: session } = useSession();
return (
<div className="min-h-screen flex flex-col justify-between">
@@ -14,8 +20,8 @@ export default function HomeLayout({ children }: { children: ReactNode }) {
<div className="max-w-screen-xl mx-auto px-5 sm:px-20">
<div className="h-16 flex justify-between items-center">
<div className="flex items-center">
- <Link href="/">
- <a>
+ {domain ? (
+ <a href="https://dub.sh" target="_blank" rel="noreferrer">
<Image
src="/static/logotype.svg"
alt="Dub.sh logo"
@@ -24,7 +30,19 @@ export default function HomeLayout({ children }: { children: ReactNode }) {
className="w-24"
/>
</a>
- </Link>
+ ) : (
+ <Link href="/">
+ <a>
+ <Image
+ src="/static/logotype.svg"
+ alt="Dub.sh logo"
+ width={834}
+ height={236}
+ className="w-24"
+ />
+ </a>
+ </Link>
+ )}
</div>
{session ? (
<a
@@ -45,7 +63,33 @@ export default function HomeLayout({ children }: { children: ReactNode }) {
</div>
</div>
{children}
- <Footer />
+ <div className="border-t border-gray-200 h-20 flex items-center justify-center space-x-12">
+ <a href="https://twitter.com/dubdotsh" target="_blank" rel="noreferrer">
+ <span className="sr-only">Twitter</span>
+ <Twitter className="w-6 h-6 text-gray-600" />
+ </a>
+ {domain ? (
+ <a href="https://dub.sh" target="_blank" rel="noreferrer">
+ <span className="sr-only">Dub.sh Logo</span>
+ <Logo className="w-7 h-7 text-gray-600" />
+ </a>
+ ) : (
+ <Link href="/">
+ <a>
+ <span className="sr-only">Dub.sh Logo</span>
+ <Logo className="w-7 h-7 text-gray-600" />
+ </a>
+ </Link>
+ )}
+ <a
+ href="https://github.com/steven-tey/dub"
+ target="_blank"
+ rel="noreferrer"
+ >
+ <span className="sr-only">Github</span>
+ <Github className="w-6 h-6 text-gray-600" />
+ </a>
+ </div>
</div>
);
}
diff --git a/components/shared/blur-image.tsx b/components/shared/blur-image.tsx
index a1a238c944..63bb8c7df8 100644
--- a/components/shared/blur-image.tsx
+++ b/components/shared/blur-image.tsx
@@ -12,9 +12,7 @@ export default function BlurImage(props: ImageProps) {
src={src}
alt={props.alt}
className={`${props.className} ${
- isLoading
- ? "grayscale blur-2xl scale-110"
- : "grayscale-0 blur-0 scale-100"
+ isLoading ? "grayscale blur-md" : "grayscale-0 blur-0"
}`}
onLoadingComplete={async () => {
setLoading(false);
diff --git a/lib/constants.ts b/lib/constants.ts
index 4aa6e6a25d..228ddf73f3 100644
--- a/lib/constants.ts
+++ b/lib/constants.ts
@@ -13,17 +13,18 @@ export const FRAMER_MOTION_LIST_ITEM_VARIANTS = {
show: { scale: 1, opacity: 1, transition: { type: "spring" } },
};
-export const HOME_HOSTNAMES = [
+export const HOME_HOSTNAMES = new Set([
// comment for better diffs
"dub.sh",
"preview.dub.sh",
"localhost:3000",
-];
+]);
-export const RESERVED_KEYS = [
+export const RESERVED_KEYS = new Set([
+ "stats",
+ "proxy",
"pricing",
"about",
- "stats",
"placeholder",
"blog",
"careers",
@@ -36,8 +37,18 @@ export const RESERVED_KEYS = [
"new",
"info",
"demo",
- "proxy",
-];
+]);
+
+export const DEFAULT_REDIRECTS = {
+ home: "https://dub.sh",
+ signin: "https://app.dub.sh/login",
+ login: "https://app.dub.sh/login",
+ register: "https://app.dub.sh/register",
+ signup: "https://app.dub.sh/register",
+ app: "https://app.dub.sh",
+ dashboard: "https://app.dub.sh",
+ links: "https://app.dub.sh/links",
+};
export const COUNTRIES: { [key: string]: string } = {
AF: "Afghanistan",
diff --git a/lib/middleware/link.ts b/lib/middleware/link.ts
index 15931a1708..807ff63977 100644
--- a/lib/middleware/link.ts
+++ b/lib/middleware/link.ts
@@ -1,6 +1,6 @@
import { NextRequest, NextFetchEvent, NextResponse } from "next/server";
import { redis, recordClick } from "@/lib/upstash";
-import { parse } from "@/lib/middleware/utils";
+import { parse, detectBot } from "@/lib/middleware/utils";
import { LinkProps } from "../types";
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
@@ -37,9 +37,7 @@ export default async function LinkMiddleware(
const { url: target, description, image } = response || {};
if (target) {
- const isBot =
- url.searchParams.get("bot") ||
- /bot/i.test(req.headers.get("user-agent"));
+ const isBot = detectBot(req);
ev.waitUntil(recordClick(hostname, req, key)); // increment click count
diff --git a/lib/middleware/utils.ts b/lib/middleware/utils.ts
index 61cdd39e28..ed3f40c8c0 100644
--- a/lib/middleware/utils.ts
+++ b/lib/middleware/utils.ts
@@ -3,8 +3,21 @@ import { HOME_HOSTNAMES } from "@/lib/constants";
export const parse = (req: NextRequest) => {
let hostname = req.headers.get("host");
- if (HOME_HOSTNAMES.includes(hostname)) hostname = "dub.sh";
+ if (HOME_HOSTNAMES.has(hostname)) hostname = "dub.sh";
const path = req.nextUrl.pathname;
const key = path.split("/")[1];
return { hostname, path, key };
};
+
+export const detectBot = (req: NextRequest) => {
+ const url = req.nextUrl;
+ if (url.searchParams.get("bot")) return true;
+ const ua = req.headers.get("User-Agent");
+ if (ua) {
+ // Note: MetaInspector is for https://metatags.io/
+ return /bot|google|baidu|bing|msn|duckduckbot|teoma|slurp|yandex|MetaInspector/i.test(
+ ua
+ );
+ }
+ return false;
+};
diff --git a/lib/types.ts b/lib/types.ts
index a6c376708d..f5140d74a2 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -7,7 +7,7 @@ export interface LinkProps {
key: string;
url: string;
title: string;
- timestamp: number;
+ timestamp?: number;
description?: string;
image?: string;
}
diff --git a/lib/upstash.ts b/lib/upstash.ts
index 6409156007..80c1243b62 100644
--- a/lib/upstash.ts
+++ b/lib/upstash.ts
@@ -3,7 +3,7 @@ import { NextRequest, userAgent } from "next/server";
import { LOCALHOST_GEO_DATA, RESERVED_KEYS } from "@/lib/constants";
import { LinkProps } from "@/lib/types";
import { customAlphabet } from "nanoid";
-import { getTitleFromUrl } from "@/lib/utils";
+import { getDescriptionFromUrl, getTitleFromUrl } from "@/lib/utils";
// Initiate Redis instance
export const redis = new Redis({
@@ -35,7 +35,8 @@ export async function setKey(
return await redis.hsetnx(`${hostname}:links`, key, {
url,
title: title || (await getTitleFromUrl(url)),
- description,
+ description:
+ image && !description ? getDescriptionFromUrl(url) : description,
image,
timestamp: Date.now(),
});
@@ -70,7 +71,7 @@ export async function getRandomKey(hostname: string): Promise<string> {
}
export async function checkIfKeyExists(hostname: string, key: string) {
- if (hostname === "dub.sh" && RESERVED_KEYS.includes(key)) {
+ if (hostname === "dub.sh" && RESERVED_KEYS.has(key)) {
return 1; // reserved keys for dub.sh
}
return await redis.hexists(`${hostname}:links`, key);
@@ -148,14 +149,18 @@ export async function getLinkClicksCount(hostname: string, key: string) {
export async function addLink(
hostname: string,
- url: string,
- key?: string, // if key is provided, it will be used
- title?: string, // if title is provided, it will be used
- description?: string, // only for Pro users: customize description
- image?: string, // only for Pro users: customize OG image
+ link: LinkProps,
userId?: string // only applicable for dub.sh links
) {
- if (hostname === "dub.sh" && key && RESERVED_KEYS.includes(key)) {
+ const {
+ key, // if key is provided, it will be used
+ url,
+ title, // if title is provided, it will be used
+ description, // only for Pro users: customize description
+ image, // only for Pro users: customize OG image
+ } = link;
+
+ if (hostname === "dub.sh" && key && RESERVED_KEYS.has(key)) {
return null; // reserved keys for dub.sh
}
const response = key
@@ -179,56 +184,68 @@ export async function addLink(
* Edit a link
**/
export async function editLink(
- hostname: string,
- key: string,
- newKey: string,
- url: string,
- title: string,
- timestamp: number,
+ domain: string,
+ oldKey: string,
+ link: LinkProps,
userId?: string
) {
- if (key === newKey) {
+ let { key, url, title, timestamp, description: rawDescription, image } = link;
+
+ // if there's an image but no description, try and auto generate one
+ const description =
+ image && !rawDescription ? getDescriptionFromUrl(url) : rawDescription;
+
+ if (oldKey === key) {
// if key is the same, just update the url and title
- return await redis.hset(`${hostname}:links`, {
- [key]: { url, title, timestamp },
+ return await redis.hset(`${domain}:links`, {
+ [oldKey]: { url, title, timestamp, description, image },
});
} else {
// if key is different
- if (hostname === "dub.sh" && RESERVED_KEYS.includes(newKey)) {
+ if (domain === "dub.sh" && RESERVED_KEYS.has(key)) {
return null; // reserved keys for dub.sh
}
- const keyExists = await checkIfKeyExists(hostname, newKey);
+ const keyExists = await checkIfKeyExists(domain, key);
if (keyExists === 1) {
return null; // key already exists
}
- // get number of clicks for key (we'll add it to newKey)
- const numClicks = await redis.zcard(`${hostname}:clicks:${key}`);
+
+ // get number of clicks for oldKey (we'll add it to key)
+ const numClicks = await redis.zcard(`${domain}:clicks:${oldKey}`);
const pipeline = redis.pipeline();
// delete old key and add new key from hash
- pipeline.hdel(`${hostname}:links`, key);
- pipeline.hset(`${hostname}:links`, {
- [newKey]: { url, title, timestamp },
+ pipeline.hdel(`${domain}:links`, oldKey);
+ pipeline.hset(`${domain}:links`, {
+ [key]: { url, title, timestamp, description, image },
});
// remove old key from links:timestamps and add new key (with same timestamp)
pipeline.zrem(
- `${hostname}:links:timestamps${userId ? `:${userId}` : ""}`,
- key
+ `${domain}:links:timestamps${userId ? `:${userId}` : ""}`,
+ oldKey
);
- pipeline.zadd(`${hostname}:links:timestamps${userId ? `:${userId}` : ""}`, {
+ pipeline.zadd(`${domain}:links:timestamps${userId ? `:${userId}` : ""}`, {
score: timestamp,
- member: newKey,
+ member: key,
});
// update name for clicks:[key] (if numClicks > 0, because we don't create clicks:[key] until the first click)
if (numClicks > 0) {
- pipeline.rename(
- `${hostname}:clicks:${key}`,
- `${hostname}:clicks:${newKey}`
- );
+ pipeline.rename(`${domain}:clicks:${oldKey}`, `${domain}:clicks:${key}`);
}
return await pipeline.exec();
}
}
+/**
+ * Delete a link
+ **/
+export async function deleteLink(domain: string, key: string, userId?: string) {
+ const pipeline = redis.pipeline();
+ pipeline.hdel(`${domain}:links`, key);
+ pipeline.zrem(`${domain}:links:timestamps${userId ? `:${userId}` : ""}`, key);
+ pipeline.del(`${domain}:clicks:${key}`);
+ return await pipeline.exec();
+}
+
export async function getUsage(hostname: string, billingCycleStart?: Date) {
const cachedUsage = await redis.get(`usage:${hostname}`);
if (cachedUsage) {
diff --git a/lib/utils.ts b/lib/utils.ts
index 645e078af5..551b5afcd5 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -1,5 +1,6 @@
import ms from "ms";
import { ccTLDs } from "./constants";
+import { LinkProps } from "./types";
interface SWRError extends Error {
status: number;
@@ -143,6 +144,6 @@ export const generateSlugFromName = (name: string) => {
return `${shortestString}.sh`;
};
-export const domainRegex = new RegExp(
+export const validDomainRegex = new RegExp(
"^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]$"
);
diff --git a/middleware.ts b/middleware.ts
index c691f5e897..3fdf6d758d 100644
--- a/middleware.ts
+++ b/middleware.ts
@@ -5,7 +5,11 @@ import {
RootMiddleware,
} from "@/lib/middleware";
import { parse } from "@/lib/middleware/utils";
-import { HOME_HOSTNAMES, RESERVED_KEYS } from "@/lib/constants";
+import {
+ HOME_HOSTNAMES,
+ RESERVED_KEYS,
+ DEFAULT_REDIRECTS,
+} from "@/lib/constants";
export const config = {
matcher: [
@@ -22,7 +26,7 @@ export const config = {
export default async function middleware(req: NextRequest, ev: NextFetchEvent) {
const { hostname, key } = parse(req);
- const home = HOME_HOSTNAMES.includes(hostname);
+ const home = HOME_HOSTNAMES.has(hostname);
const app = hostname === "app.dub.sh" || hostname === "app.localhost:3000";
if (app) {
@@ -33,8 +37,13 @@ export default async function middleware(req: NextRequest, ev: NextFetchEvent) {
return RootMiddleware(req, ev);
}
- if (home && RESERVED_KEYS.includes(key)) {
- return NextResponse.next();
+ if (home) {
+ if (DEFAULT_REDIRECTS[key]) {
+ return NextResponse.redirect(DEFAULT_REDIRECTS[key]);
+ }
+ if (RESERVED_KEYS.has(key)) {
+ return NextResponse.next();
+ }
}
return LinkMiddleware(req, ev);
diff --git a/pages/api/links/[key].ts b/pages/api/links/[key].ts
index 4365b99ebc..56f924cff9 100644
--- a/pages/api/links/[key].ts
+++ b/pages/api/links/[key].ts
@@ -1,46 +1,48 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { redis, editLink } from "@/lib/upstash";
+import { redis, editLink, deleteLink } from "@/lib/upstash";
import { getSession } from "@/lib/auth";
-import { RESERVED_KEYS } from "@/lib/constants";
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 { key: oldKey } = req.query as { key: string };
- if (req.method === "PUT") {
- const { key } = req.query as { key: string };
-
- const isOwner = await redis.zscore(
- `dub.sh:links:timestamps:${session.user.id}`,
- key
- );
+ const isOwner = await redis.zscore(
+ `dub.sh:links:timestamps:${session.user.id}`,
+ oldKey
+ );
- if (!isOwner) return res.status(401).end("Unauthorized");
+ if (!session?.user.id || !isOwner) return res.status(401).end("Unauthorized");
- let { key: newKey, url, title, timestamp } = req.body;
- if (!newKey || !url || !title || !timestamp) {
+ if (req.method === "PUT") {
+ let { key, url, title, timestamp } = req.body;
+ if (!key || !url || !title || !timestamp) {
return res
.status(400)
.json({ error: "Missing key or url or title or timestamp" });
}
const response = await editLink(
"dub.sh",
- key,
- newKey,
- url,
- title,
- timestamp,
+ oldKey,
+ {
+ key,
+ url,
+ title,
+ timestamp,
+ },
session.user.id
);
if (response === null) {
return res.status(400).json({ error: "Key already exists" });
}
return res.status(200).json(response);
+ } else if (req.method === "DELETE") {
+ const response = await deleteLink("dub.sh", oldKey, session.user.id);
+ return res.status(200).json(response);
} else {
- res.setHeader("Allow", ["GET", "POST"]);
+ res.setHeader("Allow", ["GET", "POST", "DELETE"]);
return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
}
}
diff --git a/pages/api/links/index.ts b/pages/api/links/index.ts
index 96363450ee..5571251aaf 100644
--- a/pages/api/links/index.ts
+++ b/pages/api/links/index.ts
@@ -1,7 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next";
import { getLinksForProject, addLink } from "@/lib/upstash";
import { getSession } from "@/lib/auth";
-import { RESERVED_KEYS } from "@/lib/constants";
// This is a special route for creating custom dub.sh links.
@@ -25,13 +24,10 @@ export default async function handler(
}
const response = await addLink(
"dub.sh",
- url,
- key,
- title,
- undefined,
- undefined,
+ { url, key, title },
session.user.id
);
+
if (response === null) {
return res.status(400).json({ error: "Key already exists" });
}
diff --git a/pages/api/projects/[slug]/domains/[domain]/index.ts b/pages/api/projects/[slug]/domains/[domain]/index.ts
index e6fa9726fa..8f541544fb 100644
--- a/pages/api/projects/[slug]/domains/[domain]/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/index.ts
@@ -2,7 +2,7 @@ import { NextApiRequest, NextApiResponse } from "next";
import prisma from "@/lib/prisma";
import { withProjectAuth } from "@/lib/auth";
import { changeDomain } from "@/lib/upstash";
-import { domainRegex } from "@/lib/utils";
+import { validDomainRegex } from "@/lib/utils";
import { addDomain, removeDomain } from "@/lib/domains";
export default withProjectAuth(
@@ -11,7 +11,9 @@ export default withProjectAuth(
const { slug, domain } = req.query as { slug: string; domain: string }; // slug is the domain
const newDomain = req.body;
- const validDomain = domainRegex.test(newDomain);
+ const validDomain =
+ validDomainRegex.test(newDomain) && !newDomain.endsWith(".dub.sh");
+
if (!validDomain) {
return res.status(422).json({
domainError: "Invalid domain",
diff --git a/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts b/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts
index 3a11f1370b..b9ad8e1b95 100644
--- a/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/links/[key]/index.ts
@@ -1,32 +1,58 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { redis, editLink } from "@/lib/upstash";
+import { editLink, deleteLink } from "@/lib/upstash";
import { withProjectAuth } from "@/lib/auth";
+import cloudinary from "cloudinary";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
- if (req.method === "PUT") {
- const { domain, key } = req.query as { domain: string; key: string };
+ const { domain, key: oldKey } = req.query as {
+ domain: string;
+ key: string;
+ };
- let { key: newKey, url, title, timestamp } = req.body;
- if (!newKey || !url || !title || !timestamp) {
+ if (req.method === "PUT") {
+ let { key, url, title, timestamp, description, image } = req.body;
+ if (!key || !url || !title || !timestamp) {
return res
.status(400)
.json({ error: "Missing key or url or title or timestamp" });
}
- const response = await editLink(
- domain,
+ if (image) {
+ const { secure_url } = await cloudinary.v2.uploader.upload(image, {
+ public_id: key,
+ folder: domain,
+ overwrite: true,
+ invalidate: true,
+ });
+ image = secure_url;
+ if (key !== oldKey) {
+ await cloudinary.v2.uploader.destroy(`${domain}/${oldKey}`, {
+ invalidate: true,
+ });
+ }
+ }
+ const response = await editLink(domain, oldKey, {
key,
- newKey,
url,
title,
- timestamp
- );
+ timestamp,
+ description,
+ image,
+ });
if (response === null) {
return res.status(400).json({ error: "Key already exists" });
}
return res.status(200).json(response);
+ } else if (req.method === "DELETE") {
+ const response = await Promise.all([
+ deleteLink(domain, oldKey),
+ cloudinary.v2.uploader.destroy(`${domain}/${oldKey}`, {
+ invalidate: true,
+ }),
+ ]);
+ return res.status(200).json(response);
} else {
- res.setHeader("Allow", ["PUT"]);
+ res.setHeader("Allow", ["POST", "DELETE"]);
return res
.status(405)
.json({ error: `Method ${req.method} Not Allowed` });
diff --git a/pages/api/projects/[slug]/domains/[domain]/links/index.ts b/pages/api/projects/[slug]/domains/[domain]/links/index.ts
index 338f47af69..062dc24b97 100644
--- a/pages/api/projects/[slug]/domains/[domain]/links/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/links/index.ts
@@ -5,11 +5,13 @@ import cloudinary from "cloudinary";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
+ // GET /api/projects/[slug]/domains/[domain]/links - Get all links for a project
if (req.method === "GET") {
const { domain } = req.query as { domain: string };
const links = await getLinksForProject(domain);
return res.status(200).json(links);
- // POST /api/links – create a new link
+
+ // POST /api/projects/[slug]/domains/[domain]/links – create a new link
} else if (req.method === "POST") {
const { domain } = req.query as { domain: string };
let { key, url, title, description, image } = req.body;
@@ -24,14 +26,13 @@ export default withProjectAuth(
});
image = secure_url;
}
- const response = await addLink(
- domain,
+ const response = await addLink(domain, {
url,
key,
title,
description,
- image
- );
+ image,
+ });
if (response === null) {
return res.status(400).json({ error: "Key already exists" });
}
diff --git a/pages/api/projects/[slug]/exists.ts b/pages/api/projects/[slug]/exists.ts
index e2c252c550..146d1597b2 100644
--- a/pages/api/projects/[slug]/exists.ts
+++ b/pages/api/projects/[slug]/exists.ts
@@ -1,6 +1,7 @@
import { NextApiRequest, NextApiResponse } from "next";
import { getSession } from "@/lib/auth";
import prisma from "@/lib/prisma";
+import { RESERVED_KEYS, DEFAULT_REDIRECTS } from "@/lib/constants";
export default async function handler(
req: NextApiRequest,
@@ -13,6 +14,9 @@ export default async function handler(
// GET /api/projects/[slug]/exists – check if a project exists
if (req.method === "GET") {
+ if (RESERVED_KEYS.has(slug) || DEFAULT_REDIRECTS[slug]) {
+ return res.status(200).json(1);
+ }
const project = await prisma.project.findUnique({
where: {
slug,
diff --git a/pages/api/projects/index.ts b/pages/api/projects/index.ts
index e36581f0b7..67ac43faf8 100644
--- a/pages/api/projects/index.ts
+++ b/pages/api/projects/index.ts
@@ -1,8 +1,9 @@
import { NextApiRequest, NextApiResponse } from "next";
import { getSession } from "@/lib/auth";
import prisma from "@/lib/prisma";
-import { domainRegex } from "@/lib/utils";
+import { validDomainRegex } from "@/lib/utils";
import { addDomain, removeDomain } from "@/lib/domains";
+import { RESERVED_KEYS, DEFAULT_REDIRECTS } from "@/lib/constants";
export default async function handler(
req: NextApiRequest,
@@ -30,11 +31,14 @@ export default async function handler(
if (!name || !slug || !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 validDomain = domainRegex.test(domain);
+ let slugError = null;
+ if (slug.includes(" ") || slug.includes(".")) {
+ slugError = "Slug cannot contain spaces or periods";
+ } else if (RESERVED_KEYS.has(slug) || DEFAULT_REDIRECTS[slug]) {
+ slugError = "Cannot use reserved slugs";
+ }
+ const validDomain =
+ validDomainRegex.test(domain) && !domain.endsWith(".dub.sh");
if (slugError || !validDomain) {
return res.status(422).json({
slugError,
diff --git a/pages/app/[slug]/index.tsx b/pages/app/[slug]/index.tsx
index 9ddd2364e3..f9bea9e53a 100644
--- a/pages/app/[slug]/index.tsx
+++ b/pages/app/[slug]/index.tsx
@@ -1,20 +1,14 @@
import AppLayout from "components/layout/app";
-import { useMemo } from "react";
import useProject from "@/lib/swr/use-project";
-import useUsage from "@/lib/swr/use-usage";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
-import { useAddLinkModal } from "@/components/app/add-link-modal";
+import { useAddEditLinkModal } from "@/components/app/add-link-modal";
import LinksContainer from "@/components/app/links-container";
import ErrorPage from "next/error";
export default function ProjectLinks() {
const { project, error } = useProject();
- const { exceededUsage } = useUsage(project);
- const { AddLinkModal, AddLinkButton } = useAddLinkModal({
- domainVerified: project?.domainVerified,
- exceededUsage,
- });
+ const { AddEditLinkModal, AddEditLinkButton } = useAddEditLinkModal({});
// handle error page
if (error && error.status === 404) {
@@ -23,22 +17,16 @@ export default function ProjectLinks() {
return (
<AppLayout>
- {project && <AddLinkModal />}
+ {project && <AddEditLinkModal />}
<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>
- <AddLinkButton />
+ <AddEditLinkButton />
</div>
</MaxWidthWrapper>
</div>
- {project && (
- <LinksContainer
- exceededUsage={exceededUsage}
- AddLinkButton={AddLinkButton}
- domain={project?.domain}
- />
- )}
+ {project && <LinksContainer AddEditLinkButton={AddEditLinkButton} />}
</AppLayout>
);
}
diff --git a/pages/app/links/index.tsx b/pages/app/links/index.tsx
index 7e1079d6ec..38b5f3e0ca 100644
--- a/pages/app/links/index.tsx
+++ b/pages/app/links/index.tsx
@@ -1,26 +1,29 @@
import AppLayout from "components/layout/app";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
-import { useAddLinkModal } from "@/components/app/add-link-modal";
+import { useAddEditLinkModal } from "@/components/app/add-link-modal";
import LinksContainer from "@/components/app/links-container";
export default function Links() {
- const { AddLinkModal, AddLinkButton } = useAddLinkModal({
+ const { AddEditLinkModal, AddEditLinkButton } = useAddEditLinkModal({
domainVerified: true,
exceededUsage: false,
});
return (
<AppLayout>
- <AddLinkModal />
+ <AddEditLinkModal />
<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">My Dub.sh Links</h1>
- <AddLinkButton />
+ <AddEditLinkButton />
</div>
</MaxWidthWrapper>
</div>
- <LinksContainer exceededUsage={false} AddLinkButton={AddLinkButton} />
+ <LinksContainer
+ exceededUsage={false}
+ AddEditLinkButton={AddEditLinkButton}
+ />
</AppLayout>
);
}
diff --git a/pages/placeholder/[[...domain]].tsx b/pages/placeholder/[[...domain]].tsx
index f21cde6b02..ee30321da1 100644
--- a/pages/placeholder/[[...domain]].tsx
+++ b/pages/placeholder/[[...domain]].tsx
@@ -6,7 +6,7 @@ import { GetStaticProps } from "next";
export default function Placeholder({ domain }: { domain: string }) {
return (
- <HomeLayout>
+ <HomeLayout domain={domain}>
<Globe hostname={domain} />
</HomeLayout>
);