Link Preview JS

raw JSON →
4.0.0 verified Thu Apr 23 auth: no javascript

link-preview-js is a JavaScript/TypeScript module designed to extract and fetch rich HTTP link information, such as title, description, images, and videos, primarily leveraging OpenGraph tags. It processes either direct URLs or text blocks containing URLs to return structured metadata. The library is currently on stable version 4.0.0 and demonstrates an active release cadence with frequent updates. A key differentiator is its explicit focus on server-side execution (Node.js >=18 environments) or specific mobile runtimes (like React Native/Cordova), strictly advising against direct client-side usage due to browser-enforced Cross-Origin Resource Sharing (CORS) policies. It also provides a utility to parse already-fetched HTML content.

error Access to fetch at 'https://example.com' from origin 'https://your-app.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
cause Attempting to use `link-preview-js` directly in a browser environment, triggering browser security (CORS).
fix
Move link-preview-js usage to a backend server (Node.js) and create an API endpoint to fetch and return the preview data to your frontend.
error TypeError: (0 , link_preview_js_1.getLinkPreview) is not a function
cause Incorrect import syntax, typically trying to use CommonJS `require` or a default import for a named export in an ESM context.
fix
Ensure you are using named imports correctly: import { getLinkPreview } from 'link-preview-js'; and that your environment supports ESM (Node.js >=18 with appropriate type: 'module' in package.json or transpilation).
error The link preview data is empty or incorrect, showing login page content.
cause The target website redirected to a login or consent page, and the library parsed that page instead of the intended content.
fix
This is a common behavior. Try passing a different User-Agent string in the options (e.g., mimicking a search engine bot) to see if the website serves different content. There is no guaranteed fix as websites can implement various anti-scraping measures.
breaking Version 4.0.0 migrates internal URL handling to the standard WHATWG URL API. While this improves robustness and compliance, it might subtly change parsing behavior for malformed or non-standard URLs compared to previous versions. Ensure your input URLs are well-formed.
fix Review how URLs are constructed and passed to `getLinkPreview`. Ensure they adhere to standard URL specifications. If encountering issues, validate URLs before passing them to the function.
gotcha This library is strictly intended for server-side (Node.js) or specific mobile runtime usage (e.g., React Native, Cordova). Attempting to use `getLinkPreview` directly in a browser environment will fail due to browser security policies (Cross-Origin Resource Sharing - CORS).
fix Always run this library on your backend server. If you need link previews in a web application, implement an API endpoint on your server that calls `link-preview-js` and then serves the results to your frontend.
gotcha The preview process simulates a user visiting a page. If a target website redirects to a login page, consent screen, or another intermediary page, the library will parse that redirected content instead of the intended page, leading to incorrect preview data.
fix Consider trying different `User-Agent` headers (e.g., 'Googlebot', 'Twitterbot') via the options object to see if the target site serves different content to known bots. However, there's no universal fix for all redirect scenarios.
gotcha The library primarily relies on OpenGraph (OG) tags for extracting metadata. If a target website does not implement OpenGraph tags, the preview will be less accurate or incomplete, despite some fallbacks.
fix No direct fix for missing OpenGraph tags on target sites. Understand that some links may yield minimal data. You can inspect the returned data and apply custom fallbacks if certain fields are missing.
breaking The minimum required Node.js version has been updated to `^18.0.0`. Older Node.js versions are no longer supported, which might cause compatibility issues if deployed in an older environment.
fix Ensure your Node.js environment is updated to version 18 or newer. Use `nvm` or similar tools to manage Node.js versions efficiently.
npm install link-preview-js
yarn add link-preview-js
pnpm add link-preview-js

This quickstart demonstrates how to use `getLinkPreview` with both a direct URL and a text string, and `getPreviewFromContent` for pre-fetched HTML, showcasing basic usage and error handling.

import { getLinkPreview, getPreviewFromContent } from 'link-preview-js';

// Example 1: Directly fetching a link
getLinkPreview('https://www.youtube.com/watch?v=MejbOFk7H6c').then((data) => {
  console.log('Link preview data:', data);
}).catch(error => {
  console.error('Error fetching link preview:', error.message);
});

// Example 2: Fetching from a text block
const textWithLink = 'Check out this video: https://www.youtube.com/watch?v=MejbOFk7H6c and some more text.';
getLinkPreview(textWithLink).then((data) => {
  console.log('Link preview from text:', data);
}).catch(error => {
  console.error('Error fetching link preview from text:', error.message);
});

// Example 3: Parsing pre-fetched HTML content
// In a real application, 'yourAjaxCall' would be your server-side fetch.
const mockResponse = {
  data: '<!DOCTYPE html><html><head><title>Mock Title</title><meta property="og:description" content="Mock Description"></head><body></body></html>',
  headers: {
    'content-type': 'text/html; charset=utf-8'
  },
  url: 'https://example.com/mock-page'
};

getPreviewFromContent(mockResponse).then((data) => {
  console.log('Link preview from content:', data);
}).catch(error => {
  console.error('Error fetching link preview from content:', error.message);
});