The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
made stats work
Steven Teyb09d7baa6eb6
diff --git a/apps/web/app/api/edge/stats/route.ts b/apps/web/app/api/edge/stats/route.tsnew file mode 100644index 0000000000..c32dbc421a--- /dev/null+++ b/apps/web/app/api/edge/stats/route.ts@@ -0,0 +1,57 @@+import { getParams } from "@/lib/auth-app";+import { isBlacklistedReferrer } from "@/lib/edge-config";+import { getLinkViaEdge } from "@/lib/planetscale";+import { getStats } from "@/lib/stats";+import { ratelimit } from "@/lib/upstash";+import { LOCALHOST_IP } from "@dub/utils";+import { ipAddress } from "@vercel/edge";+import { NextResponse, type NextRequest } from "next/server";++// switch to 'edge' after https://github.com/vercel/next.js/issues/48295 is fixed+export const runtime = "nodejs";++export const GET = async (req: NextRequest) => {+ const { domain, key, endpoint, interval } = getParams(req.url);++ // demo link (dub.sh/github)+ if (domain === "dub.sh" && key === "github") {+ // Rate limit in production+ if (process.env.NODE_ENV !== "development") {+ if (await isBlacklistedReferrer(req.headers.get("referer"))) {+ return new Response("Don't DDoS me pls 🥺", { status: 429 });+ }+ const ip = ipAddress(req) || LOCALHOST_IP;+ const { success } = await ratelimit(+ 15,+ endpoint !== "clicks" ? "1 h" : "10 s",+ ).limit(`${ip}:${domain}:${key}:${endpoint}`);++ if (!success) {+ return new Response("Don't DDoS me pls 🥺", { status: 429 });+ }+ }+ } else {+ const data = await getLinkViaEdge(domain, key);+ // if the link is explicitly private (publicStats === false)+ // or if the link doesn't exist in database (data === undefined) and is not a dub.sh link+ // (we need to exclude dub.sh public demo links here)+ if (data?.publicStats === 0 || (domain !== "dub.sh" && !data)) {+ return new Response(`Stats for this link are not public`, {+ status: 403,+ });+ }+ // return 403 if interval is 90d or all+ if (interval === "all" || interval === "90d") {+ return new Response(`Require higher plan`, { status: 403 });+ }+ }++ const response = await getStats({+ domain,+ key,+ endpoint,+ interval,+ });++ return NextResponse.json(response);+};diff --git a/apps/web/app/api/stats/route.ts b/apps/web/app/api/stats/route.tsnew file mode 100644index 0000000000..3368550186--- /dev/null+++ b/apps/web/app/api/stats/route.ts@@ -0,0 +1,14 @@+import { getParams, withAuth } from "@/lib/auth-app";+import { getStats } from "@/lib/stats";+import { NextResponse } from "next/server";++export const GET = withAuth(async (req) => {+ const { domain, key, endpoint, interval } = getParams(req.url);+ const response = await getStats({+ domain,+ key,+ endpoint,+ interval,+ });+ return NextResponse.json(response);+});diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/page.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/page.tsxindex 718c89eb7f..3f12c5ac99 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/page.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/analytics/page.tsx@@ -1,7 +1,7 @@import { getProject } from "@/lib/fetchers";import LayoutLoader from "@/ui/layout/layout-loader";-import ProjectExceededUsage from "@/ui/layout/project-exceeded-usage";-import ProjectNotFound from "@/ui/layout/project-not-found";+import ProjectExceededUsage from "@/ui/projects/project-exceeded-usage";+import ProjectNotFound from "@/ui/projects/project-not-found";import Stats from "@/ui/stats";import { Suspense } from "react";diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/layout.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/layout.tsxindex b406d362d7..06cb09dfe1 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/layout.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/layout.tsx@@ -1,7 +1,7 @@import { ReactNode, Suspense } from "react";import { getProject } from "@/lib/fetchers";import LayoutLoader from "@/ui/layout/layout-loader";-import ProjectNotFound from "@/ui/layout/project-not-found";+import ProjectNotFound from "@/ui/projects/project-not-found";export default function ProjectLayout({params,diff --git a/apps/web/app/app.dub.co/(dashboard)/[slug]/page-client.tsx b/apps/web/app/app.dub.co/(dashboard)/[slug]/page-client.tsxindex eab3813803..6206933b75 100644--- a/apps/web/app/app.dub.co/(dashboard)/[slug]/page-client.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/[slug]/page-client.tsx@@ -2,11 +2,18 @@import LinksContainer from "@/ui/links/links-container";import { useAddEditLinkModal } from "@/ui/modals/add-edit-link-modal";-import { IconMenu, MaxWidthWrapper, Popover, Tooltip } from "@dub/ui";+import {+ IconMenu,+ MaxWidthWrapper,+ Popover,+ Tooltip,+ TooltipContent,+} from "@dub/ui";import useProject from "@/lib/swr/use-project";import { ChevronDown, FilePlus2, Sheet } from "lucide-react";import { useRouter } from "next/navigation";-import { useState } from "react";+import { useContext, useState } from "react";+import { ModalContext } from "@/ui/modals/provider";export default function ProjectLinksClient() {const { AddEditLinkModal, AddEditLinkButton } = useAddEditLinkModal();@@ -32,50 +39,107 @@ export default function ProjectLinksClient() {const AddLinkOptions = () => {const router = useRouter();- const { slug } = useProject();+ const { slug, exceededUsage } = useProject();const [openPopover, setOpenPopover] = useState(false);+ const { setShowUpgradePlanModal } = useContext(ModalContext);return (<Popovercontent={<div className="w-full divide-y divide-gray-200 md:w-52"><div className="p-2">- <button- onClick={() => {- setOpenPopover(false);- router.push(`/${slug}?import=bitly`);- }}- className="w-full rounded-md p-2 hover:bg-gray-100 active:bg-gray-200"- >- <IconMenu- text="Import from Bitly"- icon={- <img- src="/_static/icons/bitly.svg"- alt="Bitly logo"- className="h-4 w-4 rounded-full grayscale"+ {slug && exceededUsage ? (+ <Tooltip+ content={+ <TooltipContent+ title="Your project has exceeded its usage limit. We're still collecting data on your existing links, but you need to upgrade to edit them."+ cta="Upgrade to Pro"+ onClick={() => {+ setOpenPopover(false);+ setShowUpgradePlanModal(true);+ }}/>}- />- </button>- <button- onClick={() => {- setOpenPopover(false);- router.push(`/${slug}?import=short`);- }}- className="w-full rounded-md p-2 hover:bg-gray-100 active:bg-gray-200"- >- <IconMenu- text="Import from Short.io"- icon={- <img- src="/_static/icons/short.svg"- alt="Short.io logo"- className="h-4 w-4 grayscale"+ >+ <div className="flex w-full cursor-not-allowed items-center justify-between space-x-2 rounded-md p-2 text-sm text-gray-400">+ <IconMenu+ text="Import from Bitly"+ icon={+ <img+ src="/_static/icons/bitly.svg"+ alt="Bitly logo"+ className="h-4 w-4 rounded-full grayscale"+ />+ }+ />+ </div>+ </Tooltip>+ ) : (+ <button+ onClick={() => {+ setOpenPopover(false);+ router.push(`/${slug}?import=bitly`);+ }}+ className="w-full rounded-md p-2 hover:bg-gray-100 active:bg-gray-200"+ >+ <IconMenu+ text="Import from Bitly"+ icon={+ <img+ src="/_static/icons/bitly.svg"+ alt="Bitly logo"+ className="h-4 w-4 rounded-full grayscale"+ />+ }+ />+ </button>+ )}+ {slug && exceededUsage ? (+ <Tooltip+ content={+ <TooltipContent+ title="Your project has exceeded its usage limit. We're still collecting data on your existing links, but you need to upgrade to edit them."+ cta="Upgrade to Pro"+ onClick={() => {+ setOpenPopover(false);+ setShowUpgradePlanModal(true);+ }}/>}- />- </button>+ >+ <div className="flex w-full cursor-not-allowed items-center justify-between space-x-2 rounded-md p-2 text-sm text-gray-400">+ <IconMenu+ text="Import from Short.io"+ icon={+ <img+ src="/_static/icons/short.svg"+ alt="Short.io logo"+ className="h-4 w-4 grayscale"+ />+ }+ />+ </div>+ </Tooltip>+ ) : (+ <button+ onClick={() => {+ setOpenPopover(false);+ router.push(`/${slug}?import=short`);+ }}+ className="w-full rounded-md p-2 hover:bg-gray-100 active:bg-gray-200"+ >+ <IconMenu+ text="Import from Short.io"+ icon={+ <img+ src="/_static/icons/short.svg"+ alt="Short.io logo"+ className="h-4 w-4 grayscale"+ />+ }+ />+ </button>+ )}<Tooltip content="This feature is still in development – we'll let you know when it's ready!"><div className="flex w-full cursor-not-allowed items-center justify-between space-x-2 rounded-md p-2 text-sm text-gray-400"><IconMenudiff --git a/apps/web/app/app.dub.co/(dashboard)/analytics/page.tsx b/apps/web/app/app.dub.co/(dashboard)/analytics/page.tsxindex 43720bd046..030da40b56 100644--- a/apps/web/app/app.dub.co/(dashboard)/analytics/page.tsx+++ b/apps/web/app/app.dub.co/(dashboard)/analytics/page.tsx@@ -1,7 +1,7 @@-import { getAppSession } from "@/lib/auth";+import { getSession } from "@/lib/auth-app";import { getLink } from "@/lib/fetchers";import LayoutLoader from "@/ui/layout/layout-loader";-import ProjectNotFound from "@/ui/layout/project-not-found";+import LinkNotFound from "@/ui/links/link-not-found";import Stats from "@/ui/stats";import { Suspense } from "react";@@ -10,6 +10,7 @@ export default function LinkAnalytics({}: {searchParams: { [key: string]: string | undefined };}) {+ console.log({ searchParams });return (<Suspense fallback={<LayoutLoader />}><AnalyticsAuth searchParams={searchParams}>@@ -27,7 +28,7 @@ async function AnalyticsAuth({children: React.ReactNode;}) {const [session, link] = await Promise.all([- getAppSession(),+ getSession(),getLink({domain: searchParams.domain || "dub.sh",key: searchParams.key || "github",@@ -35,7 +36,7 @@ async function AnalyticsAuth({]);if (session?.user?.id !== link?.userId) {- return <ProjectNotFound />;+ return <LinkNotFound />;}return children as JSX.Element;diff --git a/apps/web/lib/auth-app.ts b/apps/web/lib/auth-app.tsnew file mode 100644index 0000000000..0811bb3a99--- /dev/null+++ b/apps/web/lib/auth-app.ts@@ -0,0 +1,158 @@+import { NextRequest } from "next/server";+import prisma from "@/lib/prisma";+import { authOptions } from "@/pages/api/auth/[...nextauth]";+import { PlanProps, ProjectProps } from "./types";+import { getServerSession } from "next-auth/next";++export interface Session {+ user: {+ email: string;+ id: string;+ name: string;+ image?: string;+ };+}++export async function getSession() {+ return getServerSession(authOptions) as Promise<Session>;+}++export function getParams(url: string) {+ // Create a params object+ let params = {} as any;++ new URL(url).searchParams.forEach(function (val, key) {+ params[key] = val;+ });++ return params;+}++interface WithAuthHandler {+ (req: NextRequest, session: Session, project?: ProjectProps): any;+}+const withAuth =+ (+ handler: WithAuthHandler,+ {+ excludeGet, // if the action doesn't need to be gated for GET requests+ requiredPlan = ["free", "pro", "enterprise"], // if the action needs a specific plan+ requiredRole = ["owner", "member"],+ needNotExceededUsage, // if the action needs the user to not have exceeded their usage+ }: {+ excludeGet?: boolean;+ requiredPlan?: Array<PlanProps>;+ requiredRole?: Array<"owner" | "member">;+ needNotExceededUsage?: boolean;+ } = {},+ ) =>+ async (req: NextRequest) => {+ const session = await getSession();+ if (!session?.user.id) {+ return new Response("Unauthorized: Login required.", { status: 401 });+ }++ const { slug } = getParams(req.url);++ // it's a project+ if (slug) {+ const project = (await prisma.project.findUnique({+ where: {+ slug,+ },+ select: {+ id: true,+ name: true,+ slug: true,+ logo: true,+ usage: true,+ usageLimit: true,+ plan: true,+ stripeId: true,+ billingCycleStart: true,+ createdAt: true,+ users: {+ where: {+ userId: session.user.id,+ },+ select: {+ role: true,+ },+ },+ },+ })) as ProjectProps;++ if (project && project.users) {+ // project exists but user is not part of it+ if (project.users.length === 0) {+ const pendingInvites = await prisma.projectInvite.findUnique({+ where: {+ email_projectId: {+ email: session.user.email,+ projectId: project.id,+ },+ },+ select: {+ expires: true,+ },+ });+ if (!pendingInvites) {+ return new Response("Project not found.", {+ status: 404,+ });+ } else if (pendingInvites.expires < new Date()) {+ return new Response("Project invite expired.", {+ status: 410,+ });+ } else {+ return new Response("Project invite pending.", {+ status: 409,+ });+ }+ }+ } else {+ // project doesn't exist+ return new Response("Project not found.", {+ status: 404,+ });+ }++ // if the action doesn't need to be gated for GET requests, return handler now+ if (req.method === "GET" && excludeGet) {+ return handler(req, session, project);+ }++ if (+ project.plan === "enterprise" &&+ !requiredRole.includes(project.users[0].role) &&+ // removing self from project should be allowed (DELETE /api/projects/[slug]/users?userId=...)+ !(+ req.url === `/api/projects/${slug}/users?userId=${session.user.id}` &&+ req.method === "DELETE"+ )+ ) {+ return new Response("Unauthorized: Insufficient permissions.", {+ status: 403,+ });+ }++ if (needNotExceededUsage && project.usage > project.usageLimit) {+ return new Response("Unauthorized: Usage limits exceeded.", {+ status: 403,+ });+ }++ if (!requiredPlan.includes(project.plan)) {+ // return res.status(403).end("Unauthorized: Need higher plan.");+ return new Response("Unauthorized: Need higher plan.", {+ status: 403,+ });+ }++ return handler(req, session, project);+ }++ return handler(req, session);+ };++export { withAuth };diff --git a/apps/web/lib/auth.ts b/apps/web/lib/auth.tsindex e1836e0758..05c16cca3a 100644--- a/apps/web/lib/auth.ts+++ b/apps/web/lib/auth.ts@@ -22,10 +22,6 @@ export async function getSession(req: NextApiRequest, res: NextApiResponse) {return (await getServerSession(req, res, authOptions)) as Session;}-export async function getAppSession() {- return getServerSession(authOptions) as Promise<Session>;-}-export const hashToken = (token: string,{diff --git a/apps/web/lib/fetchers.ts b/apps/web/lib/fetchers.tsindex d876f419f7..b947dad366 100644--- a/apps/web/lib/fetchers.ts+++ b/apps/web/lib/fetchers.ts@@ -1,9 +1,9 @@-import { getAppSession } from "./auth";+import { getSession } from "./auth-app";import prisma from "./prisma";import { ProjectWithDomainProps } from "./types";export async function getProjects() {- const session = await getAppSession();+ const session = await getSession();if (!session) {return null;}@@ -28,7 +28,7 @@ export async function getProjects() {}export async function getProject({ slug }: { slug: string }) {- const session = await getAppSession();+ const session = await getSession();if (!session) {return null;}diff --git a/apps/web/lib/middleware/api.ts b/apps/web/lib/middleware/api.tsindex 0490fd7170..5f00976642 100644--- a/apps/web/lib/middleware/api.ts+++ b/apps/web/lib/middleware/api.ts@@ -3,14 +3,14 @@ import { HOME_DOMAIN } from "@dub/utils";import { NextRequest, NextResponse } from "next/server";export default function ApiMiddleware(req: NextRequest) {- const { fullPath, domain } = parse(req);+ const { path, fullPath, domain } = parse(req);if (fullPath === "/" && domain === "api.dub.co") {return NextResponse.redirect(`${HOME_DOMAIN}/help/article/dub-api`, {status: 307,});// special case for metatags- } else if (fullPath.startsWith("/metatags")) {+ } else if (path === "/metatags") {const url = req.nextUrl.searchParams.get("url");if (!url) {return NextResponse.redirect(`${HOME_DOMAIN}/metatags`, {diff --git a/apps/web/lib/middleware/app.ts b/apps/web/lib/middleware/app.tsindex ca2a0625ea..3ac8dd6558 100644--- a/apps/web/lib/middleware/app.ts+++ b/apps/web/lib/middleware/app.ts@@ -5,7 +5,7 @@ import { conn } from "../planetscale";import { UserProps } from "../types";export default async function AppMiddleware(req: NextRequest) {- const { path } = parse(req);+ const { path, fullPath } = parse(req);const session = (await getToken({req,secret: process.env.NEXTAUTH_SECRET,@@ -22,7 +22,7 @@ export default async function AppMiddleware(req: NextRequest) {) {return NextResponse.redirect(new URL(- `/login${path !== "/" ? `?next=${encodeURIComponent(path)}` : ""}`,+ `/login${path === "/" ? "" : `?next=${encodeURIComponent(fullPath)}`}`,req.url,),);@@ -80,6 +80,6 @@ export default async function AppMiddleware(req: NextRequest) {// otherwise, rewrite the path to /appreturn NextResponse.rewrite(- new URL(`/app.dub.co${path === "/" ? "" : path}`, req.url),+ new URL(`/app.dub.co${fullPath === "/" ? "" : fullPath}`, req.url),);}diff --git a/apps/web/lib/stats.ts b/apps/web/lib/stats.tsindex 5dcec3d0a5..4d42dbee76 100644--- a/apps/web/lib/stats.ts+++ b/apps/web/lib/stats.ts@@ -5,27 +5,27 @@ export type IntervalProps = "1h" | "24h" | "7d" | "30d" | "90d" | "all";export const INTERVALS = [{display: "Last hour",- slug: "1h",+ value: "1h",},{display: "Last 24 hours",- slug: "24h",+ value: "24h",},{display: "Last 7 days",- slug: "7d",+ value: "7d",},{display: "Last 30 days",- slug: "30d",+ value: "30d",},{display: "Last 3 months",- slug: "90d",+ value: "90d",},{display: "All Time",- slug: "all",+ value: "all",},];diff --git a/apps/web/pages/api/edge/links/[key]/stats/[endpoint].ts b/apps/web/pages/api/edge/links/[key]/stats/[endpoint].tsdeleted file mode 100644index 4b660238f9..0000000000--- a/apps/web/pages/api/edge/links/[key]/stats/[endpoint].ts+++ /dev/null@@ -1,64 +0,0 @@-import { isBlacklistedReferrer } from "@/lib/edge-config";-import { getLinkViaEdge } from "@/lib/planetscale";-import { getStats } from "@/lib/stats";-import { ratelimit } from "@/lib/upstash";-import { LOCALHOST_IP } from "@dub/utils";-import { ipAddress } from "@vercel/edge";-import type { NextRequest } from "next/server";--export const config = {- runtime: "edge",-};--export default async function handler(req: NextRequest) {- if (req.method === "GET") {- const domain = req.nextUrl.searchParams.get("domain") || "dub.sh";- const key = req.nextUrl.pathname.split("/")[4];- const interval = req.nextUrl.searchParams.get("interval");- const endpoint = req.nextUrl.searchParams.get("endpoint") as string;-- // demo link (dub.sh/github)- if (domain === "dub.sh" && key === "github") {- // Rate limit in production- if (process.env.NODE_ENV !== "development") {- if (await isBlacklistedReferrer(req.headers.get("referer"))) {- return new Response("Don't DDoS me pls 🥺", { status: 429 });- }- const ip = ipAddress(req) || LOCALHOST_IP;- const { success } = await ratelimit(- 15,- endpoint !== "clicks" ? "1 h" : "10 s",- ).limit(`${ip}:${domain}:${key}:${endpoint}`);-- if (!success) {- return new Response("Don't DDoS me pls 🥺", { status: 429 });- }- }- } else {- const data = await getLinkViaEdge(domain, key);- // if the link is explicitly private (publicStats === false)- // or if the link doesn't exist in database (data === undefined) and is not a dub.sh link- // (we need to exclude dub.sh public demo links here)- if (data?.publicStats === 0 || (domain !== "dub.sh" && !data)) {- return new Response(`Stats for this link are not public`, {- status: 403,- });- }- // return 403 if interval is 90d or all- if (interval === "all" || interval === "90d") {- return new Response(`Require higher plan`, { status: 403 });- }- }-- const response = await getStats({- domain,- key,- endpoint,- interval,- });-- return new Response(JSON.stringify(response), { status: 200 });- } else {- return new Response(`Method ${req.method} Not Allowed`, { status: 405 });- }-}diff --git a/apps/web/pages/api/edge/links/index.ts b/apps/web/pages/api/edge/links/index.tsdeleted file mode 100644index f23fcba20d..0000000000--- a/apps/web/pages/api/edge/links/index.ts+++ /dev/null@@ -1,50 +0,0 @@-import { isBlacklistedDomain } from "@/lib/edge-config";-import { ratelimit, setRandomKey } from "@/lib/upstash";-import { LOCALHOST_IP, isValidUrl } from "@dub/utils";-import { ipAddress } from "@vercel/edge";-import { NextResponse, type NextRequest } from "next/server";--export const config = {- runtime: "edge",-};--export default async function handler(req: NextRequest) {- if (req.method === "POST") {- const { url } = (await req.json()) as { url?: string };- if (!url || !isValidUrl(url)) {- return new Response("Invalid URL", { status: 400 });- }-- const ip = ipAddress(req) || LOCALHOST_IP;- const { success } = await ratelimit(5, "1 m").limit(ip);- if (!success) {- return new Response("Don't DDoS me pls 🥺", { status: 429 });- }-- const domainBlacklisted = await isBlacklistedDomain(url);- if (domainBlacklisted) {- return new Response("Invalid URL", { status: 400 });- }-- const { response, key } = await setRandomKey(url);- if (response === "OK") {- // if key was successfully added- return NextResponse.json(- {- key,- url,- },- { status: 200 },- );- } else {- return NextResponse.json(- {- error: "Failed to create link",- },- { status: 500 },- );- }- } else {- return new Response(`Method ${req.method} Not Allowed`, { status: 405 });- }-}diff --git a/apps/web/ui/layout/nav-tabs.tsx b/apps/web/ui/layout/nav-tabs.tsxindex 1d78d004e5..52f97cb9a8 100644--- a/apps/web/ui/layout/nav-tabs.tsx+++ b/apps/web/ui/layout/nav-tabs.tsx@@ -17,15 +17,17 @@ export default function NavTabs() {const { loading, error } = useProject();const tabs = useMemo(() => {- if (slug) {+ if (pathname?.endsWith("/analytics")) {+ return [+ { name: "← Back to all links", href: slug ? `/${slug}` : "/links" },+ ];+ } else if (slug) {return [{ name: "Links", href: `/${slug}` },- { name: "Analytics", href: `/${slug}/analytics` },+ // { name: "Analytics", href: `/${slug}/analytics` },{ name: "Domains", href: `/${slug}/domains` },{ name: "Settings", href: `/${slug}/settings` },];- } else if (pathname === "/analytics") {- return [{ name: "← Back to all links", href: "/links" }];}// home page (e.g. app.dub.co, app.dub.co/settings)return [diff --git a/apps/web/ui/layout/project-select/index.tsx b/apps/web/ui/layout/project-select/index.tsxindex 8043a2e0dd..eb578f27d3 100644--- a/apps/web/ui/layout/project-select/index.tsx+++ b/apps/web/ui/layout/project-select/index.tsx@@ -1,11 +1,8 @@-import { getAppSession } from "@/lib/auth";+import { getSession } from "@/lib/auth-app";import { getProjects } from "@/lib/fetchers";import ProjectSelectClient from "./client";export default async function ProjectSelect() {- const [session, projects] = await Promise.all([- getAppSession(),- getProjects(),- ]);+ const [session, projects] = await Promise.all([getSession(), getProjects()]);return <ProjectSelectClient session={session} projects={projects || []} />;}diff --git a/apps/web/ui/links/link-card.tsx b/apps/web/ui/links/link-card.tsxindex d3a55381a0..d174282112 100644--- a/apps/web/ui/links/link-card.tsx+++ b/apps/web/ui/links/link-card.tsx@@ -91,6 +91,7 @@ export default function LinkCard({const { data: clicks } = useSWR<number>(isVisible &&+ !exceededUsage &&`/api/links/${encodeURIComponent(key)}/stats/clicks${slug ? `?slug=${slug}&domain=${domain}` : ""}`,diff --git a/apps/web/ui/links/link-not-found.tsx b/apps/web/ui/links/link-not-found.tsxnew file mode 100644index 0000000000..8792b62d57--- /dev/null+++ b/apps/web/ui/links/link-not-found.tsx@@ -0,0 +1,35 @@+import { BlurImage } from "@/ui/shared/blur-image";+import { MaxWidthWrapper } from "@dub/ui";+import { FileX2 } from "lucide-react";+import Link from "next/link";++export default function LinkNotFound() {+ return (+ <MaxWidthWrapper>+ <div className="my-10 flex flex-col items-center justify-center rounded-md border border-gray-200 bg-white py-12">+ <div className="rounded-full bg-gray-100 p-3">+ <FileX2 className="h-6 w-6 text-gray-600" />+ </div>+ <h1 className="my-3 text-xl font-semibold text-gray-700">+ Link Not Found+ </h1>+ <p className="z-10 max-w-sm text-center text-sm text-gray-600">+ Bummer! The link you are looking for does not exist. You either typed+ in the wrong URL or don't have access to this link.+ </p>+ <BlurImage+ src="/_static/illustrations/coffee-call.svg"+ alt="No links yet"+ width={400}+ height={400}+ />+ <Link+ href="/links"+ className="z-10 rounded-md border border-black bg-black px-10 py-2 text-sm font-medium text-white transition-all duration-75 hover:bg-white hover:text-black"+ >+ Back to my links+ </Link>+ </div>+ </MaxWidthWrapper>+ );+}diff --git a/apps/web/ui/links/links-container.tsx b/apps/web/ui/links/links-container.tsxindex dc1f9e00e1..81ac281169 100644--- a/apps/web/ui/links/links-container.tsx+++ b/apps/web/ui/links/links-container.tsx@@ -40,8 +40,8 @@ export default function LinksContainer({{links && !isValidating ? (links.length > 0 ? (links.map((props) => (- <Suspense fallback={<LinkCardPlaceholder />}>- <LinkCard key={props.id} props={props} />+ <Suspense key={props.id} fallback={<LinkCardPlaceholder />}>+ <LinkCard props={props} /></Suspense>))) : (diff --git a/apps/web/ui/layout/project-exceeded-usage.tsx b/apps/web/ui/projects/project-exceeded-usage.tsxsimilarity index 100%rename from apps/web/ui/layout/project-exceeded-usage.tsxrename to apps/web/ui/projects/project-exceeded-usage.tsxdiff --git a/apps/web/ui/layout/project-not-found.tsx b/apps/web/ui/projects/project-not-found.tsxsimilarity index 100%rename from apps/web/ui/layout/project-not-found.tsxrename to apps/web/ui/projects/project-not-found.tsxdiff --git a/apps/web/ui/stats/bar-chart.tsx b/apps/web/ui/stats/bar-chart.tsxindex d78b42f351..6775f1848c 100644--- a/apps/web/ui/stats/bar-chart.tsx+++ b/apps/web/ui/stats/bar-chart.tsx@@ -31,10 +31,10 @@ const rangeFormatter = (maxN: number): number => {};export default function BarChart() {- const { endpoint, queryString, interval } = useContext(StatsContext);+ const { baseApiPath, getQueryString, interval } = useContext(StatsContext);const { data } = useSWR<{ start: Date; clicks: number }[]>(- `${endpoint}/timeseries${queryString}`,+ `${baseApiPath}?${getQueryString({ endpoint: "timeseries" })}`,fetcher,);diff --git a/apps/web/ui/stats/clicks.tsx b/apps/web/ui/stats/clicks.tsxindex aac144dbb8..de669f3889 100644--- a/apps/web/ui/stats/clicks.tsx+++ b/apps/web/ui/stats/clicks.tsx@@ -1,18 +1,12 @@import { Chart } from "@/ui/shared/icons";import { NumberTooltip } from "@dub/ui";-import { fetcher, nFormatter } from "@dub/utils";+import { nFormatter } from "@dub/utils";import { useContext } from "react";-import useSWR from "swr";import { StatsContext } from ".";import BarChart from "./bar-chart";export default function Clicks() {- const { endpoint, queryString } = useContext(StatsContext);-- const { data: totalClicks } = useSWR<number>(- `${endpoint}/clicks${queryString}`,- fetcher,- );+ const { totalClicks } = useContext(StatsContext);return (<div className="max-w-4xl border border-gray-200 bg-white p-5 sm:rounded-lg sm:border-gray-100 sm:p-10 sm:pr-20 sm:shadow-lg ">diff --git a/apps/web/ui/stats/devices.tsx b/apps/web/ui/stats/devices.tsxindex 03f4bf25a2..7878b00de1 100644--- a/apps/web/ui/stats/devices.tsx+++ b/apps/web/ui/stats/devices.tsx@@ -11,18 +11,19 @@ import DeviceIcon from "./device-icon";export default function Devices() {const [tab, setTab] = useState<DeviceTabs>("device");- const { endpoint, queryString, modal } = useContext(StatsContext);+ const { baseApiPath, getQueryString, totalClicks, modal } =+ useContext(StatsContext);const { data } = useSWR<({[key in DeviceTabs]: string;} & { clicks: number })[]- >(`${endpoint}/${tab}${queryString}`, fetcher);-- const { data: totalClicks } = useSWR<number>(- `${endpoint}/clicks${queryString}`,+ >(+ // `${baseApiPath}?${new URLSearchParams(queryString).set("endpoint", tab)}`,+ `${baseApiPath}?${getQueryString({ endpoint: tab })}`,fetcher,);+const [showModal, setShowModal] = useState(false);const barList = (limit?: number) => (diff --git a/apps/web/ui/stats/index.tsx b/apps/web/ui/stats/index.tsxindex 0a72d585a8..020f11fd73 100644--- a/apps/web/ui/stats/index.tsx+++ b/apps/web/ui/stats/index.tsx@@ -22,23 +22,28 @@ import Locations from "./locations";import Referer from "./referer";import Toggle from "./toggle";import Feedback from "./feedback";+import useSWR from "swr";+import { fetcher } from "@dub/utils";export const StatsContext = createContext<{basePath: string;- endpoint: string;- queryString: string;- interval: string;+ baseApiPath: string;domain: string;key: string;+ getQueryString: (+ opts: { endpoint?: string; interval?: string },+ excludeSlug?: boolean,+ ) => string;+ interval: string;+ totalClicks?: number;modal?: boolean;}>({basePath: "",- endpoint: "",- queryString: "",- interval: "",+ baseApiPath: "",domain: "",key: "",- modal: false,+ getQueryString: () => "",+ interval: "",});export default function Stats({@@ -52,59 +57,70 @@ export default function Stats({const pathname = usePathname();const router = useRouter();- // Note: interestingly, useParams() returns `key` as encoded, unlike useRouter().query- // so we don't need to do encodeURIComponent() here- const { slug } = useParams() as {+ let { slug, key } = useParams() as {slug?: string;+ key?: string;};const domainSlug = searchParams?.get("domain");- const key = searchParams?.get("key");-+ key = searchParams?.get("key") || key;const interval = searchParams?.get("interval") || "24h";- const queryString = `?${new URLSearchParams({- ...(slug && { slug }),- ...(interval && { interval }),- domain: staticDomain || domainSlug || "dub.sh",- }).toString()}`;-- const { basePath, domain, endpoint } = useMemo(() => {+ const { basePath, domain, baseApiPath } = useMemo(() => {// Project link analytics page, e.g. app.dub.co/dub/analytics?domain=dub.sh&key=githubif (slug) {return {- basePath: `/${slug}/${domainSlug}/${key}`,+ basePath: `/${slug}/analytics`,+ baseApiPath: `/api/stats`,domain: domainSlug,- endpoint:- key === "_root"- ? `/api/projects/${slug}/domains/${domainSlug}/stats`- : `/api/links/${key}/stats`,};// Generic Dub.sh links analytics page, e.g. app.dub.co/analytics?domain=dub.sh&key=github} else if (pathname === "/analytics") {return {- basePath: `/links/${key}`,+ basePath: `/analytics`,+ baseApiPath: `/api/stats`,domain: "dub.sh",- endpoint: `/api/links/${key}/stats`,};}// Public stats page, e.g. dub.co/stats/github, stey.me/stats/weathergptreturn {basePath: `/stats/${key}`,+ baseApiPath: `/api/edge/stats`,domain: staticDomain,- endpoint: `/api/edge/links/${key}/stats`,};}, [slug, key, pathname]);+ const getQueryString = (+ opts: { endpoint?: string; interval?: string }, // query params to set+ excludeSlug?: boolean, // whether or not to exclude the slug param+ ) => {+ let params = new URLSearchParams({+ ...(slug && !excludeSlug && { slug }),+ domain: domain!,+ ...(key && { key }),+ ...(interval && { interval }),+ });+ for (const [key, value] of Object.entries(opts)) {+ params.set(key, value);+ }+ return params.toString();+ };++ const { data: totalClicks } = useSWR<number>(+ `${baseApiPath}?${getQueryString({ endpoint: "clicks" })}`,+ fetcher,+ );+return (<StatsContext.Providervalue={{basePath, // basePath for the page (e.g. /stats/[key], /links/[key], /[slug]/[domain]/[key])+ baseApiPath, // baseApiPath for the API (e.g. /api/edge/links/[key]/stats)+ getQueryString,domain: domain!, // domain for the link (e.g. dub.sh, stey.me, etc.)- endpoint, // endpoint for the API (e.g. /api/edge/links/[key]/stats)- queryString, // query string for the API (e.g. ?interval=24h&domain=dub.sh, ?interval=24h, etc.)- interval, // time interval (e.g. 24h, 7d, 30d, etc.)key: key ? decodeURIComponent(key) : "", // link key (e.g. github, weathergpt, etc.)+ interval, // time interval (e.g. 24h, 7d, 30d, etc.)+ totalClicks, // total clicks for the linkmodal, // whether or not this is a modal}}>diff --git a/apps/web/ui/stats/locations.tsx b/apps/web/ui/stats/locations.tsxindex a15dd2ee72..5bafb59661 100644--- a/apps/web/ui/stats/locations.tsx+++ b/apps/web/ui/stats/locations.tsx@@ -10,15 +10,11 @@ import BarList from "./bar-list";export default function Locations() {const [tab, setTab] = useState<LocationTabs>("country");- const { endpoint, queryString, modal } = useContext(StatsContext);+ const { baseApiPath, getQueryString, totalClicks, modal } =+ useContext(StatsContext);const { data } = useSWR<{ country: string; city: string; clicks: number }[]>(- `${endpoint}/${tab}${queryString}`,- fetcher,- );-- const { data: totalClicks } = useSWR<number>(- `${endpoint}/clicks${queryString}`,+ `${baseApiPath}?${getQueryString({ endpoint: tab })}`,fetcher,);diff --git a/apps/web/ui/stats/referer.tsx b/apps/web/ui/stats/referer.tsxindex 0a179e3317..df6c7fdbd6 100644--- a/apps/web/ui/stats/referer.tsx+++ b/apps/web/ui/stats/referer.tsx@@ -8,15 +8,15 @@ import { StatsContext } from ".";import BarList from "./bar-list";export default function Referer() {- const { endpoint, queryString, modal } = useContext(StatsContext);+ const { baseApiPath, getQueryString, totalClicks, modal } =+ useContext(StatsContext);const { data } = useSWR<{ referer: string; clicks: number }[]>(- `${endpoint}/referer${queryString}`,- fetcher,- );-- const { data: totalClicks } = useSWR<number>(- `${endpoint}/clicks${queryString}`,+ // `${baseApiPath}?${new URLSearchParams(queryString).set(+ // "endpoint",+ // "referer",+ // )}`,+ `${baseApiPath}?${getQueryString({ endpoint: "referer" })}`,fetcher,);diff --git a/apps/web/ui/stats/toggle.tsx b/apps/web/ui/stats/toggle.tsxindex 897fd27b3e..b27284ef7a 100644--- a/apps/web/ui/stats/toggle.tsx+++ b/apps/web/ui/stats/toggle.tsx@@ -17,27 +17,32 @@ import Link from "next/link";import { useParams } from "next/navigation";import punycode from "punycode/";import { useContext, useMemo, useState } from "react";-import { toast } from "sonner";-import useSWR, { mutate } from "swr";import { StatsContext } from ".";+import { ModalContext } from "../modals/provider";export default function Toggle() {- const { slug: projectSlug } = useParams() as { slug?: string };- const { basePath, domain, interval, key, modal } = useContext(StatsContext);+ const { slug } = useParams() as { slug?: string };+ const { setShowUpgradePlanModal, setShowAddProjectModal } =+ useContext(ModalContext);++ const { basePath, domain, key, getQueryString, interval, modal } =+ useContext(StatsContext);const [openDatePopover, setOpenDatePopover] = useState(false);const selectedInterval = useMemo(() => {- return INTERVALS.find((s) => s.slug === interval) || INTERVALS[1];+ return INTERVALS.find((s) => s.value === interval) || INTERVALS[1];}, [interval]);const scrolled = useScroll(80);const { plan } = useProject();+ const isPublicStatsPage = basePath.startsWith("/stats");+return (<div- className={cn("sticky top-[6.95rem] z-10 mb-5 bg-gray-50 py-3 md:py-5", {- "top-14": basePath.startsWith("/stats"),+ className={cn("sticky top-[6.9rem] z-10 mb-5 bg-gray-50 py-3 md:py-5", {+ "top-14": isPublicStatsPage,"top-6 md:top-0": modal,"shadow-md": scrolled && !modal,})}@@ -57,28 +62,39 @@ export default function Toggle() {<ExpandingArrow className="h-5 w-5" /></a><div className="flex items-center">- {!basePath.startsWith("/stats") && key !== "_root" && (+ {/* {!isPublicStatsPage && key !== "_root" && (<SharePopover />- )}+ )} */}<Popovercontent={<div className="grid w-full p-2 md:w-48">- {INTERVALS.map(({ display, slug }) =>- (slug === "all" || slug === "90d") &&+ {INTERVALS.map(({ display, value }) =>+ (value === "all" || value === "90d") &&(!plan || plan === "free") ? (<Tooltip- key={slug}+ key={value}content={<TooltipContenttitle={- projectSlug+ slug? `${display} stats can only be viewed on a Pro plan or higher. Upgrade now to view all-time stats.`: `${display} stats can only be viewed on a project with a Pro plan or higher. Create a project or navigate to an existing project to upgrade.`}- cta={- projectSlug ? "Upgrade to Pro" : "Create Project"- }- href={APP_DOMAIN}+ cta={slug ? "Upgrade to Pro" : "Create Project"}+ {...(isPublicStatsPage+ ? {+ href: APP_DOMAIN,+ }+ : {+ onClick: () => {+ setOpenDatePopover(false);+ if (slug) {+ setShowUpgradePlanModal(true);+ } else {+ setShowAddProjectModal(true);+ }+ },+ })}/>}>@@ -89,13 +105,17 @@ export default function Toggle() {</Tooltip>) : (<Link- key={slug}- href={`${basePath}?interval=${slug}`}+ key={value}+ href={`${basePath}?${+ isPublicStatsPage+ ? `interval=${value}`+ : getQueryString({ interval: value }, true)+ }`}replaceclassName="flex w-full items-center justify-between space-x-2 rounded-md p-2 hover:bg-gray-100 active:bg-gray-200"><p className="text-sm">{display}</p>- {selectedInterval.slug === slug && (+ {selectedInterval.value === value && (<Tick className="h-4 w-4" aria-hidden="true" />)}</Link>@@ -127,115 +147,115 @@ export default function Toggle() {);}-const SharePopover = () => {- const [openSharePopover, setopenSharePopoverPopover] = useState(false);+// const SharePopover = () => {+// const [openSharePopover, setopenSharePopoverPopover] = useState(false);- const { endpoint, domain, key, queryString } = useContext(StatsContext);+// const { endpoint, domain, key, queryString } = useContext(StatsContext);- const { data: { publicStats } = {} } = useSWR<{ publicStats: boolean }>(- `${endpoint}${queryString}`,- fetcher,- );+// const { data: { publicStats } = {} } = useSWR<{ publicStats: boolean }>(+// `${endpoint}${queryString}`,+// fetcher,+// );- const [updating, setUpdating] = useState(false);+// const [updating, setUpdating] = useState(false);- const handleChange = async () => {- toast.promise(- new Promise<void>(async (resolve) => {- setUpdating(true);- const res = await fetch(`${endpoint}${queryString}`, {- method: "PUT",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify({- publicStats: !publicStats,- }),- });- if (res.status === 200) {- await mutate(`${endpoint}${queryString}`);- !publicStats &&- navigator.clipboard.writeText(- `https://${domain}/stats/${encodeURIComponent(key)}`,- );- }- setUpdating(false);- resolve();- }),- {- loading: "Updating...",- success: `Stats page is now ${- publicStats ? "private." : "public. Link copied to clipboard."- }`,- error: "Something went wrong",- },- );- };- const [copied, setCopied] = useState(false);+// const handleChange = async () => {+// toast.promise(+// new Promise<void>(async (resolve) => {+// setUpdating(true);+// const res = await fetch(`${endpoint}${queryString}`, {+// method: "PUT",+// headers: {+// "Content-Type": "application/json",+// },+// body: JSON.stringify({+// publicStats: !publicStats,+// }),+// });+// if (res.status === 200) {+// await mutate(`${endpoint}${queryString}`);+// !publicStats &&+// navigator.clipboard.writeText(+// `https://${domain}/stats/${encodeURIComponent(key)}`,+// );+// }+// setUpdating(false);+// resolve();+// }),+// {+// loading: "Updating...",+// success: `Stats page is now ${+// publicStats ? "private." : "public. Link copied to clipboard."+// }`,+// error: "Something went wrong",+// },+// );+// };+// const [copied, setCopied] = useState(false);- return (- <Popover- content={- <div className="w-full divide-y divide-gray-200 text-sm md:w-60">- <div className="p-4">- <p className="text-gray-500">Share stats for</p>- <p className="truncate font-semibold text-gray-800">- {linkConstructor({ key, domain, pretty: true })}- </p>- </div>- <div className="p-4">- <div className="mb-2 flex items-center justify-between">- <p className="font-semibold text-gray-800">Public Stats Page</p>- <Switch- checked={publicStats}- fn={handleChange}- disabled={updating}- />- </div>- <p className="text-gray-500">- Making stats public will allow anyone with the link to see the- stats for this short link.- </p>- </div>- <div className="p-4">- <p className="font-semibold text-gray-800">Share Link</p>- <div className="divide-x-200 mt-2 flex items-center justify-between divide-x overflow-hidden rounded-md border border-gray-200 bg-gray-100">- <div className="scrollbar-hide overflow-scroll pl-2">- <p className="whitespace-nowrap text-gray-600">- https://{domain}/stats/{encodeURIComponent(key)}- </p>- </div>- <button- className="h-8 flex-none border-l bg-white px-2 hover:bg-gray-50 active:bg-gray-100"- onClick={() => {- navigator.clipboard.writeText(- `https://${domain}/stats/${encodeURIComponent(key)}`,- );- setCopied(true);- toast.success("Copied to clipboard");- setTimeout(() => setCopied(false), 3000);- }}- >- {copied ? (- <Tick className="h-4 w-4 text-gray-500" />- ) : (- <Copy className="h-4 w-4 text-gray-500" />- )}- </button>- </div>- </div>- </div>- }- align="end"- openPopover={openSharePopover}- setOpenPopover={setopenSharePopoverPopover}- >- <button- onClick={() => setopenSharePopoverPopover(!openSharePopover)}- className="mr-2 flex w-24 items-center justify-center space-x-2 rounded-md bg-white px-3 py-2.5 shadow transition-all duration-75 hover:shadow-md active:scale-95"- >- <IconMenu text="Share" icon={<Share2 className="h-4 w-4" />} />- </button>- </Popover>- );-};+// return (+// <Popover+// content={+// <div className="w-full divide-y divide-gray-200 text-sm md:w-60">+// <div className="p-4">+// <p className="text-gray-500">Share stats for</p>+// <p className="truncate font-semibold text-gray-800">+// {linkConstructor({ key, domain, pretty: true })}+// </p>+// </div>+// <div className="p-4">+// <div className="mb-2 flex items-center justify-between">+// <p className="font-semibold text-gray-800">Public Stats Page</p>+// <Switch+// checked={publicStats}+// fn={handleChange}+// disabled={updating}+// />+// </div>+// <p className="text-gray-500">+// Making stats public will allow anyone with the link to see the+// stats for this short link.+// </p>+// </div>+// <div className="p-4">+// <p className="font-semibold text-gray-800">Share Link</p>+// <div className="divide-x-200 mt-2 flex items-center justify-between divide-x overflow-hidden rounded-md border border-gray-200 bg-gray-100">+// <div className="scrollbar-hide overflow-scroll pl-2">+// <p className="whitespace-nowrap text-gray-600">+// https://{domain}/stats/{encodeURIComponent(key)}+// </p>+// </div>+// <button+// className="h-8 flex-none border-l bg-white px-2 hover:bg-gray-50 active:bg-gray-100"+// onClick={() => {+// navigator.clipboard.writeText(+// `https://${domain}/stats/${encodeURIComponent(key)}`,+// );+// setCopied(true);+// toast.success("Copied to clipboard");+// setTimeout(() => setCopied(false), 3000);+// }}+// >+// {copied ? (+// <Tick className="h-4 w-4 text-gray-500" />+// ) : (+// <Copy className="h-4 w-4 text-gray-500" />+// )}+// </button>+// </div>+// </div>+// </div>+// }+// align="end"+// openPopover={openSharePopover}+// setOpenPopover={setopenSharePopoverPopover}+// >+// <button+// onClick={() => setopenSharePopoverPopover(!openSharePopover)}+// className="mr-2 flex w-24 items-center justify-center space-x-2 rounded-md bg-white px-3 py-2.5 shadow transition-all duration-75 hover:shadow-md active:scale-95"+// >+// <IconMenu text="Share" icon={<Share2 className="h-4 w-4" />} />+// </button>+// </Popover>+// );+// };