Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

fixed stats auth, nav buttons, login/register states

Steven Teydc0b1f158aaa
diff --git a/components/layout/app/index.tsx b/components/layout/app/index.tsx
index 0f9546452d..04a9c9a914 100644
--- a/components/layout/app/index.tsx
+++ b/components/layout/app/index.tsx
@@ -5,6 +5,7 @@ import Meta from "../meta";
import { Logo, Divider } from "@/components/shared/icons";
import ListBox from "./list-box";
import UserDropdown from "./user-dropdown";
+import { useRouter } from "next/router";
const NavTabs = dynamic(() => import("./nav-tabs"), {
ssr: false,
@@ -12,6 +13,12 @@ const NavTabs = dynamic(() => import("./nav-tabs"), {
}); // dynamic import to avoid react hydration mismatch error
export default function AppLayout({ children }: { children: ReactNode }) {
+ const router = useRouter();
+ const { slug, key } = router.query as {
+ slug?: string;
+ key?: string;
+ };
+
return (
<div>
<Meta />
@@ -27,6 +34,14 @@ export default function AppLayout({ children }: { children: ReactNode }) {
</Link>
<Divider className="h-8 w-8 ml-3 text-gray-200" />
<ListBox />
+ {key && slug && (
+ <>
+ <Divider className="h-8 w-8 mr-3 text-gray-200" />
+ <Link href={`/${slug}/${key}`}>
+ <a className="text-sm font-medium">{key}</a>
+ </Link>
+ </>
+ )}
</div>
<UserDropdown />
</div>
diff --git a/components/layout/app/nav-tabs.tsx b/components/layout/app/nav-tabs.tsx
index 274ff827d8..2cf8f831fb 100644
--- a/components/layout/app/nav-tabs.tsx
+++ b/components/layout/app/nav-tabs.tsx
@@ -3,8 +3,13 @@ import Link from "next/link";
import { NextRouter, useRouter } from "next/router";
const TabsHelper = (router: NextRouter): { name: string; href: string }[] => {
- const { slug } = router.query;
- if (slug) {
+ const { slug, key } = router.query as {
+ slug?: string;
+ key?: string;
+ };
+ if (key) {
+ return [{ name: "← All Links", href: `/${slug || "links"}` }];
+ } else if (slug) {
return [
{ name: "Links", href: `/${slug}` },
{ name: "Settings", href: `/${slug}/settings` },
diff --git a/components/stats/index.tsx b/components/stats/index.tsx
index d04a947463..fa577c4fe1 100644
--- a/components/stats/index.tsx
+++ b/components/stats/index.tsx
@@ -7,14 +7,30 @@ import useSWR from "swr";
import { fetcher } from "@/lib/utils";
import { useRouter } from "next/router";
-export default function Stats({ atModalTop }: { atModalTop?: boolean }) {
+export default function Stats({
+ modal,
+ atModalTop,
+ domain,
+}: {
+ modal?: boolean;
+ atModalTop?: boolean;
+ domain?: string;
+}) {
const router = useRouter();
+ const { slug, key, interval } = router.query as {
+ slug?: string;
+ key: string;
+ interval?: string;
+ };
+
const { data, isValidating } = useSWR<StatsProps>(
- router.query.key &&
- `/api/edge/links/${router.query.key}/stats${
- router.query.interval ? `?interval=${router.query.interval}` : ""
- }`,
+ router.isReady &&
+ `${
+ slug && domain
+ ? `/api/projects/${slug}/domains/${domain}/links/${key}/stats`
+ : `/api/edge/links/${key}/stats`
+ }${interval ? `?interval=${interval}` : ""}`,
fetcher,
{
keepPreviousData: true,
@@ -24,7 +40,12 @@ export default function Stats({ atModalTop }: { atModalTop?: boolean }) {
return (
<div className="relative bg-gray-50 dark:bg-black py-20 mx-auto lg:px-0 px-2.5">
- <Toggle data={data!} atModalTop={atModalTop} />
+ <Toggle
+ data={data!}
+ domain={domain}
+ modal={modal}
+ atModalTop={atModalTop}
+ />
<div className="max-w-4xl mx-auto grid gap-5">
<Clicks data={data!} isValidating={isValidating} />
<div className="grid grid-cols-1 sm:grid-cols-2 gap-5">
diff --git a/components/stats/stats-modal.tsx b/components/stats/stats-modal.tsx
index 032a4fa5e4..8fb19ed7e5 100644
--- a/components/stats/stats-modal.tsx
+++ b/components/stats/stats-modal.tsx
@@ -46,7 +46,7 @@ function StatsModalHelper({
>
<X className="w-6 h-6" />
</button>
- <Stats atModalTop={atModalTop} />
+ <Stats modal={true} atModalTop={atModalTop} />
</div>
</Modal>
);
diff --git a/components/stats/toggle.tsx b/components/stats/toggle.tsx
index 5092b5adc1..680a6f5d11 100644
--- a/components/stats/toggle.tsx
+++ b/components/stats/toggle.tsx
@@ -8,9 +8,13 @@ import { IntervalProps, StatsProps } from "@/lib/stats";
export default function Toggle({
data,
+ domain,
+ modal,
atModalTop,
}: {
data: StatsProps;
+ domain?: string;
+ modal?: boolean;
atModalTop?: boolean;
}) {
const router = useRouter();
@@ -21,19 +25,19 @@ export default function Toggle({
return (
<div
- className={`mb-5 sticky top-0 py-5 bg-gray-50 dark:bg-black ${
- atTop ? "shadow-md" : ""
- }`}
+ className={`mb-5 ${
+ modal ? "top-0" : "top-24"
+ } sticky py-5 bg-gray-50 dark:bg-black ${atTop ? "shadow-md" : ""}`}
>
<div className="max-w-4xl mx-auto flex justify-between items-center">
<div className="group flex">
<a
className="text-xl text-gray-800 dark:text-gray-200 font-semibold"
- href={linkConstructor({ key })}
+ href={linkConstructor({ key, domain })}
target="_blank"
rel="noreferrer"
>
- {linkConstructor({ key, pretty: true })}
+ {linkConstructor({ key, domain, pretty: true })}
</a>
<ExpandingArrow className="w-5 h-5" />
</div>
diff --git a/lib/middleware/app.ts b/lib/middleware/app.ts
index 428c279e7f..d9d4f4d31a 100644
--- a/lib/middleware/app.ts
+++ b/lib/middleware/app.ts
@@ -5,9 +5,9 @@ import { getToken } from "next-auth/jwt";
export default async function AppMiddleware(req: NextRequest) {
const { path } = parse(req);
const session = await getToken({ req, secret: process.env.NEXTAUTH_SECRET });
- if (!session && path !== "/login") {
+ if (!session && path !== "/login" && path !== "/register") {
return NextResponse.redirect(new URL("/login", req.url));
- } else if (session && path === "/login") {
+ } else if (session && (path === "/login" || path === "/register")) {
return NextResponse.redirect(new URL("/", req.url));
}
return NextResponse.rewrite(new URL(`/app${path}`, req.url));
diff --git a/pages/api/auth/account-exists.ts b/pages/api/auth/account-exists.ts
new file mode 100644
index 0000000000..13c688caae
--- /dev/null
+++ b/pages/api/auth/account-exists.ts
@@ -0,0 +1,22 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import prisma from "@/lib/prisma";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ if (req.method === "POST") {
+ const { email } = req.body;
+ const user = await prisma.user.findUnique({
+ where: { email },
+ select: { email: true },
+ });
+ if (user) {
+ return res.status(200).json({ exists: true });
+ }
+ return res.status(200).json({ exists: false });
+ } 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]/links/[key]/stats.ts b/pages/api/projects/[slug]/domains/[domain]/links/[key]/stats.ts
index bb3b89c653..f21dbc45d9 100644
--- a/pages/api/projects/[slug]/domains/[domain]/links/[key]/stats.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/links/[key]/stats.ts
@@ -1,7 +1,12 @@
import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
import { redis } from "@/lib/upstash";
-import { IntervalProps, intervalData, RawStatsProps } from "@/lib/stats";
+import {
+ IntervalProps,
+ intervalData,
+ RawStatsProps,
+ processData,
+} from "@/lib/stats";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
@@ -21,7 +26,8 @@ export default withProjectAuth(
byScore: true,
}
);
- return res.status(200).json(response);
+ const data = await processData(key, response, interval);
+ return res.status(200).json(data);
} else {
res.setHeader("Allow", ["GET"]);
return res
diff --git a/pages/app/[slug]/[key].tsx b/pages/app/[slug]/[key].tsx
index 4a00f1bdbd..ef0a663876 100644
--- a/pages/app/[slug]/[key].tsx
+++ b/pages/app/[slug]/[key].tsx
@@ -1,10 +1,25 @@
import Stats from "@/components/stats";
import AppLayout from "@/components/layout/app";
+import { useRouter } from "next/router";
+import useSWR from "swr";
+import { fetcher } from "@/lib/utils";
+import { ProjectProps } from "@/lib/types";
+import ErrorPage from "next/error";
export default function StatsPage() {
- return (
- <AppLayout>
- <Stats />
- </AppLayout>
+ const router = useRouter();
+ const { slug } = router.query as {
+ slug: string;
+ };
+
+ const { data: project, error } = useSWR<ProjectProps>(
+ router.isReady && `/api/projects/${slug}`,
+ fetcher
);
+ // handle error page
+ if (error && error.status === 404) {
+ return <ErrorPage statusCode={404} />;
+ }
+
+ return <AppLayout>{project && <Stats domain={project.domain} />}</AppLayout>;
}
diff --git a/pages/app/[slug]/index.tsx b/pages/app/[slug]/index.tsx
index c0474d2896..bd3ab60207 100644
--- a/pages/app/[slug]/index.tsx
+++ b/pages/app/[slug]/index.tsx
@@ -2,7 +2,7 @@ import AppLayout from "components/layout/app";
import { useRouter } from "next/router";
import useSWR from "swr";
import { fetcher } from "@/lib/utils";
-import { useMemo, useEffect } from "react";
+import { useMemo } from "react";
import { ProjectProps } from "@/lib/types";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
import { useAddLinkModal } from "@/components/app/add-link-modal";
diff --git a/pages/app/login.tsx b/pages/app/login.tsx
index 70c139712c..310518d6fd 100644
--- a/pages/app/login.tsx
+++ b/pages/app/login.tsx
@@ -1,29 +1,46 @@
import { useState } from "react";
+import Link from "next/link";
import { signIn } from "next-auth/react";
import { LoadingDots } from "@/components/shared/icons";
export default function Login() {
const [signInClicked, setSignInClicked] = useState(false);
+ const [noSuchAccount, setNoSuchAccount] = useState(false);
+ const [email, setEmail] = useState("");
const [buttonText, setButtonText] = useState("Send magic link");
return (
- <div className="h-screen w-screen flex justify-center items-center">
- <div className="inline-block w-full max-w-md py-8 px-4 sm:px-16 overflow-hidden text-center align-middle transition-all transform bg-white shadow-xl rounded-2xl">
- <h1 className="font-bold text-3xl mb-4">Log In to Dub</h1>
-
+ <div className="h-screen w-screen flex justify-center items-center bg-gray-50">
+ <div className="flex flex-col space-y-4 w-full max-w-md py-12 px-4 sm:px-16 overflow-hidden text-center align-middle transition-all transform bg-white shadow-xl rounded-2xl">
+ <h1 className="font-bold font-display text-3xl">Sign In</h1>
+ <p className="text-gray-600 text-sm">
+ Use your email address to sign in.
+ </p>
<form
onSubmit={async (e) => {
e.preventDefault();
setSignInClicked(true);
- signIn("email", {
- email: e.currentTarget.email.value,
- redirect: false,
- }).then((res) => {
- setSignInClicked(false);
- if (res?.ok && !res?.error) {
- setButtonText("Email sent - check your inbox!");
+ fetch("/api/auth/account-exists", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ email }),
+ }).then(async (res) => {
+ const { exists } = await res.json();
+ if (exists) {
+ signIn("email", {
+ email,
+ redirect: false,
+ }).then((res) => {
+ setSignInClicked(false);
+ if (res?.ok && !res?.error) {
+ setButtonText("Email sent - check your inbox!");
+ } else {
+ setButtonText("Error sending email - try again?");
+ }
+ });
} else {
- setButtonText("Error sending email - try again?");
+ setNoSuchAccount(true);
+ setSignInClicked(false);
}
});
}}
@@ -35,6 +52,10 @@ export default function Login() {
placeholder="Email Address"
autoComplete="email"
required
+ onChange={(e) => {
+ setNoSuchAccount(false);
+ setEmail(e.target.value);
+ }}
className="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-black focus:border-black sm:text-sm"
/>
<button
@@ -52,6 +73,23 @@ export default function Login() {
)}
</button>
</form>
+ {noSuchAccount ? (
+ <p className="text-red-500 text-sm">
+ No such account.{" "}
+ <Link href="/register">
+ <a className="text-red-600 font-semibold">Sign up</a>
+ </Link>{" "}
+ instead?
+ </p>
+ ) : (
+ <p className="text-gray-600 text-sm">
+ Don't have an account?{" "}
+ <Link href="/register">
+ <a className="text-gray-800 font-semibold">Sign up</a>
+ </Link>{" "}
+ for free.
+ </p>
+ )}
</div>
</div>
);
diff --git a/pages/app/register.tsx b/pages/app/register.tsx
new file mode 100644
index 0000000000..166099dbb0
--- /dev/null
+++ b/pages/app/register.tsx
@@ -0,0 +1,96 @@
+import { useState } from "react";
+import Link from "next/link";
+import { signIn } from "next-auth/react";
+import { LoadingDots } from "@/components/shared/icons";
+
+export default function Login() {
+ const [signInClicked, setSignInClicked] = useState(false);
+ const [accountExists, setAccountExists] = useState(false);
+ const [email, setEmail] = useState("");
+ const [buttonText, setButtonText] = useState("Send magic link");
+
+ return (
+ <div className="h-screen w-screen flex justify-center items-center bg-gray-50">
+ <div className="flex flex-col space-y-4 w-full max-w-md py-12 px-4 sm:px-16 overflow-hidden text-center align-middle transition-all transform bg-white shadow-xl rounded-2xl">
+ <h1 className="font-bold font-display text-3xl">Sign Up</h1>
+ <p className="text-gray-600 text-sm">
+ Get started for free. No credit card required.
+ </p>
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ setSignInClicked(true);
+ fetch("/api/auth/account-exists", {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ email }),
+ }).then(async (res) => {
+ const { exists } = await res.json();
+ if (!exists) {
+ signIn("email", {
+ email,
+ redirect: false,
+ }).then((res) => {
+ setSignInClicked(false);
+ if (res?.ok && !res?.error) {
+ setButtonText("Email sent - check your inbox!");
+ } else {
+ setButtonText("Error sending email - try again?");
+ }
+ });
+ } else {
+ setAccountExists(true);
+ setSignInClicked(false);
+ }
+ });
+ }}
+ className="mt-5 flex flex-col space-y-4"
+ >
+ <input
+ name="email"
+ type="email"
+ placeholder="Email Address"
+ autoComplete="email"
+ required
+ onChange={(e) => {
+ setAccountExists(false);
+ setEmail(e.target.value);
+ }}
+ className="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-black focus:border-black sm:text-sm"
+ />
+ <button
+ disabled={signInClicked}
+ className={`${
+ signInClicked
+ ? "cursor-not-allowed bg-gray-100 border-gray-200"
+ : "bg-black hover:bg-white text-white hover:text-black border-black"
+ } flex justify-center items-center w-full text-sm h-10 rounded-md border transition-all focus:outline-none`}
+ >
+ {signInClicked ? (
+ <LoadingDots color="#808080" />
+ ) : (
+ <p>{buttonText}</p>
+ )}
+ </button>
+ </form>
+ {accountExists ? (
+ <p className="text-red-500 text-sm">
+ This email is already registered.{" "}
+ <Link href="/login">
+ <a className="text-red-600 font-semibold">Log in</a>
+ </Link>{" "}
+ instead?
+ </p>
+ ) : (
+ <p className="text-gray-600 text-sm">
+ Already registered?{" "}
+ <Link href="/login">
+ <a className="text-gray-800 font-semibold">Sign in</a>
+ </Link>{" "}
+ to your account.
+ </p>
+ )}
+ </div>
+ </div>
+ );
+}