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.

updated pricing

Steven Teyc87cf2afa426
diff --git a/components/app/modals/add-edit-domain-modal.tsx b/components/app/modals/add-edit-domain-modal.tsx
index a2e3ee6827..63e98ba63a 100644
--- a/components/app/modals/add-edit-domain-modal.tsx
+++ b/components/app/modals/add-edit-domain-modal.tsx
@@ -361,32 +361,13 @@ function AddEditDomainButton({
}: {
setShowAddEditDomainModal: Dispatch<SetStateAction<boolean>>;
}) {
- const router = useRouter();
- const { slug } = router.query as { slug?: string };
-
- const { plan } = useProject();
-
- return slug && plan && plan !== "free" ? (
+ return (
<button
onClick={() => setShowAddEditDomainModal(true)}
className="rounded-md border border-black bg-black px-5 py-2 text-sm font-medium text-white transition-all duration-75 hover:bg-white hover:text-black active:scale-95"
>
Add Domain
</button>
- ) : (
- <Tooltip
- content={
- <TooltipContent
- title={`You can only add 1 custom domain on the ${plan} plan. Upgrade to add more.`}
- cta="Upgrade"
- ctaLink="/settings"
- />
- }
- >
- <div className="cursor-not-allowed rounded-md border border-gray-200 px-5 py-2 text-sm font-medium text-gray-300 transition-all duration-75">
- Add Domain
- </div>
- </Tooltip>
);
}
diff --git a/components/app/modals/upgrade-plan-modal.tsx b/components/app/modals/upgrade-plan-modal.tsx
index 547f232054..049f130a6e 100644
--- a/components/app/modals/upgrade-plan-modal.tsx
+++ b/components/app/modals/upgrade-plan-modal.tsx
@@ -5,14 +5,8 @@ import {
useMemo,
useState,
} from "react";
-import BlurImage from "@/components/shared/blur-image";
-import LoadingDots from "@/components/shared/icons/loading-dots";
import Modal from "@/components/shared/modal";
-import Slider from "@/components/shared/slider";
-import Switch from "@/components/shared/switch";
-import { getStripe } from "@/lib/stripe/client";
-import { PRO_TIERS } from "@/lib/stripe/constants";
-import { nFormatter } from "@/lib/utils";
+import Pricing from "@/components/home/pricing";
function UpgradePlanModal({
showUpgradePlanModal,
@@ -21,110 +15,13 @@ function UpgradePlanModal({
showUpgradePlanModal: boolean;
setShowUpgradePlanModal: Dispatch<SetStateAction<boolean>>;
}) {
- const [clicked, setClicked] = useState(false);
- const [tier, setTier] = useState(0);
- const [annualBilling, setAnnualBilling] = useState(true);
- const period = useMemo(
- () => (annualBilling ? "yearly" : "monthly"),
- [annualBilling],
- );
- const env =
- process.env.NEXT_PUBLIC_VERCEL_ENV === "production" ? "production" : "test";
-
return (
<Modal
showModal={showUpgradePlanModal}
setShowModal={setShowUpgradePlanModal}
>
- <div className="inline-block w-full transform overflow-hidden bg-white align-middle shadow-xl transition-all sm:max-w-md sm:rounded-2xl sm:border sm:border-gray-200">
- <div className="flex flex-col items-center justify-center space-y-3 border-b border-gray-200 px-4 pt-8 pb-24 sm:px-16">
- <BlurImage
- src="/_static/logo.png"
- alt="Dub logo"
- className="h-10 w-10 rounded-full border border-gray-200"
- width={20}
- height={20}
- />
- <h3 className="text-xl font-medium">Upgrade to Pro</h3>
- <div className="flex items-center space-x-2">
- <p className="text-sm text-gray-600">Billed Monthly</p>
- <Switch fn={setAnnualBilling} />
- <p className="text-sm text-gray-600">Billed Annually</p>
- </div>
- </div>
-
- <div className="relative mx-auto -mt-[5.1rem] -mb-[5.3rem] max-w-sm rounded-lg border border-gray-200 bg-white shadow-md">
- {annualBilling && (
- <span className="absolute top-2 -right-0.5 rounded-l-md bg-gradient-to-r from-blue-600 to-cyan-600 px-2 py-0.5 text-xs text-white">
- 2 Free Months
- </span>
- )}
- <div className="flex w-full max-w-md items-center justify-between p-5 pt-7">
- <h3 className="bg-gradient-to-r from-blue-600 to-cyan-600 bg-clip-text text-2xl text-transparent">
- {PRO_TIERS[tier].name}
- </h3>
- <div className="flex items-center">
- <p className="text-2xl font-semibold text-gray-700">
- ${PRO_TIERS[tier].price[period].amount}
- </p>
- <p className="text-sm text-gray-700">
- /{annualBilling ? "yr" : "mo"}
- </p>
- </div>
- </div>
- <div className="flex w-full flex-col items-center space-y-1 rounded-b-lg border-t border-gray-200 bg-gray-50 p-5 text-center">
- <Slider
- value={tier}
- setValue={setTier}
- maxValue={PRO_TIERS.length - 1}
- />
- <p className="text-sm text-gray-700">
- Up to {nFormatter(PRO_TIERS[tier].quota)} link clicks/mo
- </p>
- </div>
- </div>
-
- <div className="flex flex-col items-center bg-gray-50 px-4 pt-28 pb-8 text-left sm:px-16">
- <button
- disabled={clicked}
- onClick={() => {
- setClicked(true);
- fetch(
- `/api/stripe/upgrade?priceId=${PRO_TIERS[tier].price[period].priceIds[env]}&usageLimit=${PRO_TIERS[tier].quota}`,
- {
- method: "POST",
- },
- )
- .then(async (res) => {
- const data = await res.json();
- const { id: sessionId } = data;
- const stripe = await getStripe();
- stripe.redirectToCheckout({ sessionId });
- })
- .catch((err) => {
- alert(err);
- setClicked(false);
- });
- }}
- className={`${
- clicked
- ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"
- : "border-blue-500 bg-blue-500 text-white hover:bg-white hover:text-blue-500"
- } mb-2 flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none`}
- >
- {clicked ? (
- <LoadingDots color="#808080" />
- ) : (
- <p>Upgrade to {PRO_TIERS[tier].name}</p>
- )}
- </button>
- <a
- href="mailto:[email protected]?subject=Upgrade%20to%20Enterprise%20Plan"
- className="text-sm text-gray-500 transition-all hover:text-gray-700"
- >
- Or contact us for Enterprise
- </a>
- </div>
+ <div className="inline-block max-h-[calc(100vh-150px)] w-full max-w-screen-xl transform overflow-scroll bg-white align-middle shadow-xl scrollbar-hide sm:rounded-2xl sm:border sm:border-gray-200">
+ <Pricing />
</div>
</Modal>
);
diff --git a/components/app/settings/plan-usage.tsx b/components/app/settings/plan-usage.tsx
index 15c2ef8dd5..5d04ce9762 100644
--- a/components/app/settings/plan-usage.tsx
+++ b/components/app/settings/plan-usage.tsx
@@ -17,7 +17,7 @@ import PlanBadge from "./plan-badge";
export default function PlanUsage() {
const router = useRouter();
- const { plan, usage, usageLimit, billingCycleStart } = useProject();
+ const { slug, plan, usage, usageLimit, billingCycleStart } = useProject();
const { domains } = useDomains();
const [clicked, setClicked] = useState(false);
@@ -142,7 +142,7 @@ export default function PlanUsage() {
<button
onClick={() => {
setClicked(true);
- fetch(`/api/stripe/manage-subscription`, {
+ fetch(`/api/projects/${slug}/billing/manage`, {
method: "POST",
})
.then(async (res) => {
diff --git a/components/home/pricing.tsx b/components/home/pricing.tsx
index 3f96d453f4..0eac5d05b3 100644
--- a/components/home/pricing.tsx
+++ b/components/home/pricing.tsx
@@ -3,31 +3,34 @@ import { useMemo, useState } from "react";
import Confetti from "react-dom-confetti";
import {
CheckCircleFill,
+ LoadingDots,
QuestionCircle,
XCircleFill,
} from "@/components/shared/icons";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
-import Slider from "@/components/shared/slider";
import Switch from "@/components/shared/switch";
-import Tooltip, { OGImageProxy } from "@/components/shared/tooltip";
-import { PRO_TIERS } from "@/lib/stripe/constants";
-import { nFormatter } from "@/lib/utils";
+import Tooltip from "@/components/shared/tooltip";
+import { getStripe } from "@/lib/stripe/client";
+import { PLANS } from "@/lib/stripe/constants";
+import { capitalize, nFormatter } from "@/lib/utils";
+import useProject from "@/lib/swr/use-project";
const pricingItems = [
{
plan: "Free",
tagline: "For startups & side projects",
- clicksLimit: "Up to 1K link clicks/mo",
+ quota: 1000,
features: [
+ { text: "Unlimited users" },
+ { text: "Unlimited branded links" },
+ {
+ text: "Unlimited custom domains",
+ },
{
- text: "Free custom domains",
+ text: "Advanced link features",
footnote:
- "Just bring any domain you own and turn it into a custom domain link shortener for free.",
+ "Password protection, link expiration, device targeting, custom social media cards, etc.",
},
- { text: "Unlimited branded links" },
- { text: "5 projects" },
- { text: "Password-protected links" },
- { text: "Custom Social Previews", footnote: <OGImageProxy /> },
{
text: "Root domain redirect",
footnote:
@@ -37,21 +40,22 @@ const pricingItems = [
{ text: "SSO/SAML", negative: true },
],
cta: "Start for free",
- ctaLink: "https://app.dub.sh/register",
},
{
plan: "Pro",
tagline: "For larger teams with increased usage",
+ quota: PLANS.find((p) => p.slug === "pro").quota,
features: [
+ { text: "Unlimited users" },
+ { text: "Unlimited branded links" },
+ {
+ text: "Unlimited custom domains",
+ },
{
- text: "Free custom domains",
+ text: "Advanced link features",
footnote:
- "Just bring any domain you own and turn it into a custom domain link shortener for free.",
+ "Password protection, link expiration, device targeting, custom social media cards, etc.",
},
- { text: "Unlimited branded links" },
- { text: "Unlimited projects" },
- { text: "Password-protected links" },
- { text: "Custom Social Previews", footnote: <OGImageProxy /> },
{
text: "Root domain redirect",
footnote:
@@ -60,22 +64,22 @@ const pricingItems = [
{ text: "SSO/SAML", negative: true },
],
cta: "Get started",
- ctaLink: "https://app.dub.sh/register",
},
{
plan: "Enterprise",
tagline: "For businesses with custom needs",
- clicksLimit: "Unlimited link clicks",
+ quota: PLANS.find((p) => p.slug === "enterprise").quota,
features: [
+ { text: "Unlimited users" },
+ { text: "Unlimited branded links" },
+ {
+ text: "Unlimited custom domains",
+ },
{
- text: "Free custom domains",
+ text: "Advanced link features",
footnote:
- "Just bring any domain you own and turn it into a custom domain link shortener for free.",
+ "Password protection, link expiration, device targeting, custom social media cards, etc.",
},
- { text: "Unlimited branded links" },
- { text: "Unlimited projects" },
- { text: "Password-protected links" },
- { text: "Custom Social Previews", footnote: <OGImageProxy /> },
{
text: "Root domain redirect",
footnote:
@@ -83,18 +87,20 @@ const pricingItems = [
},
{ text: "SSO/SAML" },
],
- cta: "Contact us",
- ctaLink: "mailto:[email protected]?subject=Interested%20in%20Dub%20Enterprise",
+ cta: "Get started",
},
];
-const Pricing = () => {
- const [tier, setTier] = useState(0);
- const [annualBilling, setAnnualBilling] = useState(false);
+const Pricing = ({ homePage }: { homePage?: boolean }) => {
+ const [annualBilling, setAnnualBilling] = useState(homePage ? false : true);
const period = useMemo(
() => (annualBilling ? "yearly" : "monthly"),
[annualBilling],
);
+ const { plan: currentPlan, slug } = useProject();
+ const [clicked, setClicked] = useState(false);
+ const env =
+ process.env.NEXT_PUBLIC_VERCEL_ENV === "production" ? "production" : "test";
return (
<MaxWidthWrapper className="my-20 text-center">
@@ -102,12 +108,13 @@ const Pricing = () => {
<h2 className="font-display text-4xl font-extrabold text-black sm:text-5xl">
Simple,{" "}
<span className="bg-gradient-to-r from-blue-600 to-cyan-600 bg-clip-text text-transparent">
- usage-based
+ affordable
</span>{" "}
- pricing
+ pricing.
</h2>
<p className="mt-5 text-gray-600 sm:text-lg">
- Start for free, no credit card required. Upgrade anytime.
+ Shorten your links without breaking your bank. <br />
+ Start for free, no credit card required.
</p>
</div>
@@ -122,7 +129,7 @@ const Pricing = () => {
trackDimensions="h-6 w-12"
thumbDimensions="h-5 w-5"
thumbTranslate="translate-x-6"
- checked={false}
+ checked={annualBilling}
/>
<p className="text-gray-600">Billed Annually</p>
<span className="absolute -top-8 -right-12 rounded-full bg-purple-200 px-3 py-1 text-sm text-purple-700 sm:-right-[9.5rem] sm:-top-2">
@@ -131,80 +138,53 @@ const Pricing = () => {
</div>
<div className="grid grid-cols-1 gap-10 lg:grid-cols-3">
- {pricingItems.map(
- ({ plan, tagline, clicksLimit, features, cta, ctaLink }) => (
+ {pricingItems.map(({ plan, tagline, quota, features, cta }) => {
+ const price =
+ PLANS.find((p) => p.slug === plan.toLowerCase())?.price[period]
+ .amount || 0;
+ const highlighted =
+ (currentPlan && currentPlan === plan.toLowerCase()) ||
+ (plan === "Pro" && !currentPlan);
+ return (
<div
key={plan}
className={`relative rounded-2xl bg-white ${
- plan === "Pro"
+ highlighted
? "border-2 border-blue-600 shadow-blue-200"
: "border border-gray-200"
} shadow-lg`}
>
- {plan === "Pro" && (
+ {highlighted && (
<div className="absolute -top-5 left-0 right-0 mx-auto w-32 rounded-full bg-gradient-to-r from-blue-600 to-cyan-600 px-3 py-2 text-sm font-medium text-white">
- Popular
+ {currentPlan ? "Current Plan" : "Popular"}
</div>
)}
+
<div className="p-5">
<h3 className="my-3 text-center font-display text-3xl font-bold">
{plan}
</h3>
<p className="text-gray-500">{tagline}</p>
- {plan === "Enterprise" ? (
- <p className="my-5 font-display text-6xl font-semibold">
- Custom
- </p>
- ) : (
- <div className="my-5 flex justify-center">
- <p className="font-display text-6xl font-semibold">
- $
- {plan === "Pro"
- ? period === "yearly"
- ? nFormatter(
- PRO_TIERS[tier].price.yearly.amount / 12,
- 1,
- )
- : PRO_TIERS[tier].price.monthly.amount
- : 0}
- </p>
- </div>
- )}
+ <p className="my-5 font-display text-6xl font-semibold">
+ ${period === "yearly" ? nFormatter(price / 12, 1) : price}
+ </p>
<p className="text-gray-500">
per {period === "yearly" ? "month, billed annually" : "month"}
</p>
</div>
<div className="flex h-20 items-center justify-center border-t border-b border-gray-200 bg-gray-50">
- {plan === "Pro" ? (
- <div className="flex flex-col items-center space-y-1">
- <Slider
- value={tier}
- setValue={setTier}
- maxValue={PRO_TIERS.length - 1}
- />
- <div className="flex items-center">
- <p className="text-sm text-gray-600">
- Up to {nFormatter(PRO_TIERS[tier].quota)} link clicks/mo
- </p>
- <Tooltip content="If you exceed your monthly usage, your existing links will still work, but you need to upgrade to view their stats/add more links. Link clicks are shared across all projects.">
- <div className="flex h-4 w-6 justify-center">
- <QuestionCircle className="h-4 w-4 text-gray-600" />
- </div>
- </Tooltip>
+ <div className="flex items-center">
+ <p className="text-gray-600">
+ Up to {nFormatter(quota)} link clicks/mo
+ </p>
+ <Tooltip content="If you exceed your monthly usage, your existing links will still work, but you need to upgrade to view their stats/add more links. Link clicks are shared across all projects.">
+ <div className="flex h-4 w-8 justify-center">
+ <QuestionCircle className="h-4 w-4 text-gray-600" />
</div>
- </div>
- ) : (
- <div className="flex items-center">
- <p className="text-gray-600">{clicksLimit}</p>
- <Tooltip content="If you exceed your monthly usage, your existing links will still work, but you need to upgrade to view their stats/add more links. Link clicks are shared across all projects.">
- <div className="flex h-4 w-8 justify-center">
- <QuestionCircle className="h-4 w-4 text-gray-600" />
- </div>
- </Tooltip>
- </div>
- )}
+ </Tooltip>
+ </div>
</div>
- <ul className="my-10 space-y-5 px-10">
+ <ul className="my-10 space-y-5 px-8">
{features.map(({ text, footnote, negative }) => (
<li key={text} className="flex space-x-5">
<div className="flex-shrink-0">
@@ -241,20 +221,63 @@ const Pricing = () => {
</ul>
<div className="border-t border-gray-200" />
<div className="p-5">
- <Link
- href={ctaLink}
- className={`${
- plan === "Pro"
- ? "border border-transparent bg-gradient-to-r from-blue-600 to-cyan-600 text-white hover:border-blue-700 hover:bg-white hover:bg-clip-text hover:text-transparent"
- : "border border-gray-200 bg-black text-white hover:border-black hover:bg-white hover:text-black"
- } block w-full rounded-full py-2 font-medium transition-all`}
- >
- {cta}
- </Link>
+ {currentPlan ? (
+ <button
+ disabled={clicked || highlighted}
+ onClick={() => {
+ setClicked(true);
+ fetch(
+ `/api/projects/${slug}/billing/upgrade?priceId=${
+ PLANS.find((p) => p.slug === plan.toLowerCase())
+ .price[period].priceIds[env]
+ }`,
+ {
+ method: "POST",
+ },
+ )
+ .then(async (res) => {
+ const data = await res.json();
+ const { id: sessionId } = data;
+ const stripe = await getStripe();
+ stripe.redirectToCheckout({ sessionId });
+ })
+ .catch((err) => {
+ alert(err);
+ setClicked(false);
+ });
+ }}
+ className={`${
+ clicked || highlighted
+ ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"
+ : "border-blue-500 bg-blue-500 text-white hover:bg-white hover:text-blue-500"
+ } mb-2 flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none`}
+ >
+ {clicked ? (
+ <LoadingDots color="#808080" />
+ ) : (
+ <p>
+ {highlighted
+ ? "Current Plan"
+ : `Upgrade to ${plan} ${capitalize(period)}`}
+ </p>
+ )}
+ </button>
+ ) : (
+ <Link
+ href="https://app.dub.sh/register"
+ className={`${
+ plan === "Pro"
+ ? "border border-transparent bg-gradient-to-r from-blue-600 to-cyan-600 text-white hover:border-blue-700 hover:bg-white hover:bg-clip-text hover:text-transparent"
+ : "border border-gray-200 bg-black text-white hover:border-black hover:bg-white hover:text-black"
+ } block w-full rounded-full py-2 font-medium transition-all`}
+ >
+ {cta}
+ </Link>
+ )}
</div>
</div>
- ),
- )}
+ );
+ })}
</div>
</MaxWidthWrapper>
);
diff --git a/components/shared/tooltip.tsx b/components/shared/tooltip.tsx
index 5350ce849e..e81b089a5c 100644
--- a/components/shared/tooltip.tsx
+++ b/components/shared/tooltip.tsx
@@ -6,9 +6,6 @@ import { ReactNode, useRef, useState } from "react";
import * as TooltipPrimitive from "@radix-ui/react-tooltip";
import { AnimatePresence, motion, useAnimation } from "framer-motion";
import BlurImage from "@/components/shared/blur-image";
-import Slider from "@/components/shared/slider";
-import { PRO_TIERS } from "@/lib/stripe/constants";
-import { nFormatter } from "@/lib/utils";
export default function Tooltip({
children,
@@ -156,42 +153,11 @@ export function OGImageProxy() {
className="w-full overflow-hidden rounded-md shadow-md"
/>
<p className="text-sm text-gray-700">
- Add a custom OG image in front of your target URL. Bots like
- Twitter/Facebook will be served this image, while users will be
- redirected to your target URL.
+ Password protection, link expiration, device targeting, custom social
+ media cards, etc. Add a custom OG image in front of your target URL.
+ Bots like Twitter/Facebook will be served this image, while users will
+ be redirected to your target URL.
</p>
</div>
);
}
-
-export function ProTiers({ usageLimit }: { usageLimit?: number }) {
- const [tier, setTier] = useState(
- usageLimit > 1000 ? PRO_TIERS.map((t) => t.quota).indexOf(usageLimit) : 0,
- );
-
- return (
- <div className="w-full rounded-md">
- <div className="flex w-full max-w-md items-center justify-between p-5">
- <h3 className="bg-gradient-to-r from-blue-600 to-cyan-600 bg-clip-text text-2xl text-transparent">
- {PRO_TIERS[tier].name}
- </h3>
- <div className="flex items-center">
- <p className="text-2xl font-semibold text-gray-700">
- ${PRO_TIERS[tier].price.monthly.amount}
- </p>
- <p className="text-sm text-gray-700">/mo</p>
- </div>
- </div>
- <div className="flex w-full flex-col items-center space-y-1 border-t border-gray-200 bg-gray-50 p-5 text-center">
- <Slider
- value={tier}
- setValue={setTier}
- maxValue={PRO_TIERS.length - 1}
- />
- <p className="text-sm text-gray-700">
- Up to {nFormatter(PRO_TIERS[tier].quota)} link clicks/mo
- </p>
- </div>
- </div>
- );
-}
diff --git a/lib/api/links.ts b/lib/api/links.ts
index 8ce53ce0d0..9055becbef 100644
--- a/lib/api/links.ts
+++ b/lib/api/links.ts
@@ -72,7 +72,6 @@ export async function getLinksForProject({
sort?: "createdAt" | "clicks"; // always descending for both
userId?: string;
}): Promise<LinkProps[]> {
- const filters = getFiltersFromStatus(status);
return await prisma.link.findMany({
where: {
projectId,
@@ -81,7 +80,6 @@ export async function getLinksForProject({
key: { search },
url: { search },
}),
- ...filters,
// ...(tag && { tags: { has: tag } }),
...(userId && { userId }),
},
diff --git a/lib/auth.ts b/lib/auth.ts
index 5e5190b438..5d81f2f4d6 100644
--- a/lib/auth.ts
+++ b/lib/auth.ts
@@ -63,6 +63,7 @@ const withProjectAuth =
usage: true,
usageLimit: true,
plan: true,
+ stripeId: true,
billingCycleStart: true,
users: {
where: {
diff --git a/lib/cron/usage.tsx b/lib/cron/usage.tsx
index 6c7e4449cf..235f777b52 100644
--- a/lib/cron/usage.tsx
+++ b/lib/cron/usage.tsx
@@ -5,41 +5,28 @@ import { getClicksUsage } from "@/lib/tinybird";
import { getFirstAndLastDay, log } from "@/lib/utils";
export const updateUsage = async () => {
- const users = await prisma.user.findMany({
+ const projects = await prisma.project.findMany({
where: {
- NOT: {
- projects: {
- none: {},
- },
- },
- projects: {
+ domains: {
some: {
- project: {
- domainVerified: true,
- },
+ verified: true,
},
},
},
select: {
- id: true,
- email: true,
usageLimit: true,
- stripeId: true,
billingCycleStart: true,
- projects: {
+ users: {
where: {
role: "owner",
- project: {
- domainVerified: true,
- },
},
select: {
- project: {
- select: {
- id: true,
- domain: true,
- },
- },
+ user: true,
+ },
+ },
+ domains: {
+ where: {
+ verified: true,
},
},
sentEmails: true,
@@ -47,120 +34,102 @@ export const updateUsage = async () => {
orderBy: {
usageUpdatedAt: "asc",
},
- take: 50,
});
- const response = await Promise.all(
- users.map(
- async ({
- id,
- email,
- usageLimit,
- billingCycleStart,
- projects,
- sentEmails,
- }) => {
- const usageArr = await Promise.all(
- projects.map(async ({ project: { id, domain } }) => {
- return {
- id,
- usage: await getUsageForProject(domain, billingCycleStart),
- };
- }),
- );
- let totalUsage = usageArr.reduce((acc, { usage }) => acc + usage, 0);
- let ownerExceededUsage = totalUsage > usageLimit;
-
- if (ownerExceededUsage) {
- await log(
- `${email} is over usage limit. Usage: ${totalUsage}, Limit: ${usageLimit}`,
- "cron",
- );
- const sentFirstUsageLimitEmail = sentEmails.some(
- (email) => email.type === "firstUsageLimitEmail",
- );
- if (!sentFirstUsageLimitEmail) {
- sendUsageLimitEmail(email, totalUsage, usageLimit, "first");
- } else {
- const sentSecondUsageLimitEmail = sentEmails.some(
- (email) => email.type === "secondUsageLimitEmail",
- );
- if (!sentSecondUsageLimitEmail) {
- const daysSinceFirstEmail = Math.floor(
- (new Date().getTime() -
- new Date(sentEmails[0].createdAt).getTime()) /
- (1000 * 3600 * 24),
- );
- if (daysSinceFirstEmail >= 3) {
- sendUsageLimitEmail(email, totalUsage, usageLimit, "second");
- }
- }
- }
- }
-
- const newBillingCycle = new Date().getDate() === billingCycleStart;
+ // const response = await Promise.all(
+ // projects.map(
+ // async ({
+ // id,
+ // email,
+ // usageLimit,
+ // billingCycleStart,
+ // projects,
+ // sentEmails,
+ // }) => {
+ // const usageArr = await Promise.all(
+ // projects.map(async ({ project: { id, domain } }) => {
+ // return {
+ // id,
+ // usage: await getUsageForProject(domain, billingCycleStart),
+ // };
+ // }),
+ // );
+ // let totalUsage = usageArr.reduce((acc, { usage }) => acc + usage, 0);
+ // let ownerExceededUsage = totalUsage > usageLimit;
- const [updateUser, updateProjects] = await Promise.all([
- prisma.user.update({
- where: {
- id,
- },
- data: {
- usage: totalUsage,
- usageUpdatedAt: new Date(),
- // reset usage email warnings if it's a new billing cycle
- ...(newBillingCycle && {
- sentEmails: {
- deleteMany: {
- type: {
- in: ["firstUsageLimitEmail", "secondUsageLimitEmail"],
- },
- },
- },
- }),
- },
- }),
- Promise.all(
- usageArr.map(async ({ id, usage }) => {
- return await prisma.project.update({
- where: {
- id,
- },
- data: {
- usage,
- ownerExceededUsage,
- },
- });
- }),
- ),
- ]);
+ // if (ownerExceededUsage) {
+ // await log(
+ // `${email} is over usage limit. Usage: ${totalUsage}, Limit: ${usageLimit}`,
+ // "cron",
+ // );
+ // const sentFirstUsageLimitEmail = sentEmails.some(
+ // (email) => email.type === "firstUsageLimitEmail",
+ // );
+ // if (!sentFirstUsageLimitEmail) {
+ // sendUsageLimitEmail(email, totalUsage, usageLimit, "first");
+ // } else {
+ // const sentSecondUsageLimitEmail = sentEmails.some(
+ // (email) => email.type === "secondUsageLimitEmail",
+ // );
+ // if (!sentSecondUsageLimitEmail) {
+ // const daysSinceFirstEmail = Math.floor(
+ // (new Date().getTime() -
+ // new Date(sentEmails[0].createdAt).getTime()) /
+ // (1000 * 3600 * 24),
+ // );
+ // if (daysSinceFirstEmail >= 3) {
+ // sendUsageLimitEmail(email, totalUsage, usageLimit, "second");
+ // }
+ // }
+ // }
+ // }
- return {
- updateUser,
- updateProjects,
- };
- },
- ),
- );
+ // const newBillingCycle = new Date().getDate() === billingCycleStart;
- return response;
-};
+ // const [updateUser, updateProjects] = await Promise.all([
+ // prisma.user.update({
+ // where: {
+ // id,
+ // },
+ // data: {
+ // usage: totalUsage,
+ // usageUpdatedAt: new Date(),
+ // // reset usage email warnings if it's a new billing cycle
+ // ...(newBillingCycle && {
+ // sentEmails: {
+ // deleteMany: {
+ // type: {
+ // in: ["firstUsageLimitEmail", "secondUsageLimitEmail"],
+ // },
+ // },
+ // },
+ // }),
+ // },
+ // }),
+ // Promise.all(
+ // usageArr.map(async ({ id, usage }) => {
+ // return await prisma.project.update({
+ // where: {
+ // id,
+ // },
+ // data: {
+ // usage,
+ // ownerExceededUsage,
+ // },
+ // });
+ // }),
+ // ),
+ // ]);
-/**
- * Get the usage for a project
- **/
-const getUsageForProject = async (
- domain: string,
- billingCycleStart: number,
-): Promise<number> => {
- const { firstDay, lastDay } = getFirstAndLastDay(billingCycleStart);
+ // return {
+ // updateUser,
+ // updateProjects,
+ // };
+ // },
+ // ),
+ // );
- const usage = await getClicksUsage({
- domain,
- start: firstDay.toISOString().replace("T", " ").replace("Z", ""),
- end: lastDay.toISOString().replace("T", " ").replace("Z", ""),
- });
- return usage;
+ return projects;
};
const sendUsageLimitEmail = async (
diff --git a/lib/stripe/constants.ts b/lib/stripe/constants.ts
index 8a6e217472..d519b67a78 100644
--- a/lib/stripe/constants.ts
+++ b/lib/stripe/constants.ts
@@ -1,11 +1,8 @@
-export const getPlanFromUsageLimit = (usageLimit: number) => {
- return PRO_TIERS.find((tier) => tier.quota === usageLimit)?.name || "Free";
-};
-
-export const PRO_TIERS = [
+export const PLANS = [
{
- name: "Pro 10K",
- quota: 10000,
+ name: "Pro",
+ slug: "pro",
+ quota: 50000,
price: {
monthly: {
amount: 9,
@@ -24,48 +21,9 @@ export const PRO_TIERS = [
},
},
{
- name: "Pro 25K",
- quota: 25000,
- price: {
- monthly: {
- amount: 19,
- priceIds: {
- test: "price_1LoytHAlJJEpqkPVonefD3RW",
- production: "price_1LodMrAlJJEpqkPVq3XV2Y3R",
- },
- },
- yearly: {
- amount: 190,
- priceIds: {
- test: "price_1LoytHAlJJEpqkPVP25C5yjd",
- production: "price_1LodMrAlJJEpqkPViKR29tq8",
- },
- },
- },
- },
- {
- name: "Pro 50K",
- quota: 50000,
- price: {
- monthly: {
- amount: 29,
- priceIds: {
- test: "price_1LoyrzAlJJEpqkPVVZfXIZE5",
- production: "price_1LodMEAlJJEpqkPVrMdRwaSk",
- },
- },
- yearly: {
- amount: 290,
- priceIds: {
- test: "price_1LoyrzAlJJEpqkPVtCBUz78P",
- production: "price_1LodMEAlJJEpqkPV5ztz7wyg",
- },
- },
- },
- },
- {
- name: "Pro 100K",
- quota: 100000,
+ name: "Enterprise",
+ slug: "enterprise",
+ quota: 500000,
price: {
monthly: {
amount: 49,
@@ -83,44 +41,4 @@ export const PRO_TIERS = [
},
},
},
- {
- name: "Pro 500K",
- quota: 500000,
- price: {
- monthly: {
- amount: 79,
- priceIds: {
- test: "price_1LoyqQAlJJEpqkPVGy7kyuxS",
- production: "price_1LodLIAlJJEpqkPVi7javvun",
- },
- },
- yearly: {
- amount: 790,
- priceIds: {
- test: "price_1LoyqQAlJJEpqkPVdWYVpS76",
- production: "price_1LodLIAlJJEpqkPValZ9TmgF",
- },
- },
- },
- },
- {
- name: "Pro 1M",
- quota: 1000000,
- price: {
- monthly: {
- amount: 99,
- priceIds: {
- test: "price_1Lis30AlJJEpqkPVAuSVxbT1",
- production: "price_1Lis1VAlJJEpqkPV7sUnggB3",
- },
- },
- yearly: {
- amount: 990,
- priceIds: {
- test: "price_1LoymUAlJJEpqkPVDX9fNCu7",
- production: "price_1LodJMAlJJEpqkPV2K0xX2kF",
- },
- },
- },
- },
];
diff --git a/lib/tinybird.ts b/lib/tinybird.ts
index 149087010f..ddfc76c441 100644
--- a/lib/tinybird.ts
+++ b/lib/tinybird.ts
@@ -56,6 +56,11 @@ export async function recordClick(
"UPDATE Link SET clicks = clicks + 1 WHERE domain = ? AND `key` = ?",
[domain, key],
),
+ // increment the usage count for the project, and then we have a cron that will reset it at the start of new billing cycle
+ conn.execute(
+ "UPDATE Project p JOIN Domain d ON p.id = d.projectId SET p.usage = p.usage + 1 WHERE d.slug = ?",
+ [domain],
+ ),
]),
]);
}
diff --git a/lib/types.ts b/lib/types.ts
index da5cdfaa03..0807e9e064 100644
--- a/lib/types.ts
+++ b/lib/types.ts
@@ -36,6 +36,7 @@ export interface ProjectProps {
usage: number;
usageLimit: number;
plan: "free" | "pro" | "enterprise";
+ stripeId?: string;
billingCycleStart?: number;
// TO DELETE
diff --git a/pages/api/auth/[...nextauth].tsx b/pages/api/auth/[...nextauth].tsx
index c7596e122e..92bf9d6109 100644
--- a/pages/api/auth/[...nextauth].tsx
+++ b/pages/api/auth/[...nextauth].tsx
@@ -71,10 +71,6 @@ export const authOptions: NextAuthOptions = {
to: email,
component: <WelcomeEmail />,
}),
- prisma.user.update({
- where: { email },
- data: { billingCycleStart: new Date().getDate() },
- }),
]);
}
},
diff --git a/pages/api/cron/domains.ts b/pages/api/cron/domains.ts
index b6257b0d84..e77cdbdf5a 100644
--- a/pages/api/cron/domains.ts
+++ b/pages/api/cron/domains.ts
@@ -20,19 +20,24 @@ async function handler(_req: NextApiRequest, res: NextApiResponse) {
const domains = await prisma.domain.findMany({
select: {
slug: true,
- domainVerified: true,
+ verified: true,
createdAt: true,
projectId: true,
+ project: {
+ select: {
+ createdAt: true,
+ },
+ },
},
orderBy: {
- domainLastChecked: "asc",
+ lastChecked: "asc",
},
take: 100,
});
const results = await Promise.allSettled(
domains.map(async (domain) => {
- const { slug, domainVerified, createdAt, projectId } = domain;
+ const { slug, verified, createdAt, projectId } = domain;
const [domainJson, configJson] = await Promise.all([
getDomainResponse(slug),
getConfigResponse(slug),
@@ -60,12 +65,12 @@ async function handler(_req: NextApiRequest, res: NextApiResponse) {
slug,
},
data: {
- domainVerified: newDomainVerified,
- domainLastChecked: new Date(),
+ verified: newDomainVerified,
+ lastChecked: new Date(),
},
});
- const changed = newDomainVerified !== domainVerified;
+ const changed = newDomainVerified !== verified;
const updates = await handleDomainUpdates(
slug,
@@ -76,7 +81,7 @@ async function handler(_req: NextApiRequest, res: NextApiResponse) {
return {
domain,
- previousStatus: domainVerified,
+ previousStatus: verified,
currentStatus: newDomainVerified,
changed,
updates,
@@ -96,7 +101,15 @@ async function handler(_req: NextApiRequest, res: NextApiResponse) {
* To test out the endpoint manually (wihtout using QStash), you can do `export default handler` instead and
* hit this endpoint via http://localhost:3000/api/cron/domains
*/
-export default verifySignature(handler);
+const Cron = () => {
+ if (process.env.NODE_ENV === "development") {
+ return handler;
+ } else {
+ return verifySignature(handler);
+ }
+};
+
+export default Cron();
export const config = {
api: {
diff --git a/pages/api/cron/usage.ts b/pages/api/cron/usage.ts
index a63d78e55d..05253296cf 100644
--- a/pages/api/cron/usage.ts
+++ b/pages/api/cron/usage.ts
@@ -22,7 +22,15 @@ async function handler(_req: NextApiRequest, res: NextApiResponse) {
* To test out the endpoint manually (wihtout using QStash), you can do `export default handler` instead and
* hit this endpoint via http://localhost:3000/api/cron/domains
*/
-export default verifySignature(handler);
+const Cron = () => {
+ if (process.env.NODE_ENV === "development") {
+ return handler;
+ } else {
+ return verifySignature(handler);
+ }
+};
+
+export default Cron();
export const config = {
api: {
diff --git a/pages/api/projects/[slug]/billing/manage.ts b/pages/api/projects/[slug]/billing/manage.ts
new file mode 100644
index 0000000000..14b3fbf339
--- /dev/null
+++ b/pages/api/projects/[slug]/billing/manage.ts
@@ -0,0 +1,21 @@
+import { withProjectAuth } from "@/lib/auth";
+import { stripe } from "@/lib/stripe";
+
+export default withProjectAuth(async (req, res, project) => {
+ // POST /api/projects/[slug]/billing/manage – manage a user's subscription
+ if (req.method === "POST") {
+ const { slug } = req.query as { slug: string };
+ const { url } = await stripe.billingPortal.sessions.create({
+ customer: project.stripeId,
+ return_url: `${
+ process.env.VERCEL === "1"
+ ? "https://app.dub.sh"
+ : "http://app.localhost:3000"
+ }/${slug}/settings/billing`,
+ });
+ return res.status(200).json(url);
+ } else {
+ res.setHeader("Allow", ["POST"]);
+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+ }
+});
diff --git a/pages/api/projects/[slug]/billing/upgrade.ts b/pages/api/projects/[slug]/billing/upgrade.ts
new file mode 100644
index 0000000000..a7ca5f406b
--- /dev/null
+++ b/pages/api/projects/[slug]/billing/upgrade.ts
@@ -0,0 +1,38 @@
+import { withProjectAuth } from "@/lib/auth";
+import { stripe } from "@/lib/stripe";
+
+export default withProjectAuth(async (req, res, project, session) => {
+ // POST /api/projects/[slug]/billing/upgrade – upgrade a project from free to pro
+ if (req.method === "POST") {
+ const { slug, priceId } = req.query as { slug: string; priceId: string };
+
+ const stripeSession = await stripe.checkout.sessions.create({
+ customer_email: session.user.email,
+ payment_method_types: ["card"],
+ billing_address_collection: "required",
+ success_url: `${
+ process.env.VERCEL === "1"
+ ? "https://app.dub.sh"
+ : "http://app.localhost:3000"
+ }/${slug}/settings/billing`,
+ cancel_url: `${
+ process.env.VERCEL === "1"
+ ? "https://app.dub.sh"
+ : "http://app.localhost:3000"
+ }/${slug}/settings/billing`,
+ line_items: [{ price: priceId, quantity: 1 }],
+ automatic_tax: {
+ enabled: true,
+ },
+ tax_id_collection: {
+ enabled: true,
+ },
+ mode: "subscription",
+ client_reference_id: project.id,
+ });
+ return res.status(200).json(stripeSession);
+ } else {
+ res.setHeader("Allow", ["POST"]);
+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+ }
+});
diff --git a/pages/api/projects/[slug]/domains/[domain]/index.ts b/pages/api/projects/[slug]/domains/[domain]/index.ts
index fa4b35ada6..7296cd82ac 100644
--- a/pages/api/projects/[slug]/domains/[domain]/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/index.ts
@@ -1,4 +1,3 @@
-import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
import { addDomain, removeDomain, validateDomain } from "@/lib/api/domains";
import prisma from "@/lib/prisma";
@@ -8,28 +7,26 @@ import {
deleteDomainLinks,
setRootDomain,
} from "@/lib/api/domains";
-import { ProjectProps } from "@/lib/types";
-export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {
- const { slug, domain } = req.query as { slug: string; domain: string };
+export default withProjectAuth(async (req, res, project) => {
+ const { slug, domain } = req.query as { slug: string; domain: string };
- if (
- !slug ||
- typeof slug !== "string" ||
- !domain ||
- typeof domain !== "string"
- ) {
- return res
- .status(400)
- .json({ error: "Missing or misconfigured project slug or domain" });
- }
+ if (
+ !slug ||
+ typeof slug !== "string" ||
+ !domain ||
+ typeof domain !== "string"
+ ) {
+ return res
+ .status(400)
+ .json({ error: "Missing or misconfigured project slug or domain" });
+ }
- // PUT /api/projects/[slug]/domains/[domain] edit a project's domain
- if (req.method === "PUT") {
- const { slug: newDomain, target, type, primary } = req.body;
+ // PUT /api/projects/[slug]/domains/[domain] edit a project's domain
+ if (req.method === "PUT") {
+ const { slug: newDomain, target, type, primary } = req.body;
- /*
+ /*
If the domain is being changed (and the new domain is valid), we need to:
1. Remove the old domain from Vercel
2. Add the new domain to Vercel
@@ -39,95 +36,91 @@ export default withProjectAuth(
6. If the domain is being set as the primary domain, set all other domains to not be the primary domain
7. Update the domain in the database along with its primary status
*/
- if (newDomain !== domain) {
- const validDomain = await validateDomain(newDomain);
+ if (newDomain !== domain) {
+ const validDomain = await validateDomain(newDomain);
- if (validDomain !== true) {
- return res.status(422).json({
- domainError: validDomain,
- });
- }
- const response = await Promise.allSettled([
- removeDomain(domain),
- addDomain(newDomain),
- target &&
- setRootDomain(domain, target, type === "rewrite", newDomain),
- changeDomainForLinks(domain, newDomain),
- changeDomainForImages(domain, newDomain),
- primary &&
- prisma.domain.updateMany({
- where: {
- projectId: project.id,
- primary: true,
- },
- data: {
- primary: false,
- },
- }),
- prisma.domain.update({
+ if (validDomain !== true) {
+ return res.status(422).json({
+ domainError: validDomain,
+ });
+ }
+ const response = await Promise.allSettled([
+ removeDomain(domain),
+ addDomain(newDomain),
+ target && setRootDomain(domain, target, type === "rewrite", newDomain),
+ changeDomainForLinks(domain, newDomain),
+ changeDomainForImages(domain, newDomain),
+ primary &&
+ prisma.domain.updateMany({
where: {
- slug: domain,
+ projectId: project.id,
+ primary: true,
},
data: {
- slug: newDomain,
- target,
- type,
- primary,
+ primary: false,
},
}),
- ]);
- return res.status(200).json(response);
- } else {
- /*
+ prisma.domain.update({
+ where: {
+ slug: domain,
+ },
+ data: {
+ slug: newDomain,
+ target,
+ type,
+ primary,
+ },
+ }),
+ ]);
+ return res.status(200).json(response);
+ } else {
+ /*
If the domain is not being changed, we only need to:
1. If there's a landing page set, update the root domain in Redis
2. If the domain is being set as the primary domain, set all other domains to not be the primary domain
3. Then, update the domain in the database along with its primary status
*/
- const response = await Promise.allSettled([
- target && setRootDomain(domain, target, type === "rewrite"),
- primary &&
- prisma.domain.updateMany({
- where: {
- projectId: project.id,
- primary: true,
- },
- data: {
- primary: false,
- },
- }),
- prisma.domain.update({
+ const response = await Promise.allSettled([
+ target && setRootDomain(domain, target, type === "rewrite"),
+ primary &&
+ prisma.domain.updateMany({
where: {
- slug: domain,
+ projectId: project.id,
+ primary: true,
},
data: {
- target,
- type,
- primary,
+ primary: false,
},
}),
- ]);
- return res.status(200).json(response);
- }
- } else if (req.method === "DELETE") {
- const response = await Promise.allSettled([
- removeDomain(domain),
- deleteDomainLinks(domain),
+ prisma.domain.update({
+ where: {
+ slug: domain,
+ },
+ data: {
+ target,
+ type,
+ primary,
+ },
+ }),
]);
- const deletedDomain = await prisma.domain.delete({
- where: {
- slug: domain,
- },
- });
- return res.status(200).json({
- ...response,
- deletedDomain,
- });
- } else {
- res.setHeader("Allow", ["PUT", "DELETE"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
+ return res.status(200).json(response);
}
- },
-);
+ } else if (req.method === "DELETE") {
+ const response = await Promise.allSettled([
+ removeDomain(domain),
+ deleteDomainLinks(domain),
+ ]);
+ const deletedDomain = await prisma.domain.delete({
+ where: {
+ slug: domain,
+ },
+ });
+ return res.status(200).json({
+ ...response,
+ deletedDomain,
+ });
+ } else {
+ res.setHeader("Allow", ["PUT", "DELETE"]);
+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+ }
+});
diff --git a/pages/api/projects/[slug]/domains/[domain]/root/clicks.ts b/pages/api/projects/[slug]/domains/[domain]/root/clicks.ts
index 147a3f5717..0ed85dfa03 100644
--- a/pages/api/projects/[slug]/domains/[domain]/root/clicks.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/root/clicks.ts
@@ -1,26 +1,21 @@
-import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
import { getStats } from "@/lib/stats";
-export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse) => {
- // GET /api/projects/[slug]/domains/[domain]/root/clicks - get # of clicks on root of domain (e.g. dub.sh, vercel.fyi)
- if (req.method === "GET") {
- const { domain } = req.query as {
- domain: string;
- };
- const response = await getStats({
- domain,
- key: "_root",
- endpoint: "clicks",
- });
+export default withProjectAuth(async (req, res) => {
+ // GET /api/projects/[slug]/domains/[domain]/root/clicks - get # of clicks on root of domain (e.g. dub.sh, vercel.fyi)
+ if (req.method === "GET") {
+ const { domain } = req.query as {
+ domain: string;
+ };
+ const response = await getStats({
+ domain,
+ key: "_root",
+ endpoint: "clicks",
+ });
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
-);
+ 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]/domains/[domain]/root/index.ts b/pages/api/projects/[slug]/domains/[domain]/root/index.ts
index 2396fd5235..27b9de008b 100644
--- a/pages/api/projects/[slug]/domains/[domain]/root/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/root/index.ts
@@ -1,10 +1,9 @@
-import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
import { redis } from "@/lib/upstash";
import { RootDomainProps } from "@/lib/types";
export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse) => {
+ async (req, res) => {
const { domain } = req.query as { domain: string };
// GET /api/projects/[slug]/domains/[domain]/root - get root domain
diff --git a/pages/api/projects/[slug]/domains/[domain]/verify.ts b/pages/api/projects/[slug]/domains/[domain]/verify.ts
index a50ced9236..eacd748610 100644
--- a/pages/api/projects/[slug]/domains/[domain]/verify.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/verify.ts
@@ -1,4 +1,3 @@
-import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
import {
getConfigResponse,
@@ -8,88 +7,84 @@ import {
import prisma from "@/lib/prisma";
import { DomainVerificationStatusProps } from "@/lib/types";
-export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse) => {
- // GET /api/projects/[slug]/domains/[domain]/verify - get domain verification status
- if (req.method === "GET") {
- const { slug, domain } = req.query as { slug: string; domain: string };
- let status: DomainVerificationStatusProps = "Valid Configuration";
+export default withProjectAuth(async (req, res) => {
+ // GET /api/projects/[slug]/domains/[domain]/verify - get domain verification status
+ if (req.method === "GET") {
+ const { slug, domain } = req.query as { slug: string; domain: string };
+ let status: DomainVerificationStatusProps = "Valid Configuration";
- const [domainJson, configJson] = await Promise.all([
- getDomainResponse(domain),
- getConfigResponse(domain),
- ]);
+ const [domainJson, configJson] = await Promise.all([
+ getDomainResponse(domain),
+ getConfigResponse(domain),
+ ]);
- if (domainJson?.error?.code === "not_found") {
- // domain not found on Vercel project
- status = "Domain Not Found";
- return res
- .status(200)
- .json({ status, response: { configJson, domainJson } });
- } else if (domainJson.error) {
- status = "Unknown Error";
- return res
- .status(200)
- .json({ status, response: { configJson, domainJson } });
- }
-
- /**
- * If domain is not verified, we try to verify now
- */
- if (!domainJson.verified) {
- status = "Pending Verification";
- const verificationJson = await verifyDomain(domain);
-
- if (verificationJson && verificationJson.verified) {
- /**
- * Domain was just verified
- */
- status = "Valid Configuration";
- }
+ if (domainJson?.error?.code === "not_found") {
+ // domain not found on Vercel project
+ status = "Domain Not Found";
+ return res
+ .status(200)
+ .json({ status, response: { configJson, domainJson } });
+ } else if (domainJson.error) {
+ status = "Unknown Error";
+ return res
+ .status(200)
+ .json({ status, response: { configJson, domainJson } });
+ }
- return res.status(200).json({
- status,
- response: {
- configJson,
- domainJson,
- verificationJson,
- },
- });
- }
+ /**
+ * If domain is not verified, we try to verify now
+ */
+ if (!domainJson.verified) {
+ status = "Pending Verification";
+ const verificationJson = await verifyDomain(domain);
- let prismaResponse = null;
- if (!configJson.misconfigured) {
- prismaResponse = await prisma.domain.update({
- where: {
- slug: domain,
- },
- data: {
- verified: true,
- lastChecked: new Date(),
- },
- });
- } else {
- status = "Invalid Configuration";
- prismaResponse = await prisma.domain.update({
- where: {
- slug: domain,
- },
- data: {
- verified: false,
- lastChecked: new Date(),
- },
- });
+ if (verificationJson && verificationJson.verified) {
+ /**
+ * Domain was just verified
+ */
+ status = "Valid Configuration";
}
return res.status(200).json({
status,
- response: { configJson, domainJson, prismaResponse },
+ response: {
+ configJson,
+ domainJson,
+ verificationJson,
+ },
+ });
+ }
+
+ let prismaResponse = null;
+ if (!configJson.misconfigured) {
+ prismaResponse = await prisma.domain.update({
+ where: {
+ slug: domain,
+ },
+ data: {
+ verified: true,
+ lastChecked: new Date(),
+ },
});
} else {
- res.setHeader("Allow", ["GET"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
+ status = "Invalid Configuration";
+ prismaResponse = await prisma.domain.update({
+ where: {
+ slug: domain,
+ },
+ data: {
+ verified: false,
+ lastChecked: new Date(),
+ },
+ });
}
- },
-);
+
+ return res.status(200).json({
+ status,
+ response: { configJson, domainJson, prismaResponse },
+ });
+ } else {
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+ }
+});
diff --git a/pages/api/projects/[slug]/domains/index.ts b/pages/api/projects/[slug]/domains/index.ts
index 9ceebb5e3e..a08eca6df5 100644
--- a/pages/api/projects/[slug]/domains/index.ts
+++ b/pages/api/projects/[slug]/domains/index.ts
@@ -1,82 +1,72 @@
-import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
-import { ProjectProps } from "@/lib/types";
import prisma from "@/lib/prisma";
import { addDomain, validateDomain } from "@/lib/api/domains";
import { redis } from "@/lib/upstash";
-export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {
- // GET /api/projects/[slug]/domains – get all domains for a project
- if (req.method === "GET") {
- const domains = await prisma.domain.findMany({
- where: {
- projectId: project.id,
- },
- select: {
- slug: true,
- verified: true,
- primary: true,
- target: true,
- type: true,
- },
- });
- return res.status(200).json(domains);
+export default withProjectAuth(async (req, res, project) => {
+ // GET /api/projects/[slug]/domains – get all domains for a project
+ if (req.method === "GET") {
+ const domains = await prisma.domain.findMany({
+ where: {
+ projectId: project.id,
+ },
+ select: {
+ slug: true,
+ verified: true,
+ primary: true,
+ target: true,
+ type: true,
+ },
+ });
+ return res.status(200).json(domains);
- // POST /api/projects/[slug]/domains - add a domain
- } else if (req.method === "POST") {
- const { slug: domain, primary, target, type } = req.body;
+ // POST /api/projects/[slug]/domains - add a domain
+ } else if (req.method === "POST") {
+ const { slug: domain, primary, target, type } = req.body;
- const validDomain = await validateDomain(domain);
- if (validDomain !== true) {
- return res.status(422).json({
- domainError: validDomain,
- });
- }
- /*
+ const validDomain = await validateDomain(domain);
+ if (validDomain !== true) {
+ return res.status(422).json({
+ domainError: validDomain,
+ });
+ }
+ /*
If the domain is being added, we need to:
1. Add the domain to Vercel
2. If there's a landing page set, update the root domain in Redis
3. If the domain is being set as the primary domain, set all other domains to not be the primary domain
4. Add the domain to the database along with its primary status
*/
- const response = await Promise.allSettled([
- addDomain(domain),
- target &&
- redis.set(`root:${domain}`, {
- target,
- rewrite: type === "rewrite",
- }),
- primary &&
- prisma.domain.updateMany({
- where: {
- projectId: project.id,
- primary: true,
- },
- data: {
- primary: false,
- },
- }),
- prisma.domain.create({
- data: {
- slug: domain,
- target,
- type,
+ const response = await Promise.allSettled([
+ addDomain(domain),
+ target &&
+ redis.set(`root:${domain}`, {
+ target,
+ rewrite: type === "rewrite",
+ }),
+ primary &&
+ prisma.domain.updateMany({
+ where: {
projectId: project.id,
- primary,
+ primary: true,
+ },
+ data: {
+ primary: false,
},
}),
- ]);
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET", "POST"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
- {
- excludeGet: true,
- requiredPlan: ["pro", "enterprise"],
- },
-);
+ prisma.domain.create({
+ data: {
+ slug: domain,
+ target,
+ type,
+ projectId: project.id,
+ primary,
+ },
+ }),
+ ]);
+ return res.status(200).json(response);
+ } else {
+ res.setHeader("Allow", ["GET", "POST"]);
+ 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 d295fc9a24..2d28dd54cd 100644
--- a/pages/api/projects/[slug]/index.ts
+++ b/pages/api/projects/[slug]/index.ts
@@ -1,69 +1,63 @@
-import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
import { removeDomain, deleteDomainLinks } from "@/lib/api/domains";
import prisma from "@/lib/prisma";
-import { ProjectProps } from "@/lib/types";
-export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {
- const { slug } = req.query;
- if (!slug || typeof slug !== "string") {
- return res
- .status(400)
- .json({ error: "Missing or misconfigured project slug" });
- }
- // GET /api/projects/[slug] – get a specific project
- if (req.method === "GET") {
- return res.status(200).json(project);
+export default withProjectAuth(async (req, res, project) => {
+ const { slug } = req.query;
+ if (!slug || typeof slug !== "string") {
+ return res
+ .status(400)
+ .json({ error: "Missing or misconfigured project slug" });
+ }
+ // GET /api/projects/[slug] – get a specific project
+ if (req.method === "GET") {
+ return res.status(200).json(project);
- // PUT /api/projects/[slug] – edit a specific project
- } else if (req.method === "PUT") {
- const { name, newSlug } = req.body;
- try {
- const response = await prisma.project.update({
- where: {
- slug,
- },
- data: {
- ...(name && { name }),
- ...(newSlug && { slug: newSlug }),
- },
- });
- return res.status(200).json(response);
- } catch (error) {
- if (error.code === "P2002") {
- return res.status(422).json({ error: "Key already exists" });
- }
+ // PUT /api/projects/[slug] – edit a specific project
+ } else if (req.method === "PUT") {
+ const { name, newSlug } = req.body;
+ try {
+ const response = await prisma.project.update({
+ where: {
+ slug,
+ },
+ data: {
+ ...(name && { name }),
+ ...(newSlug && { slug: newSlug }),
+ },
+ });
+ return res.status(200).json(response);
+ } catch (error) {
+ if (error.code === "P2002") {
+ return res.status(422).json({ error: "Key already exists" });
}
- // DELETE /api/projects/[slug] – delete a project
- } else if (req.method === "DELETE") {
- const domains = (
- await prisma.domain.findMany({
- where: {
- projectId: project.id,
- },
- select: {
- slug: true,
- },
- })
- ).map((domain) => domain.slug);
+ }
+ // DELETE /api/projects/[slug] – delete a project
+ } else if (req.method === "DELETE") {
+ const domains = (
+ await prisma.domain.findMany({
+ where: {
+ projectId: project.id,
+ },
+ select: {
+ slug: true,
+ },
+ })
+ ).map((domain) => domain.slug);
- const response = await Promise.allSettled([
- prisma.project.delete({
- where: {
- slug,
- },
- }),
- ...domains.map((domain) => removeDomain(domain)),
- ...domains.map((domain) => deleteDomainLinks(domain)),
- ]);
+ const response = await Promise.allSettled([
+ prisma.project.delete({
+ where: {
+ slug,
+ },
+ }),
+ ...domains.map((domain) => removeDomain(domain)),
+ ...domains.map((domain) => deleteDomainLinks(domain)),
+ ]);
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["GET", "PUT", "DELETE"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
-);
+ return res.status(200).json(response);
+ } else {
+ res.setHeader("Allow", ["GET", "PUT", "DELETE"]);
+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+ }
+});
diff --git a/pages/api/projects/[slug]/invite/index.tsx b/pages/api/projects/[slug]/invite/index.tsx
index ccf3e8155f..019bad36c2 100644
--- a/pages/api/projects/[slug]/invite/index.tsx
+++ b/pages/api/projects/[slug]/invite/index.tsx
@@ -1,10 +1,8 @@
-import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
import prisma from "@/lib/prisma";
import sendMail from "emails";
import ProjectInvite from "emails/ProjectInvite";
import { randomBytes, createHash } from "crypto";
-import { ProjectProps } from "@/lib/types";
const hashToken = (token: string) => {
return createHash("sha256")
@@ -12,99 +10,95 @@ const hashToken = (token: string) => {
.digest("hex");
};
-export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {
- const { slug } = req.query;
- if (!slug || typeof slug !== "string") {
+export default withProjectAuth(async (req, res, project) => {
+ const { slug } = req.query;
+ if (!slug || typeof slug !== "string") {
+ return res
+ .status(400)
+ .json({ error: "Missing or misconfigured project slug" });
+ }
+
+ // GET /api/projects/[slug]/invite - Get all pending invites for a project
+ if (req.method === "GET") {
+ const invites = await prisma.projectInvite.findMany({
+ where: {
+ projectId: project.id,
+ },
+ select: {
+ email: true,
+ createdAt: true,
+ },
+ });
+ return res.status(200).json(
+ invites.map((invite) => ({
+ email: invite.email,
+ joinedAt: invite.createdAt,
+ })),
+ );
+
+ // POST /api/projects/[slug]/invite – invite a teammate
+ } else if (req.method === "POST") {
+ const { email } = req.body;
+
+ const alreadyInTeam = await prisma.projectUsers.findFirst({
+ where: {
+ projectId: project.id,
+ user: {
+ email,
+ },
+ },
+ });
+ if (alreadyInTeam) {
return res
.status(400)
- .json({ error: "Missing or misconfigured project slug" });
+ .json({ error: "User already exists in this project" });
}
- // GET /api/projects/[slug]/invite - Get all pending invites for a project
- if (req.method === "GET") {
- const invites = await prisma.projectInvite.findMany({
- where: {
+ // same method of generating a token as next-auth
+ const token = randomBytes(32).toString("hex");
+ const ONE_WEEK_IN_SECONDS = 604800;
+ const expires = new Date(Date.now() + ONE_WEEK_IN_SECONDS * 1000);
+
+ // create a project invite record and a verification request token that lasts for a week
+ // here we use a try catch to account for the case where the user has already been invited
+ // for which `prisma.projectInvite.create()` will throw a unique constraint error
+ try {
+ await prisma.projectInvite.create({
+ data: {
+ email,
+ expires,
projectId: project.id,
},
- select: {
- email: true,
- createdAt: true,
- },
});
- return res.status(200).json(
- invites.map((invite) => ({
- email: invite.email,
- joinedAt: invite.createdAt,
- })),
- );
-
- // POST /api/projects/[slug]/invite – invite a teammate
- } else if (req.method === "POST") {
- const { email } = req.body;
- const alreadyInTeam = await prisma.projectUsers.findFirst({
- where: {
- projectId: project.id,
- user: {
- email,
- },
+ await prisma.verificationToken.create({
+ data: {
+ identifier: email,
+ token: hashToken(token),
+ expires,
},
});
- if (alreadyInTeam) {
- return res
- .status(400)
- .json({ error: "User already exists in this project" });
- }
-
- // same method of generating a token as next-auth
- const token = randomBytes(32).toString("hex");
- const ONE_WEEK_IN_SECONDS = 604800;
- const expires = new Date(Date.now() + ONE_WEEK_IN_SECONDS * 1000);
-
- // create a project invite record and a verification request token that lasts for a week
- // here we use a try catch to account for the case where the user has already been invited
- // for which `prisma.projectInvite.create()` will throw a unique constraint error
- try {
- await prisma.projectInvite.create({
- data: {
- email,
- expires,
- projectId: project.id,
- },
- });
-
- await prisma.verificationToken.create({
- data: {
- identifier: email,
- token: hashToken(token),
- expires,
- },
- });
- const params = new URLSearchParams({
- callbackUrl: `${process.env.NEXTAUTH_URL}/${slug}`,
- email,
- token,
- });
+ const params = new URLSearchParams({
+ callbackUrl: `${process.env.NEXTAUTH_URL}/${slug}`,
+ email,
+ token,
+ });
- const url = `${process.env.NEXTAUTH_URL}/api/auth/callback/email?${params}`;
+ const url = `${process.env.NEXTAUTH_URL}/api/auth/callback/email?${params}`;
- sendMail({
- subject: "You've been invited to join a project on Dub",
- to: email,
- component: <ProjectInvite url={url} projectName={project.name} />,
- });
+ sendMail({
+ subject: "You've been invited to join a project on Dub",
+ to: email,
+ component: <ProjectInvite url={url} projectName={project.name} />,
+ });
- return res.status(200).json({ message: "Invite sent" });
- } catch (error) {
- return res.status(400).json({ error: "User already invited" });
- }
- } else {
- res.setHeader("Allow", ["GET", "POST"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
+ return res.status(200).json({ message: "Invite sent" });
+ } catch (error) {
+ return res.status(400).json({ error: "User already invited" });
}
- },
-);
+ } else {
+ res.setHeader("Allow", ["GET", "POST"]);
+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+ }
+});
diff --git a/pages/api/projects/[slug]/links/[key]/archive.ts b/pages/api/projects/[slug]/links/[key]/archive.ts
index 74e7465958..b739dbe9ab 100644
--- a/pages/api/projects/[slug]/links/[key]/archive.ts
+++ b/pages/api/projects/[slug]/links/[key]/archive.ts
@@ -1,25 +1,20 @@
-import { NextApiRequest, NextApiResponse } from "next";
import { archiveLink } from "@/lib/api/links";
import { withProjectAuth } from "@/lib/auth";
-export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse) => {
- const { domain, key } = req.query as {
- domain: string;
- key: string;
- };
+export default withProjectAuth(async (req, res) => {
+ const { domain, key } = req.query as {
+ domain: string;
+ key: string;
+ };
- if (req.method === "POST") {
- const response = await archiveLink(domain, key);
- return res.status(200).json(response);
- } else if (req.method === "DELETE") {
- const response = await archiveLink(domain, key, false);
- return res.status(200).json(response);
- } else {
- res.setHeader("Allow", ["POST", "DELETE"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
-);
+ if (req.method === "POST") {
+ const response = await archiveLink(domain, key);
+ return res.status(200).json(response);
+ } else if (req.method === "DELETE") {
+ const response = await archiveLink(domain, key, false);
+ return res.status(200).json(response);
+ } else {
+ res.setHeader("Allow", ["POST", "DELETE"]);
+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+ }
+});
diff --git a/pages/api/projects/[slug]/links/[key]/exists.ts b/pages/api/projects/[slug]/links/[key]/exists.ts
index fa62043258..7648b042f0 100644
--- a/pages/api/projects/[slug]/links/[key]/exists.ts
+++ b/pages/api/projects/[slug]/links/[key]/exists.ts
@@ -1,19 +1,14 @@
-import { NextApiRequest, NextApiResponse } from "next";
import { checkIfKeyExists } from "@/lib/api/links";
import { withProjectAuth } from "@/lib/auth";
-export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse) => {
- // GET /api/projects/[slug]/domains/[domain]/links/[key]/exists - check if a key exists
- if (req.method === "GET") {
- 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` });
- }
- },
-);
+export default withProjectAuth(async (req, res) => {
+ // GET /api/projects/[slug]/domains/[domain]/links/[key]/exists - check if a key exists
+ if (req.method === "GET") {
+ 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]/links/[key]/index.ts
index ac045e4f74..bb89f04f56 100644
--- a/pages/api/projects/[slug]/links/[key]/index.ts
+++ b/pages/api/projects/[slug]/links/[key]/index.ts
@@ -1,4 +1,3 @@
-import { NextApiRequest, NextApiResponse } from "next";
import { deleteLink, editLink } from "@/lib/api/links";
import { withProjectAuth } from "@/lib/auth";
@@ -11,7 +10,7 @@ export const config = {
};
export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse) => {
+ async (req, res) => {
const { domain, key: oldKey } = req.query as {
domain: string;
key: string;
diff --git a/pages/api/projects/[slug]/links/[key]/stats/[endpoint].ts b/pages/api/projects/[slug]/links/[key]/stats/[endpoint].ts
index 93c164f40a..2118c2f847 100644
--- a/pages/api/projects/[slug]/links/[key]/stats/[endpoint].ts
+++ b/pages/api/projects/[slug]/links/[key]/stats/[endpoint].ts
@@ -1,9 +1,8 @@
-import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
import { getStats, IntervalProps } from "@/lib/stats";
export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse) => {
+ async (req, res) => {
// GET /api/projects/[slug]/links/[key]/stats/[endpoint] - get link stats from Tinybird
if (req.method === "GET") {
const { domain, key, endpoint, interval } = req.query as {
diff --git a/pages/api/projects/[slug]/links/[key]/stats/index.ts b/pages/api/projects/[slug]/links/[key]/stats/index.ts
index a182fcc303..ec33636f87 100644
--- a/pages/api/projects/[slug]/links/[key]/stats/index.ts
+++ b/pages/api/projects/[slug]/links/[key]/stats/index.ts
@@ -1,9 +1,8 @@
-import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
import prisma from "@/lib/prisma";
export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse) => {
+ async (req, res) => {
const { domain, key } = req.query as {
domain: string;
key: string;
diff --git a/pages/api/projects/[slug]/links/count.ts b/pages/api/projects/[slug]/links/count.ts
index 26b0c60a21..6533748535 100644
--- a/pages/api/projects/[slug]/links/count.ts
+++ b/pages/api/projects/[slug]/links/count.ts
@@ -1,22 +1,16 @@
-import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
-import { ProjectProps } from "@/lib/types";
import { getLinksCount } from "@/lib/api/links";
-export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {
- // GET /api/projects/[slug]/domains/[domain]/links/count – count the number of links for a project
- if (req.method === "GET") {
- const count = await getLinksCount({
- req,
- projectId: project.id,
- });
- return res.status(200).json(count);
- } else {
- res.setHeader("Allow", ["GET"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
-);
+export default withProjectAuth(async (req, res, project) => {
+ // GET /api/projects/[slug]/domains/[domain]/links/count – count the number of links for a project
+ if (req.method === "GET") {
+ const count = await getLinksCount({
+ req,
+ projectId: project.id,
+ });
+ return res.status(200).json(count);
+ } else {
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+ }
+});
diff --git a/pages/api/projects/[slug]/links/index.ts b/pages/api/projects/[slug]/links/index.ts
index 7a63cbb3d2..c5b623ad22 100644
--- a/pages/api/projects/[slug]/links/index.ts
+++ b/pages/api/projects/[slug]/links/index.ts
@@ -1,4 +1,3 @@
-import { NextApiRequest, NextApiResponse } from "next";
import { addLink, getLinksForProject } from "@/lib/api/links";
import { withProjectAuth } from "@/lib/auth";
@@ -11,7 +10,7 @@ export const config = {
};
export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse, project, session) => {
+ async (req, res, project, session) => {
// GET /api/projects/[slug]/links - Get all links for a project
if (req.method === "GET") {
const { domain, status, tag, search, sort, userId } = req.query as {
diff --git a/pages/api/projects/[slug]/links/random.ts b/pages/api/projects/[slug]/links/random.ts
index a3fb418a11..b43a94de0a 100644
--- a/pages/api/projects/[slug]/links/random.ts
+++ b/pages/api/projects/[slug]/links/random.ts
@@ -1,22 +1,17 @@
-import { NextApiRequest, NextApiResponse } from "next";
import { getRandomKey } from "@/lib/api/links";
import { withProjectAuth } from "@/lib/auth";
-export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse) => {
- // GET /api/projects/[slug]/domains/[domain]/links/random – get a random link
- if (req.method === "GET") {
- const { domain } = req.query as { domain: string };
- if (!domain) {
- return res.status(400).json({ error: "Missing domain" });
- }
- const key = await getRandomKey(domain);
- return res.status(200).json(key);
- } else {
- res.setHeader("Allow", ["GET"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
+export default withProjectAuth(async (req, res) => {
+ // GET /api/projects/[slug]/domains/[domain]/links/random – get a random link
+ if (req.method === "GET") {
+ const { domain } = req.query as { domain: string };
+ if (!domain) {
+ return res.status(400).json({ error: "Missing domain" });
}
- },
-);
+ const key = await getRandomKey(domain);
+ return res.status(200).json(key);
+ } else {
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+ }
+});
diff --git a/pages/api/projects/[slug]/users.ts b/pages/api/projects/[slug]/users.ts
index deffd0c3c4..5bcc439b4d 100644
--- a/pages/api/projects/[slug]/users.ts
+++ b/pages/api/projects/[slug]/users.ts
@@ -1,46 +1,40 @@
-import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
import prisma from "@/lib/prisma";
-import { ProjectProps } from "@/lib/types";
-export default withProjectAuth(
- async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {
- const { slug } = req.query;
- if (!slug || typeof slug !== "string") {
- return res
- .status(400)
- .json({ error: "Missing or misconfigured project slug" });
- }
+export default withProjectAuth(async (req, res, project) => {
+ const { slug } = req.query;
+ if (!slug || typeof slug !== "string") {
+ return res
+ .status(400)
+ .json({ error: "Missing or misconfigured project slug" });
+ }
- // GET /api/projects/[slug]/users – get users for a specific project
- if (req.method === "GET") {
- const { id: projectId } = project;
- const users = await prisma.projectUsers.findMany({
- where: {
- projectId,
- },
- select: {
- user: {
- select: {
- id: true,
- name: true,
- email: true,
- },
+ // GET /api/projects/[slug]/users – get users for a specific project
+ if (req.method === "GET") {
+ const { id: projectId } = project;
+ const users = await prisma.projectUsers.findMany({
+ where: {
+ projectId,
+ },
+ select: {
+ user: {
+ select: {
+ id: true,
+ name: true,
+ email: true,
},
- createdAt: true,
},
- });
- return res.status(200).json(
- users.map((u) => ({
- ...u.user,
- joinedAt: u.createdAt,
- })),
- );
- } else {
- res.setHeader("Allow", ["GET"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
-);
+ createdAt: true,
+ },
+ });
+ return res.status(200).json(
+ users.map((u) => ({
+ ...u.user,
+ joinedAt: u.createdAt,
+ })),
+ );
+ } else {
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+ }
+});
diff --git a/pages/api/projects/index.ts b/pages/api/projects/index.ts
index d42e9f742b..d584315d32 100644
--- a/pages/api/projects/index.ts
+++ b/pages/api/projects/index.ts
@@ -69,15 +69,6 @@ export default withUserAuth(
});
}
- const { usageLimit: ownerUsageLimit } = await prisma.user.findUnique({
- where: {
- id: session.user.id,
- },
- select: {
- usageLimit: true,
- },
- });
-
const project = await prisma.project.create({
data: {
name,
@@ -89,6 +80,7 @@ export default withUserAuth(
role: "owner",
},
},
+ billingCycleStart: new Date().getDate(),
},
});
const response = await Promise.allSettled([
diff --git a/pages/api/stripe/manage-subscription.ts b/pages/api/stripe/manage-subscription.ts
deleted file mode 100644
index a4cecd6f6d..0000000000
--- a/pages/api/stripe/manage-subscription.ts
+++ /dev/null
@@ -1,27 +0,0 @@
-import { NextApiRequest, NextApiResponse } from "next";
-import { withUserAuth } from "@/lib/auth";
-import { stripe } from "@/lib/stripe";
-import { UserProps } from "@/lib/types";
-
-export default withUserAuth(
- async (req: NextApiRequest, res: NextApiResponse, _, user: UserProps) => {
- // POST /api/stripe/manage-subscription – manage a user's subscription
- if (req.method === "POST") {
- const { url } = await stripe.billingPortal.sessions.create({
- customer: user.stripeId,
- return_url: `${
- process.env.VERCEL === "1"
- ? "https://app.dub.sh"
- : "http://app.localhost:3000"
- }/settings`,
- });
- return res.status(200).json(url);
- } else {
- res.setHeader("Allow", ["POST"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
- { needUserDetails: true },
-);
diff --git a/pages/api/stripe/upgrade.ts b/pages/api/stripe/upgrade.ts
deleted file mode 100644
index 76a7b6fb9c..0000000000
--- a/pages/api/stripe/upgrade.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { NextApiRequest, NextApiResponse } from "next";
-import { Session, withUserAuth } from "@/lib/auth";
-import { stripe } from "@/lib/stripe";
-import { UserProps } from "@/lib/types";
-
-export default withUserAuth(
- async (
- req: NextApiRequest,
- res: NextApiResponse,
- session: Session,
- user: UserProps,
- ) => {
- // POST /api/stripe/upgrade – upgrade a user's account from free to pro
- if (req.method === "POST") {
- const { priceId } = req.query as { priceId: string };
- const stripeSession = await stripe.checkout.sessions.create({
- customer_email: user.email,
- payment_method_types: ["card"],
- billing_address_collection: "required",
- success_url: `${
- process.env.VERCEL === "1"
- ? "https://app.dub.sh"
- : "http://app.localhost:3000"
- }/settings`,
- cancel_url: `${
- process.env.VERCEL === "1"
- ? "https://app.dub.sh"
- : "http://app.localhost:3000"
- }/settings`,
- line_items: [{ price: priceId, quantity: 1 }],
- automatic_tax: {
- enabled: true,
- },
- tax_id_collection: {
- enabled: true,
- },
- mode: "subscription",
- client_reference_id: session.user.id,
- });
- return res.status(200).json(stripeSession);
- } else {
- res.setHeader("Allow", ["POST"]);
- return res
- .status(405)
- .json({ error: `Method ${req.method} Not Allowed` });
- }
- },
- { needUserDetails: true },
-);
diff --git a/pages/api/stripe/webhook.ts b/pages/api/stripe/webhook.ts
index 872a4054e7..25687961b1 100644
--- a/pages/api/stripe/webhook.ts
+++ b/pages/api/stripe/webhook.ts
@@ -3,7 +3,7 @@ import { Readable } from "node:stream";
import Stripe from "stripe";
import prisma from "@/lib/prisma";
import { stripe } from "@/lib/stripe";
-import { PRO_TIERS } from "@/lib/stripe/constants";
+import { PLANS } from "@/lib/stripe/constants";
import { redis } from "@/lib/upstash";
import { log } from "@/lib/utils";
@@ -32,7 +32,7 @@ export default async function webhookHandler(
req: NextApiRequest,
res: NextApiResponse,
) {
- // POST /api/projects/[slug]/upgrade/webhook – listen to Stripe webhooks
+ // POST /api/stripe/webhook – listen to Stripe webhooks
if (req.method === "POST") {
const buf = await buffer(req);
const sig = req.headers["stripe-signature"];
@@ -50,10 +50,11 @@ export default async function webhookHandler(
if (event.type === "checkout.session.completed") {
const checkoutSession = event.data.object as Stripe.Checkout.Session;
- // when the user subscribes to a plan, set their stripe customer ID
+ // when the project subscribes to a plan, set their stripe customer ID
// in the database for easy identification in future webhook events
+ // also update the billingCycleStart to today's date
- await prisma.user.update({
+ await prisma.project.update({
where: {
id: checkoutSession.client_reference_id,
},
@@ -69,114 +70,62 @@ export default async function webhookHandler(
process.env.NEXT_PUBLIC_VERCEL_ENV === "production"
? "production"
: "test";
- const tier = PRO_TIERS.find(
- (tier) =>
- tier.price.monthly.priceIds[env] === newPriceId ||
- tier.price.yearly.priceIds[env] === newPriceId,
+ const plan = PLANS.find(
+ (plan) =>
+ plan.price.monthly.priceIds[env] === newPriceId ||
+ plan.price.yearly.priceIds[env] === newPriceId,
);
- const usageLimit = tier.quota;
+ const usageLimit = plan.quota;
const stripeId = subscriptionUpdated.customer.toString();
- // If a user upgrades/downgrades their subscription, update their usage limit in the database.
- // We also need to update the ownerUsageLimit field for all their projects.
-
- const { projects } = await prisma.user.findUnique({
+ // If a project upgrades/downgrades their subscription, update their usage limit in the database.
+ await prisma.project.update({
where: {
stripeId,
},
- select: {
- projects: {
- where: {
- role: "owner",
- },
- select: {
- projectId: true,
- },
- },
+ data: {
+ usageLimit,
+ plan: plan.slug,
},
});
-
- await Promise.all([
- prisma.user.update({
- where: {
- stripeId,
- },
- data: {
- usageLimit,
- billingCycleStart: new Date().getDate(),
- },
- }),
- Promise.all(
- projects.map(async ({ projectId }) => {
- return await prisma.project.update({
- where: {
- id: projectId,
- },
- data: {
- ownerUsageLimit: usageLimit,
- },
- });
- }),
- ),
- ]);
} else if (event.type === "customer.subscription.deleted") {
const subscriptionDeleted = event.data.object as Stripe.Subscription;
const stripeId = subscriptionDeleted.customer.toString();
- // If a user deletes their subscription, reset their usage limit in the database to 1000.
- // We also need to reset the ownerUsageLimit field for all their projects to 1000.
-
- const { email, usage, projects } = await prisma.user.findUnique({
+ // If a project deletes their subscription, reset their usage limit in the database to 1000.
+ // Also remove the root domain redirect for all their domains from Redis.
+ const project = await prisma.project.findUnique({
where: {
stripeId,
},
select: {
- email: true,
- usage: true,
- projects: {
- where: {
- role: "owner",
- },
- select: {
- projectId: true,
- project: {
- select: {
- domain: true,
- },
- },
- },
- },
+ name: true,
+ domains: true,
},
});
+ const projectDomains = project.domains.map((domain) => domain.slug);
+
+ const pipeline = redis.pipeline();
+ // remove root domain redirect for all domains
+ projectDomains.forEach((domain) => {
+ pipeline.del(`root:${domain}`);
+ });
+
const response = await Promise.all([
- prisma.user.update({
+ prisma.project.update({
where: {
stripeId,
},
data: {
usageLimit: 1000,
+ plan: "free",
},
}),
- Promise.all(
- projects.map(async ({ projectId, project: { domain } }) => {
- return await Promise.all([
- prisma.project.update({
- where: {
- id: projectId,
- },
- data: {
- ownerUsageLimit: 1000,
- ownerExceededUsage: usage > 1000,
- },
- }),
- redis.del(`root:${domain}`), // remove root domain redirect
- ]);
- }),
- ),
+ pipeline.exec(),
log(
- ":cry: User *`" + email + "`* deleted their subscription",
+ ":cry: Project *`" + name + "`* deleted their subscription",
"links",
),
]);
diff --git a/pages/index.tsx b/pages/index.tsx
index c84b0cc3bc..93616bf145 100644
--- a/pages/index.tsx
+++ b/pages/index.tsx
@@ -56,7 +56,7 @@ export default function Home({
<Globe />
<Features />
<Testimonials userCount={userCount} tweets={tweets} />
- <Pricing />
+ <Pricing homePage />
<OSS stars={stars} />
</div>
<Background />
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 31510b39f4..240d6b950c 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -24,6 +24,7 @@ model User {
usage Int @default(0)
usageLimit Int @default(1000)
billingCycleStart Int? // day of the month when the billing cycle starts
+ usageUpdatedAt DateTime @default(now())
accounts Account[]
sessions Session[]
@@ -31,7 +32,6 @@ model User {
sentEmails SentEmail[]
links Link[]
createdAt DateTime @default(now())
- usageUpdatedAt DateTime @default(now())
}
model Account {
@@ -83,8 +83,6 @@ model Project {
domainVerified Boolean @default(false)
domainLastChecked DateTime @default(now())
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
users ProjectUsers[]
invites ProjectInvite[]
usage Int @default(0)
@@ -101,6 +99,12 @@ model Project {
domains Domain[]
links Link[]
tags Tag[]
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ usageUpdatedAt DateTime @default(now())
+
+ @@index(usageUpdatedAt)
}
model ProjectInvite {