[TERMINAL · SKILLS]
> mounting /skills...
> indexing skill manifests...
> linking agents: claude · codex · gemini · cursor
> ready.
[░░░░░░░░░░░░░░░░░░░░░░░░░░░░] 0%
Use Cases/Build a Link Preview Generator

Build a Link Preview Generator

Build a link preview service that extracts Open Graph metadata, generates thumbnail previews, caches results, handles edge cases like SPAs and paywalled content, and serves previews via API.

Development#typescript#tsconfig#type-checking#type-safety#javascript-migration
Works with:claude-codeopenai-codexgemini-clicursor

Skills stack · 4 skills

Avg quality 95/100·All SAFE
>

typescript

v1.0.0

Sets up and repairs TypeScript projects: picks tsconfig.json settings for a Node.js service, an npm library or a bundled web app, runs type-checking in CI, and replaces `any` and unsafe casts with types the compiler can verify. Use when someone asks to "set up TypeScript", "fix this tsconfig", "fix a TypeScript error", "upgrade to TypeScript 6 or 7", "migrate JavaScript to TypeScript", "publish types for a package", "run .ts files in Node" or "make this type-safe". Covers the changed defaults in TypeScript 6.0 and 7.0, module and moduleResolution, strict mode, project references, declaration output, narrowing, satisfies and common compiler errors.

93/100 quality
7.30× impact
SAFE· stale score
View skill
>

redis

v1.1.0

Redis is an in-memory data store used as a cache, session store, message broker and counter service. Use when adding a cache layer, storing sessions, rate limiting an API, running pub/sub or Streams with consumer groups, taking a distributed lock, building a leaderboard, or configuring Redis for production (persistence, maxmemory, eviction).

93/100 quality
1.79× impact
SAFE· stale score
View skill
>

hono

v1.1.0

Hono is a small web framework built on Web Standards (Request/Response) that runs unchanged on Cloudflare Workers, Deno, Bun, Node.js, AWS Lambda and Vercel. Use it when the user asks to build a Hono API, add Zod validation, JWT auth, CORS or middleware, use the type-safe RPC client (hc), render JSX, stream responses, or deploy one codebase to several runtimes.

100/100 quality
6.20× impact
SAFE· stale score
View skill
>

zod

v1.1.0

Zod is a TypeScript-first schema library that validates data at runtime and infers static types from the same schema. Use when validating API request bodies, form input, environment variables or config files, parsing untrusted JSON, or migrating from Zod 3 to Zod 4. Covers z.object, safeParse, z.infer, coercion, discriminated unions, refinements, JSON Schema output and the v4 API changes.

93/100 quality
3.87× impact
SAFE· stale score
View skill
$

The Problem

Zara leads product at a 20-person messaging platform. Users paste links but see raw URLs — no preview, no context. Users click blind and sometimes land on spam or NSFW content. Competitors (Slack, Discord) show rich link previews with title, description, and thumbnail. They tried fetching Open Graph tags client-side but hit CORS errors. Some sites return no OG tags, some return broken images, and SPAs return empty HTML until JavaScript runs. They need a server-side preview service: fast, cached, and resilient to broken sites.

Step 1: Build the Preview Engine

typescript
// src/preview/unfurler.ts — Link preview with OG extraction, fallbacks, and caching
import { Redis } from "ioredis";
import { createHash } from "node:crypto";

const redis = new Redis(process.env.REDIS_URL!);

interface LinkPreview {
  url: string;
  title: string;
  description: string;
  image: string | null;
  favicon: string | null;
  siteName: string;
  type: string;                // "article" | "video" | "website" | "image"
  domain: string;
  author: string | null;
  publishedDate: string | null;
  videoUrl: string | null;
  embedHtml: string | null;    // for YouTube, Twitter, etc.
  contentType: string;
  fetchedAt: string;
}

const MAX_FETCH_TIME = 5000;   // 5s timeout
const MAX_HTML_SIZE = 512000;  // 500KB max
const CACHE_TTL = 86400 * 7;   // 7 days

