How to create & use backend GraphQL fragments in Gatsby

Oscar de la Hera Gomez
Three flowers that represent Craft CMS, GraphQL and GatsbyJS side by side, beneath it sits the text 'Backend Fragments'.

A step by step tutorial on creating and using reusable GraphQL fragments for a GatsbyJS backend.

The following tutorial builds off our Open Source starter project and walks you through how to create and use reusable GraphQL fragments that can be used as part of the createPages, or other gatsby-node functionality, in GatsbyJS.

We recommend downloading our Open Source project, checking out the tutorial/page-queries-with-variables branch and carrying out the steps outlined below. All relevant changes can be found on the tutorial/backend-fragments branch.

git clone git@github.com:delasign/gatsbyjs-typescript-starter.git<a href="https://github.com/delasign/gatsbyjs-typescript-starter.git"></a>

Step One: Create the fragment

A screenshot of VSCode showing you the base fragment whose code is available below along with the location in which we suggest you create it within the project.

In our case, we will be creating a fragment called base which will include the slug and uri that we used as part of our tutorial on creating pages programatically.

In the graphql folder at the root directory, create a new folder called fragments and within it create a new file called base.js and paste in the code found below.

Step Two: Import & Consume

A screenshot of VSCode showing you how we imported the fragment into the query and applied it.

In graphl/post.js import the fragment that was created in Step One and add it to your query as demonstrated in the code below.

Step Three: Verify

A screenshot of Chrome showing you the website running as intended after the application of the backend fragment.

Run yarn start to confirm that the page generation algorithm succeeds.

Once complete, navigate to a webpage generated by Gatsby to see your results.

Any Questions ?

We are actively looking for feedback on how to improve this resource. Please send us a note to inquiries@delasign.com with any thoughts or feedback you may have.

delasign logo

Book a Free Consultation.

An icon of an email.

Click here to email us.

Fill in the details below to book a free consultation or to let us know about something else. Whatever it is, we are here to help.

How can we help you ?

Contact Details