Notion Blog Starter
August 16, 2022
Updated on October 13, 2022
Create Dynamic Open Graph images with Next.js
In this post, I want to show you how to generate dynamic Open graph images with Next.js
article cover

Iโ€™m sure you have heard of Open graph images which are images displayed on social media for the website or blog post

A visual depiction of what is being written about

In this post, I want to show you how to generate dynamic Open graph images with Next.js with just a few steps.

To generate the images we will use a library next-api-og-image and Nextjs API routes.

You might be familiar with the official library that handles Open graph images by nextJS - https://github.com/vercel/og-image. next-api-og-image does pretty much the same but it is plug-and-play without any configuration

In the documentation, we can find the example for OG image with support for React

javascript
import { withOGImage } from 'next-api-og-image'
export default withOGImage({
template: {
react: ({ myQueryParam }) => <div>๐Ÿ”ฅ {myQueryParam}</div>,
},
})

In my case, added support for a tailwind and made this basic template with the date and blog title to render the OG image ad you can see below.

pages/api/og-image.js
import { withOGImage } from 'next-api-og-image';
export default withOGImage({
template: {
react: ({ title, date }) => (
<html>
<div
dangerouslySetInnerHTML={{
__html: `<head>
<script src="https://cdn.tailwindcss.com"></script>
</head>`
}}
/>
<div className="w-[1200px] h-[630px] border flex items-center justify-center p-16">
<div className="flex flex-col items-center justify-center text-center">
<div className="text-2xl">
<div className="">{date}</div>
</div>
<div className="mt-4 mb-8 font-extrabold text-7xl leading-[80px] text-center">
{title}
</div>
</div>
</div>
</html>
)
}
});

What we need to do next is create an API endpoint that resolves the OG image for us.

The route for the API for `/api/og-image` with title and date as parameters. Once we have the imageUrl we can use it in <Head />

Head.tsx
import siteData from 'data/siteData';
import Head from 'next/head';
export function MetaHead(props) {
const { publishedOn, title } = props
const imageUrl = `https://www.phung.io/api/og-image?title=${encodeURIComponent(
title
)}&date=${encodeURIComponent(publishedOn)}`;
return (
<Head>
<title>{titleName}</title>
<meta content={description} name="description" />
<meta property="og:image" content={imageUrl} />
</Head>
);
}

And here is the result ๐ŸŽ‰

A visual depiction of what is being written about

For checking OG image you can use https://www.opengraph.xyz/ or directly check the OG image for this article

Subscribe to the newsletter
Get emails from me about web development, tech, and early access to new articles.
Be the first to know when the blog is published
;