The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
feat: add new implementation to fetch meta tags
rwlc06f5c5dd5bac
diff --git a/package.json b/package.jsonindex 63fe5f1abf..2f7269985b 100644--- a/package.json+++ b/package.json@@ -41,6 +41,7 @@"cobe": "^0.6.2","focus-trap-react": "^10.0.1","framer-motion": "^7.6.12",+ "he": "^1.2.0","html-escaper": "^3.0.3","i": "^0.3.7","mailing-core": "^0.9.1",diff --git a/pages/api/edge/metatags.ts b/pages/api/edge/metatags.tsindex 5756c1febf..04dc925cdf 100644--- a/pages/api/edge/metatags.ts+++ b/pages/api/edge/metatags.ts@@ -1,106 +1,123 @@-import type { NextFetchEvent, NextRequest } from "next/server";-import { unescape } from "html-escaper";-import { recordMetatags } from "@/lib/upstash";+import { NextRequest, NextResponse } from "next/server";+import { parse, walk, ELEMENT_NODE } from "ultrahtml";+import he from "he";-export const config = {- runtime: "experimental-edge",+const getHtml = async (url: string) => {+ const res = await fetch(url);+ return await res.text();+};++const getAst = async (url: string) => {+ const html = await getHtml(url);+ const ast = parse(html);+ return ast;};-export default async function handler(req: NextRequest, ev: NextFetchEvent) {- if (req.method === "GET") {- const url = req.nextUrl.searchParams.get("url");- try {- new URL(url).hostname;- } catch (e) {- return new Response("Invalid URL", { status: 400 });- }- 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 escapeEntities = (string: string) => {+ return he.decode(string);+};++const validateUrl = (input: string) => {+ let url: URL;++ try {+ url = new URL(input);+ } catch (_) {+ return false;+ }++ return url.protocol === "http:" || url.protocol === "https:";+};+const getMetaTags = async (url: string) => {+ const ast = await getAst(url);++ let final = {+ title: new Set(),+ description: new Set(),+ image: new Set(),+ };++ // I use a Set here because Set.has() is O(1). Array.includes() is O(n)+ const combinations = {+ description: new Set([+ "description",+ "og:description",+ "twitter:description",+ ]),+ image: new Set(["og:image", "twitter:image", "icon", "image_src"]),+ title: new Set(["og:title", "twitter:title", "title"]),+ };++ await walk(ast, (node) => {+ if (node.type === ELEMENT_NODE) {+ const { name, attributes } = node;++ const { content: unescapedContent } = attributes;++ const property = attributes.property || attributes.name;++ if (name === "title") {+ const title: string = node.children[0].value;+ title && final.title.add(title);+ }++ if (unescapedContent) {+ const content = escapeEntities(unescapedContent);++ if (name === "meta") {+ const { description, image, title } = combinations;+ if (description.has(property)) {+ final.description.add(content);+ }++ if (image.has(property)) {+ const isUrl = validateUrl(content);+ let value = "";+ if (isUrl) {+ value = content;+ } else {+ const { protocol, host } = new URL(url);+ const baseURL = `${protocol}//${host}`;++ value = new URL(content, baseURL).toString();+ }+ final.image.add(value);+ }++ if (title.has(property)) {+ final.title.add(content);+ }+ }+ }+ }+ });+ return {+ metaTags: {+ title: [...final.title],+ description: [...final.description],+ image: [...final.image],+ },+ };+};++export default async function handler(req: NextRequest, res: NextResponse) {+ const { searchParams } = new URL(req.url);+ const url = searchParams.get("url");++ if (typeof url === "string") {+ const tags = await getMetaTags(url);++ return new Response(JSON.stringify({ url, ...tags }), {+ status: 200,+ headers: {+ "content-type": "application/json",+ },+ });+ }++ return new Response("Please provide a URL!");}-const getMetadataFromUrl = async (url: string, ev: NextFetchEvent) => {- const controller = new AbortController();- const timeoutId = setTimeout(() => controller.abort(), 5000); // timeout if it takes longer than 5 seconds- const metatags = await fetch(url, {- signal: controller.signal,- headers: {- "User-Agent": "dub-bot/1.0",- },- })- .then((res) => {- clearTimeout(timeoutId);- return res.text();- })- .then((body: string) => {- const obj = {};- // get all meta tags- body.replace(- /<meta\s+(?:name|property|itemprop|http-equiv)="([^"]+)"\s+content="([^"]+)"/g,- // @ts-ignore- (_, key, value) => {- obj[key] = unescape(value).replaceAll("'", "'");- },- );- // get all meta tags (reversed order for content & name/property)- body.replace(- /<meta\s+content="([^"]+)"\s+(?:name|property|itemprop|http-equiv)="([^"]+)"/g,- // @ts-ignore- (_, value, key) => {- obj[key] = unescape(value).replaceAll("'", "'");- },- );- // get all title tags- body.replace(- /<title>([^<]+)<\/title>/g,- // @ts-ignore- (_, value) => {- obj["title"] = unescape(value).replaceAll("'", "'");- },- );- // get all link tags- body.replace(- /<link\s+(?:rel|itemprop)="([^"]+)"\s+href="([^"]+)"/g,- // @ts-ignore- (_, key, value) => {- obj[key] = unescape(value).replaceAll("'", "'");- },- );-- 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"] ||- obj["twitter:image"] ||- obj["icon"] ||- obj["image_src"];-- if (image && image.startsWith("//")) {- image = "https:" + image;- } else if (image && image.startsWith("/")) {- image = new URL(url).origin + image;- }-- ev.waitUntil(- recordMetatags(url, title && description && image ? false : true),- );-- return {- title,- description,- image,- };- })- .catch((err) => {- console.log(err);- return {}; // if there's an error, return ""- });- return metatags;+export const config = {+ runtime: "experimental-edge",};