Search code examples
reactjsgatsbyreact-helmetgatsby-image

How to set FuturedImage to og: image. in gatsby.js


I using gatsby.js.

I want to set the featuredimage described in markdown in the og: image attribute of the meta tag, but it does not work.

The featuredimage is optimized for different paths by gatsby, but the relative path is set to the physical path before build.

How do I set the path for the featuredimage created by the build?

My React Helmet code (excerpt):

<Helmet
    meta={{
      property: `og:image`,
      content: `https://example.com/${post.frontmatter.featuredimage.relativePath}`
    }}
 />

My GraphQL query:

export const pageQuery = graphql`
  query($slug: String!) {
    site {
      siteMetadata {
        title
        author
      }
    }
    mdx(fields: { slug: { eq: $slug } }) {
      frontmatter {
        featuredimage {
          relativePath
          childImageSharp {
            fluid(maxWidth: 400, quality: 100) {
              ...GatsbyImageSharpFluid
            }
          }
        }
      }
    }
  }
`

Thanks.


Solution

  • You can query path of generated image (format is '/static/name') and use it with site root url like:

    export const pageQuery = graphql`
      query($slug: String!) {
        site {
          siteMetadata {
            title
            author
          }
        }
        mdx(fields: { slug: { eq: $slug } }) {
          frontmatter {
            featuredimage {
              childImageSharp {
                original {
                  src
                }
              }
            }
          }
        }
      }
    `
    
    <Helmet
        meta={{
          property: `og:image`,
          content: `${siteUrlRoot}${post.frontmatter.featuredimage.childImageSharp.original.src}`
        }}
     />