// Known embed providers
const EMBED_PROVIDERS: Record<string, (url: URL) => string | null> = {
  "youtube.com": (url) => {
    const id = url.searchParams.get("v") || url.pathname.split("/").pop();
    return id ? `<iframe src="https://www.youtube.com/embed/${id}" frameborder="0" allowfullscreen></iframe>` : null;
  },
  "youtu.be": (url) => {
    const id = url.pathname.slice(1);
    return id ? `<iframe src="https://www.youtube.com/embed/${id}" frameborder="0" allowfullscreen></iframe>` : null;
  },
  "twitter.com": () => null, // use Twitter oEmbed API
  "x.com": () => null,
  "vimeo.com": (url) => {
    const id = url.pathname.split("/").pop();
    return id ? `<iframe src="https://player.vimeo.com/video/${id}" frameborder="0" allowfullscreen></iframe>` : null;
  },
};

// Get link preview with caching
export async function getPreview(url: string): Promise<LinkPreview> {
  // Validate URL
  let parsed: URL;
  try {
    parsed = new URL(url);
    if (!["http:", "https:"].includes(parsed.protocol)) throw new Error("Invalid protocol");
  } catch {
    throw new Error("Invalid URL");
  }

  // Block private IPs (SSRF prevention)
  if (isPrivateIP(parsed.hostname)) {
    throw new Error("Private URLs not allowed");
  }

  // Check cache
  const cacheKey = `preview:${createHash("md5").update(url).digest("hex")}`;
  const cached = await redis.get(cacheKey);
  if (cached) return JSON.parse(cached);

  // Check if it's a direct image
  if (/\.(jpg|jpeg|png|gif|webp|svg)(\?|$)/i.test(parsed.pathname)) {
    const preview: LinkPreview = {
      url, title: parsed.pathname.split("/").pop() || url,
      description: "", image: url, favicon: null,
      siteName: parsed.hostname, type: "image",
      domain: parsed.hostname, author: null, publishedDate: null,
      videoUrl: null, embedHtml: null, contentType: "image",
      fetchedAt: new Date().toISOString(),
    };
    await redis.setex(cacheKey, CACHE_TTL, JSON.stringify(preview));
    return preview;
  }

  // Fetch the page
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), MAX_FETCH_TIME);

  try {
    const response = await fetch(url, {
      headers: {
        "User-Agent": "Mozilla/5.0 (compatible; LinkPreviewBot/1.0)",
        "Accept": "text/html,application/xhtml+xml",
        "Accept-Language": "en-US,en;q=0.9",
      },
      redirect: "follow",
      signal: controller.signal,
    });

    clearTimeout(timeout);

    const contentType = response.headers.get("content-type") || "";

    // Handle non-HTML (PDFs, images, etc.)
    if (!contentType.includes("html")) {
      const preview: LinkPreview = {
        url, title: decodeURIComponent(parsed.pathname.split("/").pop() || url),
        description: `${contentType} file`, image: null, favicon: null,
        siteName: parsed.hostname, type: "website", domain: parsed.hostname,
        author: null, publishedDate: null, videoUrl: null, embedHtml: null,
        contentType, fetchedAt: new Date().toISOString(),
      };
      await redis.setex(cacheKey, CACHE_TTL, JSON.stringify(preview));
      return preview;
    }

    const html = await response.text();
    const truncatedHtml = html.slice(0, MAX_HTML_SIZE);

    // Extract metadata
    const preview = extractMetadata(truncatedHtml, url, parsed);

    // Check for embed
    const embedDomain = Object.keys(EMBED_PROVIDERS).find((d) => parsed.hostname.endsWith(d));
    if (embedDomain) {
      preview.embedHtml = EMBED_PROVIDERS[embedDomain](parsed);
      if (preview.embedHtml) preview.type = "video";
    }

    // Resolve relative image URLs
    if (preview.image && !preview.image.startsWith("http")) {
      preview.image = new URL(preview.image, url).href;
    }

    // Get favicon
    preview.favicon = extractFavicon(truncatedHtml, url) || `https://www.google.com/s2/favicons?domain=${parsed.hostname}&sz=32`;

    await redis.setex(cacheKey, CACHE_TTL, JSON.stringify(preview));
    return preview;
  } catch (err: any) {
    clearTimeout(timeout);
    // Return minimal preview on failure
    const fallback: LinkPreview = {
      url, title: parsed.hostname, description: "",
      image: null, favicon: `https://www.google.com/s2/favicons?domain=${parsed.hostname}&sz=32`,
      siteName: parsed.hostname, type: "website", domain: parsed.hostname,
      author: null, publishedDate: null, videoUrl: null, embedHtml: null,
      contentType: "unknown", fetchedAt: new Date().toISOString(),
    };
    await redis.setex(cacheKey, 3600, JSON.stringify(fallback)); // shorter cache for failures
    return fallback;
  }
}

