Category pages in Gatsby can be driven by structured content stored in Sanity.io, and the same approach works with any content source. The demonstration uses Sanity's blog starter, and the goal is to generate a page for each category node, populate it from the CMS, and then expose the posts belonging to that category through Gatsby's GraphQL API.

Preparing the project

The starter can be launched from sanity.io/create, which copies the Sanity Studio and Gatsby front-end code into a GitHub account and configures deployment for both on Netlify, including example content. After cloning the repository locally, install the dependencies:

git clone [email protected]:username/your-repository-name.git
cd your-repository-name
npm i

Run npm run dev from the project root to start both the Studio and the front-end, or cd into the web folder and run Gatsby alone. Installing the Sanity CLI and logging in (npm i -g @sanity/cli && sanity login) provides commands for interacting with Sanity projects; the --help flag documents them. Because gatsby-node.js will be modified, restart the dev server afterwards — typically CTRL + C followed by npm run dev.

The content model and category slugs

The schema files under /studio/schemas/documents define the main content types: author, category, site settings, and post. The category field inside post.js is an array of reference objects pointing at category documents:

{
  name: 'categories',
  type: 'array',
  title: 'Categories',
  of: [
    {
      type: 'reference',
      to: [{
        type: 'category'
      }]
    }
  ]
},

In /studio/schemas/documents/category.js, a category currently consists of a title and a description. Since categories now get dedicated pages, add a slug field to the schema:

// studio/schemas/documents/category.js
export default {
  name: 'category',
  type: 'document',
  title: 'Category',
  fields: [
    {
      name: 'title',
      type: 'string',
      title: 'Title'
    },
    {
      name: 'slug',
      type: 'slug',
      title: 'Slug',
      options: {
        // add a button to generate slug from the title field
        source: 'title'
      }
    },
    {
      name: 'description',
      type: 'text',
      title: 'Description'
    }
  ]
}

Changing the content model means updating the GraphQL schema definition with npm run graphql-deploy (or sanity graphql deploy) in the studio folder. Warnings about breaking changes are expected, but adding a field is safe to proceed with. To make the field available in the Studio on Netlify, commit and push the change (git add . && git commit -m"add slug field", then git push origin master). After generating and publishing slugs for the categories, restart Gatsby's development server so the changes become visible.

How the Sanity source plugin fetches content

When Gatsby starts in development or builds the site, the source plugin first retrieves the GraphQL Schema Definitions from Sanity's deployed GraphQL API, which tells Gatsby which fields should exist so missing content doesn't break the build. It then hits the project's export endpoint, which streams all accessible documents into Gatsby's in-memory datastore; the whole site is therefore built with two requests. In development, the plugin also sets up a listener that pushes changes from Sanity to Gatsby in real time without further API queries, and with a token that may read drafts the changes appear instantly — the same experience available through Gatsby Preview.

Creating the category page template

Two things are required: instructing Gatsby to create pages for category nodes, and supplying a template file that renders the page data. In /web/gatsby-node.js, existing code already creates blog post pages; the category version follows the same pattern. The following goes between the createBlogPostPages function and the line starting with exports.createPages:

// web/gatsby-node.js

// ...

async function createCategoryPages (graphql, actions) {
  // Get Gatsby‘s method for creating new pages
  const {createPage} = actions
  // Query Gatsby‘s GraphAPI for all the categories that come from Sanity
  // You can query this API on http://localhost:8000/___graphql
  const result = await graphql(`{
    allSanityCategory {
      nodes {
        slug {
          current
        }
        id
      }
    }
  }
  `)
  // If there are any errors in the query, cancel the build and tell us
  if (result.errors) throw result.errors

  // Let‘s gracefully handle if allSanityCatgogy is null
  const categoryNodes = (result.data.allSanityCategory || {}).nodes || []

  categoryNodes
    // Loop through the category nodes, but don't return anything
    .forEach((node) => {
      // Desctructure the id and slug fields for each category
      const {id, slug = {}} = node
      // If there isn't a slug, we want to do nothing
      if (!slug) return

      // Make the URL with the current slug
      const path = `/categories/${slug.current}`

      // Create the page using the URL path and the template file, and pass down the id
      // that we can use to query for the right category in the template file
      createPage({
        path,
        component: require.resolve('./src/templates/category.js'),
        context: {id}
      })
    })
}

The function must then be invoked at the bottom of the file:

// /web/gatsby-node.js

// ...

exports.createPages = async ({graphql, actions}) => {
  await createBlogPostPages(graphql, actions)
  await createCategoryPages(graphql, actions) // <= add the function here
}

The template itself, based on the existing blog post template for consistent styling but kept simple, queries the category by the ID passed into the context in gatsby-node.js and reads the title and description fields:

