How to create & use backend GraphQL fragments in Gatsby

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

Oscar de la Hera Gomez
Written by Oscar de la Hera Gomez
First published on 09/14/2022 at 13:37
Last Updated on 11/12/2022 at 21:53
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.

Download Open Source projectHow to programmatically create pages using the GraphQL & Gatsby

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>
View Github Repository

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.

How to programmatically create pages using the GraphQL & Gatsby

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.

SubscribeInquireView All PostsView All ServicesView All Work

Partner with us

We would love to get to know you and see how we can help your organization with its goals and needs.
Let's Talk

Stay Informed

Get occasional updates about our company, research, and product launches.
Subscribe