Important: Add OGify packages to This prevents Next.js from bundling OGify packages, which is necessary for proper font loading and image generation.
serverExternalPackages in your next.config.js:Copy
const nextConfig = {
...
experimental: {
serverExternalPackages: ["@ogify/core", "@ogify/templates"],
},
...
};
module.exports = nextConfig;
Using API Routes
Create the API Route
Create a file at
pages/api/og.ts:Copy
import { createRenderer } from '@ogify/core';
import template from '@ogify/templates/basic';
import type { TemplateParams } from '@ogify/templates/basic';
import type { NextApiRequest, NextApiResponse } from 'next';
const renderer = createRenderer<{ basic: TemplateParams }>({
templates: { basic: template },
});
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { title } = req.query;
const imageBuffer = await renderer.renderToImage('basic', {
title: (title as string) || 'Hello World',
layout: 'centered',
});
res.setHeader('Content-Type', 'image/png');
res.send(imageBuffer);
}
Use in Pages
In your pages, point the
og:image meta tag to your API route.Copy
import Head from 'next/head';
export default function Page() {
return (
<>
<Head>
<title>My Page</title>
<meta property="og:image" content="/api/og?title=My Page" />
<meta name="twitter:image" content="/api/og?title=My Page" />
<meta name="twitter:card" content="summary_large_image" />
</Head>
<h1>My Page</h1>
</>
);
}