The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Migrated sitemap and metatags API to App Router
Steven Tey8b1ecf23298a
diff --git a/app/(marketing)/@modal/(...)stats/[key]/modal.tsx b/app/(marketing)/@modal/(...)stats/[key]/modal.tsxindex 2b428435c5..8cce5c25ac 100644--- a/app/(marketing)/@modal/(...)stats/[key]/modal.tsx+++ b/app/(marketing)/@modal/(...)stats/[key]/modal.tsx@@ -5,8 +5,7 @@ import { useRouter } from "next/navigation";import { AnimatePresence, motion } from "framer-motion";export default function Modal({ children }) {- const backdrop = useRef<HTMLDivElement | null>(null);- const wrapper = useRef<HTMLDivElement | null>(null);+ const modalRef = useRef<HTMLDivElement | null>(null);const router = useRouter();const onKeyDown = useCallback((e: KeyboardEvent) => {@@ -24,23 +23,26 @@ export default function Modal({ children }) {<AnimatePresence><div className="absolute"><motion.div- ref={wrapper}+ ref={modalRef}key="desktop-modal"initial={{ scale: 0.95 }}animate={{ scale: 1 }}exit={{ scale: 0.95 }}className="fixed inset-0 z-40 hidden min-h-screen items-center justify-center sm:flex"+ onMouseDown={(e) => {+ if (modalRef.current === e.target) {+ router.back();+ }+ }}>{children}</motion.div><motion.div- ref={backdrop}key="modal-backdrop"initial={{ opacity: 0 }}animate={{ opacity: 1 }}exit={{ opacity: 0 }}className="fixed inset-0 z-30 bg-gray-100 bg-opacity-10 backdrop-blur"- onClick={() => router.back()}/></div></AnimatePresence>diff --git a/app/(marketing)/layout.tsx b/app/(marketing)/layout.tsxindex b188b476bd..020f137f02 100644--- a/app/(marketing)/layout.tsx+++ b/app/(marketing)/layout.tsx@@ -5,9 +5,10 @@ import Nav from "#/ui/home/nav";export default function MarketingLayout(props) {return (<div className="flex min-h-screen flex-col justify-between">+ {/* Only show stats modal if not on the /stats page */}+ {props.children.props.childProp.segment !== "stats" && props.modal}<Nav />{props.children}- {props.modal}<div className="z-10 flex h-20 items-center justify-center space-x-12 border-t border-gray-200"><a href="https://twitter.com/dubdotsh" target="_blank" rel="noreferrer"><span className="sr-only">Twitter</span>diff --git a/app/(marketing)/metatags/content.tsx b/app/(marketing)/metatags/content.tsxnew file mode 100644index 0000000000..48b884df15--- /dev/null+++ b/app/(marketing)/metatags/content.tsx@@ -0,0 +1,129 @@+"use client";++import { useMemo, useState } from "react";+import { useDebounce } from "use-debounce";+import useSWR from "swr";+import { Copy, Photo, Tick } from "@/components/shared/icons";+import { LoadingCircle } from "#/ui/icons";+import { fetcher, getDomainWithoutWWW, getUrlFromString } from "@/lib/utils";++export default function MetatagsContent() {+ const [url, setUrl] = useState("https://github.com/steven-tey/dub");+ const [debouncedUrl] = useDebounce(getUrlFromString(url), 500);+ const hostname = useMemo(() => {+ return getDomainWithoutWWW(debouncedUrl || "");+ }, [debouncedUrl]);++ const { data, isValidating } = useSWR<{+ title: string | null;+ description: string | null;+ image: string | null;+ }>(debouncedUrl && `/api/edge/metatags?url=${debouncedUrl}`, fetcher, {+ revalidateOnFocus: false,+ });++ const { title, description, image } = data || {};++ const [copied, setCopied] = useState(false);+ return (+ <>+ <div className="w-full rounded-md shadow-sm">+ <input+ name="url"+ id="url"+ type="url"+ className="block w-full rounded-md border-gray-300 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500"+ placeholder="Enter your URL"+ value={url}+ onChange={(e) => setUrl(e.target.value)}+ aria-invalid="true"+ />+ </div>++ <div className="relative overflow-hidden rounded-md border border-gray-300 bg-gray-50">+ {isValidating && (+ <div className="absolute flex h-[250px] w-full flex-col items-center justify-center space-y-4 border-b border-gray-300 bg-gray-50">+ <LoadingCircle />+ </div>+ )}+ {image ? (+ <img+ src={image}+ alt="Preview"+ className="h-[250px] w-full border-b border-gray-300 object-cover"+ />+ ) : (+ <div className="flex h-[250px] w-full flex-col items-center justify-center space-y-4 border-b border-gray-300">+ <Photo className="h-8 w-8 text-gray-400" />+ <p className="text-sm text-gray-400">+ Enter a link to generate a preview.+ </p>+ </div>+ )}+ <div className="grid gap-1 bg-white p-3 text-left">+ {hostname ? (+ <p className="text-sm text-[#536471]">{hostname}</p>+ ) : (+ <div className="mb-1 h-4 w-24 rounded-md bg-gray-100" />+ )}+ {title ? (+ <h3 className="truncate text-sm font-medium text-[#0f1419]">+ {title}+ </h3>+ ) : (+ <div className="mb-1 h-4 w-full rounded-md bg-gray-100" />+ )}+ {description ? (+ <p className="line-clamp-2 text-sm text-[#536471]">{description}</p>+ ) : (+ <div className="grid gap-2">+ <div className="h-4 w-full rounded-md bg-gray-100" />+ <div className="h-4 w-48 rounded-md bg-gray-100" />+ </div>+ )}+ </div>+ </div>++ <button+ className="hover:bg/black-[0.08] group relative flex cursor-copy items-center space-x-5 rounded-full bg-black/5 py-2.5 pl-5 pr-3 transition-all"+ onClick={() => {+ navigator.clipboard.writeText(+ `https://api.dub.sh/metatags?url=${getUrlFromString(url)}`,+ );+ setCopied(true);+ setTimeout(() => {+ setCopied(false);+ }, 2000);+ }}+ >+ <div className="w-11/12 overflow-scroll scrollbar-hide">+ <p className="whitespace-nowrap text-sm font-medium text-gray-600">+ https://api.dub.sh/metatags?url=+ <span className="text-amber-600">{getUrlFromString(url)}</span>+ </p>+ </div>+ <span className="absolute inset-y-0 right-1 top-1 flex h-8 w-8 items-center justify-center rounded-full bg-black/[0.07] transition-all group-hover:bg-black/10">+ {copied ? (+ <Tick className="h-4 w-4 text-gray-700" />+ ) : (+ <Copy className="h-4 w-4 text-gray-700" />+ )}+ </span>+ </button>++ <pre className="overflow-auto rounded-md border border-gray-400 bg-stone-800 p-5 text-left">+ <code className="text-xs text-white">+ {JSON.stringify(+ {+ title: title || null,+ description: description || null,+ image: image || null,+ },+ null,+ 2,+ )}+ </code>+ </pre>+ </>+ );+}diff --git a/app/(marketing)/metatags/launch.tsx b/app/(marketing)/metatags/launch.tsxnew file mode 100644index 0000000000..8da991f09c--- /dev/null+++ b/app/(marketing)/metatags/launch.tsx@@ -0,0 +1,11 @@+import Tweet from "@/components/shared/tweet";+import { getTweet } from "@/lib/twitter/get-tweet";++export default async function LaunchTweet() {+ const tweet = await getTweet("1595465648938930180");+ return (+ <div className="text-left">+ <Tweet key={tweet.id} metadata={JSON.stringify(tweet)} />+ </div>+ );+}diff --git a/app/(marketing)/metatags/page.tsx b/app/(marketing)/metatags/page.tsxnew file mode 100644index 0000000000..cef92e9a57--- /dev/null+++ b/app/(marketing)/metatags/page.tsx@@ -0,0 +1,60 @@+import { Github, Twitter } from "@/components/shared/icons";+import { Suspense } from "react";+import Background from "@/components/shared/background";+import LaunchTweet from "./launch";+import MetatagsContent from "./content";++export const metadata = {+ title: "Metatags API - The Free API to Get Meta Tags from a URL",+ description:+ "Dub's Metatags API is a free & simple API to retrieve meta & OG tags from a URL, powered by Vercel Edge Functions.",+};++export default function Metatags() {+ return (+ <>+ <div className="z-10 mx-2 my-10 flex max-w-md flex-col space-y-5 px-2.5 text-center sm:mx-auto sm:max-w-lg sm:px-0 lg:mb-28">+ <a+ href="https://twitter.com/dubdotsh/status/1595459224498233347"+ target="_blank"+ rel="noreferrer"+ className="mx-auto flex max-w-fit items-center justify-center space-x-2 overflow-hidden rounded-full bg-blue-100 px-7 py-2 transition-all hover:bg-blue-200"+ >+ <Twitter className="h-5 w-5 text-[#1d9bf0]" />+ <p className="text-sm font-semibold text-[#1d9bf0]">+ Watch it in action+ </p>+ </a>++ <h1 className="font-display text-5xl font-extrabold leading-[1.15] text-black sm:text-6xl sm:leading-[1.15]">+ <span className="bg-gradient-to-r from-amber-500 via-orange-600 to-yellow-500 bg-clip-text text-transparent">+ Metatags+ </span>{" "}+ API+ </h1>+ <h2 className="text-lg text-gray-600 sm:text-xl">+ A dead-simple API to retrieve the meta tags for a URL. Completely free+ and open-source.+ </h2>++ <MetatagsContent />++ <a+ href="https://dub.sh/metatags-code"+ target="_blank"+ rel="noreferrer"+ className="mx-auto mt-2 flex items-center justify-center space-x-2 text-sm text-gray-500 transition-all hover:text-black"+ >+ <Github className="h-4 w-4" />+ <p>View the source code</p>+ </a>++ <Suspense fallback="">+ {/* @ts-expect-error Async Server Component */}+ <LaunchTweet />+ </Suspense>+ </div>+ <Background />+ </>+ );+}diff --git a/app/sitemap.ts b/app/sitemap.tsnew file mode 100644index 0000000000..d2dd83e0c2--- /dev/null+++ b/app/sitemap.ts@@ -0,0 +1,53 @@+import { isHomeHostname } from "@/lib/utils";+import { headers } from "next/headers";+import prisma from "@/lib/prisma";+import { allChangelogPosts } from "contentlayer/generated";++export default async function Sitemap() {+ const headersList = headers();+ let domain = headersList.get("host") as string;+ if (isHomeHostname(domain)) domain = "dub.sh";++ // Get top 100 links (sorted by clicks in descending order)+ const links = await prisma.link.findMany({+ where: {+ domain: domain,+ publicStats: true,+ },+ select: {+ domain: true,+ key: true,+ },+ orderBy: {+ clicks: "desc",+ },+ take: 100,+ });++ return [+ {+ url: `https://${domain}`,+ lastModified: new Date(),+ },+ ...(domain === "dub.sh"+ ? [+ {+ url: `https://${domain}/changelog`,+ lastModified: new Date(),+ },+ ...allChangelogPosts.map((post) => ({+ url: `https://${domain}/changelog/${post.slug}`,+ lastModified: new Date(),+ })),+ {+ url: `https://${domain}/metatags`,+ lastModified: new Date(),+ },+ ]+ : []),+ ...links.map(({ key }) => ({+ url: `https://${domain}/stats/${key}`,+ lastModified: new Date(),+ })),+ ];+}diff --git a/app/ui/home/nav.tsx b/app/ui/home/nav.tsxindex 4c1a9ef20d..4d79fdcf38 100644--- a/app/ui/home/nav.tsx+++ b/app/ui/home/nav.tsx@@ -2,18 +2,22 @@import Link from "next/link";import Image from "next/image";-import { usePathname } from "next/navigation";+import { usePathname, useSelectedLayoutSegment } from "next/navigation";import useScroll from "#/lib/hooks/use-scroll";import clsx from "clsx";+const transparentHeaderSegments = new Set(["metatags"]);+export default function Nav() {- const pathname = usePathname();const scrolled = useScroll(80);+ const segment = useSelectedLayoutSegment();+return (<divclassName={clsx(`sticky inset-x-0 top-0 z-20 w-full transition-all`, {"border-b border-gray-200 bg-white/75 backdrop-blur-lg": scrolled,- "border-b border-gray-200": pathname !== "/",+ "border-b border-gray-200 bg-white":+ segment && !transparentHeaderSegments.has(segment),})}><div className="mx-auto w-full max-w-screen-xl px-5 md:px-20">@@ -29,9 +33,19 @@ export default function Nav() {</Link><div className="flex items-center space-x-6">+ <Link+ href="/metatags"+ className={`hidden rounded-md text-sm font-medium ${+ segment === "metatags" ? "text-black" : "text-gray-500"+ } transition-colors ease-out hover:text-black sm:block`}+ >+ Metatags API+ </Link><Linkhref="/changelog"- className="rounded-md text-sm font-medium text-gray-500 transition-colors ease-out hover:text-black"+ className={`rounded-md text-sm font-medium ${+ segment === "changelog" ? "text-black" : "text-gray-500"+ } transition-colors ease-out hover:text-black`}>Changelog</Link>diff --git a/pages/metatags.tsx b/pages/metatags.tsxdeleted file mode 100644index 07419ce10b..0000000000--- a/pages/metatags.tsx+++ /dev/null@@ -1,193 +0,0 @@-import HomeLayout from "@/components/layout/home";-import { Copy, Github, Photo, Tick, Twitter } from "@/components/shared/icons";-import { LoadingCircle } from "#/ui/icons";-import getTweetsMetadata from "@/lib/twitter";-import Tweet from "@/components/shared/tweet";-import { useMemo, useState } from "react";-import Background from "@/components/shared/background";-import { useDebounce } from "use-debounce";-import { fetcher, getDomainWithoutWWW, getUrlFromString } from "@/lib/utils";-import useSWR from "swr";--export default function Metatags({ tweets }: { tweets: any }) {- const [url, setUrl] = useState("https://github.com/steven-tey/dub");- const [debouncedUrl] = useDebounce(getUrlFromString(url), 500);- const hostname = useMemo(() => {- return getDomainWithoutWWW(debouncedUrl || "");- }, [debouncedUrl]);-- const { data, isValidating } = useSWR<{- title: string | null;- description: string | null;- image: string | null;- }>(debouncedUrl && `/api/edge/metatags?url=${debouncedUrl}`, fetcher, {- revalidateOnFocus: false,- });-- const { title, description, image } = data || {};-- const [copied, setCopied] = useState(false);-- return (- <HomeLayout- meta={{- title: "Metatags API - The Free API to Get Meta Tags from a URL",- description:- "Dub's Metatags API is a free & simple API to retrieve meta & OG tags from a URL, powered by Vercel Edge Functions.",- }}- >- <Background />- <div className="z-10 mx-2 my-10 flex max-w-md flex-col space-y-5 px-2.5 text-center sm:mx-auto sm:max-w-lg sm:px-0 lg:mb-28">- <a- href="https://twitter.com/dubdotsh/status/1595459224498233347"- target="_blank"- rel="noreferrer"- className="mx-auto flex max-w-fit items-center justify-center space-x-2 overflow-hidden rounded-full bg-blue-100 px-7 py-2 transition-all hover:bg-blue-200"- >- <Twitter className="h-5 w-5 text-[#1d9bf0]" />- <p className="text-sm font-semibold text-[#1d9bf0]">- Watch it in action- </p>- </a>-- <h1 className="font-display text-5xl font-extrabold leading-[1.15] text-black sm:text-6xl sm:leading-[1.15]">- <span className="bg-gradient-to-r from-amber-500 via-orange-600 to-yellow-500 bg-clip-text text-transparent">- Metatags- </span>{" "}- API- </h1>- <h2 className="text-lg text-gray-600 sm:text-xl">- A dead-simple API to retrieve the meta tags for a URL. Completely free- and open-source.- </h2>-- <div className="w-full rounded-md shadow-sm">- <input- name="url"- id="url"- type="url"- className="block w-full rounded-md border-gray-300 text-sm text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:outline-none focus:ring-gray-500"- placeholder="Enter your URL"- value={url}- onChange={(e) => setUrl(e.target.value)}- aria-invalid="true"- />- </div>-- <div className="relative overflow-hidden rounded-md border border-gray-300 bg-gray-50">- {isValidating && (- <div className="absolute flex h-[250px] w-full flex-col items-center justify-center space-y-4 border-b border-gray-300 bg-gray-50">- <LoadingCircle />- </div>- )}- {image ? (- <img- src={image}- alt="Preview"- className="h-[250px] w-full border-b border-gray-300 object-cover"- />- ) : (- <div className="flex h-[250px] w-full flex-col items-center justify-center space-y-4 border-b border-gray-300">- <Photo className="h-8 w-8 text-gray-400" />- <p className="text-sm text-gray-400">- Enter a link to generate a preview.- </p>- </div>- )}- <div className="grid gap-1 bg-white p-3 text-left">- {hostname ? (- <p className="text-sm text-[#536471]">{hostname}</p>- ) : (- <div className="mb-1 h-4 w-24 rounded-md bg-gray-100" />- )}- {title ? (- <h3 className="truncate text-sm font-medium text-[#0f1419]">- {title}- </h3>- ) : (- <div className="mb-1 h-4 w-full rounded-md bg-gray-100" />- )}- {description ? (- <p className="line-clamp-2 text-sm text-[#536471]">- {description}- </p>- ) : (- <div className="grid gap-2">- <div className="h-4 w-full rounded-md bg-gray-100" />- <div className="h-4 w-48 rounded-md bg-gray-100" />- </div>- )}- </div>- </div>-- <button- className="hover:bg/black-[0.08] group relative flex cursor-copy items-center space-x-5 rounded-full bg-black/5 py-2.5 pl-5 pr-3 transition-all"- onClick={() => {- navigator.clipboard.writeText(- `https://api.dub.sh/metatags?url=${getUrlFromString(url)}`,- );- setCopied(true);- setTimeout(() => {- setCopied(false);- }, 2000);- }}- >- <div className="w-11/12 overflow-scroll scrollbar-hide">- <p className="whitespace-nowrap text-sm font-medium text-gray-600">- https://api.dub.sh/metatags?url=- <span className="text-amber-600">{getUrlFromString(url)}</span>- </p>- </div>- <span className="absolute inset-y-0 right-1 top-1 flex h-8 w-8 items-center justify-center rounded-full bg-black/[0.07] transition-all group-hover:bg-black/10">- {copied ? (- <Tick className="h-4 w-4 text-gray-700" />- ) : (- <Copy className="h-4 w-4 text-gray-700" />- )}- </span>- </button>-- <pre className="overflow-auto rounded-md border border-gray-400 bg-stone-800 p-5 text-left">- <code className="text-xs text-white">- {JSON.stringify(- {- title: title || null,- description: description || null,- image: image || null,- },- null,- 2,- )}- </code>- </pre>-- <a- href="https://dub.sh/metatags-code"- target="_blank"- rel="noreferrer"- className="mx-auto mt-2 flex items-center justify-center space-x-2 text-sm text-gray-500 transition-all hover:text-black"- >- <Github className="h-4 w-4" />- <p>View the source code</p>- </a>-- <div className="text-left">- {tweets.filter(Boolean).map((tweet) => (- <Tweet key={tweet.id} metadata={JSON.stringify(tweet)} />- ))}- </div>- </div>- </HomeLayout>- );-}--export async function getStaticProps() {- const tweets = await getTweetsMetadata(["1595465648938930180"]);-- return {- props: {- tweets,- },- revalidate: 10,- };-}diff --git a/pages/old-index.tsx b/pages/old-index.tsxdeleted file mode 100644index d1a3920914..0000000000--- a/pages/old-index.tsx+++ /dev/null@@ -1,93 +0,0 @@-import { useRouter } from "next/router";-import { useCallback, useEffect } from "react";-import prisma from "@/lib/prisma";-import { useStatsModal } from "@/components/app/modals/stats-modal";-import Background from "@/components/shared/background";-import Demo from "#/ui/home/demo";-import Features from "#/ui/home/features";-import Globe from "#/ui/home/globe";-import Hero from "#/ui/home/hero";-import Logos from "#/ui/home/logos";-import Pricing from "#/ui/home/pricing";-import HomeLayout from "@/components/layout/home";-import OSS from "#/ui/home/oss";-import Testimonials from "#/ui/home/testimonials";-import getTweetsMetadata, { homepageTweets } from "@/lib/twitter";--export default function Home({- userCount,- stars,- tweets,-}: {- userCount: number;- stars: number;- tweets: any;-}) {- const router = useRouter();- const { key: stats } = router.query;- const { setShowStatsModal, StatsModal } = useStatsModal();-- const onKeyDown = useCallback((e: KeyboardEvent) => {- if (e.key === "Escape") {- router.push("/", undefined, { scroll: false });- }- }, []);-- useEffect(() => {- if (stats) {- setShowStatsModal(true);- } else {- setShowStatsModal(false);- }- }, [stats]);-- useEffect(() => {- document.addEventListener("keydown", onKeyDown);- return () => document.removeEventListener("keydown", onKeyDown);- }, [onKeyDown]);-- return (- <HomeLayout>- <StatsModal />- <div className="z-10">- <Hero />- <Demo />- <Logos />- <Globe />- <Features />- <Testimonials userCount={userCount} tweets={tweets} />- <Pricing homePage />- <OSS stars={stars} />- </div>- <Background />- </HomeLayout>- );-}--export async function getStaticProps() {- const userCount = process.env.DATABASE_URL ? await prisma.user.count() : 5000;-- const { stargazers_count: stars } = await fetch(- "https://api.github.com/repos/steven-tey/dub",- {- // optional – feel free to remove if you don't want to display star count- ...(process.env.GITHUB_OAUTH_TOKEN && {- headers: {- Authorization: `Bearer ${process.env.GITHUB_OAUTH_TOKEN}`,- "Content-Type": "application/json",- },- }),- },- ).then((res) => res.json());-- const tweets = await getTweetsMetadata(homepageTweets);-- return {- props: {- userCount,- stars: stars || 6100,- tweets,- },- revalidate: 60,- };-}diff --git a/pages/sitemap.xml.tsx b/pages/sitemap.xml.tsxdeleted file mode 100644index ef8908d496..0000000000--- a/pages/sitemap.xml.tsx+++ /dev/null@@ -1,84 +0,0 @@-import prisma from "@/lib/prisma";-import { isHomeHostname } from "@/lib/utils";-import { NextApiRequest, NextApiResponse } from "next";--function generateSiteMap({- hostname,- links,-}: {- hostname: string;- links: { key: string }[];-}) {- return `<?xml version="1.0" encoding="UTF-8"?>- <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">- <url>- <loc>${hostname}</loc>- </url>- ${- hostname === "https://dub.sh"- ? `<url>- <loc>${hostname}/metatags</loc>- </url>- `- : ""- }- ${links- .map(({ key }) => {- return `- <url>- <loc>${`${hostname}/stats/${key}`}</loc>- </url>- `;- })- .join("")}- </urlset>- `;-}--function SiteMap() {- // getServerSideProps will do the heavy lifting-}--export async function getServerSideProps({- req,- res,-}: {- req: NextApiRequest;- res: NextApiResponse;-}) {- let domain = req.headers.host as string;- if (isHomeHostname(domain)) domain = "dub.sh";-- // Get top 100 links (sorted by clicks in descending order)- const links = await prisma.link.findMany({- where: {- domain: domain,- publicStats: true,- },- select: {- domain: true,- key: true,- },- orderBy: {- clicks: "desc",- },- take: 100,- });-- // We generate the XML sitemap with the posts data- const sitemap = generateSiteMap({- hostname: `https://${domain}`,- links,- });-- res.setHeader("Content-Type", "text/xml");- // we send the XML to the browser- res.write(sitemap);- res.end();-- return {- props: {},- };-}--export default SiteMap;diff --git a/static/media/background.681e0321.png b/static/media/background.681e0321.pngnew file mode 100644index 0000000000..8a58dc2686Binary files /dev/null and b/static/media/background.681e0321.png differdiff --git a/static/media/logo.99d7a2d3.png b/static/media/logo.99d7a2d3.pngnew file mode 100644index 0000000000..1653c4e3cdBinary files /dev/null and b/static/media/logo.99d7a2d3.png differ