Generating compelling social preview images can make a huge difference in how your content is perceived and shared online. Dynamic OG (Open Graph) images personalize previews for every page, boosting engagement and giving your project a professional edge. With Next.js and SVG, you can automate this process—no more manual image editing or boring, static previews. Let's explore how to build an efficient OG image generator for your Next.js site, using SVG for crisp graphics and real-time customization.
Why Dynamic OG Images Matter
Open Graph images are the preview thumbnails you see when sharing links on platforms like Twitter, LinkedIn, or Facebook. A relevant and visually appealing OG image increases click-through rates and makes your content stand out. The default—one generic image for every page—misses an opportunity to communicate unique value. Dynamic OG images allow you to:
- Personalize previews with page titles, authors, or featured images
- Automatically generate up-to-date visuals for new content
- Stay on-brand across your entire site without manual effort
SVG: The Secret Sauce for OG Images
SVG (Scalable Vector Graphics) is ideal for OG image generation:
- Scalable and crisp: No blurry text or icons, regardless of resolution.
- Easily composable: Combine text, shapes, and images programmatically.
- Lightweight: Much smaller than raster graphics for simple designs.
By generating SVG on-demand, you can customize every aspect of the image—colors, layout, content—using code.
Next.js API Routes: The Dynamic Backend
Next.js API routes are perfect for server-side generation of OG images. They allow you to:
- Create an endpoint like
/api/og?title=Hello+World - Parse query parameters for dynamic data
- Return an image as the response
Let's walk through building a simple dynamic OG image generator using Next.js and SVG.
Step 1: Creating a Next.js API Route
First, set up an API route to handle OG image requests.
// pages/api/og.ts
import { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { title = 'My Site', author = '' } = req.query;
const svg = `
<svg width="1200" height="630" viewBox="0 0 1200 630" xmlns="http://www.w3.org/2000/svg">
<rect fill="#1a202c" width="1200" height="630"/>
<text x="60" y="200" font-size="80" fill="#fff" font-family="Inter, Arial, sans-serif" font-weight="bold">
${escapeXml(decodeURIComponent(String(title)))}
</text>
<text x="60" y="300" font-size="40" fill="#CBD5E1" font-family="Inter, Arial, sans-serif">
${escapeXml(decodeURIComponent(String(author)))}
</text>
</svg>
`;
res.setHeader('Content-Type', 'image/svg+xml');
res.setHeader('Cache-Control', 'public, max-age=86400');
res.status(200).send(svg);
}
// Simple XML escaping to prevent injection
function escapeXml(str: string) {
return str.replace(/[<>&'"]/g, char => (
{ '<': '<', '>': '>', '&': '&', "'": ''', '"': '"' }[char]!
));
}
This endpoint dynamically generates SVG images based on the title and author query parameters. The escapeXml function ensures user input doesn't break your SVG.
Step 2: Converting SVG to PNG (Optional)
Many social platforms (like Twitter and Facebook) require OG images to be in JPEG or PNG format. While SVG is great for generation, you’ll often need to serve a rasterized version.
Using @resvg/resvg-js for Server-side Rendering
Install the package:
npm install @resvg/resvg-js
Update your handler to convert SVG to PNG:
import { Resvg } from '@resvg/resvg-js';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
// ... SVG generation as above ...
const resvg = new Resvg(svg, { fitTo: { mode: 'width', value: 1200 } });
const pngData = resvg.render().asPng();
res.setHeader('Content-Type', 'image/png');
res.setHeader('Cache-Control', 'public, max-age=86400');
res.status(200).end(pngData);
}
Now, your endpoint returns a PNG image, suitable for use as a Next.js OG image.
Step 3: Configuring Open Graph Meta Tags
Next, include your dynamic OG image in your Next.js pages. In your page or layout component:
import Head from 'next/head';
export default function BlogPost({ title, author }) {
const ogImageUrl = `/api/og?title=${encodeURIComponent(title)}&author=${encodeURIComponent(author)}`;
return (
<>
<Head>
<meta property="og:image" content={ogImageUrl} />
<meta name="twitter:image" content={ogImageUrl} />
<meta property="og:type" content="website" />
{/* other meta tags */}
</Head>
{/* page content */}
</>
);
}
Now, every page can have a unique, dynamically generated OG image.
Step 4: Designing Richer SVG Templates
SVG gives you full control over design. Beyond text, you can add:
- Custom backgrounds or gradients
- Logos and icons (inline SVG paths or
<image>tags) - Author avatars (by fetching and embedding user images)
For example, to include a logo and a gradient background:
const svg = `
<svg width="1200" height="630" viewBox="0 0 1200 630" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="gradient" x1="0" y1="0" x2="1200" y2="630" gradientUnits="userSpaceOnUse">
<stop stop-color="#6366f1"/>
<stop offset="1" stop-color="#0ea5e9"/>
</linearGradient>
</defs>
<rect fill="url(#gradient)" width="1200" height="630"/>
<image href="https://yourcdn.com/logo.svg" x="60" y="60" width="100" height="100"/>
<text x="180" y="120" font-size="60" fill="#fff" font-family="Inter, Arial, sans-serif" font-weight="bold">
${escapeXml(decodeURIComponent(String(title)))}
</text>
<!-- more SVG elements -->
</svg>
`;
Step 5: Caching and Performance
Generating images on-demand can be resource-intensive. Use caching strategies to improve performance:
-
HTTP caching: Set appropriate
Cache-Controlheaders. - Edge functions/CDN: Deploy your endpoint to the edge (Vercel, Netlify Edge Functions) for low-latency responses.
- Serverless cold starts: Minimize dependencies and avoid heavy libraries if possible.
Testing Your Dynamic Social Images
To preview your OG images:
- Use the Open Graph Debugger (Facebook)
- Try the Twitter Card Validator
- Share links in Slack or Discord to see how previews render
Beyond Hand-Crafted SVG: Existing OG Image Generator Tools
If you want more advanced designs without hand-coding SVG, several tools can help:
-
Vercel OG Image Generation: Vercel’s
@vercel/oglibrary allows you to create images using React components. - Satori: Used by Vercel under the hood; renders React to SVG/PNG.
- Puppeteer/Playwright: For complex, browser-rendered images.
- IcoGenie, Cloudinary, and Bannerbear: Platforms that automate dynamic social image generation with templates and APIs.
These solutions can save time if you need rich layouts, custom fonts, or want a no-code/low-code workflow.
Key Takeaways
- Dynamic OG images personalize social previews, increasing engagement and professionalism.
- SVG is a powerful foundation for an og image generator: flexible, scalable, and easy to generate on the fly.
- Next.js API routes make it easy to serve dynamic social images for every page.
- Convert SVG to PNG for compatibility with major social platforms.
- Consider existing tools like
@vercel/og, Satori, or third-party platforms for advanced features or template-based workflows.
With these techniques, you can automate and elevate your Open Graph images, ensuring every page on your Next.js site looks great when shared across the web.
Top comments (0)