10

I'm working on a Gatsby app with Netlify CMS (and hosted on Netlify). Trying to get the metadata working so that Twitter cards display correctly with images.

The metadata is generally all right, but the images aren't showing on the Twitter validator or if I try to post to Twitter. The problem is clearly the images themselves, which are hosted on the site using Gatsby and Gatsby Image Sharp to render.

In fact, the validator seems to show no fundamental issues. Simply, the image doesn't show up:

validator

Example relevant metadata:

<meta name="twitter:url" content="https://example.com/" data-react-helmet="true">
<meta name="twitter:image" content="https://example.com/static/12345/c5b20/blah.jpg" data-react-helmet="true">
<meta data-react-helmet="true" name="twitter:title" content="Site title">
<meta data-react-helmet="true" name="twitter:card" content="summary_large_image">

I know the images the issue, because if I replace my image URL (which is the full image URL) with an external URL, it works fine, showing the full card with image.

Any idea what could be causing this? I'm sizing the image down so it loads quickly, and it seems to load just fine directly (eg). (I mean, is there something weird/off about that image?)

NOTE: In a previous version of this question, I referenced Cloudinary and Uploadcare, but have since removed those two in a branch to simplify the problem. (They seem to have been unecessary holdovers from the starter app I used.) You can now see an example page for that branch here and the associated image in the twitter:image tag here. I feed this pre-processed/shrunk image into the header using React Helmet (and Gatsby React Helmet) and using the following code in my GraphQL call to get the image associated with the blogpost in that particular, smaller format:

    featuredimage {
      childImageSharp {
        fixed(width: 480, quality: 75) {
          src
        }
    }

Second Note/thought: Should I be worried about the fact that the pages in production seem to be re-rendering on every reload? Isn't SSR supposed to ensure that doesn't happen? I tested this by including a call to Math.random(), hidden, in the page. You can see the result by running document.getElementsByClassName('document')[0].children[0].innerText, and note that it produces a different number on each page reload. This implies to me that the whole page is being re-rendered by the client. Isn't that wrong? Why would that be happening? Might that relate to some sort of client processing of the images on each request, which might be screwing up the Twitter cards?

Third update: I put together a simpler reproduction here. It's based off of this starter template, with Uploadcare/Cloudinary removed and Twitter card metadata added to the header. Other than that, and removing unnecessary pages, I didn't make any other changes. I used this starter for a repro rather than a vanilla starter app, because I'm unsure whether the issue is caused by the interaction of Netlify CMS and the Gatsby Sharp Image plugin. I might try to put together a second reproduction. For now, the code for this repo is here, and the pages that should show Twitter cards are the blog posts, such as this one.

ACTUALLY, it seems that a super basic reproduction, with Gatsby 3 and no Netlify CMS or anything, has the same issue. Here's the minimal reproduction, with the image taken from src/images using an allImageSharp query and inserted into the metadata for each page. Code here.

FINAL UPDATE

Based on Derek's answer below, I removed the @reach/router stuff, and got the site URL from Netlify build env variables. It appeared that @reach/router only gave this information when JS was running, which excluded the Twitterbot, resulting in an undefined base URL, which broke the Twitter image. Including the URL from Netlify (using process.env.URL in the Gatsby config and pulling that in through a siteMetadata query) fixed the problem!

Sasha
  • 6,224
  • 10
  • 55
  • 102

2 Answers2

3

Update:

I think I might have found the issue. When opening the minimal production with script disabled, the url for twitter:image is invalid:

<meta data-react-helmet="true" name="twitter:image" content="undefined/static/03475800ca60d2a62669c6ad87f5fda0/58026/energy.jpg">

Original

So for some reasons, during build, the hostname is missing, but when JS kicks in, it appears (Might have something to do with the way you get the hostname). Twitter crawlers probably does not have JS enabled & couldn't fetch the image.

Make sure your opengraph images are absolute urls with https:// or http:// protocols. I checked your example link & saw that it was a relative link (/static/etc.)

For Twitter, it seems to demand social cards to be 2:1

Images for this Card support an aspect ratio of 2:1 with minimum dimensions of 300x157 or maximum of 4096x4096 pixels.

https://developer.twitter.com/en/docs/twitter-for-websites/cards/overview/summary-card-with-large-image

If you're using the latest Gatsby image plugin, you can use aspectRatio to crop the image.

Also note that you can skip the twitter:image tag, if your og:image has already satisfied Twitter's card requirement.

SSR does not mean to never run JS in the client, React will render your page on the client side regardless of SSR.

Derek Nguyen
  • 11,294
  • 1
  • 40
  • 64
  • Thanks. Updated to give the full URL for the OG image, but no dice with Twitter cards still: https://60c8ed6c2c262200072c2025--infallible-cray-5d6a51.netlify.app/esg-divestment/ – Sasha Jun 15 '21 at 18:16
  • @Sasha I check your site against [the Facebook debugger](https://developers.facebook.com/tools/debug) and it loads the image just fine, so I think Twitter is being picky about your image. I've updated the answer to include a link to Twitter spec. – Derek Nguyen Jun 16 '21 at 04:07
  • Just FYI, changing the aspect ratio (and falling back to the `og:image`) didn't work either. Also tried a couple robots.txt variants, and no dice. This is a truly perplexing issue, IMO. – Sasha Jun 21 '21 at 19:40
  • @Sasha hah, that's perplexing indeed. If you update the question with a minimal reproducible example (i.e a Gatsby site with nothing but an og image + twitter header tags), I'll put a 100 point bounty on this question on your behalf. – Derek Nguyen Jun 22 '21 at 01:04
  • Added a simpler reproduction, though not as simple as you asked for, because I wanted it to be similar to my app, which uses Netlify CMS. This is actually the same template I built my app on. No presh re the bounty if you'd rather a simpler reproduction. I might try to add that as well. – Sasha Jun 23 '21 at 21:49
  • A super minimal reproduction has been added above. – Sasha Jun 23 '21 at 22:26
  • Thanks Sasha! Indeed the twitter:image tag doesn't show up, despite everything satisfy the docs, I'll add a new bounty – Derek Nguyen Jun 24 '21 at 03:12
  • Hey Sasha, might have a clue as why your image is not rendering — I've update the question. Will leave the bounty for you or someone who can show code changes that will fix the issue. – Derek Nguyen Jun 24 '21 at 03:20
  • Your solution worked!! This should be your bounty, lol. – Sasha Jun 24 '21 at 17:27
3

This was solved here: https://github.com/gatsbyjs/gatsby/discussions/32100.

"location and thus origin is not available during gatsby build and thus the generated HTML has undefined there."

I got it working by changing the way I create the image URL inside seo.js from this:

let origin = "";
if (typeof window !== "undefined") {
  origin = window.location.origin;
}
const image = origin + imageSrc;

to this:

const imageSrc = thumbnail && thumbnail.childImageSharp.fixed.src;
const image = site.siteMetadata?.siteUrl + imageSrc;

You need to use siteUrl from siteMetadata.

Below is my pageQuery from inside blog-post.js:

export const pageQuery = graphql`
  query BlogPostBySlug(
    $id: String!
    $previousPostId: String
    $nextPostId: String
  ) {
    site {
      siteMetadata {
        title
        siteUrl
      }
    }
    markdownRemark(id: { eq: $id }) {
      id
      excerpt(pruneLength: 160)
      html
      frontmatter {
        title
        date(formatString: "MMMM DD, YYYY")
        description

        thumbnail {
          childImageSharp {
            fixed(width: 1200) {
              ...GatsbyImageSharpFixed
            }
          }
        }
        
      }
    }   
  }
`
Cole S
  • 408
  • 1
  • 3
  • 13