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.

Added redirect root domain functionality

Steven Tey34dc2a3a8af8
diff --git a/components/app/settings/delete-project.tsx b/components/app/settings/delete-project.tsx
index f234c795d3..315234b371 100644
--- a/components/app/settings/delete-project.tsx
+++ b/components/app/settings/delete-project.tsx
@@ -16,7 +16,7 @@ export default function DeleteProject() {
</div>
<div className="border-b border-gray-200" />
- <div className="px-10 py-5 flex justify-end items-center">
+ <div className="px-10 py-4 flex justify-end items-center">
<button
onClick={() => setShowDeleteProjectModal(true)}
className="bg-red-500 text-white border-red-500 hover:text-red-500 hover:bg-white h-9 w-32 text-sm border rounded-md focus:outline-none transition-all ease-in-out duration-150"
diff --git a/components/app/settings/landing-page.tsx b/components/app/settings/landing-page.tsx
new file mode 100644
index 0000000000..af760658c8
--- /dev/null
+++ b/components/app/settings/landing-page.tsx
@@ -0,0 +1,126 @@
+import useProject from "@/lib/swr/use-project";
+import { useRouter } from "next/router";
+import { useState } from "react";
+import { Chart, LoadingDots } from "@/components/shared/icons";
+import { fetcher, nFormatter } from "@/lib/utils";
+import useSWR from "swr";
+import Tooltip from "@/components/shared/tooltip";
+import toast from "react-hot-toast";
+
+export default function DefaultPage() {
+ const router = useRouter();
+ const { slug } = router.query as { slug: string };
+
+ const { project: { domain, domainVerified } = {} } = useProject();
+
+ const { data: rootDomain } = useSWR<string>(
+ slug && domain && `/api/projects/${slug}/domains/${domain}/root`,
+ fetcher
+ );
+
+ const { data: clicks, isValidating } = useSWR<string>(
+ slug && domain && `/api/projects/${slug}/domains/${domain}/root/clicks`,
+ fetcher
+ );
+
+ const [saving, setSaving] = useState(false);
+
+ return (
+ <form
+ onSubmit={(e) => {
+ e.preventDefault();
+ setSaving(true);
+ fetch(`/api/projects/${slug}/domains/${domain}/root`, {
+ method: "PUT",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ // @ts-ignore
+ rootDomain: e.target.root.value,
+ }),
+ }).then(async (res) => {
+ setSaving(false);
+ if (res.status === 200) {
+ toast.success("Successfully updated landing page");
+ }
+ });
+ }}
+ 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">Landing Page</h2>
+ <div className="h-7 flex items-center space-x-1">
+ <p className="text-gray-500 text-sm">
+ Configure a page to redirect visitors when they land on
+ </p>
+ <a
+ href={`https://${domain}`}
+ target="_blank"
+ rel="noreferrer"
+ className="text-blue-800 font-semibold text-sm hover:text-black transition-all"
+ >
+ {domain}
+ </a>
+ {domainVerified && (
+ <div className="flex items-center space-x-1 rounded-md bg-gray-100 px-2 py-0.5 cursor-default">
+ <Chart className="w-4 h-4" />
+ <p className="text-sm text-gray-500">
+ {isValidating || !clicks ? (
+ <LoadingDots color="#71717A" />
+ ) : (
+ nFormatter(parseInt(clicks))
+ )}{" "}
+ clicks
+ </p>
+ </div>
+ )}
+ </div>
+ <div />
+ {domainVerified ? (
+ <input
+ type="url"
+ name="root"
+ id="root"
+ placeholder="https://yourdomain.com"
+ required
+ defaultValue={rootDomain}
+ className="border border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:ring-gray-500 w-full max-w-md rounded-md focus:outline-none text-sm"
+ />
+ ) : (
+ <Tooltip content="You need to verify your domain first.">
+ <div className="border border-gray-300 text-gray-300 text-sm px-3 py-2 w-full max-w-md cursor-not-allowed rounded-md">
+ https://yourdomain.com
+ </div>
+ </Tooltip>
+ )}
+ </div>
+
+ <div className="border-b border-gray-200" />
+
+ <div className="px-10 py-4 flex justify-end items-center">
+ {domainVerified ? (
+ <button
+ disabled={saving}
+ className={`${
+ saving
+ ? "cursor-not-allowed bg-gray-100 border-gray-200"
+ : "bg-black border-black hover:text-black hover:bg-white"
+ } text-white h-9 w-32 text-sm border rounded-md focus:outline-none transition-all ease-in-out duration-150`}
+ >
+ {saving ? <LoadingDots /> : "Save Changes"}
+ </button>
+ ) : (
+ <Tooltip content="You need to verify your domain first.">
+ <button
+ disabled
+ className="cursor-not-allowed bg-gray-100 border-gray-200 text-gray-300 h-9 w-32 text-sm border rounded-md focus:outline-none transition-all ease-in-out duration-150"
+ >
+ Save Changes
+ </button>
+ </Tooltip>
+ )}
+ </div>
+ </form>
+ );
+}
diff --git a/components/app/settings/plan-usage.tsx b/components/app/settings/plan-usage.tsx
index 5a370c41c4..dd077e201e 100644
--- a/components/app/settings/plan-usage.tsx
+++ b/components/app/settings/plan-usage.tsx
@@ -133,7 +133,7 @@ export default function PlanUsage() {
</div>
</div>
<div className="border-b border-gray-200" />
- <div className="px-10 py-5 flex justify-between items-center">
+ <div className="px-10 py-4 flex justify-between items-center">
{project?.plan === "free" ? (
<p className="text-gray-500 text-sm">
For{" "}
diff --git a/lib/auth.ts b/lib/auth.ts
index 0413b02b82..9eb96487e2 100644
--- a/lib/auth.ts
+++ b/lib/auth.ts
@@ -32,7 +32,7 @@ interface CustomNextApiHandler {
}
const withProjectAuth =
- (handler: CustomNextApiHandler, isWriteEditLink?: boolean) =>
+ (handler: CustomNextApiHandler, requireValidDomain?: boolean) =>
// TODO - fix `handler` type when we figure it out
// `isWriteEditLink` is only true when it's a POST or PUT request for links
// (you can't add/edit a link when domain is not configured)
@@ -70,7 +70,7 @@ const withProjectAuth =
if (!project) return res.status(404).json({ error: "Project not found" });
- if (isWriteEditLink && req.method !== "GET") {
+ if (requireValidDomain && req.method !== "GET") {
if (!project.domainVerified) {
return res
.status(401)
diff --git a/lib/middleware/root.ts b/lib/middleware/root.ts
index 347a79c607..92cf88392e 100644
--- a/lib/middleware/root.ts
+++ b/lib/middleware/root.ts
@@ -2,7 +2,10 @@ import { NextRequest, NextFetchEvent, NextResponse } from "next/server";
import { recordClick, redis } from "@/lib/upstash";
import { parse } from "./utils";
-export default function RootMiddleware(req: NextRequest, ev: NextFetchEvent) {
+export default async function RootMiddleware(
+ req: NextRequest,
+ ev: NextFetchEvent
+) {
const { hostname } = parse(req);
if (!hostname) {
@@ -26,8 +29,13 @@ export default function RootMiddleware(req: NextRequest, ev: NextFetchEvent) {
) {
return NextResponse.next();
} else {
- const url = req.nextUrl;
- url.pathname = `/placeholder/${hostname}`; // rewrite to a /placeholder page unless the user defines a site to redirect to
- return NextResponse.rewrite(url);
+ const target = await redis.get<string>(`root:${hostname}`);
+ if (target) {
+ return NextResponse.redirect(target);
+ } else {
+ const url = req.nextUrl;
+ url.pathname = `/placeholder/${hostname}`; // rewrite to a /placeholder page unless the user defines a site to redirect to
+ return NextResponse.rewrite(url);
+ }
}
}
diff --git a/pages/api/projects/[slug]/domains/[domain]/root/clicks.ts b/pages/api/projects/[slug]/domains/[domain]/root/clicks.ts
new file mode 100644
index 0000000000..e30dbe6b16
--- /dev/null
+++ b/pages/api/projects/[slug]/domains/[domain]/root/clicks.ts
@@ -0,0 +1,21 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { withProjectAuth } from "@/lib/auth";
+import { redis } from "@/lib/upstash";
+
+export default withProjectAuth(
+ async (req: NextApiRequest, res: NextApiResponse) => {
+ const { domain } = req.query as { domain: string };
+
+ // GET /api/projects/[slug]/domains/[domain]/root/clicks - get number of clicks on root domain
+ if (req.method === "GET") {
+ const clicks = (await redis.zcard(`${domain}:root:clicks`)) || 0;
+ return res.status(200).json(clicks);
+ } else {
+ res.setHeader("Allow", ["GET"]);
+ return res
+ .status(405)
+ .json({ error: `Method ${req.method} Not Allowed` });
+ }
+ },
+ true
+);
diff --git a/pages/api/projects/[slug]/domains/[domain]/root/index.ts b/pages/api/projects/[slug]/domains/[domain]/root/index.ts
new file mode 100644
index 0000000000..45893d8b0d
--- /dev/null
+++ b/pages/api/projects/[slug]/domains/[domain]/root/index.ts
@@ -0,0 +1,27 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { withProjectAuth } from "@/lib/auth";
+import { redis } from "@/lib/upstash";
+
+export default withProjectAuth(
+ async (req: NextApiRequest, res: NextApiResponse) => {
+ const { domain } = req.query as { domain: string };
+
+ // GET /api/projects/[slug]/domains/[domain]/root - get root domain
+ if (req.method === "GET") {
+ const rootDomain = await redis.get<string>(`root:${domain}`);
+ return res.status(200).json(rootDomain);
+
+ // PUT /api/projects/[slug]/domains/[domain]/root - change root domain
+ } else if (req.method === "PUT") {
+ const { rootDomain } = req.body as { rootDomain: string };
+ const response = await redis.set(`root:${domain}`, rootDomain);
+ res.status(200).json(response);
+ } else {
+ res.setHeader("Allow", ["GET", "PUT"]);
+ return res
+ .status(405)
+ .json({ error: `Method ${req.method} Not Allowed` });
+ }
+ },
+ true
+);
diff --git a/pages/app/[slug]/settings.tsx b/pages/app/[slug]/settings.tsx
index 327d35baef..aaa1dcc88f 100644
--- a/pages/app/[slug]/settings.tsx
+++ b/pages/app/[slug]/settings.tsx
@@ -2,6 +2,7 @@ import AppLayout from "components/layout/app";
import useProject from "@/lib/swr/use-project";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
import CustomDomain from "@/components/app/settings/custom-domain";
+import DefaultPage from "@/components/app/settings/landing-page";
import PlanUsage from "@/components/app/settings/plan-usage";
import ErrorPage from "next/error";
import DeleteProject from "@/components/app/settings/delete-project";
@@ -27,6 +28,7 @@ export default function ProjectLinks() {
<div className="py-10 grid gap-5">
<PlanUsage />
<CustomDomain />
+ <DefaultPage />
<DeleteProject />
</div>
</MaxWidthWrapper>