Creating Custom Open Graph Image for Each Post in Next.js Static Blog

In previous articles, several methods for improving the SEO of a static blog built on the Next.js platform were discussed, including using the NextSeo component to improve sharing by placing content summaries and titles using Open Graph meta tags. In that article, a static image was used for the Open Graph.

The Open Graph images are one of the key factors in improving your website's ranking on search engines. These images are displayed on social networks and are very important for enhancing the shareability of your posts on these networks.

Cloudinary image service is one of the most popular image storage and processing services on the web. By using Cloudinary, you can easily upload your images and take advantage of its various features to process and optimize your images.

Before any action, to easily and quickly integrate your program with Cloudinary, you need to add the @cloudinary/url-gen package to your project. With this package, you can easily and quickly integrate your work with Cloudinary. To add this package to your project, use the following command.

pnpm add @cloudinary/url-gen

After installing the package, we can import the required modules and create a new instance with our account details and authentication information.

Now, create a file named .env.local in the project's root directory and add the following content to the created file.

CLOUDINARY_CLOUD_NAME=<your_cloud_name>
CLOUDINARY_API_KEY=<your_api_key>
CLOUDINARY_API_SECRET=<your_api_secret>

The following environmental variables will be used to configure the cloudinary object in our code.

Create a new file named cloudinary.ts with the following content in the utils folder in your project root directory.

import { Cloudinary } from '@cloudinary/url-gen'

const cloudinary = new Cloudinary({
  cloud: {
    cloudName: process.env.CLOUDINARY_CLOUD_NAME,
    apiKey: process.env.CLOUDINARY_API_KEY,
    apiSecret: process.env.CLOUDINARY_API_SECRET,
  },
})

export { cloudinary }

Now we can write a function that takes the blog post information as input and returns the Open Graph image URL. In this example, we use the post title as the text on the image.

import { Post } from './posts'
import { source } from '@cloudinary/url-gen/actions/overlay'
import { Position } from '@cloudinary/url-gen/qualifiers'
import { center } from '@cloudinary/url-gen/qualifiers/compass'
import { compass } from '@cloudinary/url-gen/qualifiers/gravity'
import { text } from '@cloudinary/url-gen/qualifiers/source'
import { TextFitQualifier } from '@cloudinary/url-gen/qualifiers/textFit'
import { TextStyle } from '@cloudinary/url-gen/qualifiers/textStyle'
import { cloudinary } from './cloudinary'

export function createOgImageUrl(post: Post): string {
  const image = cloudinary.image('blank.png')

  image.overlay(
    source(
      text(post.title, new TextStyle('Cairo', 48))
        .textFit(new TextFitQualifier(840))
        .textColor('BLACK'),
    ).position(new Position().gravity(compass(center())).offsetX(0).offsetY(0)),
  )

  return image.toURL()
}

In the above code, first we create a new image instance with an empty image. Then, we add a text layer with the post title to the image. We set the font family to Cairo and the font size to 48 pixels. Additionally, we use TextFitQualifier to make sure the text fits inside a width of 840 pixels. Finally, we position the text layer at the center of the image using position and compass.

In the createOgImageUrl function, a Cloudinary object is created that includes the necessary authentication information to create the image. Then, the base image is created using overlay.

Here, text sets the post text using the TextStyle function. This image is set up with textFit and TextFitQualifier to be suitable for an Open Graph image. Finally, the image position is set using compass and position.

To use this function in your Next.js project, you can use the NextSeo component in the next-seo package that we previously covered.

import { NextSeo } from 'next-seo'

type Props = {
  post: Post
}

function Blog({ post }: Props) {
  const ogImageUrl = createOgImageUrl(post)

  return (
    <>
      <NextSeo
        title={`${post.title} - My Blog`}
        description={`${post.content.substring(0, 100)}...`}
        openGraph={{
          url: `https://myblog.com/posts/${post.slug}`,
          title: `${post.title} - My Blog`,
          description: `${post.content.substring(0, 100)}...`,
          images: [
            {
              url: ogImageUrl,
              width: 1200,
              height: 630,
              alt: post.title,
            },
          ],
          site_name: 'My Blog',
        }}
      />
      {/* Display post */}
    </>
  )
}

export default Blog

In this example, createOgImageUrl has been used as the variable ogImageUrl. Values have been provided to configure the Open Graph image.

Overall, using Open Graph images can help improve the ranking of your website and create more appealing and engaging images for your content on social networks. With functions like createOgImageUrl, you can easily create optimized and attractive Open Graph images for your content.

In this article, the createOgImageUrl function was introduced as a powerful tool for creating Open Graph images in Next.js. You can improve this function by referring to the Cloudinary documentation and adding more details and layers.

By using this function and creating attractive Open Graph images, you can help improve the ranking of your website on search engines and allow your users to share appropriate images for their content.