back

How to generate dynamic open graph images

Oct 17, 2021

6 min read

You might probably think, what is an open graph? This article will show the open graph protocol and how to generate an open graph image for all pages with Next.js.

What is an open graph?

You probably noticed that fancy images appear when you share an url on Facebook, slack or Whatsapp. Those images are called the open graph image, and Facebook created this protocol to use metadata to represent the page's content.

Here is an example of how open-graph metatags look like

I assume that everyone knows how to create a Next.js project. If not, then follow this to get started.

Get Started with an open graph.

To generate an open graph image, we need to install these packages.

To get an idea, we'll see what our final output looks like by navigating to this . We'll get a result like this

From the above output, we can understand the dynamic images are generated based on the url parameters. We need to add this logic to our website by accepting data from url parameters.

In my case, I use tailwind css with Next.js, but you can use any css framework or custom css.

Let's dive deeply to see what's happening in the above code.

First, we need to parse the url to get the data. To do that, import the router from next.js and pass the query params to the . Now use the received data to render the ui per our needs.

While creating an ui, the most recommended size for an og image is 1200 x 630.

Things now we need to do,

  • Navigate to our ui website with the required data.
  • Take a screenshot of our content.
  • Store it in our static folder.
  • Create a script to generate an image on build time

All these points translate into this code.

Let's dive deeper into our code to understand what is happening.

First, we need to get the executable path and options which help us to launch the browser.

Now we need to import the playwright package, start the browser by passing all the values we get from options, and then open a new page and set the viewport size. Now navigate to the respective page url, wait for all the contents to get loaded, and take a screenshot.

We need to store the screenshot in our local folder to do that import file system module. Check whether the file path has already existed or not by using the option inside the function. It'll create a new folder if the file path doesn't exist. Otherwise, use the existing one. After all the checks, use the function to save the screenshots.

Let's set up our prebuild script

That's it for today. I hope you like this article. If you have any questions or comments, let me know on Twitter at or via email at . But until next time, happy coding!

Share this post