Auto Generate Open Graph Images in NextJS

Paulund - May 20 - - Dev Community

Next.js has a feature that allows you to generate Open Graph images using code. This feature is useful when you want to generate images for your blog posts, social media posts, or any other content that requires an image.

In a previous article we looked at Adding Metadata to NextJS in this article, we will look at how to generate Open Graph images using code in Next.js.

Install @vercel/og

The first thing you need to do is install the @vercel/og package. This package is a utility for generating Open Graph images. You can install it using npm or yarn.

npm install @vercel/og
# or
yarn add @vercel/og
Enter fullscreen mode Exit fullscreen mode

Generate Images Using Code

Once you have installed the @vercel/og package, you can start generating images using code. The @vercel/og package provides a generate function that you can use to generate images.

Here is an example of how you can generate an Open Graph image using code:

import { generate } from "@vercel/og";

const image = await generate({
  title: "Hello, World!",
  description: "This is an example Open Graph image",
  theme: "light",
  md: true,
  fontSize: 64,
  images: [
    {
      src: "https://example.com/image.jpg",
      width: 800,
      height: 600,
    },
  ],
});

console.log(image);
Enter fullscreen mode Exit fullscreen mode

In this example, we are generating an Open Graph image with the title "Hello, World!" and the description "This is an example Open Graph image". We are using the light theme, rendering the description in markdown, setting the font size to 64, and using an image as the background.

The generate function returns a base64-encoded image that you can use in your application.

Creating A Image Route

To take advantage of this in a Next.js blog you can create a new route that will generate the Open Graph image for a specific blog post. This route will take the blog post content and generate an image that can be used in the Open Graph meta tags.

In this example we're going to use the ImageResponse to generate the image and return it as a response. Create a new file in app/api/og of route.tsx and add the following code:

import { ImageResponse } from 'next/og';

export async function GET() {
  return new ImageResponse(
    (
      <div
        style={{
          fontSize: 40,
          color: 'black',
          background: 'white',
          width: '100%',
          height: '100%',
          padding: '50px 200px',
          textAlign: 'center',
          justifyContent: 'center',
          alignItems: 'center',
        }}
      >
        👋 Hello, World!
      </div>
    ),
    {
      width: 1200,
      height: 630,
    },
  );
}
Enter fullscreen mode Exit fullscreen mode

This code will generate an Open Graph image with the text "👋 Hello, World!" in the center of the image. The image will have a width of 1200 pixels and a height of 630 pixels.

Navigate to http://localhost:3000/api/og/route to see the generated image.

Blog Posts Open Graph Images

You can use this approach to generate the open graph images for your blog posts.

We will do this by passing in a querystring of the blog post title and use this content to generate the image.

import { ImageResponse } from 'next/og'

export async function GET(request: Request) {
    const { searchParams } = new URL(request.url);

    return new ImageResponse(
        (
            // ImageResponse JSX element
            <div
                style={{
                    background: 'black',
                    width: '100%',
                    height: '100%',
                    display: 'flex',
                    flexDirection: 'column',
                    alignItems: 'center',
                    justifyContent: 'center',
                    padding: '0 100px',
                }}
            >
                <h1 style={{fontSize: 64, color: 'white', display: 'block' }}>
                    { searchParams.get('title') }
                </h1>

            </div>
        ),
        {
            width: 1200,
            height: 630,
        }
    )
}
Enter fullscreen mode Exit fullscreen mode

Now you can navigate to http://localhost:3000/api/og/route?title=Hello%20World to see the generated image with the title "Hello World".

Within you generateMetadata function you can now use this route to generate the Open Graph image for your blog post.

    openGraph: {
            title: post.title,
            description: post.description,
            images: [
                {
                    url: `/api/op?title=${post.title}`,
                    width: 1200,
                    height: 630,
                    alt: post.title,
                    type: "image/png",
                }
            ],
            type: "article"
        },
    }
Enter fullscreen mode Exit fullscreen mode

This will generate the Open Graph image for the blog post with the title of the post.

Now when you share the blog post on social media the image will be generated using the content of the blog post.

This is a great way to generate Open Graph images for your blog posts using code in Next.js.

Technical Details

  • Recommended OG image size: 1200x630 pixels
  • @vercel/og uses Satori and Resvg to convert HTML and CSS into PNG
  • @vercel/og API reference
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .