How to Build a Link Preview Tool: A Step-by-Step Guide
A link preview tool fetches a URL and generates a rich snippet containing a title, description, and image – exactly what you see when sharing links on social media. Building your own gives you full control over caching, styling, and privacy. This tutorial walks you through the essential steps using Node.js and standard web APIs.
The core idea is to fetch the target URL server-side, parse its HTML, extract Open Graph (OG) and Twitter Card meta tags, then fall back to other elements like the <title> and <meta name="description">. You’ll serve the result as JSON (for API consumers) or as an HTML snippet for direct embedding.
1. Fetch and Parse the HTML
Use a server-side HTTP client (like axios or Node’s built-in fetch) to request the URL. Set a reasonable timeout (e.g., 5 seconds) and accept any content type. Parse the response body with an HTML parser such as cheerio (Node.js ecosystem).
- Always validate the URL before fetching to prevent SSRF attacks.
- Handle redirects – your tool should follow them and capture the final URL.
2. Extract Open Graph and Fallback Data
Use the parsed DOM to query for OG meta tags: og:title, og:description, og:image. If any of these are missing, fall back to Twitter Card tags (twitter:title, etc.). If still missing, use the document’s <title> and <meta name="description">.
- For the image, ensure you resolve relative URLs against the page’s base URL.
- Sanitize all extracted text to avoid HTML injection.
3. Generate and Return the Preview Object
Build a JSON object with fields like url, title, description, image, and favicon (optional). For an HTML snippet, embed these into a styled card. Cache the result per URL to avoid repeated fetches – a simple in‑memory cache works for prototyping.
{
"title": "Example Domain",
"description": "This domain is for use in illustrative examples.",
"image": "https://example.com/og-image.jpg",
"url": "https://example.com"
}
Conclusion
Your link preview tool is now ready. Test it with URLs that have strong OG tags (like a news article) and weak ones (like a plain PDF). Improve reliability by adding a headless browser fallback for JavaScript‑heavy pages. This approach is lightweight, fast, and easily deployable as a microservice.