react-og-previewer
v1.0.4
Published
This package is build for react projects for getting the OGTitle, OGImage and OGDescription from any URL and show it as a previewer
Downloads
119
Readme
react-og-previewer
A lightweight React hook to fetch Open Graph metadata (title, image, description) from any public URL and display a rich link preview.
Perfect for:
- Blogs
- Chat applications
- Social feeds
- URL embedding
- Rich preview cards
🚀 Installation
npm install react-og-previeweror
yarn add react-og-previewer📦 Usage
Import the hook
import useOGPreview from "react-og-previewer";Use it inside your component
const { loading, error, metadata } = useOGPreview(url);📌 API Reference
useOGPreview(url: string)
Returns an object:
{
loading: boolean;
error: any;
metadata: {
title: string;
image: string;
description: string;
};
}loading
Indicates if the fetch request is still running.
true→ fetchingfalse→ done
error
Returns the error object if the request fails (CORS, network issue, invalid URL).
metadata
Contains extracted Open Graph values:
metadata.title // og:title
metadata.image // og:image
metadata.description // og:descriptionIf a tag does not exist, an empty string is returned.
🧪 Full Working Example
import React from "react";
import useOGPreview from "react-og-previewer";
export default function LinkPreviewDemo() {
const url = "https://openai.com";
const { loading, error, metadata } = useOGPreview(url);
if (loading) return <p>Fetching preview…</p>;
if (error) return <p>Failed to load preview.</p>;
return (
<div
style={{
border: "1px solid #ccc",
padding: "16px",
width: "350px",
borderRadius: "8px",
}}
>
{metadata.image && (
<img
src={metadata.image}
alt="Preview"
style={{
width: "100%",
borderRadius: "4px",
marginBottom: "12px",
}}
/>
)}
<h3>{metadata.title || "No title found"}</h3>
<p style={{ fontSize: "14px", color: "#555" }}>
{metadata.description || "No description available"}
</p>
<a
href={url}
target="_blank"
rel="noopener noreferrer"
style={{ marginTop: "8px", color: "#0070f3" }}
>
Visit site
</a>
</div>
);
}⚠️ CORS Warning
Some websites block HTML fetching from browsers, so metadata cannot be retrieved from the frontend.
When blocked:
errorbecomes non-null- Metadata will be empty
- Request fails silently
Sites that usually block CORS
❌ Instagram
❌ Facebook
❌ LinkedIn
❌ Twitter
❌ Amazon
❌ Flipkart
Sites that usually allow scraping
✔ Blogs
✔ News websites
✔ Portfolio sites
✔ Small business sites
Why?
Browsers require the site to allow:
Access-Control-Allow-Origin: *Most platforms do NOT enable this for security reasons.
💡 How to Fix CORS (Recommended)
If you want consistent behavior for all URLs:
Use your backend as a proxy:
- React → calls your backend
- Backend → fetches the target URL (Node has no CORS restrictions)
- Backend → returns the HTML to React
- Hook parses metadata safely
If you want, I can generate a ready-to-use Express/Node backend for you.
📄 License
MIT — free for personal and commercial use.
