Contentful reference fields with Gatsby.js & GraphQL

Ville Halminen
2 min readNov 19, 2018

--

Building static sites with Gatsby and Contentful can be a pretty nice experience. Being able to query on build-time using GraphQL enables you to pick just the data you need.

Gatsby creates the GraphQL schema based on the data it fetches from different data sources. This logic works great most of the time but creates a problem with optional fields in Contentful types. If none of your Contentful entries have a value in an optional field, it will never be present in the GraphQL schema created by Gatsby. Unfortunately, this means that your queries will fail and cause your build to fail as well.

I encountered this problem with content types that have references. GraphQL schemas will not always reflect your content types when you have reference fields that allow entries of multiple content types to be added.

I wanted to allow users to create and arrange different kinds of sections on a page entry in Contentful. In my GraphQL query, I wanted to be able to get all the sections referred on the page and render them as React components on my page.

I created a few content types and a GraphQL query to fetch them with my pages.

Section-based page content
GraphQL content page query with fragments

The problem

This worked fine as long as I had both sections on one of my pages. When I removed all the entries of type ImageAndTextSection from my pages, I got an error when trying to build.

8:17:02 PM: GraphQL request: Fragment "ImageAndTextSection" cannot be spread here as objects of type "unionContentSectionsNode_2" can never be of type "ContentfulImageAndTextSection".

How to fix this?

Fear not. While a lot of the problems with optional data are not trivial to fix, the problem with references has a simple workaround.

Just wrap your GraphQL fragments into a Node -type. Node is “An object with an id, parent, and children”. All Contentful related types implement this type. Your query will now pass regardless of missing entries.

Sections wrapped in Node {}

I hope this helps you avoid build errors with your Contentful references.

Related GitHub issues:

--

--