The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Fix Custom Link Preview + Metatags API
Steven Teydea655107e7c
diff --git a/apps/web/app/api/metatags/utils.ts b/apps/web/app/api/metatags/utils.tsindex 522388b437..5be950ebb2 100644--- a/apps/web/app/api/metatags/utils.ts+++ b/apps/web/app/api/metatags/utils.ts@@ -5,7 +5,11 @@ import he from "he";import { parse } from "node-html-parser";export const getHtml = async (url: string) => {- return await fetchWithTimeout(url)+ return await fetchWithTimeout(url, {+ headers: {+ "User-Agent": "Dub.co Metatags API (https://api.dub.co/metatags)",+ },+ }).then((r) => r.text()).catch(() => null);};diff --git a/apps/web/lib/middleware/utils/detect-bot.ts b/apps/web/lib/middleware/utils/detect-bot.tsindex c6a94abfba..72db59f704 100644--- a/apps/web/lib/middleware/utils/detect-bot.ts+++ b/apps/web/lib/middleware/utils/detect-bot.ts@@ -5,6 +5,7 @@ export const detectBot = (req: Request) => {if (ua) {/* Note:* - bot is for most bots & crawlers+ * - metatags is for Dub.co Metatags API (https://api.dub.co/metatags)* - ChatGPT is for ChatGPT* - bluesky is for Bluesky crawler* - facebookexternalhit is for Facebook crawler@@ -13,7 +14,7 @@ export const detectBot = (req: Request) => {* - Go-http-client/1.1 is a bot: https://user-agents.net/string/go-http-client-1-1* - iframely is for https://iframely.com/docs/about (used by Notion, Linear)*/- return /bot|chatgpt|bluesky|facebookexternalhit|WhatsApp|google|baidu|bing|msn|duckduckbot|teoma|slurp|yandex|MetaInspector|Go-http-client|iframely/i.test(+ return /bot|metatags|chatgpt|bluesky|facebookexternalhit|WhatsApp|google|baidu|bing|msn|duckduckbot|teoma|slurp|yandex|MetaInspector|Go-http-client|iframely/i.test(ua,);}diff --git a/apps/web/lib/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.tsindex a4e5a6bca6..ad21cf01e1 100644--- a/apps/web/lib/tinybird/record-click.ts+++ b/apps/web/lib/tinybird/record-click.ts@@ -106,7 +106,7 @@ export async function recordClick({city: geo.city || "Unknown",latitude: geo.latitude || "Unknown",longitude: geo.longitude || "Unknown",- vercel_region: req.headers.get("x-vercel-id") || "",+ vercel_region: geo.region || "",device: capitalize(ua.device.type) || "Desktop",device_vendor: ua.device.vendor || "Unknown",device_model: ua.device.model || "Unknown",diff --git a/apps/web/ui/links/link-title-column.tsx b/apps/web/ui/links/link-title-column.tsxindex 9186af2ead..5a7433875e 100644--- a/apps/web/ui/links/link-title-column.tsx+++ b/apps/web/ui/links/link-title-column.tsx@@ -20,7 +20,7 @@ import {Cards,CircleHalfDottedClock,EarthPosition,- EyeSlash,+ Incognito,InputPassword,Page2,Robot,@@ -44,8 +44,8 @@ import { ResponseLink } from "./links-container";import { LinksDisplayContext } from "./links-display-provider";const quickViewSettings = [- { label: "Custom Social Media Cards", icon: Cards, key: "proxy" },- { label: "Link Cloaking", icon: EyeSlash, key: "rewrite" },+ { label: "Custom Link Preview", icon: Cards, key: "proxy" },+ { label: "Link Cloaking", icon: Incognito, key: "rewrite" },{ label: "Password Protection", icon: InputPassword, key: "password" },{ label: "Link Expiration", icon: CircleHalfDottedClock, key: "expiresAt" },{ label: "iOS Targeting", icon: Apple, key: "ios" },diff --git a/apps/web/ui/modals/link-builder/advanced-modal.tsx b/apps/web/ui/modals/link-builder/advanced-modal.tsxindex 383f195678..0ba84e60e9 100644--- a/apps/web/ui/modals/link-builder/advanced-modal.tsx+++ b/apps/web/ui/modals/link-builder/advanced-modal.tsx@@ -37,23 +37,19 @@ function AdvancedModal({register,handleSubmit,formState: { isDirty },- } = useForm<Pick<LinkFormData, "externalId" | "identifier">>({+ } = useForm<Pick<LinkFormData, "externalId">>({values: {externalId: getValuesParent("externalId"),- identifier: getValuesParent("identifier"),},});- const [externalIdParent, identifierParent] = watchParent([- "externalId",- "identifier",- ]);+ const [externalIdParent] = watchParent(["externalId"]);useKeyboardShortcut("a", () => setShowAdvancedModal(true), {modal: true,});- const parentEnabled = Boolean(externalIdParent || identifierParent);+ const parentEnabled = Boolean(externalIdParent);const { conversionEnabled } = useWorkspace();@@ -71,9 +67,6 @@ function AdvancedModal({setValueParent("externalId", data.externalId, {shouldDirty: true,});- setValueParent("identifier", data.identifier, {- shouldDirty: true,- });setShowAdvancedModal(false);})(e);}}@@ -136,38 +129,6 @@ function AdvancedModal({/></div></div>-- {/* Identifier */}- {conversionEnabled && (- <div>- <div className="flex items-center gap-2">- <label- htmlFor={`${id}-identifier`}- className="block text-sm font-medium text-gray-700"- >- Identifier- </label>- <InfoTooltip- content={- <SimpleTooltipContent- title="A unique string to identify this link."- cta="Learn more about identifiers."- href="https://dub.co/help/article/link-identifiers"- />- }- />- </div>- <div className="mt-2 rounded-md shadow-sm">- <input- id={`${id}-identifier`}- type="text"- placeholder="Eg: david"- className="block w-full rounded-md border-gray-300 text-gray-900 placeholder-gray-400 focus:border-gray-500 focus:outline-none focus:ring-gray-500 sm:text-sm"- {...register("identifier")}- />- </div>- </div>- )}</div><div className="mt-6 flex items-center justify-between">@@ -178,7 +139,6 @@ function AdvancedModal({className="text-xs font-medium text-gray-700 transition-colors hover:text-gray-950"onClick={() => {setValueParent("externalId", null, { shouldDirty: true });- setValueParent("identifier", null, { shouldDirty: true });setShowAdvancedModal(false);}}>diff --git a/apps/web/ui/modals/link-builder/index.tsx b/apps/web/ui/modals/link-builder/index.tsxindex 009f5702a8..3ff9b7d6bb 100644--- a/apps/web/ui/modals/link-builder/index.tsx+++ b/apps/web/ui/modals/link-builder/index.tsx@@ -158,7 +158,7 @@ function LinkBuilderInner({const { generatingMetatags } = useMetatags({initial: Boolean(props),- enabled: showLinkBuilder && !proxy && debouncedUrl.length > 0,+ enabled: showLinkBuilder && debouncedUrl.length > 0,});const saveDisabled = useMemo(() => {diff --git a/apps/web/ui/modals/link-builder/link-preview.tsx b/apps/web/ui/modals/link-builder/link-preview.tsxindex 64f90beaef..799c94a924 100644--- a/apps/web/ui/modals/link-builder/link-preview.tsx+++ b/apps/web/ui/modals/link-builder/link-preview.tsx@@ -35,7 +35,7 @@ import { useDebounce } from "use-debounce";import { LinkFormData, LinkModalContext } from ".";import { useOGModal } from "./og-modal";-const tabs = ["default", "facebook", "linkedin", "x"] as const;+const tabs = ["default", "x", "linkedin", "facebook"] as const;type Tab = (typeof tabs)[number];const tabTitles: Record<Tab, string> = {@@ -47,9 +47,9 @@ const tabTitles: Record<Tab, string> = {const tabIcons: Record<Tab, Icon> = {default: GlobePointer,- facebook: Facebook,- linkedin: LinkedIn,x: Twitter,+ linkedin: LinkedIn,+ facebook: Facebook,};type OGPreviewProps = PropsWithChildren<{@@ -61,14 +61,14 @@ type OGPreviewProps = PropsWithChildren<{const tabComponents: Record<Tab, ComponentType<OGPreviewProps>> = {default: DefaultOGPreview,- facebook: FacebookOGPreview,- linkedin: LinkedInOGPreview,x: XOGPreview,+ linkedin: LinkedInOGPreview,+ facebook: FacebookOGPreview,};export function LinkPreview() {const { watch, setValue } = useFormContext<LinkFormData>();- const { title, description, image, url, password } = watch();+ const { proxy, title, description, image, url, password } = watch();const [debouncedUrl] = useDebounce(url, 500);const hostname = useMemo(() => {@@ -109,7 +109,9 @@ export function LinkPreview() {<Buttontype="button"variant="outline"- icon={<Pen2 className="mx-px size-4" />}+ icon={+ <Pen2 className={cn("mx-px size-4", proxy && "text-blue-500")} />+ }className="h-7 w-fit px-1"onClick={() => setShowOGModal(true)}/>@@ -273,28 +275,24 @@ function DefaultOGPreview({ title, description, children }: OGPreviewProps) {<div className="group relative overflow-hidden rounded-md border border-gray-300">{children}</div>- {title && (- <ReactTextareaAutosize- className="mt-4 line-clamp-2 w-full resize-none border-none p-0 text-xs font-medium text-gray-700 outline-none focus:ring-0"- value={title}- maxRows={2}- onChange={(e) => {- setValue("title", e.currentTarget.value);- setValue("proxy", true);- }}- />- )}- {description && (- <ReactTextareaAutosize- className="mt-2.5 line-clamp-2 w-full resize-none border-none p-0 text-xs text-gray-700/80 outline-none focus:ring-0"- value={description}- maxRows={2}- onChange={(e) => {- setValue("description", e.currentTarget.value);- setValue("proxy", true);- }}- />- )}+ <ReactTextareaAutosize+ className="mt-4 line-clamp-2 w-full resize-none border-none p-0 text-xs font-medium text-gray-700 outline-none focus:ring-0"+ value={title || "Add a title..."}+ maxRows={2}+ onChange={(e) => {+ setValue("title", e.currentTarget.value);+ setValue("proxy", true);+ }}+ />+ <ReactTextareaAutosize+ className="mt-1.5 line-clamp-2 w-full resize-none border-none p-0 text-xs text-gray-700/80 outline-none focus:ring-0"+ value={description || "Add a description..."}+ maxRows={2}+ onChange={(e) => {+ setValue("description", e.currentTarget.value);+ setValue("proxy", true);+ }}+ /></div>);}@@ -316,27 +314,23 @@ function FacebookOGPreview({{hostname && (<p className="text-xs uppercase text-[#606770]">{hostname}</p>)}- {(title || title === "") && (- <input- className="truncate border-none bg-transparent p-0 text-xs font-semibold text-[#1d2129] outline-none focus:ring-0"- value={title}- onChange={(e) => {- setValue("title", e.currentTarget.value);- setValue("proxy", true);- }}- />- )}- {(description || description === "") && (- <ReactTextareaAutosize- className="mb-1 line-clamp-2 w-full resize-none rounded-md border-none bg-gray-200 bg-transparent p-0 text-xs text-[#606770] outline-none focus:ring-0"- value={description}- maxRows={2}- onChange={(e) => {- setValue("description", e.currentTarget.value);- setValue("proxy", true);- }}- />- )}+ <input+ className="truncate border-none bg-transparent p-0 text-xs font-semibold text-[#1d2129] outline-none focus:ring-0"+ value={title || "Add a title..."}+ onChange={(e) => {+ setValue("title", e.currentTarget.value);+ setValue("proxy", true);+ }}+ />+ <ReactTextareaAutosize+ className="mb-1 line-clamp-2 w-full resize-none rounded-md border-none bg-gray-200 bg-transparent p-0 text-xs text-[#606770] outline-none focus:ring-0"+ value={description || "Add a description..."}+ maxRows={2}+ onChange={(e) => {+ setValue("description", e.currentTarget.value);+ setValue("proxy", true);+ }}+ /></div>)}</div>@@ -355,44 +349,32 @@ function LinkedInOGPreview({ title, hostname, children }: OGPreviewProps) {>{children}</div>- {(hostname || title) && (- <div className="grid gap-2">- {(title || title === "") && (- <ReactTextareaAutosize- className="line-clamp-2 w-full resize-none border-none p-0 text-sm font-semibold text-[#000000E6] outline-none focus:ring-0"- value={title}- maxRows={2}- onChange={(e) => {- setValue("title", e.currentTarget.value);- setValue("proxy", true);- }}- />- )}- {hostname && <p className="text-xs text-[#00000099]">{hostname}</p>}- </div>- )}+ <div className="grid gap-2">+ <ReactTextareaAutosize+ className="line-clamp-2 w-full resize-none border-none p-0 text-sm font-semibold text-[#000000E6] outline-none focus:ring-0"+ value={title || "Add a title..."}+ maxRows={2}+ onChange={(e) => {+ setValue("title", e.currentTarget.value);+ setValue("proxy", true);+ }}+ />+ <p className="text-xs text-[#00000099]">{hostname || "domain.com"}</p>+ </div></div>);}function XOGPreview({ title, hostname, children }: OGPreviewProps) {- const hasTitle = title || title === "";return (<div><div className="group relative overflow-hidden rounded-2xl border border-gray-300">{children}<div className="absolute bottom-2 left-0 w-full px-2">- <div- className={cn(- "w-fit max-w-full rounded px-1.5 py-px",- hasTitle ? "bg-black/[0.77]" : "bg-gray-200",- )}- >- {hasTitle && (- <span className="block max-w-sm truncate text-xs text-white">- {title}- </span>- )}+ <div className="w-fit max-w-full rounded bg-black/[0.77] px-1.5 py-px">+ <span className="block max-w-sm truncate text-xs text-white">+ {title || "Add a title..."}+ </span></div></div></div>diff --git a/apps/web/ui/modals/link-builder/use-metatags.ts b/apps/web/ui/modals/link-builder/use-metatags.tsindex d187c0bbb6..c403a9f63b 100644--- a/apps/web/ui/modals/link-builder/use-metatags.ts+++ b/apps/web/ui/modals/link-builder/use-metatags.ts@@ -12,7 +12,14 @@ export function useMetatags({enabled: boolean;}) {const { watch, setValue } = useFormContext<LinkFormData>();- const [url, password, proxy] = watch(["url", "password", "proxy"]);+ const [url, password, proxy, title, description, image] = watch([+ "url",+ "password",+ "proxy",+ "title",+ "description",+ "image",+ ]);const [debouncedUrl] = useDebounce(getUrlWithoutUTMParams(url), 500);const [generatingMetatags, setGeneratingMetatags] = useState(initial);@@ -36,11 +43,7 @@ export function useMetatags({* - custom OG proxy is not enabled* - url is not empty**/- if (enabled && !proxy) {- setValue("title", null);- setValue("description", null);- setValue("image", null);-+ if (enabled) {try {// if url is valid, continue to generate metatags, else return nullnew URL(debouncedUrl);@@ -48,9 +51,10 @@ export function useMetatags({fetch(`/api/metatags?url=${debouncedUrl}`).then(async (res) => {if (res.status === 200) {const results = await res.json();- setValue("title", truncate(results.title, 120));- setValue("description", truncate(results.description, 240));- setValue("image", results.image);+ !title && setValue("title", truncate(results.title, 120));+ !description &&+ setValue("description", truncate(results.description, 240));+ !image && setValue("image", results.image);}// set timeout to prevent flickeringsetTimeout(() => setGeneratingMetatags(false), 200);