Skip to main content
View plugin on GitHub
See starters using this

gatsby-plugin-og-image

This Gatsby plugin allows you to easily create social media share images for your Gatsby site, and inserts them in an og:image meta tag.

Install

npm install @benborgers/gatsby-plugin-og-image

How to Use

// in plugins array of gatsby-config.js 

{
  resolve: "@benborgers/gatsby-plugin-og-image",
  options: {
    domain: "https://example.com",
    fn: title => {

      if(title === "Home - Example Site") {
        return `
          <style>
            h1 {
              color: rebeccapurple;
            }
          </style>

          <h1>Example Site</h1>
        `
      } else {
        return `
          <style>
            @import url("https://fonts.googleapis.com/css?family=Roboto:700");

            h1, h2 {
              font-family: "Roboto";
              font-weight: 700;
            }

            h2 {
              color: rebeccapurple;
            }
          </style>

          <h2>Example Site</h2>
          <h1>${title}</h2>
        `
      }

    }
  }
}

The plugin requires two options in gatsby-config.js:

  • domain: the base domain of the final hosted site. This will be used for the beginning of the og:image URL.
  • fn: a function that accepts each page title (if the page has one), and returns HTML markup for that page’s share image.

During the build process, the HTML returned by fn will be rendered and screenshotted by a hosted microservice. Then, the resulting image will be saved to your Gatsby output and linked in the og:image meta tag of the final page.

In the example above, one type of share image is rendered for the home page (which we know has a title of “Home - Example Site”), and a standard template is used for all other pages.