Skip to content

Gatsby open graph meta tags are not recognized

The plugin gatsby-plugin-react-helmet is helpful to generate og meta tags but I recently noticed that facebook and twitter stopped to recognize the meta tags in my site.

Looking for a solution, I discovered that other people had the same issue and infact there is an open issue on github, at the moment I’m writing this article.

The main problem is that this plugin put all the tags at the bottom of the header and in some projects, when large style tag being placed before the meta tags, Facebook does not always parse the ogtags if they come too late in the head. So the easiest way to resolve the problem is to prioritize Helmet tags in the <head /> tag.

An elegant workaround proposed by ttstauss and Ciantic in this issue:

Create a gatsby-ssr.js in the root of your gatsbyjs project with the following content:

const React = require("react")
const { Helmet } = require("react-helmet")

exports.onRenderBody = (
  { setHeadComponents, setHtmlAttributes, setBodyAttributes },
) => {
  const helmet = Helmet.renderStatic()

exports.onPreRenderHTML = ({ getHeadComponents, replaceHeadComponents }) => {
  const headComponents = getHeadComponents()
  headComponents.sort((x, y) => {
    if (x.props && x.props["data-react-helmet"]) {
      return -1
    } else if (y.props && y.props["data-react-helmet"]) {
      return 1
    return 0

More info about Gatsby Server Rendering APIs and OnPreRenderHTMLfunction here

Note: the content of gatsby-ssr.js worked for me only after gatsby build in production, not with the gatsby develop command