function extractMetadata(html: string, url: string, parsed: URL): LinkPreview {
  const get = (patterns: RegExp[]): string => {
    for (const p of patterns) {
      const match = html.match(p);
      if (match?.[1]) return decodeHtmlEntities(match[1].trim());
    }
    return "";
  };

  const title = get([
    /property="og:title"\s+content="([^"]+)"/i,
    /name="twitter:title"\s+content="([^"]+)"/i,
    /<title[^>]*>([^<]+)<\/title>/i,
  ]);

  const description = get([
    /property="og:description"\s+content="([^"]+)"/i,
    /name="twitter:description"\s+content="([^"]+)"/i,
    /name="description"\s+content="([^"]+)"/i,
  ]);

  const image = get([
    /property="og:image"\s+content="([^"]+)"/i,
    /name="twitter:image"\s+content="([^"]+)"/i,
    /name="twitter:image:src"\s+content="([^"]+)"/i,
  ]) || null;

  const siteName = get([/property="og:site_name"\s+content="([^"]+)"/i]) || parsed.hostname;
  const type = get([/property="og:type"\s+content="([^"]+)"/i]) || "website";
  const author = get([/name="author"\s+content="([^"]+)"/i]) || null;
  const publishedDate = get([
    /property="article:published_time"\s+content="([^"]+)"/i,
    /name="date"\s+content="([^"]+)"/i,
  ]) || null;

  return {
    url, title: title || parsed.hostname, description,
    image, favicon: null, siteName, type, domain: parsed.hostname,
    author, publishedDate, videoUrl: null, embedHtml: null,
    contentType: "text/html", fetchedAt: new Date().toISOString(),
  };
}

function extractFavicon(html: string, url: string): string | null {
  const match = html.match(/<link[^>]+rel="(?:shortcut )?icon"[^>]+href="([^"]+)"/i)
    || html.match(/<link[^>]+href="([^"]+)"[^>]+rel="(?:shortcut )?icon"/i);
  if (match?.[1]) {
    const href = match[1];
    return href.startsWith("http") ? href : new URL(href, url).href;
  }
  return null;
}

function decodeHtmlEntities(str: string): string {
  return str.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">")
    .replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&#x27;/g, "'");
}

function isPrivateIP(hostname: string): boolean {
  if (hostname === "localhost" || hostname === "127.0.0.1") return true;
  if (hostname.startsWith("10.") || hostname.startsWith("192.168.")) return true;
  if (/^172\.(1[6-9]|2\d|3[01])\./.test(hostname)) return true;
  return false;
}

// Batch preview (for message with multiple links)
export async function batchPreview(urls: string[]): Promise<Map<string, LinkPreview>> {
  const results = new Map<string, LinkPreview>();
  const unique = [...new Set(urls)].slice(0, 5); // max 5 previews

  await Promise.all(unique.map(async (url) => {
    try {
      const preview = await getPreview(url);
      results.set(url, preview);
    } catch {}
  }));

  return results;
}

Results

  • Rich link previews in messages — title, description, thumbnail, and favicon show inline; users understand what they're clicking before they click
  • YouTube/Vimeo embeds — video links render as playable embeds; users watch without leaving the chat
  • 7-day cache — popular links fetched once; subsequent requests served from Redis in <1ms; reduced external fetches by 95%
  • SSRF protection — private IPs blocked; no fetching internal services through the preview endpoint
  • Graceful degradation — broken sites, SPAs with no OG tags, and timeouts all return a minimal preview (domain + favicon) instead of an error

Related use cases