Fetch Category Post Count Using GraphQL in Gatsby
Displaying how many posts belong to each category is a common need in Gatsby blogs. With Gatsby’s built‑in GraphQL layer, you can query your content and compute category counts efficiently—without extra plugins or manual processing.
This short guide shows you how to structure your data, write the query, and display the results.
Prerequisites
Before starting, ensure your Gatsby project:
- Uses MDX, Markdown, or a CMS (Contentful, Sanity, Ghost, Strapi, etc.).
- Includes a
categoryfield in each post’s frontmatter or CMS model. - Has basic familiarity with GraphQL queries in Gatsby components or pages.
Step 1: Verify Your Data Structure
Each post should include a category field:
---
title: "My Guide"
category: "JavaScript"
date: "2025-01-01"
---If you’re using Contentful or another CMS, make sure your model exposes a category field.
Step 2: Write a GraphQL Query to Group Posts by Category
Gatsby’s GraphQL API supports grouping nodes by any field using group.
Here’s an improved and modern example using allMdx:
import { graphql } from "gatsby";
export const query = graphql`
query CategoryCountQuery {
allMdx {
group(field: frontmatter___category) {
category: fieldValue
totalCount
}
totalPostCount: totalCount
}
}
`;What this query returns
-
group— array of unique categories -
category— category name -
totalCount— number of posts in that category -
totalPostCount— total number of MDX posts
Step 3: Render Category Counts in a Component
import React from "react";
const CategoryList = ({ data }) => {
const categories = data.allMdx.group;
return (
<section>
<h2>Categories</h2>
<ul>
{categories.map(cat => (
<li key={cat.category}>
{cat.category} — {cat.totalCount} posts
</li>
))}
</ul>
</section>
);
};
export default CategoryList;Now, Gatsby injects the data prop into this component, letting you render the grouped results.
Bonus: Sorting Categories Alphabetically
Modify the render logic:
const sorted = [...categories].sort((a, b) =>
a.category.localeCompare(b.category)
);Then render sorted instead of categories.
Bonus: Querying Category Count for a Single Category
Useful for category pages such as /category/javascript/.
query CategoryPage($category: String!) {
allMdx(filter: { frontmatter: { category: { eq: $category } } }) {
totalCount
}
}Conclusion
Using Gatsby’s built‑in GraphQL APIs, you can easily group posts by category and compute total counts. This pattern works for MDX, Markdown, and all major headless CMS integrations. It improves navigation, helps users explore your content, and makes your blog more structured and engaging.
Gatsby handles all aggregation at build time—making the result fast, scalable, and SEO‑friendly.