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.

started on Stripe integration + usage limits

Steven Tey56cb9ddbda2a
diff --git a/components/app/add-link-modal.tsx b/components/app/add-link-modal.tsx
index 6b1d56467c..fcaba46470 100644
--- a/components/app/add-link-modal.tsx
+++ b/components/app/add-link-modal.tsx
@@ -18,8 +18,9 @@ import {
import { useDebounce } from "use-debounce";
import TextareaAutosize from "react-textarea-autosize";
import { mutate } from "swr";
+import Tooltip from "@/components/shared/tooltip";
-function AddLinkModalHelper({
+function AddLinkModal({
showAddLinkModal,
setShowAddLinkModal,
domain,
@@ -275,12 +276,51 @@ function AddLinkModalHelper({
);
}
-export function useAddLinkModal({ domain }: { domain?: string }) {
+function AddLinkButton({
+ domainVerified,
+ exceededUsage,
+ setShowAddLinkModal,
+}: {
+ domainVerified: boolean;
+ exceededUsage: boolean;
+ setShowAddLinkModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ return !domainVerified ? (
+ <Tooltip content="You can only start adding links after your project domain is configured.">
+ <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
+ </div>
+ </Tooltip>
+ ) : exceededUsage ? (
+ <Tooltip content="You have exceeded your usage limit. We're still collecting data on your existing links, but you need to upgrade to add more links.">
+ <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
+ </div>
+ </Tooltip>
+ ) : (
+ <button
+ 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>
+ );
+}
+
+export function useAddLinkModal({
+ domainVerified,
+ exceededUsage,
+ domain,
+}: {
+ domainVerified: boolean;
+ exceededUsage: boolean;
+ domain?: string;
+}) {
const [showAddLinkModal, setShowAddLinkModal] = useState(false);
- const AddLinkModal = useCallback(() => {
+ const AddLinkModalCallback = useCallback(() => {
return (
- <AddLinkModalHelper
+ <AddLinkModal
showAddLinkModal={showAddLinkModal}
setShowAddLinkModal={setShowAddLinkModal}
domain={domain}
@@ -288,8 +328,22 @@ export function useAddLinkModal({ domain }: { domain?: string }) {
);
}, [showAddLinkModal, setShowAddLinkModal, domain]);
+ const AddLinkButtonCallback = useCallback(() => {
+ return (
+ <AddLinkButton
+ domainVerified={domainVerified}
+ exceededUsage={exceededUsage}
+ setShowAddLinkModal={setShowAddLinkModal}
+ />
+ );
+ }, [domainVerified, exceededUsage, setShowAddLinkModal]);
+
return useMemo(
- () => ({ setShowAddLinkModal, AddLinkModal }),
- [setShowAddLinkModal, AddLinkModal]
+ () => ({
+ setShowAddLinkModal,
+ AddLinkModal: AddLinkModalCallback,
+ AddLinkButton: AddLinkButtonCallback,
+ }),
+ [setShowAddLinkModal, AddLinkModalCallback, AddLinkButtonCallback]
);
}
diff --git a/components/app/add-project-modal.tsx b/components/app/add-project-modal.tsx
index 8426ad5c7f..906c3c5e00 100644
--- a/components/app/add-project-modal.tsx
+++ b/components/app/add-project-modal.tsx
@@ -9,13 +9,10 @@ import {
} from "react";
import { useRouter } from "next/router";
import BlurImage from "@/components/shared/blur-image";
-import {
- LoadingDots,
- LoadingCircle,
- AlertCircleFill,
-} from "@/components/shared/icons";
+import { LoadingDots, AlertCircleFill } from "@/components/shared/icons";
import { useDebounce } from "use-debounce";
import { mutate } from "swr";
+import { generateSlugFromName } from "@/lib/utils";
function AddProjectModalHelper({
showAddProjectModal,
@@ -27,7 +24,6 @@ function AddProjectModalHelper({
const router = useRouter();
const [slugExistsError, setSlugExistsError] = useState(false);
- const [generatingSlug, setGeneratingSlug] = useState(false);
const [saving, setSaving] = useState(false);
const [data, setData] = useState<{
@@ -53,17 +49,13 @@ function AddProjectModalHelper({
}
}, [debouncedSlug]);
- const generateRandomSlug = useCallback(async () => {
- setGeneratingSlug(true);
- const res = await fetch(
- domain
- ? `/api/projects/${slug}/domains/${domain}/links/random`
- : `/api/edge/links/random`
- );
- const key = await res.json();
- setData((prev) => ({ ...prev, key }));
- setGeneratingSlug(false);
- }, []);
+ useEffect(() => {
+ setData((prev) => ({
+ ...prev,
+ slug: name.toLowerCase().replaceAll(" ", "-"),
+ domain: generateSlugFromName(name),
+ }));
+ }, [name]);
return (
<Modal
diff --git a/components/app/link-card.tsx b/components/app/link-card.tsx
index 3d493299a9..cb091f3cce 100644
--- a/components/app/link-card.tsx
+++ b/components/app/link-card.tsx
@@ -7,12 +7,15 @@ 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 from "@/components/shared/tooltip";
export default function LinkCard({
props,
+ exceededUsage,
domain,
}: {
props: LinkProps;
+ exceededUsage: boolean;
domain?: string;
}) {
const { key, url, title, timestamp } = props;
@@ -78,12 +81,20 @@ export default function LinkCard({
<p className="text-sm text-gray-500 dark:text-gray-400">
Added {timeAgo(timestamp)}
</p>
- <button
- 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
- </button>
+ {exceededUsage ? (
+ <Tooltip content="You have exceeded your usage limit. We're still collecting data on your existing links, but you need to upgrade to edit them.">
+ <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">
+ Edit
+ </div>
+ </Tooltip>
+ ) : (
+ <button
+ 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
+ </button>
+ )}
</div>
</div>
);
diff --git a/components/app/links-container.tsx b/components/app/links-container.tsx
new file mode 100644
index 0000000000..317a35582e
--- /dev/null
+++ b/components/app/links-container.tsx
@@ -0,0 +1,54 @@
+import { useRouter } from "next/router";
+import useSWR from "swr";
+import { fetcher } from "@/lib/utils";
+import LinkCard from "@/components/app/link-card";
+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 { ProjectProps, LinkProps } from "@/lib/types";
+
+export default function LinksContainer({
+ project,
+ exceededUsage,
+ AddLinkButton,
+}: {
+ project: ProjectProps;
+ exceededUsage: boolean;
+ AddLinkButton: () => JSX.Element;
+}) {
+ const router = useRouter();
+ const { slug } = router.query as {
+ slug: string;
+ };
+ const { data: links } = useSWR<LinkProps[]>(
+ router.isReady &&
+ project &&
+ `/api/projects/${slug}/domains/${project.domain}/links`,
+ fetcher
+ );
+
+ return (
+ <MaxWidthWrapper>
+ <div className="my-10 grid grid-cols-1 gap-3">
+ {links ? (
+ links.length > 0 ? (
+ links.map((props) => (
+ <LinkCard
+ key={props.key}
+ props={props}
+ domain={project?.domain}
+ exceededUsage={exceededUsage}
+ />
+ ))
+ ) : (
+ <NoLinksPlaceholder AddLinkButton={AddLinkButton} />
+ )
+ ) : (
+ Array.from({ length: 3 }).map((_, i) => (
+ <LinkCardPlaceholder key={i} />
+ ))
+ )}
+ </div>
+ </MaxWidthWrapper>
+ );
+}
diff --git a/components/app/no-links-placeholder.tsx b/components/app/no-links-placeholder.tsx
index e64b039494..7a0a443fa1 100644
--- a/components/app/no-links-placeholder.tsx
+++ b/components/app/no-links-placeholder.tsx
@@ -1,12 +1,9 @@
-import Tooltip from "@/components/shared/tooltip";
import BlurImage from "@/components/shared/blur-image";
export default function NoLinksPlaceholder({
- setShowAddLinkModal,
- domainVerified,
+ AddLinkButton,
}: {
- setShowAddLinkModal: (show: boolean) => void;
- domainVerified?: boolean;
+ AddLinkButton: () => JSX.Element;
}) {
return (
<div className="border border-gray-200 rounded-md bg-white py-12 flex flex-col justify-center items-center">
@@ -20,20 +17,9 @@ export default function NoLinksPlaceholder({
height={400}
className="-my-8"
/>
- {domainVerified || domainVerified === undefined ? (
- <button
- 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 z-10"
- >
- Add a link
- </button>
- ) : (
- <Tooltip content="You can only start adding links after your project domain is configured.">
- <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 z-10">
- Add a link
- </div>
- </Tooltip>
- )}
+ <div className="z-10">
+ <AddLinkButton />
+ </div>
</div>
);
}
diff --git a/components/app/plan-usage.tsx b/components/app/plan-usage.tsx
new file mode 100644
index 0000000000..a4cf14e75f
--- /dev/null
+++ b/components/app/plan-usage.tsx
@@ -0,0 +1,102 @@
+import useSWR from "swr";
+import { fetcher, nFormatter } from "@/lib/utils";
+import { useRouter } from "next/router";
+import { ProjectProps } from "@/lib/types";
+import Tooltip from "@/components/shared/tooltip";
+import { Divider, Infinity, QuestionCircle } from "@/components/shared/icons";
+import { motion } from "framer-motion";
+
+export default function PlanUsage({ project }: { project: ProjectProps }) {
+ const router = useRouter();
+ const { slug } = router.query as { slug: string };
+
+ const { data: usage } = useSWR<number>(
+ project && `/api/projects/${slug}/domains/${project.domain}/usage`,
+ fetcher
+ );
+
+ const { data: linkCount } = useSWR<number>(
+ project && `/api/projects/${slug}/domains/${project.domain}/links/count`,
+ fetcher
+ );
+
+ return (
+ <div className="bg-white rounded-lg border border-gray-200">
+ <div className="flex flex-col space-y-3 p-10">
+ <h2 className="text-xl font-medium">Plan &amp; Usage</h2>
+ <p className="text-gray-500 text-sm">
+ You are currently on the{" "}
+ <span className="capitalize bg-blue-500 text-white rounded-full px-2 py-0.5 text-xs">
+ {project?.plan}
+ </span>{" "}
+ plan.
+ </p>
+ </div>
+ <div className="border-b border-gray-200" />
+ <div className="grid grid-cols-1 sm:grid-cols-2 divide-y sm:divide-y-0 sm:divide-x divide-gray-200">
+ <div className="p-10 flex flex-col space-y-2">
+ <div className="flex items-center">
+ <h3 className="font-medium">Link Clicks</h3>
+ <Tooltip content="Number of link clicks that your project has had this month.">
+ <div className="flex justify-center w-8 h-4">
+ <QuestionCircle className="w-4 h-4 text-gray-600" />
+ </div>
+ </Tooltip>
+ </div>
+ {usage && project ? (
+ <p className="text-sm text-gray-600">
+ {usage} / {project.usageLimit} clicks (
+ {(usage / project.usageLimit) * 100}%)
+ </p>
+ ) : (
+ <div className="h-5 w-32 bg-gray-200 rounded-md animate-pulse" />
+ )}
+ <div className="bg-gray-200 rounded-full h-3 w-full overflow-hidden">
+ <motion.div
+ initial={{ width: 0 }}
+ animate={{
+ width:
+ project && usage
+ ? (usage / project.usageLimit) * 100 + "%"
+ : "0%",
+ }}
+ transition={{ duration: 0.5, type: "spring" }}
+ className={`${
+ usage > project?.usageLimit ? "bg-red-500" : "bg-blue-500"
+ } rounded-full h-3`}
+ />
+ </div>
+ </div>
+ <div className="p-10">
+ <h3 className="font-medium">Number of Links</h3>
+ <div className="flex items-center mt-4">
+ {linkCount ? (
+ <p className="text-2xl font-semibold text-black">
+ {nFormatter(linkCount)}
+ </p>
+ ) : (
+ <div className="w-8 h-8 bg-gray-200 rounded-md animate-pulse" />
+ )}
+ <Divider className="w-8 h-8 text-gray-500" />
+ <Infinity className="w-8 h-8 text-gray-500" />
+ </div>
+ </div>
+ </div>
+ <div className="border-b border-gray-200" />
+ <div className="px-10 py-5 flex justify-between items-center">
+ <p className="text-gray-500 text-sm">
+ For{" "}
+ <Tooltip content="1 million link clicks per month">
+ <span className="font-medium text-gray-700 underline underline-offset-2 cursor-default hover:text-black">
+ increased limits
+ </span>
+ </Tooltip>
+ , upgrade to the Pro plan.
+ </p>
+ <button className="bg-blue-500 text-white border-blue-500 hover:text-blue-500 hover:bg-white h-9 w-24 text-sm border-solid border rounded-md focus:outline-none transition-all ease-in-out duration-150">
+ Upgrade
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/components/shared/icons/alert-circle-fill.tsx b/components/shared/icons/alert-circle-fill.tsx
index 0704c4a058..0eae240285 100644
--- a/components/shared/icons/alert-circle-fill.tsx
+++ b/components/shared/icons/alert-circle-fill.tsx
@@ -8,8 +8,8 @@ export default function AlertCircleFill({ className }: { className: string }) {
strokeLinejoin="round"
strokeWidth="1.5"
viewBox="0 0 24 24"
- width="14"
- height="14"
+ width="24"
+ height="24"
className={className}
>
<circle cx="12" cy="12" r="10" fill="currentColor" />
diff --git a/components/shared/icons/index.tsx b/components/shared/icons/index.tsx
index 7fff13d2fb..d9ff6866f3 100644
--- a/components/shared/icons/index.tsx
+++ b/components/shared/icons/index.tsx
@@ -13,7 +13,9 @@ 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 QuestionCircle } from "./question-circle";
export { default as ExternalLink } from "./external-link";
export { default as XCircleFill } from "./x-circle-fill";
export { default as CheckCircleFill } from "./check-circle-fill";
export { default as Link } from "./link";
+export { default as Infinity } from "./infinity";
diff --git a/components/shared/icons/infinity.tsx b/components/shared/icons/infinity.tsx
new file mode 100644
index 0000000000..bca62cf639
--- /dev/null
+++ b/components/shared/icons/infinity.tsx
@@ -0,0 +1,18 @@
+export default function Infinity({ className }: { className: string }) {
+ return (
+ <svg
+ fill="none"
+ shapeRendering="geometricPrecision"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ viewBox="0 0 24 24"
+ width="24"
+ height="24"
+ className={className}
+ >
+ <path d="M13.833 8.875S15.085 7 18.043 7C21 7 23 9.5 23 12s-1.784 5-4.864 5-4.914-3.124-6.136-5c-1.222-1.875-3.392-5-6.446-5S1 9.5 1 12s1.351 5 4.648 5c3.296 0 4.519-1.875 4.519-1.875" />
+ </svg>
+ );
+}
diff --git a/components/shared/icons/question-circle.tsx b/components/shared/icons/question-circle.tsx
new file mode 100644
index 0000000000..d20d9ca150
--- /dev/null
+++ b/components/shared/icons/question-circle.tsx
@@ -0,0 +1,20 @@
+export default function QuestionCircle({ className }: { className: string }) {
+ return (
+ <svg
+ fill="none"
+ shapeRendering="geometricPrecision"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ viewBox="0 0 24 24"
+ width="24"
+ height="24"
+ className={className}
+ >
+ <path d="M12 22c5.523 0 10-4.477 10-10S17.523 2 12 2 2 6.477 2 12s4.477 10 10 10z" />
+ <path d="M9.09 9a3 3 0 015.83 1c0 2-3 3-3 3" />
+ <circle cx="12" cy="17" r=".5" />
+ </svg>
+ );
+}
diff --git a/lib/auth.ts b/lib/auth.ts
index 6c69dad678..0c4f03f3ac 100644
--- a/lib/auth.ts
+++ b/lib/auth.ts
@@ -2,6 +2,7 @@ import { NextApiHandler, NextApiRequest, NextApiResponse } from "next";
import { unstable_getServerSession } from "next-auth/next";
import { authOptions } from "@/pages/api/auth/[...nextauth]";
import prisma from "@/lib/prisma";
+import { getUsage } from "./upstash";
interface Session {
user: {
@@ -49,10 +50,23 @@ const withProjectAuth =
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");
+ if (isWriteEditLink && req.method !== "GET") {
+ if (!project.domainVerified) {
+ return res
+ .status(401)
+ .end(
+ "Unauthorized: Cannot add or edit links when domain is not verified."
+ );
+ } else {
+ const usage = await getUsage(project.domain);
+ if (usage > project.usageLimit) {
+ return res
+ .status(403)
+ .end(
+ "Unauthorized: Cannot add or edit links when usage limits are exceeded."
+ );
+ }
+ }
}
return handler(req, res);
diff --git a/lib/constants.ts b/lib/constants.ts
index 6cac766793..575eb142fa 100644
--- a/lib/constants.ts
+++ b/lib/constants.ts
@@ -267,3 +267,278 @@ export const COUNTRIES: { [key: string]: string } = {
SS: "South Sudan",
XK: "Kosovo",
};
+
+export const ccTLDs = [
+ "af",
+ "ax",
+ "al",
+ "dz",
+ "as",
+ "ad",
+ "ao",
+ "ai",
+ "aq",
+ "ag",
+ "ar",
+ "am",
+ "aw",
+ "ac",
+ "au",
+ "at",
+ "az",
+ "bs",
+ "bh",
+ "bd",
+ "bb",
+ "eus",
+ "by",
+ "be",
+ "bz",
+ "bj",
+ "bm",
+ "bt",
+ "bo",
+ "bq",
+ "an",
+ "nl",
+ "ba",
+ "bw",
+ "bv",
+ "br",
+ "io",
+ "vg",
+ "bn",
+ "bg",
+ "bf",
+ "mm",
+ "bi",
+ "kh",
+ "cm",
+ "ca",
+ "cv",
+ "cat",
+ "ky",
+ "cf",
+ "td",
+ "cl",
+ "cn",
+ "cx",
+ "cc",
+ "co",
+ "km",
+ "cd",
+ "cg",
+ "ck",
+ "cr",
+ "ci",
+ "hr",
+ "cu",
+ "cw",
+ "cy",
+ "cz",
+ "dk",
+ "dj",
+ "dm",
+ "do",
+ "tl",
+ "tp",
+ "ec",
+ "eg",
+ "sv",
+ "gq",
+ "er",
+ "ee",
+ "et",
+ "eu",
+ "fk",
+ "fo",
+ "fm",
+ "fj",
+ "fi",
+ "fr",
+ "gf",
+ "pf",
+ "tf",
+ "ga",
+ "gal",
+ "gm",
+ "ps",
+ "ge",
+ "de",
+ "gh",
+ "gi",
+ "gr",
+ "gl",
+ "gd",
+ "gp",
+ "gu",
+ "gt",
+ "gg",
+ "gn",
+ "gw",
+ "gy",
+ "ht",
+ "hm",
+ "hn",
+ "hk",
+ "hu",
+ "is",
+ "in",
+ "id",
+ "ir",
+ "iq",
+ "ie",
+ "im",
+ "il",
+ "it",
+ "jm",
+ "jp",
+ "je",
+ "jo",
+ "kz",
+ "ke",
+ "ki",
+ "kw",
+ "kg",
+ "la",
+ "lv",
+ "lb",
+ "ls",
+ "lr",
+ "ly",
+ "li",
+ "lt",
+ "lu",
+ "mo",
+ "mk",
+ "mg",
+ "mw",
+ "my",
+ "mv",
+ "ml",
+ "mt",
+ "mh",
+ "mq",
+ "mr",
+ "mu",
+ "yt",
+ "mx",
+ "md",
+ "mc",
+ "mn",
+ "me",
+ "ms",
+ "ma",
+ "mz",
+ "mm",
+ "na",
+ "nr",
+ "np",
+ "nl",
+ "nc",
+ "nz",
+ "ni",
+ "ne",
+ "ng",
+ "nu",
+ "nf",
+ "nc",
+ "tr",
+ "kp",
+ "mp",
+ "no",
+ "om",
+ "pk",
+ "pw",
+ "ps",
+ "pa",
+ "pg",
+ "py",
+ "pe",
+ "ph",
+ "pn",
+ "pl",
+ "pt",
+ "pr",
+ "qa",
+ "ro",
+ "ru",
+ "rw",
+ "re",
+ "bq",
+ "an",
+ "bl",
+ "gp",
+ "fr",
+ "sh",
+ "kn",
+ "lc",
+ "mf",
+ "gp",
+ "fr",
+ "pm",
+ "vc",
+ "ws",
+ "sm",
+ "st",
+ "sa",
+ "sn",
+ "rs",
+ "sc",
+ "sl",
+ "sg",
+ "bq",
+ "an",
+ "nl",
+ "sx",
+ "an",
+ "sk",
+ "si",
+ "sb",
+ "so",
+ "so",
+ "za",
+ "gs",
+ "kr",
+ "ss",
+ "es",
+ "lk",
+ "sd",
+ "sr",
+ "sj",
+ "sz",
+ "se",
+ "ch",
+ "sy",
+ "tw",
+ "tj",
+ "tz",
+ "th",
+ "tg",
+ "tk",
+ "to",
+ "tt",
+ "tn",
+ "tr",
+ "tm",
+ "tc",
+ "tv",
+ "ug",
+ "ua",
+ "ae",
+ "uk",
+ "us",
+ "vi",
+ "uy",
+ "uz",
+ "vu",
+ "va",
+ "ve",
+ "vn",
+ "wf",
+ "eh",
+ "ma",
+ "ye",
+ "zm",
+ "zw",
+];
diff --git a/lib/types.ts b/lib/types.ts
index 9f2ad0f9a1..3564bb428a 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -10,6 +10,8 @@ export interface ProjectProps {
slug: string;
domain: string;
domainVerified: boolean;
+ plan: string;
+ usageLimit: number;
links: LinkProps[];
}
diff --git a/lib/upstash.ts b/lib/upstash.ts
index 88b562d59b..ee371d0669 100644
--- a/lib/upstash.ts
+++ b/lib/upstash.ts
@@ -4,6 +4,7 @@ import { LOCALHOST_GEO_DATA } from "@/lib/constants";
import { LinkProps } from "@/lib/types";
import { customAlphabet } from "nanoid";
import { getTitleFromUrl } from "@/lib/utils";
+import { stripe } from "@/lib/stripe";
// Initiate Redis instance
export const redis = new Redis({
@@ -78,7 +79,7 @@ export async function recordClick(
req: NextRequest,
key?: string
) {
- return redis.zadd(
+ return await redis.zadd(
key ? `${hostname}:clicks:${key}` : `${hostname}:root:clicks`,
{
score: Date.now(),
@@ -215,3 +216,32 @@ export async function editLink(
return await pipeline.exec();
}
}
+
+export async function getUsage(hostname: string) {
+ const cachedUsage = await redis.get(`usage:${hostname}`);
+ if (cachedUsage) {
+ return cachedUsage;
+ }
+ console.log("no cached usage found. computing from scratch...");
+ var date = new Date();
+ var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
+ var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);
+
+ const links = await redis.zrange(`${hostname}:links:timestamps`, 0, -1);
+ let results: number[] = [];
+
+ if (links.length > 0) {
+ const pipeline = redis.pipeline();
+ links.forEach((link) => {
+ pipeline.zcount(
+ `${hostname}:clicks:${link}`,
+ firstDay.getTime(),
+ lastDay.getTime()
+ );
+ });
+ results = await pipeline.exec();
+ }
+ const usage = results.reduce((acc, curr) => acc + curr, 0);
+ await redis.setex(`usage:${hostname}`, 3600, usage); // cache for 1 hour
+ return usage;
+}
diff --git a/lib/utils.ts b/lib/utils.ts
index 80ba6fd612..11da83db70 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -1,4 +1,5 @@
import ms from "ms";
+import { ccTLDs } from "./constants";
export async function fetcher<JSON = any>(
input: RequestInfo,
@@ -88,3 +89,33 @@ export const timeAgo = (timestamp: number): string => {
if (!timestamp) return "never";
return `${ms(Date.now() - timestamp)} ago`;
};
+
+export const generateSlugFromName = (name: string) => {
+ const normalizedName = name.toLowerCase().replaceAll(" ", "-");
+ if (normalizedName.length < 3) {
+ return "";
+ }
+ if (ccTLDs.some((tld) => normalizedName.endsWith(tld))) {
+ return `${normalizedName.slice(0, -2)}.${normalizedName.slice(-2)}`;
+ }
+ // remove vowels
+ const devowel = normalizedName.replace(/[aeiou]/g, "");
+ if (devowel.length >= 3 && ccTLDs.some((tld) => devowel.endsWith(tld))) {
+ return `${devowel.slice(0, -2)}.${devowel.slice(-2)}`;
+ }
+
+ const acronym = normalizedName
+ .split("-")
+ .map((word) => word[0])
+ .join("");
+
+ if (acronym.length >= 3 && ccTLDs.some((tld) => acronym.endsWith(tld))) {
+ return `${acronym.slice(0, -2)}.${acronym.slice(-2)}`;
+ }
+
+ const shortestString = [normalizedName, devowel, acronym].reduce((a, b) =>
+ a.length < b.length ? a : b
+ );
+
+ return `${shortestString}.sh`;
+};
diff --git a/pages/api/projects/[slug]/domains/[domain]/links/index.ts b/pages/api/projects/[slug]/domains/[domain]/links/index.ts
index f9bbbadd6c..2783ac9aa4 100644
--- a/pages/api/projects/[slug]/domains/[domain]/links/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/links/index.ts
@@ -1,11 +1,15 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { addLink } from "@/lib/upstash";
+import { addLink, getLinksForProject } from "@/lib/upstash";
import { withProjectAuth } from "@/lib/auth";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
- // POST /api/links – create a new link
- if (req.method === "POST") {
+ 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
+ } else if (req.method === "POST") {
const { domain } = req.query as { domain: string };
let { key, url, title } = req.body;
if (!domain || !url) {
@@ -17,7 +21,7 @@ export default withProjectAuth(
}
return res.status(200).json({ key, url, title });
} else {
- res.setHeader("Allow", ["POST"]);
+ res.setHeader("Allow", ["GET", "POST"]);
return res
.status(405)
.json({ error: `Method ${req.method} Not Allowed` });
diff --git a/pages/api/projects/[slug]/domains/[domain]/usage.ts b/pages/api/projects/[slug]/domains/[domain]/usage.ts
index 51dc6197a8..d727598d6e 100644
--- a/pages/api/projects/[slug]/domains/[domain]/usage.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/usage.ts
@@ -1,20 +1,14 @@
import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
-import { redis } from "@/lib/upstash";
+import { getUsage } from "@/lib/upstash";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
- // GET /api/projects/[slug]/exists – check if a project exists
+ // GET /api/projects/[slug]/domains/[domain]/usage – get project usage
if (req.method === "GET") {
const { domain } = req.query as { domain: string };
-
- const clicks = await redis.zrange(`${domain}:links:clicks`, 0, -1, {
- withScores: true,
- });
- const totalClicks = (
- clicks.filter((_, i) => i % 2 === 1) as number[]
- ).reduce((a, b) => a + b, 0);
- return res.status(200).json({ totalClicks });
+ const usage = await getUsage(domain);
+ return res.status(200).json(usage);
} else {
res.setHeader("Allow", ["GET"]);
return res
diff --git a/pages/api/projects/[slug]/index.ts b/pages/api/projects/[slug]/index.ts
index 75b857787c..e2813fd90f 100644
--- a/pages/api/projects/[slug]/index.ts
+++ b/pages/api/projects/[slug]/index.ts
@@ -30,15 +30,7 @@ export default async function handler(
},
});
if (project) {
- if (project.domainVerified) {
- // only fetch links if project domain has been verified
- const links = await getLinksForProject(project.domain);
- return res.status(200).json({
- ...project,
- links,
- });
- }
- return res.status(200).json({ ...project, links: [] });
+ return res.status(200).json(project);
} else {
return res.status(404).json({ error: "Project not found" });
}
diff --git a/pages/api/projects/index.ts b/pages/api/projects/index.ts
index 56340ffddf..d871981b74 100644
--- a/pages/api/projects/index.ts
+++ b/pages/api/projects/index.ts
@@ -1,6 +1,7 @@
import { NextApiRequest, NextApiResponse } from "next";
import { getSession } from "@/lib/auth";
import prisma from "@/lib/prisma";
+import { stripe } from "@/lib/stripe";
export default async function handler(
req: NextApiRequest,
@@ -43,20 +44,34 @@ export default async function handler(
},
},
});
- if (project?.domain) {
- const response = await fetch(
- `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains?teamId=${process.env.VERCEL_TEAM_ID}`,
- {
- body: `{\n "name": "${project.domain}"\n}`,
- headers: {
- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
- "Content-Type": "application/json",
- },
- method: "POST",
- }
- );
- const json = await response.json();
- return res.status(200).json({ project, domain: json });
+ if (project) {
+ const [domainResponse, stripeResponse] = await Promise.all([
+ fetch(
+ `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains?teamId=${process.env.VERCEL_TEAM_ID}`,
+ {
+ body: `{\n "name": "${project.domain}"\n}`,
+ headers: {
+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
+ "Content-Type": "application/json",
+ },
+ method: "POST",
+ }
+ ).then((res) => res.json()),
+ stripe.customers.create({
+ name,
+ email: session.user.email,
+ }),
+ ]);
+ console.log(stripeResponse);
+ await prisma.project.update({
+ where: {
+ id: project.id,
+ },
+ data: {
+ stripeId: stripeResponse.id,
+ },
+ });
+ return res.status(200).json({ project, domain: domainResponse });
}
return res.status(400).json({ error: "Project not created" });
} catch (error: any) {
diff --git a/pages/app/[slug]/index.tsx b/pages/app/[slug]/index.tsx
index 03d8678d0f..54f2399bca 100644
--- a/pages/app/[slug]/index.tsx
+++ b/pages/app/[slug]/index.tsx
@@ -2,14 +2,11 @@ import AppLayout from "components/layout/app";
import { useRouter } from "next/router";
import useSWR from "swr";
import { fetcher } from "@/lib/utils";
-import LinkCard from "@/components/app/link-card";
-import LinkCardPlaceholder from "@/components/app/link-card-placeholder";
-import { useEffect } from "react";
+import { useMemo, useEffect } from "react";
import { ProjectProps } from "@/lib/types";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
import { useAddLinkModal } from "@/components/app/add-link-modal";
-import Tooltip from "@/components/shared/tooltip";
-import NoLinksPlaceholder from "@/components/app/no-links-placeholder";
+import LinksContainer from "@/components/app/links-container";
export default function ProjectLinks() {
const router = useRouter();
@@ -17,7 +14,7 @@ export default function ProjectLinks() {
slug: string;
};
- const { data, error } = useSWR<ProjectProps>(
+ const { data: project, error } = useSWR<ProjectProps>(
router.isReady && `/api/projects/${slug}`,
fetcher
);
@@ -28,54 +25,42 @@ export default function ProjectLinks() {
}
}, [error]);
- const { setShowAddLinkModal, AddLinkModal } = useAddLinkModal({
- domain: data?.domain,
+ const { data: usage } = useSWR(
+ router.isReady &&
+ project &&
+ `/api/projects/${slug}/domains/${project.domain}/usage`,
+ fetcher
+ );
+
+ const exceededUsage = useMemo(() => {
+ if (usage && project) {
+ return usage > project?.usageLimit;
+ }
+ return true; // assume exceeded usage until we know otherwise (not ideal tho :/)
+ }, [usage, project]);
+
+ const { AddLinkModal, AddLinkButton } = useAddLinkModal({
+ domainVerified: project?.domainVerified,
+ domain: project?.domain,
+ exceededUsage,
});
return (
<AppLayout>
- {data && <AddLinkModal />}
+ {project && <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?.domainVerified ? (
- <button
- 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.">
- <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
- </div>
- </Tooltip>
- )}
+ <AddLinkButton />
</div>
</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} domain={data.domain} />
- ))
- ) : (
- <NoLinksPlaceholder
- setShowAddLinkModal={setShowAddLinkModal}
- domainVerified={data?.domainVerified}
- />
- )
- ) : (
- Array.from({ length: 3 }).map((_, i) => (
- <LinkCardPlaceholder key={i} />
- ))
- )}
- </div>
- </MaxWidthWrapper>
+ <LinksContainer
+ project={project}
+ exceededUsage={exceededUsage}
+ AddLinkButton={AddLinkButton}
+ />
</AppLayout>
);
}
diff --git a/pages/app/[slug]/settings.tsx b/pages/app/[slug]/settings.tsx
index a5ec0e01a1..fd79779364 100644
--- a/pages/app/[slug]/settings.tsx
+++ b/pages/app/[slug]/settings.tsx
@@ -1,12 +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 { useEffect } from "react";
import { ProjectProps } from "@/lib/types";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
import CustomDomain from "@/components/app/custom-domain";
+import PlanUsage from "@/components/app/plan-usage";
export default function ProjectLinks() {
const router = useRouter();
@@ -14,7 +14,7 @@ export default function ProjectLinks() {
slug: string;
};
- const { data, error } = useSWR<ProjectProps>(
+ const { data: project, error } = useSWR<ProjectProps>(
router.isReady && `/api/projects/${slug}`,
fetcher
);
@@ -36,8 +36,8 @@ export default function ProjectLinks() {
</div>
<MaxWidthWrapper>
<div className="my-10 grid gap-5">
- {/* Custom Domain */}
- <CustomDomain domain={data?.domain || ""} />
+ <CustomDomain domain={project?.domain || ""} />
+ <PlanUsage project={project} />
</div>
</MaxWidthWrapper>
</AppLayout>
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index b98131c063..9df66933e2 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -64,6 +64,9 @@ model Project {
slug String @unique
domain String
domainVerified Boolean @default(false)
+ plan String @default("free")
+ usageLimit Int @default(1000)
+ stripeId String? @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
users ProjectUsers[]