I’m sure you have heard of Open graph images which are images displayed on social media for the website or blog post
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
javascriptimport { 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.jsimport { withOGImage } from 'next-api-og-image';export default withOGImage({template: {react: ({ title, date }) => (<html><divdangerouslySetInnerHTML={{__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.tsximport siteData from 'data/siteData';import Head from 'next/head';export function MetaHead(props) {const { publishedOn, title } = propsconst 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 🎉
For checking OG image you can use https://www.opengraph.xyz/ or directly check the OG image for this article