How to Create Dynamic Open Graph Images with Next.js

How to Create Dynamic Open Graph Images with Next.js

Open Graph (OG) images help your shared links look better on social media. They show a preview image when your link is shared, which can boost engagement. In this guide, we will learn how to create dynamic OG images using Next.js, making your content more attractive.

What Are Open Graph Images?

These images are part of the Open Graph protocol, which lets you control how your URLs look when shared on social media. The main elements are the title, description, and image. For example, when you share a link on Facebook or Twitter, the OG image will show up with the link.

Why Use Dynamic OG Images?

Static OG images are good, but dynamic OG images are even better. With dynamic OG images, you can make unique images for each page or piece of content on your website. This makes your links more personalized and attractive. For example, if you have a blog, each post can have a unique OG image with the post title and author.

Setting Up Next.js

First, make sure you have Next.js set up. If you don't, you can create a new Next.js app with the following command

npx create-next-app og-image-app
cd og-image-app

Installing Necessary Packages

To generate images dynamically, we'll use a package called @vercel/og. Install it by running

npm install @vercel/og
OR
yarn add @vercel/og

Creating the OG Image Generation Endpoint

Next, create an API route to generate the OG images. Inside the pages/api directory, create a new file called og.js. This file will have the code to create the dynamic images.

import { ImageResponse } from '@vercel/og';

export const config = {
  runtime: 'edge',
};

export default function handler(req) {
  const { searchParams } = new URL(req.url);
  const title = searchParams.get('title') || 'Default Title';
  const description = searchParams.get('description') || 'Default Description';

  return new ImageResponse(
    (
      <div
        style={{
          display: 'flex',
          height: '100%',
          width: '100%',
          alignItems: 'center',
          justifyContent: 'center',
          flexDirection: 'column',
          color: '#fff',
          fontSize: 60,
          fontFamily: 'Arial, sans-serif',
          backgroundColor:
            'gradient(linear, 0% 0%, 0% 100%, from(#f55), to(#55f))',
        }}
      >
        <div style={{ marginBottom: 20 }}>{title}</div>
        <div style={{ fontSize: 30 }}>{description}</div>
      </div>
    ),
    {
      width: 1200,
      height: 630,
    }
  );
}

This code creates an API endpoint at /api/og. When you visit this endpoint with title and description query parameters, it generates an image with that information.

Using the OG Image in Your Pages

Now that you have an endpoint to create OG images, you can use it in your Next.js pages. Here’s how to add it to the head of a page

import Head from 'next/head';

export default function BlogPost({ title, description }) {
  const ogImageUrl = `/api/og?title=${encodeURIComponent(title)}&description=${encodeURIComponent(description)}`;

  return (
    <>
      <Head>
        <title>{title}</title>
        <meta property="og:title" content={title} />
        <meta property="og:description" content={description} />
        <meta property="og:image" content={ogImageUrl} />
      </Head>
      <main>
        <h1>{title}</h1>
        <p>{description}</p>
      </main>
    </>
  );
}

export async function getStaticProps() {
  const title = 'My Blog Post';
  const description = 'This is a description of my blog post.';

  return {
    props: {
      title,
      description,
    },
  };
}

In this example, the BlogPost component gets the title and description (maybe from a CMS or API) and creates the OG image URL using these values.

Testing Your Dynamic OG Images

To test your dynamic OG images, deploy your Next.js application and share a link on social media. You should see the OG image with the title and description you provided. You can also use tools like Facebook's Sharing Debugger or Twitter's Card Validator to preview how your OG images will appear.

If you want to test the OG image locally, start the dev server and call the /api/og endpoint with title and description query parameters.

yarn run dev
OR 
npm run dev

Go to http://localhost:3000/api/og?title="My Blog Post"&description="This is a description of my blog post"

Conclusion

Dynamic OG images can make your shared links more engaging and personal. With Next.js and @vercel/og, setting this up is simple and effective. By following this guide, you can create unique OG images for each page on your site, boosting your content's visibility and appeal on social media.

That's all for this topic. Thank you for reading! If you found this article helpful, feel free to contact us to discuss further.

Resources