The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Added link builder demo to homepage, added logging for metatags endpoint
Steven Teya705bab7fb09
diff --git a/components/app/links/link-card.tsx b/components/app/links/link-card.tsxindex b299213ef3..569a267f48 100644--- a/components/app/links/link-card.tsx+++ b/components/app/links/link-card.tsx@@ -14,7 +14,6 @@ import {Chart,Delete,Edit,- Eye,LoadingDots,QR,ThreeDots,@@ -34,7 +33,7 @@ import {import useIntersectionObserver from "@/lib/hooks/use-intersection-observer";export default function LinkCard({ props }: { props: LinkProps }) {- const { key, url, proxy, createdAt, archived, expiresAt } = props;+ const { key, url, createdAt, archived, expiresAt } = props;const apexDomain = getApexDomain(url);diff --git a/components/app/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsxindex 8a678cff82..7c19d4eb19 100644--- a/components/app/modals/add-edit-link-modal/index.tsx+++ b/components/app/modals/add-edit-link-modal/index.tsx@@ -36,17 +36,20 @@ import UTMSection from "./utm-section";import IOSSection from "./ios-section";import Preview from "./preview";import AndroidSection from "./android-section";+import { DEFAULT_LINK_PROPS } from "@/lib/constants";function AddEditLinkModal({showAddEditLinkModal,setShowAddEditLinkModal,props,hideXButton,+ homepageDemo,}: {showAddEditLinkModal: boolean;setShowAddEditLinkModal: Dispatch<SetStateAction<boolean>>;props?: LinkProps;hideXButton?: boolean;+ homepageDemo?: boolean;}) {const router = useRouter();const { slug } = router.query as { slug: string };@@ -59,24 +62,10 @@ function AddEditLinkModal({const [data, setData] = useState<LinkProps>(props || {+ ...DEFAULT_LINK_PROPS,domain: domain || "",key: "",url: "",- archived: false,- expiresAt: null,- password: null,-- title: null,- description: null,- image: null,- ios: null,- android: null,-- clicks: 0,- userId: "",- createdAt: new Date(),-- proxy: false,},);const { key, url, password, proxy } = data;@@ -225,9 +214,8 @@ function AddEditLinkModal({- url is invalid- for an existing link, there's no changes*/- if (!showAddEditLinkModal) {- return true;- } else if (+ if (+ !showAddEditLinkModal ||saving ||keyExistsError ||urlError ||@@ -246,10 +234,10 @@ function AddEditLinkModal({<ModalshowModal={showAddEditLinkModal}setShowModal={setShowAddEditLinkModal}- closeWithX={true}+ closeWithX={homepageDemo ? false : true}><div className="grid max-h-[min(906px,_90vh)] w-full divide-x divide-gray-100 overflow-scroll bg-white shadow-xl transition-all scrollbar-hide sm:max-w-screen-lg sm:grid-cols-2 sm:rounded-2xl sm:border sm:border-gray-200">- {!hideXButton && (+ {!hideXButton && !homepageDemo && (<buttononClick={() => setShowAddEditLinkModal(false)}className="group absolute top-0 right-0 m-3 hidden rounded-full p-2 text-gray-500 transition-all duration-75 hover:bg-gray-100 focus:outline-none active:bg-gray-200 sm:block"@@ -458,22 +446,36 @@ function AddEditLinkModal({atBottom ? "" : "sm:shadow-[0_-20px_30px_-10px_rgba(0,0,0,0.1)]"} z-10 bg-gray-50 px-4 py-8 transition-all sm:sticky sm:bottom-0 sm:px-16`}>- <button- disabled={saveDisabled}- className={`${- saveDisabled- ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"- : "border-black bg-black text-white hover:bg-white hover:text-black"- } flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none`}- >- {saving ? (- <LoadingDots color="#808080" />- ) : (- <p className="text-sm">- {props ? "Save changes" : "Add link"}- </p>- )}- </button>+ {homepageDemo ? (+ <Tooltip+ content="This is a demo link. You can't edit it."+ fullWidth+ >+ <button+ disabled={true}+ className=" flex h-10 w-full cursor-not-allowed items-center justify-center rounded-md border border-gray-200 bg-gray-100 text-sm text-gray-400 transition-all focus:outline-none"+ >+ <p className="text-sm">Save changes</p>+ </button>+ </Tooltip>+ ) : (+ <button+ disabled={saveDisabled}+ className={`${+ saveDisabled+ ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"+ : "border-black bg-black text-white hover:bg-white hover:text-black"+ } flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none`}+ >+ {saving ? (+ <LoadingDots color="#808080" />+ ) : (+ <p className="text-sm">+ {props ? "Save changes" : "Add link"}+ </p>+ )}+ </button>+ )}</div></form></div>@@ -527,9 +529,11 @@ function AddEditLinkButton({export function useAddEditLinkModal({props,hideXButton,+ homepageDemo,}: {props?: LinkProps;hideXButton?: boolean;+ homepageDemo?: boolean;}) {const [showAddEditLinkModal, setShowAddEditLinkModal] = useState(false);@@ -540,9 +544,16 @@ export function useAddEditLinkModal({setShowAddEditLinkModal={setShowAddEditLinkModal}props={props}hideXButton={hideXButton}+ homepageDemo={homepageDemo}/>);- }, [showAddEditLinkModal, setShowAddEditLinkModal, props, hideXButton]);+ }, [+ showAddEditLinkModal,+ setShowAddEditLinkModal,+ props,+ hideXButton,+ homepageDemo,+ ]);const AddEditLinkButtonCallback = useCallback(() => {return (@@ -552,11 +563,13 @@ export function useAddEditLinkModal({return useMemo(() => ({+ showAddEditLinkModal,setShowAddEditLinkModal,AddEditLinkModal: AddEditLinkModalCallback,AddEditLinkButton: AddEditLinkButtonCallback,}),[+ showAddEditLinkModal,setShowAddEditLinkModal,AddEditLinkModalCallback,AddEditLinkButtonCallback,diff --git a/components/app/modals/link-qr-modal.tsx b/components/app/modals/link-qr-modal.tsxindex 4037674172..ba33953102 100644--- a/components/app/modals/link-qr-modal.tsx+++ b/components/app/modals/link-qr-modal.tsx@@ -354,7 +354,7 @@ export function useLinkQRModal({ props }: { props: SimpleLinkProps }) {}, [showLinkQRModal, setShowLinkQRModal, props]);return useMemo(- () => ({ setShowLinkQRModal, LinkQRModal }),- [setShowLinkQRModal, LinkQRModal],+ () => ({ showLinkQRModal, setShowLinkQRModal, LinkQRModal }),+ [showLinkQRModal, setShowLinkQRModal, LinkQRModal],);}diff --git a/components/home/demo.tsx b/components/home/demo.tsxindex 11de540c71..4e248d31dd 100644--- a/components/home/demo.tsx+++ b/components/home/demo.tsx@@ -48,7 +48,7 @@ const Demo = () => {/>}>- <div className="relative flex items-center">+ <div className="relative flex w-full items-center"><div className="block w-full rounded-md border border-gray-200 bg-white p-2 pl-3 pr-12 text-sm text-gray-400 shadow-lg focus:border-black">Shorten your link</div>diff --git a/components/home/features.tsx b/components/home/features.tsxindex bb87600297..e70aaabda6 100644--- a/components/home/features.tsx+++ b/components/home/features.tsx@@ -12,6 +12,8 @@ import { useState } from "react";import Accordion from "@/components/shared/accordion";import { AnimatePresence, motion } from "framer-motion";import { useLinkQRModal } from "../app/modals/link-qr-modal";+import { DEFAULT_LINK_PROPS } from "@/lib/constants";+import { useAddEditLinkModal } from "../app/modals/add-edit-link-modal";const featureList = [{@@ -52,42 +54,24 @@ const featureList = [),demo: "https://d2vwwcvoksz7ty.cloudfront.net/custom-domain.mp4",},+ {+ key: "link",+ title: "Powerful link builder",+ icon: <LinkIcon className="h-5 w-5 text-gray-600" />,+ description:+ "Build your links with UTM parameters, password protection, expiration dates, iOS/Android targeting, etc.",+ cta: "View demo", //custom cta+ demo: "https://d2vwwcvoksz7ty.cloudfront.net/link.mp4",+ },{key: "social",title: "Custom social media cards",icon: <Photo className="h-5 w-5 text-gray-600" />,description:"Overlay custom OG images on your links to make them stand out on social media.",- cta: (- <a- href="https://app.dub.sh"- target="_blank"- rel="noreferrer"- className="block max-w-fit rounded-full border border-black bg-black px-4 py-1.5 text-sm text-white transition-all hover:bg-white hover:text-black"- >- Customize your links- </a>- ),+ cta: "View demo", //custom ctademo: "https://d2vwwcvoksz7ty.cloudfront.net/og.mp4",},- {- key: "builder",- title: "Powerful link builder",- icon: <LinkIcon className="h-5 w-5 text-gray-600" />,- description:- "Build your links with UTM parameters, password protection, expiration dates, iOS/Android targeting, etc.",- cta: (- <a- href="https://app.dub.sh"- target="_blank"- rel="noreferrer"- className="block max-w-fit rounded-full border border-black bg-black px-4 py-1.5 text-sm text-white transition-all hover:bg-white hover:text-black"- >- Build your link- </a>- ),- demo: "https://d2vwwcvoksz7ty.cloudfront.net/link.mp4",- },{key: "qr",title: "Free QR code generator",@@ -119,6 +103,11 @@ const featureList = [export default function Features() {const [activeFeature, setActiveFeature] = useState(0);++ const { setShowAddEditLinkModal, AddEditLinkModal } = useAddEditLinkModal({+ props: DEFAULT_LINK_PROPS,+ homepageDemo: true,+ });const { setShowLinkQRModal, LinkQRModal } = useLinkQRModal({props: {key: "github",@@ -127,6 +116,7 @@ export default function Features() {});return (<div id="features">+ <AddEditLinkModal /><LinkQRModal />{featureList.map(({ key, demo }) => (// preload videos@@ -168,7 +158,14 @@ export default function Features() {<p className="mb-4 text-sm text-gray-500">{description}</p>- {key === "qr" ? (+ {key === "link" || key === "social" ? (+ <button+ onClick={() => setShowAddEditLinkModal(true)}+ className="block max-w-fit rounded-full border border-black bg-black px-4 py-1.5 text-sm text-white transition-all hover:bg-white hover:text-black"+ >+ View demo+ </button>+ ) : key === "qr" ? (<buttononClick={() => setShowLinkQRModal(true)}className="block max-w-fit rounded-full border border-black bg-black px-4 py-1.5 text-sm text-white transition-all hover:bg-white hover:text-black"diff --git a/components/home/link-card.tsx b/components/home/link-card.tsxindex dc89e7924c..b872924253 100644--- a/components/home/link-card.tsx+++ b/components/home/link-card.tsx@@ -6,8 +6,11 @@ import useSWR from "swr";import { useLinkQRModal } from "@/components/app/modals/link-qr-modal";import BlurImage from "@/components/shared/blur-image";import CopyButton from "@/components/shared/copy-button";-import { Chart, LoadingDots, QR } from "@/components/shared/icons";-import { FRAMER_MOTION_LIST_ITEM_VARIANTS } from "@/lib/constants";+import { Chart, LoadingDots, QR, ThreeDots } from "@/components/shared/icons";+import {+ DEFAULT_LINK_PROPS,+ FRAMER_MOTION_LIST_ITEM_VARIANTS,+} from "@/lib/constants";import { SimpleLinkProps } from "@/lib/types";import {fetcher,@@ -15,6 +18,7 @@ import {linkConstructor,nFormatter,} from "@/lib/utils";+import { useAddEditLinkModal } from "@/components/app/modals/add-edit-link-modal";export default function LinkCard({_key: key,@@ -31,11 +35,6 @@ export default function LinkCard({}) {const apexDomain = getApexDomain(url);- const { data: clicks, isValidating } = useSWR<number>(- `/api/edge/links/${key}/clicks`,- fetcher,- );-const cardElem = useRef(null);const x = useMotionValue(0);@@ -98,16 +97,36 @@ export default function LinkCard({return () => unsubscribeX();});- const { setShowLinkQRModal, LinkQRModal } = useLinkQRModal({+ const { showLinkQRModal, setShowLinkQRModal, LinkQRModal } = useLinkQRModal({props: {key,url,},});+ const { showAddEditLinkModal, setShowAddEditLinkModal, AddEditLinkModal } =+ useAddEditLinkModal({+ props: {+ ...DEFAULT_LINK_PROPS,+ key,+ url,+ },+ homepageDemo: true,+ });++ const { data: clicks, isValidating } = useSWR<number>(+ `/api/edge/links/${key}/clicks`,+ fetcher,+ {+ // avoid revalidation on focus when modals are open to prevent rerendering+ revalidateOnFocus: !showLinkQRModal && !showAddEditLinkModal,+ },+ );+return (<motion.li variants={FRAMER_MOTION_LIST_ITEM_VARIANTS}><LinkQRModal />+ <AddEditLinkModal /><motion.divanimate={controls}drag="x"@@ -118,53 +137,62 @@ export default function LinkCard({onDrag={() => setVelocity(x.getVelocity())}onDragEnd={() => flyAway(500)}whileTap={{ scale: 1.05 }}- className="flex max-w-md cursor-grab items-center space-x-3 rounded-md border border-gray-200 bg-white p-3 shadow-lg transition-[border-color] hover:border-black active:cursor-grabbing"+ className="flex max-w-md cursor-grab items-center justify-between rounded-md border border-gray-200 bg-white p-3 shadow-lg transition-[border-color] hover:border-black active:cursor-grabbing">- <BlurImage- src={`https://www.google.com/s2/favicons?sz=64&domain_url=${apexDomain}`}- alt={apexDomain}- className="pointer-events-none h-10 w-10 rounded-full"- width={20}- height={20}- />- <div>- <div className="mb-1 flex items-center space-x-2">- <a- className="font-semibold text-blue-800"- href={linkConstructor({ key })}- target="_blank"- rel="noreferrer"- >- {linkConstructor({ key, pretty: true })}- </a>- <CopyButton url={linkConstructor({ key })} />- <button- onClick={() => setShowLinkQRModal(true)}- className="group rounded-full bg-gray-100 p-1.5 transition-all duration-75 hover:scale-105 hover:bg-blue-100 active:scale-95"- >- <span className="sr-only">Copy</span>- <QR className="text-gray-700 transition-all group-hover:text-blue-800" />- </button>- <Link- href={{ pathname: "/", query: { key } }}- as={`/stats/${encodeURI(key)}`}- shallow- scroll={false}- className="flex items-center space-x-1 rounded-md bg-gray-100 px-2 py-0.5 text-gray-700 transition-all duration-75 hover:scale-105 active:scale-95"- >- <Chart className="h-4 w-4" />- <p className="text-sm">- {isValidating ? (- <LoadingDots color="#71717A" />- ) : (- nFormatter(clicks)- )}- <span className="ml-1 hidden sm:inline-block">clicks</span>- </p>- </Link>+ <div className="flex items-center space-x-3">+ <BlurImage+ src={`https://www.google.com/s2/favicons?sz=64&domain_url=${apexDomain}`}+ alt={apexDomain}+ className="pointer-events-none h-10 w-10 rounded-full"+ width={20}+ height={20}+ />+ <div>+ <div className="mb-1 flex items-center space-x-2">+ <a+ className="font-semibold text-blue-800"+ href={linkConstructor({ key })}+ target="_blank"+ rel="noreferrer"+ >+ {linkConstructor({ key, pretty: true })}+ </a>+ <CopyButton url={linkConstructor({ key })} />+ <button+ onClick={() => setShowLinkQRModal(true)}+ className="group rounded-full bg-gray-100 p-1.5 transition-all duration-75 hover:scale-105 hover:bg-blue-100 active:scale-95"+ >+ <span className="sr-only">Copy</span>+ <QR className="text-gray-700 transition-all group-hover:text-blue-800" />+ </button>+ <Link+ href={{ pathname: "/", query: { key } }}+ as={`/stats/${encodeURI(key)}`}+ shallow+ scroll={false}+ className="flex items-center space-x-1 rounded-md bg-gray-100 px-2 py-0.5 text-gray-700 transition-all duration-75 hover:scale-105 active:scale-95"+ >+ <Chart className="h-4 w-4" />+ <p className="text-sm">+ {isValidating ? (+ <LoadingDots color="#71717A" />+ ) : (+ nFormatter(clicks)+ )}+ <span className="ml-1 hidden sm:inline-block">clicks</span>+ </p>+ </Link>+ </div>+ <p className="w-72 truncate text-sm text-gray-500">{url}</p></div>- <p className="w-72 truncate text-sm text-gray-500">{url}</p></div>+ <button+ type="button"+ onClick={() => setShowAddEditLinkModal(true)}+ className="rounded-md px-1 py-2 transition-all duration-75 hover:bg-gray-100 active:bg-gray-200"+ >+ <ThreeDots className="h-5 w-5 text-gray-500" />+ </button></motion.div></motion.li>);diff --git a/components/layout/meta.tsx b/components/layout/meta.tsxindex 03d66838d1..120a64003f 100644--- a/components/layout/meta.tsx+++ b/components/layout/meta.tsx@@ -44,6 +44,8 @@ export default function Meta({<meta name="viewport" content="width=device-width, initial-scale=1" /><meta itemProp="image" content={image} /><meta property="og:logo" content="https://dub.sh/_static/logo.png"></meta>+ <meta property="og:title" content={title} />+ <meta property="og:description" content={description} /><meta property="og:image" content={image} /><meta name="twitter:card" content="summary_large_image" />diff --git a/lib/constants/index.ts b/lib/constants/index.tsindex be0186ac6b..8833ef36c8 100644--- a/lib/constants/index.ts+++ b/lib/constants/index.ts@@ -47,6 +47,7 @@ export const RESERVED_KEYS = new Set(["placeholder","blog","careers",+ "docs","features","contact","terms",@@ -68,6 +69,8 @@ export const DEFAULT_REDIRECTS = {links: "https://app.dub.sh/links",settings: "https://app.dub.sh/settings",welcome: "https://app.dub.sh/welcome",+ slack: "https://dub.slack.com",+ discord: "https://twitter.com/dubdotsh", // placeholder for now};export const FREE_PLAN_PROJECT_LIMIT = 5;@@ -88,3 +91,24 @@ export const SECOND_LEVEL_DOMAINS = new Set([export const SPECIAL_APEX_DOMAINS = {"youtu.be": "youtube.com",};++export const DEFAULT_LINK_PROPS = {+ key: "github",+ url: "https://github.com/steven-tey/dub",+ domain: "dub.sh",+ archived: false,+ expiresAt: null,+ password: null,++ title: null,+ description: null,+ image: null,+ ios: null,+ android: null,++ clicks: 0,+ userId: "",+ createdAt: new Date(),++ proxy: false,+};diff --git a/lib/upstash.ts b/lib/upstash.tsindex 94d3d508f7..433960eb6a 100644--- a/lib/upstash.ts+++ b/lib/upstash.ts@@ -75,6 +75,16 @@ export async function recordClick();}+/**+ * Recording metatags that were generated via `/api/edge/metatags`+ * If there's an error, it will be logged to a separate redis list for debugging+ **/+export async function recordMetatags(url: string, error: boolean) {+ return await redis.lpush(error ? "metatags-errors" : "metatags", {+ url,+ });+}+export async function getLinkClicksCount(domain: string, key: string) {const start = Date.now() - 2629746000; // 30 days agoreturn (diff --git a/pages/api/edge/metatags.ts b/pages/api/edge/metatags.tsindex 5fdf9129b7..41fd4f841a 100644--- a/pages/api/edge/metatags.ts+++ b/pages/api/edge/metatags.ts@@ -1,11 +1,12 @@-import type { NextRequest } from "next/server";+import type { NextFetchEvent, NextRequest } from "next/server";import { unescape } from "html-escaper";+import { recordMetatags } from "@/lib/upstash";export const config = {runtime: "experimental-edge",};-export default async function handler(req: NextRequest) {+export default async function handler(req: NextRequest, ev: NextFetchEvent) {if (req.method === "GET") {const url = req.nextUrl.searchParams.get("url");try {@@ -13,14 +14,14 @@ export default async function handler(req: NextRequest) {} catch (e) {return new Response("Invalid URL", { status: 400 });}- const metatags = await getMetadataFromUrl(url);+ const metatags = await getMetadataFromUrl(url, ev);return new Response(JSON.stringify(metatags), { status: 200 });} else {return new Response(`Method ${req.method} Not Allowed`, { status: 405 });}}-const getMetadataFromUrl = async (url: string) => {+const getMetadataFromUrl = async (url: string, ev: NextFetchEvent) => {const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), 5000); // timeout if it takes longer than 5 secondsconst metatags = await fetch(url, {@@ -67,7 +68,13 @@ const getMetadataFromUrl = async (url: string) => {obj[key] = unescape(value);},);- console.log(obj);++ const title = obj["og:title"] || obj["twitter:title"] || obj["title"];++ const description =+ obj["description"] ||+ obj["og:description"] ||+ obj["twitter:description"];let image =obj["og:image"] ||@@ -81,12 +88,13 @@ const getMetadataFromUrl = async (url: string) => {image = new URL(url).origin + image;}+ ev.waitUntil(+ recordMetatags(url, title && description && image ? false : true),+ );+return {- title: obj["og:title"] || obj["twitter:title"] || obj["title"],- description:- obj["description"] ||- obj["og:description"] ||- obj["twitter:description"],+ title,+ description,image,};})