How to create & use GraphQL fragments in Gatsby

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

A step by step tutorial on creating and using reusable GraphQL page query fragments with GatsbyJS.

The following tutorial builds off our Open Source starter project and walks you through how to create and use reusable frontend GraphQL fragments in GatsbyJS.

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

git clone git@github.com:delasign/gatsbyjs-typescript-starter.git

Step One: Create the Fragment

A screenshot of VSCode showing our GraphQL fragment and its location in the directory.

In the src create a new folder called fragments and within it create a new file called seo.js and paste in the code found below.

Please note that unlike backend queries, they must fall under a and include a type. You cannot simply state the fragment includes metaTitle and metaDescription. It will not work.

Step Two: Integrate fragment into a query

A screenshot of VSCode showing how we integrated the fragment into a query.

GraphQL fragments do not need to be imported. To integrate them into a query follow the paradigm ...FragmentName.

Step Three: Verify

A screenshot of Chrome showing a programmatically generated page successfully loaded with the meta data after applying the 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