Search code examples
graphqlgatsbycontentful

contentful graphql fetch a link to the image from a content's media field


When using Contentful with Gatsby, how do I retrieve an image from a content's media field via Gatsby's GraphQL? (like a link to the image would do)

Let's say I have a content model called "Article", that contains below 3 fields:

field name field type
title Short text
description Short text
photo Media

I write a content with an image attached to "photo".

When I go to GraphQL and I can find "title" and "description" under allArticle.edges.node., but not "photo".

How do I retrieve media referenced in a content from GraphQL?


Solution

  • There are three options:

    • Your changes are not published: so publish them.
    • You have the previous cache: run gatsby clean and try it again
    • You haven't added any image: so add it (publish your changes)

    Once your image is displayed and the node is created, use a GraphQL fragment to get it or the bunch of parameters needed (contained in the fragment):

    {
      allArticle {
        edges {
          node {
            title
            description
            photo {
              fixed(width: 1600) {
                width
                height
                src
                srcSet
              }
            }
          }
        }
      }
    }