Store Gatsby GraphQL Fragments in Their Own External Files

No more jamming everything in your Layout component.
Zach Zach (236)
2 minutes

Did you know that you can store your Gatsby GraphQL fragments in their own files rather than defining them all in some top-level component? Until recently, neither did I.

In order for a GraphQL fragment to be accessible by Gatsby pages, templates, and components, it generally needs to live in some parent or wrapper component. Usually, this is something like your site's PageWrapper.jsx or Layout.jsx component.

The problem

In practice, this leads to a large collection of fragments in that file, where a single syntax error can cause your gatsby develop to fail and require a restart. Not only is this extremely annoying, but a growing list of fragments means a larger and more unwieldy wrapper component.

The solution

Instead, it's a good idea to store each fragment in its own file instead. This is not a well-documented Gatsby feature, so thanks to howchooer Ryan for pointing this out to me!


You can define SomeFragment in src/graphql-fragments/SomeFragment.js!

Posted in these interests:
h/gatsby2 guides
h/react3 guides
h/graphql1 guide

You'll need to create a particular folder structure for Gatsby to detect and use your fragments. Create the following directory:


Create a file with a name matching your fragment. For example, create src/graphql-fragments/SomeFragment.js and populate it with your fragment:

import { graphql } from 'gatsby';

export const SomeFragment = graphql`
    fragment SomeFragment on SomeTypeName {

That's it! Gatsby will automatically detect these fragments and make them available for use.

Restarting develop

If you're moving existing fragments, it's possible Gatsby will puke as a result of undefined or duplicate fragments. In this case, simply restart develop by running npm start or gatsby develop.

Continue to reference and use your fragments like normal:

edges {
    node {

Now you can keep your project nice and clean while reducing the develop restarts normally associated with GraphQL fragment syntax errors!

Let's Disqus the benefits of React
Zach Zach (236)
4 minutes

The normal Disqus installation methods don't work well in React since state changes can cause your comments area to re-render, clearing everything out.