In today’s digital landscape, Open Graph (OG) images play a crucial role in enhancing the visibility and appeal of your web content when shared on social media. This blog explores the implementation of dynamic OG images using Next.js, covering everything from basic concepts to advanced techniques.
Open Graph (OG) is a protocol used to integrate web pages into the social graph. An OG image is a powerful tool that appears when a web page link is shared on social media platforms like Facebook, Twitter, and LinkedIn. These images help attract attention, increase click-through rates, and improve overall user engagement.
To include an OG image in your webpage, you need to add specific meta tags in the head section of your HTML:
<head>
<meta property="og:title" content="Your Page Title" />
<meta property="og:description" content="Your page description" />
<meta property="og:image" content="https://example.com/og-image.jpg" />
<meta property="og:url" content="https://example.com/page-url" />
</head>
Different platforms have unique requirements for image display. For example, a Twitter OG image might render differently than Facebook. When implementing a NextJS dynamic OG image, you'll need to account for these platform-specific variations to ensure consistent presentation.
Dynamic OG images are particularly beneficial for websites employing white-hat SEO practices. They allow websites to customize images based on content and user data, enhancing visual appeal and contributing to improved click-through rates on social media. This approach makes content more shareable and engaging. Some common benefits of dynamic OG images include:
Next.js provides a robust and efficient solution for generating dynamic OG images. With its server-side rendering capabilities and built-in optimizations, Next.js makes it easier to create, customize, and deploy dynamic OG images seamlessly.
Let's walk through a Blueprint to implement OG images using the @vercel/og library for Next.js open graph image generation:
import { ImageResponse } from '@vercel/og';
export const config = {
runtime: 'edge',
};
export default async function handler(req) {
const { title, description } = req.query;
return new ImageResponse(
(
<div style={{ fontSize: 42, color: 'white', background: 'black', width: '100%', height: '100%', padding: '20px' }}>
<h1>{title}</h1>
<p>{description}</p>
</div>
),{ width: 1200,height: 630,}
);
}
The Generated OG Image in Meta Tags, In your page component, dynamically set the meta tags:
import Head from 'next/head';
const Page = ({ title, description }) => (
<> <Head>
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:image" content={`/api/og-image?title=${title}&description=${description}`} />
</Head>
<h1>{title}</h1>
<p>{description}</p>
</>
);
export default Page;
Step 1: Install the Next.js starter project using
pnpm create next-app
Step 2: Once you have the next js starter project running, go inside the directory of your project and run the project using the following command
pnpm dev
Step 3: Navigate to /pages or /app depending upon if you have installed page router or app router in your next.js app; inside this folder, we’ll make a sample page whose dynamic OG image we would make a sample page of:
Below is the Barbone page whose OG image we will be generating
Experience seamless collaboration and exceptional results.
Experience seamless collaboration and exceptional results.
This above page contains meta tags that’ll help us generate the OG image for preview links, for simplicity purposes we’ll keep it to a bare minimum.
<meta property="og:title" content="Next.js" />
<meta property="og:description" content="The React Framework for the Web" />
<meta property="og:url" content="https://example.org/" />
<meta property="og:site_name" content="" />
<meta property="og:locale" content="en_US" />
<meta property="og:image:url" content="" />
<meta property="og:image:url" content="https://nextjs.org/og-alt.png" />
<meta property="twitter:image" content={""} />
<meta property="twitter:card" content="summary_large_image" />
With the index page out of the way, we now move to the dynamic Image generation part. Here, as discussed, we'll be using the next/OG library.
Some important things to note:
The library @vercel/og only supports the Edge runtime. The default Node.js runtime will not work.
In the Edge runtime, resources like fonts and images are loaded using the fetch method.
Moving on;
vercel/og library extends an ImageResponse constructor, which essentially converts our HTML, CSS template to an Image. Upon conversion to this image, we simply embed this URL to our desired page meta tags and get dynamic custom OG preview images.
We will now create a customTemplate file under the API directory in our next app.
In this custom template file, we will make our template that will be used to generate dynamic OG images.
To make a Dynamic OG Template, we’ve styled a simple layout that shows the logo, blog title and description.
Note:- Title and description are dynamic and are fetched from the page where the meta OG tag will be embedded.
This barebones OG template looks like this:
With the custom template out of the way, we’ll now fetch the title and description using server-side req:NextRequest.
import { NextRequest } from 'next/server'
// fetching the Params from the url
const { searchParams } = req.nextUrl
const title = searchParams.get('title')
const desc = searchParams.get('desc')
With all this done, we go back to our main index file, and look at adding those empty metatags with relevant data,
// Actual code snippet
const blogTitle = 'Dynamic OG Images in Next.js'
const blogDesc = 'Boost Your SEO and User Engagement'
// meta tags used
<Head>
<title>Dynamic OG Images in Next.js</title>
<meta property="og:title" content="Dynamic OG Images in Next.js" />
<meta property="og:description" content="Boost Your SEO and User Engagement" />
<meta property="og:site_name" content={'f22/Blogs'} />
<meta property="og:url" content={`${process.env.NEXT_PUBLIC_VERCEL_PROJECT_PRODUCTION_URL ? 'https://' + process.env.NEXT_PUBLIC_VERCEL_PROJECT_PRODUCTION_URL : ''
}`} />
<meta property="og:image"
content={
`${process.env.NEXT_PUBLIC_VERCEL_PROJECT_PRODUCTION_URL ? 'https://' + process.env.NEXT_PUBLIC_VERCEL_PROJECT_PRODUCTION_URL : ''
}/api/customTemplate?title=${blogTitle}&desc=${blogDesc}`} />
<meta property="twitter:image" content={`${process.env.NEXT_PUBLIC_VERCEL_PROJECT_PRODUCTION_URL ? 'https://' + process.env.NEXT_PUBLIC_VERCEL_PROJECT_PRODUCTION_URL : ''
}/api/customTemplate?title=${blogTitle}`} />
<meta property="twitter:card" content="summary_large_image" />
</Head>
The breakdown of what the above code snippet contains and what it does:
1. Variables:
2. Meta Tags
Inside the <Head> component, several meta tags are used which will help in social sharing and SEO capabilities of the blog post:
This concludes the implementation of Dynamic OG Image generation.
Finally, whenever this page's URL is visited, a dynamic Open Graph (OG) image is generated. The process is that the URL provides the blog title and description via URL query which our HTML-CSS template uses to construct a page.
The ImageResponse function then converts this HTML template page into an image and serves it using an edge compute function.
Now after deploying our application, if we share its URL link on any social media, it will look like this:
1. On Twitter (X):
2. On Slack:
3. On Facebook
4. On LinkedIn
5. On Discord
6. On WhatsApp
1. Image Caching Issues:
Use unique query parameters to force social media platforms to fetch the latest OG image.
2. Incorrect Meta Tag Configurations
Double-check meta tag properties and ensure URLs are absolute paths.
1. Optimal Dimensions
1200x630 pixels for best display on social media.
2. File Size
Keep it under 300 KB to ensure fast loading.
3. Text Readability
Use large, bold fonts and high-contrast colours.
You can customize OG images based on various factors:
1. Page Types
Different OG images for product pages, blog posts, etc.
2. User Data
Personalize OG images with user-specific information.
3. Dynamic Elements
Change OG images based on time of day, events, or promotions.
1. Generation and Loading:
Generation and Loading Optimize image generation code for performance (Use Next.js image API).
2. Caching Strategies:
Use caching headers and CDNs to reduce server load and improve response times. This is particularly important for boosting image performance.
Alternative methods to generate dynamic OG images:
Dynamic OG images significantly enhance your web content’s shareability and attractiveness on social media. By leveraging Next.js’s OG image capabilities, you can efficiently implement and optimize these images, leading to improved SEO and user engagement.
Whether you’re personalizing content for users or optimizing for different platforms, @vercel/og provides a versatile and robust solution.
Web Developer, cricket and finance enthusiast.