Skip to main content

Generating dynamic Open Graph image in Next.js

Here's how you can use Pika API to generate dynamic open graph images in your Next.js app

In Next.js 14 with app directory

Create file: /src/app/api/og/route.js with following contents:

export async function GET(req, res) {
const { searchParams } = req.nextUrl;
const title = searchParams.get("title");
const description = searchParams.get("description");

const response = await fetch(
`https://api.pika.style/v1/templates/open-graph-image-1/images`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer YOUR_PIKA_API_KEY`,
},
body: JSON.stringify({
response_format: "binary",
modifications: {
title: title || "Fallback title",
description: description || "Fallback description",
textColor: "#fff",
backgroundImageUrl: "",
backgroundColor: "#111",
},
}),
}
).then((res) => res.blob());

return new Response(response, {
headers: { "content-type": "image/png" },
});
}

This above file is a API handler which takes in dynamic information like Title, Description and returns back image generated from Pika API. Feel free to customize the look by changing backgroundColor, textColor, backgroundImage parameters

Next step is to use this API handler on your dynamic pages. In any of the page.js file, you can call this handler like below to generate Open graph image for that page:

// src/app/blog/blog-post-1

export const metadata = {
title: "Blog Post 1",
description:
"Some description",
openGraph: {
images: "https://YOUR_SITE_ADDRESS/api/og?title=Blog Post 1&description=Some description",
},
};