How to Create Dynamic Open Graph Images with Next.js

Search for a command to run...

No comments yet. Be the first to comment.
This series will consist of content such as Technical blogs, Javascript tutorials and the latest tech news on javascript. Stay tuned for updates.
Master the art of memory management in JavaScript.
Quick Summary / Key Takeaways IoT software development is the process of building software that connects devices, sensors, cloud systems, mobile apps, dashboards, and data platforms. A good IoT prod

Quick Summary / Key Takeaways Fintech in UAE is moving beyond digital wallets and mobile banking. The next wave is being shaped by instant payments, open finance, AI agents, unified digital identity,

Quick Summary / Key Takeaways ux design benefits show up directly in conversion rates because better user experience removes doubt, friction, and confusion. UX design helps users move from interest

Quick Summary / Key Takeaways Digital transformation Dubai projects work best when they begin with a business bottleneck, not a shopping list of software. Mid-size companies have a useful advantage.

Quick Summary Enterprise web application development is the work of turning complex business processes into secure, usable browser-based software. These applications are usually built for teams that h

Open Graph (OG) images help your shared links look better on social media. They show a preview image when your link is shared, which can boost engagement. In this guide, we will learn how to create dynamic OG images using Next.js, making your content more attractive.
These images are part of the Open Graph protocol, which lets you control how your URLs look when shared on social media. The main elements are the title, description, and image. For example, when you share a link on Facebook or Twitter, the OG image will show up with the link.
Static OG images are good, but dynamic OG images are even better. With dynamic OG images, you can make unique images for each page or piece of content on your website. This makes your links more personalized and attractive. For example, if you have a blog, each post can have a unique OG image with the post title and author.
First, make sure you have Next.js set up. If you don't, you can create a new Next.js app with the following command
npx create-next-app og-image-app
cd og-image-app
To generate images dynamically, we'll use a package called @vercel/og. Install it by running
npm install @vercel/og
OR
yarn add @vercel/og
Next, create an API route to generate the OG images. Inside the pages/api directory, create a new file called og.js. This file will have the code to create the dynamic images.
import { ImageResponse } from '@vercel/og';
export const config = {
runtime: 'edge',
};
export default function handler(req) {
const { searchParams } = new URL(req.url);
const title = searchParams.get('title') || 'Default Title';
const description = searchParams.get('description') || 'Default Description';
return new ImageResponse(
(
<div
style={{
display: 'flex',
height: '100%',
width: '100%',
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'column',
color: '#fff',
fontSize: 60,
fontFamily: 'Arial, sans-serif',
backgroundColor:
'gradient(linear, 0% 0%, 0% 100%, from(#f55), to(#55f))',
}}
>
<div style={{ marginBottom: 20 }}>{title}</div>
<div style={{ fontSize: 30 }}>{description}</div>
</div>
),
{
width: 1200,
height: 630,
}
);
}
This code creates an API endpoint at /api/og. When you visit this endpoint with title and description query parameters, it generates an image with that information.
Now that you have an endpoint to create OG images, you can use it in your Next.js pages. Here’s how to add it to the head of a page
import Head from 'next/head';
export default function BlogPost({ title, description }) {
const ogImageUrl = `/api/og?title=${encodeURIComponent(title)}&description=${encodeURIComponent(description)}`;
return (
<>
<Head>
<title>{title}</title>
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:image" content={ogImageUrl} />
</Head>
<main>
<h1>{title}</h1>
<p>{description}</p>
</main>
</>
);
}
export async function getStaticProps() {
const title = 'My Blog Post';
const description = 'This is a description of my blog post.';
return {
props: {
title,
description,
},
};
}
In this example, the BlogPost component gets the title and description (maybe from a CMS or API) and creates the OG image URL using these values.
To test your dynamic OG images, deploy your Next.js application and share a link on social media. You should see the OG image with the title and description you provided. You can also use tools like Facebook's Sharing Debugger or Twitter's Card Validator to preview how your OG images will appear.
If you want to test the OG image locally, start the dev server and call the /api/og endpoint with title and description query parameters.
yarn run dev
OR
npm run dev
Go to http://localhost:3000/api/og?title="My Blog Post"&description="This is a description of my blog post"

Dynamic OG images can make your shared links more engaging and personal. With Next.js and @vercel/og, setting this up is simple and effective. By following this guide, you can create unique OG images for each page on your site, boosting your content's visibility and appeal on social media.
That's all for this topic. Thank you for reading! If you found this article helpful, feel free to contact us to discuss further.