Level up your link previews with code-generated og images

24 Apr 2024 10 min read

JavaScript

In this article I will show you how to create custom Open Graph images for your website using Puppeteer, a headless browser automation library. This will allow you to enhance the visual appeal of your shared URLs on social media platforms, boosting click-through rates and SEO.

Level up your link previews with code-generated og images

What are meta tags?

Meta tags are snippets of text that describe a page’s content. They are added to the HTML code of a webpage and are used by search engines to understand the content of the page. Meta tags can also be used to provide information about the page to social media platforms when the page is shared.

Open Graph (OG) meta tags are a specific type of meta tag that are used to provide information about a page when it is shared on social media platforms like Facebook, X (Twitter), and LinkedIn. Open Graph tags include information such as the title, description, and image of the page.

Why custom Open Graph images?

When you share a URL on social media platforms, the platform will automatically generate a preview of the page. This preview includes the title, description, and image of the page. By default, if a page does not have an Open Graph image specified, the platform will generate a boring preview with just the title and description.

In order to make your shared URLs more visually appealing and engaging, it is important to provide a custom Open Graph image for each page on your website. This will help to make your shared URLs stand out from the crowd and increase the likelihood that users will click on them.

Puppeteer Library for generating Open Graph images

Puppeteer🔗 is a Node.js library which provides a high-level API to control Chrome/Chromium over the DevTools Protocol. Puppeteer runs in headless mode by default, but can be configured to run in full (“headful”) Chrome/Chromium.

We will use Puppeteer to generate custom Open Graph images for our website. The basic idea is to take a screenshot of the page using Puppeteer and then use that screenshot as the Open Graph image for the page.

Practical example

Let’s build a simple application that generates custom Open Graph images for our website. I will use Astro🔗, Tailwind🔗, and Puppeteer🔗 but you can use any Node based environment.

1. Application setup

First, create a new Astro project and navigate to the project directory:

npm create astro@latest my-og-image-generator
# or
pnpm create astro@latest my-og-image-generator
# or
yarn create astro@latest my-og-image-generator

Next, install the Puppeteer library:

npm i puppeteer
# or
pnpm add puppeteer
# or
yarn add puppeteer

2. Template creation

Here you will create a new directory called templates (Optional) in the src directory. This directory will contain the HTML templates that will be used to generate the Open Graph image.

Create a new file called hello-world.html in the templates directory with a content like this:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://cdn.tailwindcss.com"></script>
    <title>Hello, World</title>
  </head>
  <body>
    <div class="h-screen w-full">
      <div class="flex h-[630px] w-[1200px] items-center justify-center border-8 border-[#3ec4db] bg-black">
        <h1 class="text-6xl font-bold text-[#3ec4db]">Hello, World!</h1>
      </div>
    </div>
  </body>
</html>

The hello-world.html file is an HTML example that will generate a box with the size of 1200px by 630px as the recommended size 🔗 for Open Graph images. You can customize the template to suit your needs.

Note: In the template, I’m using Tailwind CSS to style the HTML elements. You can use any CSS framework or custom styles to design the Open Graph image.

3. Create Puppeteer script

You will create a file that runs using nodejs, beacause I’m using Astro, I will create a file in the pages directory with *.js or *.ts extension. The created file will be executed on the server while the page is being built.

import type { APIRoute } from "astro";
import fs from "fs/promises";
import puppeteer from "puppeteer";
import path from "path";
import { fileURLToPath } from "url";
 
export const GET: APIRoute = async function get({}) {
  const browser = await puppeteer.launch();
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
  const htmlTemplatePath = path.join(__dirname, "../../src/templates/hello-world.html");
  try {
    const page = await browser.newPage();
    const htmlContent = await fs.readFile(htmlTemplatePath, "utf8");
    await page.setContent(htmlContent);
    const screenshotBuffer = await page.screenshot({
      type: "png",
      fullPage: true,
    });
    return new Response(screenshotBuffer, {
      headers: { "Content-Type": "image/png" },
    });
  } catch (error) {
    return new Response("Internal Server Error", { status: 500 });
  } finally {
    await browser.close();
  }
};
  • Implement the GET function that will be executed when the page is being built.
  • Load the HTML template content from the hello-world.html file.
  • Create a new page in Puppeteer and set the content of the page to the HTML template.
  • Take a screenshot of the page and return the screenshot as a response.

Note: In Astro, the generated image will be saved as the prefix of the named File. For example, if the file is named hello.png.ts, the generated image will be hello.png.

4. Add the image in the meta tags

Now that you have the custom Open Graph image generated, you can add it to your meta tags header component of your website as shown below:

<meta name="image" content="/hello.png" /> <meta property="og:image" content="/hello.png" />

This will ensure that the custom Open Graph image is used when the page is shared on social media platforms.

For Astro you can add the the path to the image in two ways:

  • Using frontmatter and astro APIs:
---
const { href } = Astro.url;
---
 
<meta name="image" content={`${href}.png`} />
<meta property="og:image" content={`${href}.png`} />
  • Using the page route, for example, if the page route is /blog/og-image, you have to add the path to the image /blog/og-image.png:
<meta name="image" content="/blog/og-image.png" />
<meta property="og:image" content="/blog/og-image.png" />

5. Build and test the application

After following the steps above, you can build and test the meta images by checking the build directory and find out if the image is generated or not.

If everything is working as expected, you can deploy the application to your server or a cloud provider, you can check your website using metatags.io🔗 to see the Open Graph image generated.

Conclusion

In this article, I have shown you how to create custom Open Graph images for your website using Puppeteer. By providing custom Open Graph images for your shared URLs, you can enhance the visual appeal of your website and increase click-through rates and SEO. I hope you found this article helpful and that you will be able to use Puppeteer to create custom Open Graph images for your website. If you have any questions or comments, please feel free to contact me.

You can find the full source code for this project on GitHub🔗

happy coding! 🚀

Resources