The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
feat: implement ai meta tag and description
flooorianflo61e2a3a59c1a
diff --git a/apps/web/app/api/ai/metadata/route.ts b/apps/web/app/api/ai/metadata/route.tsnew file mode 100644index 0000000000..559da534b5--- /dev/null+++ b/apps/web/app/api/ai/metadata/route.ts@@ -0,0 +1,49 @@+import { getWorkspaceViaEdge } from "@/lib/planetscale";+import { getSearchParams } from "@dub/utils";+import { OpenAIStream, StreamingTextResponse } from "ai";+import { NextRequest } from "next/server";+import OpenAI from "openai";++const openai = new OpenAI({+ apiKey: process.env.OPENAI_API_KEY,+});++export const runtime = "edge";++export async function POST(req: NextRequest) {+ const searchParams = getSearchParams(req.url);+ const { workspaceId, type } = searchParams;++ const { metaTitle, metaDescription, doNotUseString } = await req.json();++ const workspace = await getWorkspaceViaEdge(workspaceId);++ // this endpoint is only available for paid plans+ if (!workspace || workspace.plan === "free")+ return new Response("Requires higher plan", { status: 403 });++ // generates a shortlink for the given URL by asking the AI+ try {+ const response = await openai.chat.completions.create({+ model: "gpt-4",+ max_tokens: 100,+ stream: true,+ messages: [+ {+ role: "system",+ content: `You are a helpful assistant and only answer with a suitable ${type} for SEO and sharing purposes of a website based on the one you receive. For example, you receive a question like 'What is the suitable meta ${type} for meta-title Notion and meta-description The all in one workspace?' and you respond with e.g. ${type === "title" ? "Notion - The all-in-one workspace for your productivity" : "A new tool that brings together all the apps you need for your daily work in one place: The unified workspace for you and your team."}. Don't use any special characters or spaces. For ${type} the maximum length is ${type === "title" ? "120" : "240"} characters.`,+ },+ {+ role: "user",+ content: `What is the suitable meta ${type} for meta-title ${metaTitle} and meta-description ${metaDescription}?${doNotUseString ? ` Don't use ${doNotUseString}.` : ""} and only respond with a suitable ${type} without any special formatting.`,+ },+ ],+ });++ const stream = OpenAIStream(response);++ return new StreamingTextResponse(stream);+ } catch (error) {+ return new Response(error.message, { status: 500 });+ }+}diff --git a/apps/web/ui/modals/add-edit-link-modal/og-section.tsx b/apps/web/ui/modals/add-edit-link-modal/og-section.tsxindex ac2347cc45..0be08b0ff9 100644--- a/apps/web/ui/modals/add-edit-link-modal/og-section.tsx+++ b/apps/web/ui/modals/add-edit-link-modal/og-section.tsx@@ -6,6 +6,7 @@ import {InfoTooltip,LoadingCircle,LoadingSpinner,+ Magic,Popover,SimpleTooltipContent,Switch,@@ -16,7 +17,13 @@ import { TooltipContent } from "@dub/ui/src/tooltip";import { FADE_IN_ANIMATION_SETTINGS, HOME_DOMAIN } from "@dub/utils";import { motion } from "framer-motion";import { Link2 } from "lucide-react";-import { Dispatch, SetStateAction, useEffect, useState } from "react";+import {+ Dispatch,+ SetStateAction,+ useCallback,+ useEffect,+ useState,+} from "react";import TextareaAutosize from "react-textarea-autosize";import UnsplashSearch from "./unsplash-search";@@ -31,7 +38,7 @@ export default function OGSection({setData: Dispatch<SetStateAction<LinkProps>>;generatingMetatags: boolean;}) {- const { plan } = useWorkspace();+ const { plan, id: workspaceId } = useWorkspace();const { queryParams } = useRouterStuff();const { title, description, image, proxy } = data;@@ -39,6 +46,11 @@ export default function OGSection({const [resizing, setResizing] = useState(false);const [dragActive, setDragActive] = useState(false);+ const [loadingMetaData, setLoadingMetaData] = useState({+ title: false,+ description: false,+ });+const onChangePicture = async (e: React.ChangeEvent<HTMLInputElement>) => {const file = e.target.files && e.target.files[0];if (!file) return;@@ -75,6 +87,45 @@ export default function OGSection({setCooldown(false);}, 200);}++ const generateMetaData = useCallback(+ async (type: "title" | "description") => {+ setLoadingMetaData((prev) => ({ ...prev, [type]: true }));++ const returnKey = async (doNotUseString?) =>+ await fetch(+ `/api/ai/metadata?workspaceId=${workspaceId}&type=${type}`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ metaTitle: data.title,+ metaDescription: data.description,+ doNotUseString,+ }),+ },+ ).then(async (res) => {+ if (res.status !== 200) {+ const error = await res.text();+ setLoadingMetaData((prev) => ({ ...prev, [type]: false }));+ throw new Error(error);+ }+ return res.text();+ });++ let res = await returnKey();++ if (res === data[type]) res = await returnKey(data[type]);++ setData((prev) => ({ ...prev, [type]: res }));++ setLoadingMetaData((prev) => ({ ...prev, [type]: false }));+ },+ [data],+ );+return (<div className="relative grid gap-5 border-b border-gray-200 pb-5"><div className="flex items-center justify-between">@@ -264,7 +315,23 @@ export default function OGSection({<div><div className="flex items-center justify-between"><p className="block text-sm font-medium text-gray-700">Title</p>- <p className="text-sm text-gray-500">{title?.length || 0}/120</p>+ <div className="flex items-center gap-2">+ <p className="text-sm text-gray-500">+ {title?.length || 0}/120+ </p>+ <button+ className="flex items-center space-x-2 text-sm text-gray-500 transition-all duration-75 hover:text-black active:scale-95 disabled:cursor-not-allowed"+ onClick={() => generateMetaData("title")}+ disabled={loadingMetaData.title}+ type="button"+ >+ {loadingMetaData.title ? (+ <LoadingCircle />+ ) : (+ <Magic className="h-4 w-4" />+ )}+ </button>+ </div></div><div className="relative mt-1 flex rounded-md shadow-sm">{generatingMetatags && (@@ -293,9 +360,23 @@ export default function OGSection({<p className="block text-sm font-medium text-gray-700">Description</p>- <p className="text-sm text-gray-500">- {description?.length || 0}/240- </p>+ <div className="flex items-center gap-2">+ <p className="text-sm text-gray-500">+ {description?.length || 0}/240+ </p>+ <button+ className="flex items-center space-x-2 text-sm text-gray-500 transition-all duration-75 hover:text-black active:scale-95 disabled:cursor-not-allowed"+ onClick={() => generateMetaData("description")}+ disabled={loadingMetaData.description}+ type="button"+ >+ {loadingMetaData.description ? (+ <LoadingCircle />+ ) : (+ <Magic className="h-4 w-4" />+ )}+ </button>+ </div></div><div className="relative mt-1 flex rounded-md shadow-sm">{generatingMetatags && (