// /web/src/templates/category.js
import React from 'react'
import {graphql} from 'gatsby'
import Container from '../components/container'
import GraphQLErrorList from '../components/graphql-error-list'
import SEO from '../components/seo'
import Layout from '../containers/layout'

export const query = graphql`
  query CategoryTemplateQuery($id: String!) {
    category: sanityCategory(id: {eq: $id}) {
      title
      description
    }
  }
`
const CategoryPostTemplate = props => {
  const {data = {}, errors} = props
  const {title, description} = data.category || {}

  return (
    <Layout>
      <Container>
        {errors && <GraphQLErrorList errors={errors} />}
        {!data.category && <p>No category data</p>}
        <SEO title={title} description={description} />
        <article>
          <h1>Category: {title}</h1>
          <p>{description}</p>
        </article>
      </Container>
    </Layout>
  )
}

export default CategoryPostTemplate

After saving, restart with npm run dev and open localhost:8000/categories/structured-content.

References, GROQ, and the GraphQL gap

Sanity's datastore indexes references bi-directionally even though they are defined in only one type: a post referencing the "Structured content" category marks that category as having incoming references, and the category can't be deleted while the reference exists. References can be set as "weak" to override this behavior. With GROQ, categories and their posts can be joined in a single query, producing a data structure that supports a simple category post template:

*[_type == "category"]{
  _id,
  _type,
  title,
  "posts": *[_type == "post" && references(^._id)]{
    title,
    slug
  }
}
// alternative: *[_type == "post" && ^._id in categories[]._ref]{

Gatsby's GraphQL API, as of yet, cannot express this kind of query out of the box. Gatsby's Node APIs can close the gap. Here "node" refers not to Node.js but to graph theory, where edges connect nodes; an edge, being a connection between nodes, can carry next and previous properties. The Node APIs are used primarily by plugins but also allow customization of the GraphQL API, and createResolvers in particular lets us tap into how a type's nodes are created.

Adding a posts field with createResolvers

The resolver logic checks for nodes of type SanityCategory; for each match it adds a posts field of type SanityPost, runs a query filtering all posts that list a category matching the current category's ID, and, when matching IDs exist, fills the field with those post nodes. Placed above or below the existing code in /web/gatsby-node.js:

// /web/gatsby-node.js
// Notice the capitalized type names
exports.createResolvers = ({createResolvers}) => {
  const resolvers = {
    SanityCategory: {
      posts: {
        type: ['SanityPost'],
        resolve (source, args, context, info) {
          return context.nodeModel.runQuery({
            type: 'SanityPost',
            query: {
              filter: {
                categories: {
                  elemMatch: {
                    _id: {
                      eq: source._id
                    }
                  }
                }
              }
            }
          })
        }
      }
    }
  }
  createResolvers(resolvers)
}

Restarting the dev server exposes a new posts field on the sanityCategory and allSanityCategory types.

Listing the posts on the category page

Back in /web/src/templates/category.js, the page gains a list of links to the category's posts:

// /web/src/templates/category.js
import React from 'react'
import {graphql, Link} from 'gatsby'
import Container from '../components/container'
import GraphQLErrorList from '../components/graphql-error-list'
import SEO from '../components/seo'
import Layout from '../containers/layout'
// Import a function to build the blog URL
import {getBlogUrl} from '../lib/helpers'

// Add “posts” to the GraphQL query
export const query = graphql`
  query CategoryTemplateQuery($id: String!) {
    category: sanityCategory(id: {eq: $id}) {
      title
      description
      posts {
        _id
        title
        publishedAt
        slug {
          current
        }
      }
    }
  }
`
const CategoryPostTemplate = props => {
  const {data = {}, errors} = props
  // Destructure the new posts property from props
  const {title, description, posts} = data.category || {}

  return (
    <Layout>
      <Container>
        {errors && <GraphQLErrorList errors={errors} />}
        {!data.category && <p>No category data</p>}
        <SEO title={title} description={description} />
        <article>
          <h1>Category: {title}</h1>
          <p>{description}</p>
          {/*
            If there are any posts, add the heading,
            with the list of links to the posts
          */}
          {posts && (
            <React.Fragment>
              <h2>Posts</h2>
              <ul>
                { posts.map(post => (
                  <li key={post._id}>
                    <Link to={getBlogUrl(post.publishedAt, post.slug)}>{post.title}</Link>
                  </li>))
                }
              </ul>
            </React.Fragment>)
          }
        </article>
      </Container>
    </Layout>
  )
}

export default CategoryPostTemplate

The result is a category page with a linked list of the posts assigned to it.

The same logic extends to other taxonomies — author pages, for instance, on a blog with multiple authors. The GraphQL filter can also reach beyond explicit reference relationships, matching other fields with regular expressions or string comparisons, which makes it fairly flexible.