Gatsbyjs and “data-react-helmet” problem
code, webdev, dev, gatsbyjs, react-helmet, react-data-helmet
May 14th 2020 (3 months ago)

The problem

One of projects i’m working on is using GatsbyJs with react-helmet plugin, there is a known problem , that it breaks whatsapp / twitter previews of the page (and propably others at the moment of writing) by adding data-react-helmet as a attribute to head elements.

The solution

since GatbsyJs has a gatbsy-ssr.js part, which allows you to make changes to the given page after it was renderen by gatbsy, you can simply remove some of the content, you don’t need.
exports.onPreRenderHTML = ({ getHeadComponents, replaceHeadComponents }) => {
  // remove generator and `data-react-helmet`
  // since they are breaking some SEO features
  const headComponents = getHeadComponents()
    .map(component => {
      if (component.props && component.props["data-react-helmet"]) {
        // eslint-disable-next-line
        delete component.props["data-react-helmet"]
      }

      return component
    })

  replaceHeadComponents(headComponents)
}
this part of code removes all data-react-helmet attributes from all head content and makes all previews work again properly.

There is a small hiccup with this approach – if the real user goes to the website, some of head attributes will be duplicated, since they will be rerendered by react-helmet as a part of normal browser rendering process, however, this is not important to user in any way, and those tags will be not visible to any crawler.