dynamic-og-image v1.0.0
Dynamic OG Image Generator
A lightweight and flexible Node.js package to generate dynamic Open Graph (OG) images for social media sharing. This package allows developers to inject dynamic data into an HTML template and generate images in real time.
📖 Table of Contents
- ✨ Features
- 📦 Installation
- 🛠 API Documentation
- 🌐 Using in an Express API
- 📊 Example: Generating a Stock Market OG Image
- ⚡ Performance Considerations
- 🎨 Customization Options
- 📜 License
✨ Features
- 📷 Dynamic OG Image Generation
- 🎨 Customizable Templates
- 🚀 Fast Puppeteer-based Rendering
- 🏗 Supports Any Use Case (Stock Prices, Blog Previews, Custom Metadata, etc.)
- 🔄 PNG Output Format (with potential support for JPEG/SVG in future versions)
- 🏎 Optimized for Performance & Caching
- 📦 Easy Integration with Express.js & Other Backends
📦 Installation
Install the package using npm or yarn:
npm install dynamic-og-image
yarn add dynamic-og-image
🛠 API Documentation
generateOgImage(options: OgImageOptions): Promise<Buffer>
This function generates an Open Graph (OG) image dynamically by injecting data into a provided HTML template.
📌 Parameters
Parameter | Type | Default | Description | |
---|---|---|---|---|
template | string | none | HTML template containing placeholders (e.g., {{ title }}) where dynamic data will be injected. | |
data | Record<string, any> | none | An object containing key-value pairs that replace the placeholders inside the template. | |
type | string | png | The format of the generated image ('png' | 'jpeg'). |
quality | number | 60 | Puppeteer's timeout in milliseconds. | |
puppeteerArgs | { args: string[] } | Default Puppeteer args | Custom Puppeteer launch arguments. |
🔄 Returns
- A
Promise<Buffer>
that resolves to aBuffer
containing the generated PNG image.
🌐 Using in an Express API
You can use this package inside an Express.js route to serve OG images dynamically.
const express = require('express');
import { generateOgImage } from 'dynamic-og-image';
const app = express();
// 🔹 NOTE: You can replace this api endpoint according to your project api conventions
app.get('/og-image', async (req, res) => {
try {
const { title = 'Default Title', description = 'Default Description' } = req.query;
const htmlTemplate = `
<html>
<head>
<style>
body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 500px; width: 800px; background: #f0f0f0; }
.content { text-align: center; }
h1 { color: #333; }
</style>
</head>
<body>
<div class="content">
<h1>{{ title }}</h1>
<p>{{ description }}</p>
</div>
</body>
</html>
`;
// 🔹 NOTE: You can fetch data from your API or database using the parameter here.
const imageBuffer = await generateOgImage({ template: htmlTemplate, data: { title, description } });
res.writeHead(200, { 'Content-Type': 'image/png' });
res.end(imageBuffer, 'binary');
} catch (error) {
res.status(500).json({ error: 'Failed to generate OG image' });
}
});
🖼 Using the Generated OG Image in Frontend
You can use the dynamically generated OG image URL in your frontend by adding it to the tag:
<meta property="og:image" content="https://yourdomain.com/og-image?id=_id" />
This ensures that when your page is shared on social media, the dynamically generated image appears.
📊 Example: Generating a Stock Market OG Image
You can customize your template and the data passed to it based on your use case.
Request:
GET /og-image?stockId=1234
Custom Template for Stocks:
const stockTemplate = `
<html>
<head>
<style>
body { font-family: Arial, sans-serif; display: flex; justify-content: center; align-items: center; height: 500px; width: 800px; background: #121212; color: #fff; }
.content { text-align: center; }
h1 { font-size: 40px; margin-bottom: 10px; }
p { font-size: 28px; }
.change { color: {{ changeColor }}; font-weight: bold; }
</style>
</head>
<body>
<div class="content">
<h1>{{ stock }}</h1>
<p>Current Price: ${{ price }}</p>
<p class="change">Change: {{ change }}</p>
</div>
</body>
</html>
`;
const stockData = {
stock: 'Apple',
price: '180.50',
change: '+1.25%',
changeColor: '#0f0',
};
const imageBuffer = await generateOgImage({ template: stockTemplate, data: stockData });
⚡ Performance Considerations
- Avoid Generating Images on Every Request → Implement caching (Redis, CDN) to optimize response times.
🎨 Customization Options
You can modify your template and customize the data you pass based on your needs.
- Add logos, branding, and colors to match your theme.
- Use different query parameters to generate images dynamically.
- Adjust text, styles, and layout using inline CSS.
📜 License
This project is licensed under the MIT License.
4 months ago