Boost Site Engagement with Dynamic Open Graph Images in Next.js

Dynamic Open Graph Images in Next.js

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.

Using OG Images in Meta Tags

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>

Challenges in Creating Dynamic OG Images

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.

SEO Benefits of Dynamic OG Images

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:

  • Improving click-through rates on social media.
  • Making your content more shareable and attractive.
  • Increasing overall engagement and traffic to your website.

Why @vercel/og is the Optimal Solution

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.

Terminologies Used in @vercel/og Implementation

  • Server-side rendering (SSR): This refers to generating HTML content on the server based on the request.
  • Static site generation (SSG): This means pre-rendering pages at build time.
  • API routes: It refers to creating API endpoints in Next.js.
  • Image optimization: It means techniques to reduce image load times and improve performance.

Implementing next-js/og: Blueprint

Let's walk through a Blueprint to implement OG images using the @vercel/og library for Next.js open graph image generation:

  • Install @vercel/og Library
  • Install @Vercel/og
  • Create API Route for Dynamic OG Image Generation
  • Create a file named pages/api/og-image.js:
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;

Full Implementation of Dynamic OG images with custom template and Edge function

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

Dynamic OG output Preview

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 tags in the <Head/> for the above page

<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:

 Barebones OG template

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:

  • blogTitle: Contains the title of the blog post, 'Dynamic OG Images in Next.js'.
  • blogDesc: Contains the description of the blog post, 'Boost Your SEO and User Engagement'.

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:

  • <title>: Sets the browser tab title to 'Dynamic OG Images in Next.js'.
  • <meta property="og:title">: Specifies the Open Graph title for platforms like Facebook. It uses the blogTitle variable.
  • <meta property="og:description">: Specifies the Open Graph description for platforms like Facebook. It uses the blogDesc variable.
  • <meta property="og:site_name">: Specifies the site name as 'f22/Blogs'.
  • <meta property="og:url">: Specifies the canonical URL of the blog post. It dynamically constructs the URL based on the environment variable.
  • <meta property="og:image">: Specifies the image to be used when the blog post is shared on platforms like Facebook. It dynamically generates the image URL using blogTitle, blogDesc, and the URL.
  • <meta property="twitter:image">: Specifies the image to be used when the blog post is shared on Twitter. It also dynamically generates the image URL using blogTitle and URL.
  • <meta property="twitter:card">: Specifies the type of Twitter card to use, in this case, 'summary_large_image'.
  • The NEXT_PUBLIC_VERCEL_PROJECT_PRODUCTION_URL environment variable is used to construct URLs. It checks if this variable is defined and constructs URLs accordingly. This ensures that the meta tags correctly point to the production URL 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):

Dynamic OG image preview on Twitter

2. On Slack:

Dynamic OG image preview on Slack

3. On Facebook

Dynamic OG image preview on Facebook

4. On LinkedIn

Dynamic OG image preview on Next.js

5. On Discord

Dynamic OG image preview on Discord

6. On WhatsApp

Dynamic OG image preview on Whatsapp

Common Issues

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.

Best Practices for Designing OG Images

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.

Customization Options

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.

Optimization Tips

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.

Techniques to Generate Dynamic OG Images (For Non-Next.js Users)

 Alternative methods to generate dynamic OG images:

  • Server-side rendering using frameworks like Express.js or Django.
  • Client-side libraries such as Puppeteer to capture screenshots of dynamically generated content.
  • Third-party services like  AWS, Cloudinary, etc that offer dynamic image generation APIs.

Conclusion

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.