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>
Creating static OG images for every page can be a tedious and inflexible process, especially for websites with dynamic content. Dynamic OG images, on the other hand, can be customized based on the content, user data, or other factors, providing a more personalized and engaging experience.
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
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
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
Optimize image generation code for performance (Use next/Image API)
2. Caching Strategies:
Use caching headers and CDNs to reduce server load and improve response times.
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 powerful 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.
System Integration Testing (SIT): A Complete Guide
System Integration Testing (SIT) is a crucial phase in software development where individual components are combined and tested as a whole. This guide delves into the significance of SIT, exploring its role in ensuring seamle...
10 Types of Automation Testing You Need To Know
Automation testing has become the unsung hero of the software development world. It's like having a superhero sidekick to save the day by preventing your application from crashing in production. Who needs a 3 a.m. wake-up cal...
Mobile App Development Cost (2024)
Mobile App Development Cost (2024) The mobile app development landscape in 2024 is evolving rapidly, and costs vary widely based on many factors. How much does it cost to develop an app? There is no single answer to this que...