Skip to content

Dale Blackburn

Full Stack Developer | Brighton, UK

Creating a Gatsby Plugin

Tutorial, Gatsby4 min read

I recently spent some time updating a Gatsby plugin that I had written a few months ago while contributing to the new Storybook website, and I realised that I hadn't yet written about it, or about my experience with the Gatsby plugin system.

Time to change that!

The Problem

While helping out with the storybook site an issue popped up in which we needed to get a contributor count from GitHub.

We first attempted to fetch the data from the GitHub API but we found that the Contributors endpoint responds with paginated data, showing 30 contributors at a time, with no way to get the total count:

We then tried to use this trick, where you ask for one contributor per page and count the number of pages. But the pagination maxed out at 399, preventing us from getting an accurate count.

We eventually came to the idea of scraping the data from the GitHub repo page itself, as a pre-build step.

I created a script using node-fetch and Cheerio that lifted and parsed the HTML body of the repo. This script provided the value directly from the contributor count link, and wrote it into the projects package.json, as an npm config variable called contributors:

1const fs = require('fs');
2const fetch = require('node-fetch');
3const cheerio = require('cheerio');
5const PACKAGE = require('./package');
7const repoURL = '';
9const getContributorCount = async () => {
10 await fetch(repoURL)
11 .then(res => res.text())
12 .then(body => {
13 const $ = cheerio.load(body);
14 const count = $('a[href="/storybooks/storybook/graphs/contributors"] > span').html().trim();
15 const packageJson = {...PACKAGE, config: { contributors: count }
16 fs.writeFile('package.json', JSON.stringify(packageJson}, null, 2), (err) => {
17 if(err) {
18 return console.error(err);
19 }
20 console.log('New contributor count added to package.json: ${count} contributors!');
21 });
22 });

With this config variable, we could fetch the value using either process.env.npm_package_config_contributors or by pulling it from the package.json directly via import.

This worked great locally but had some drawbacks.

  • Having a pre-build step isn't an ideal way to handle data fetching, which ideally should be a part of the build itself

  • The build time was marginally slowed down

  • The script was causing an issue for visual regression testing. As the repo's Chromatic tests all resulted in 000 as a contributor count.

Gatsby Plugin Library

Thankfully for me, Gatsby has an excellent and well-documented plugins API, that leverages an extremely flexible GraphQL implementation. This would make it very easy to convert my manual, single use case scraper into a data source that could be useful to others, providing there wasn't already a plugin out there that already did the job.

Gatsby Plugin Types

Gatsby defines a few types of plugin, each with it's own purpose and naming convention:

  • Data sources plugins, which use gatsby-source-*
  • Data transformer plugins, which use gatsby-transformer-*
  • Plugins for other plugins, which use gatsby-[some plugin name]-*
  • And a general plugin for anything else, which use gatsby-*

You can read more about these here:

I searched the Gatsby plugin library to see if a package already existed that could help us with our goal, and ended up finding some great GitHub packages, but none of them accomplished what we were trying to achieve (again, mainly due to the limitations of the GitHub API).

It looked like I was building a plugin.

Writing a Gatsby source plugin

I was happy to find that the documentation on creating a Gatsby source plugin was well written and easy to follow, giving a step by step guide on implementing data source fetching and shaping it for the GraphQL API.

I doubt I'll be able to write a better guide for source plugin authoring, but I'll run you through what I did.

A plugin primarily comprises of a single file, gatsby-node.js. You can consider this file as an extension to your Gatsby projects own file of the same name. Both are intended to work with the data layer and can be used to create pages and GraphQL nodes, transform data, run web servers, modify config, and more.

You can read up about the node APIs here:

Conveniently, Gatsby supplies a sourceNodes extension point that contains all the functions you need to create data nodes in the GraphQL endpoint. Here's what the boilerplate code looks like:

1const fetch = require('node-fetch')
2const cheerio = require('cheerio')
4exports.sourceNodes = async ({ actions, createNodeId, createContentDigest }, configOptions) => {
5 const { createNode } = actions
7 const repoData = {}
9 // Code for scraping repoData goes here.
11 const nodeId = createNodeId(`${[,].join('-')}`)
12 const nodeContent = JSON.stringify(repoData)
13 const contentDigest = createContentDigest(repoData)
15 const nodeMeta = {
16 id: nodeId,
17 parent: null,
18 children: [],
19 internal: {
20 type: `GitHubRepoData`,
21 content: nodeContent,
22 contentDigest
23 }
24 }
26 const node = Object.assign({}, repoData, nodeMeta)
28 createNode(node)
29 })

Let's take some time to break this down and see what's happening.

The Gatsby Source API Functions

First we pull out the actions, createNodeId, and createContentDigestfunctions from sourceNodes. We then pull the createNode function from actions.

Each of these has a specific role to play in the forming of our data node:

  • createNodeId is used to create a globally unique ID.
  • createContentDigest is used to create a unique hex-encoded key, which is dynamically based on changes to the content.
  • actions provides the createNode function, which is for adding data nodes to GraphQL

You can read more about sourceNodes here:

After we have scraped the parts of the repo we're interested in, we shape the data to be ready for node creation, creating custom ids and a digest along the way:

1// We generate a unique ID for our new node
2 const nodeId = createNodeId(`${[,].join('-')}`)
4 // We stringify the value of the data so that it can be be used in the contents meta data
5 const nodeContent = JSON.stringify(repoData)
7 // We generate a hex-encoded content digest, based our stringified data
8 const contentDigest = createContentDigest(repoData)
10 // We shape the required metadata, using our unique indentifiers and stringified data
11 const nodeMeta = {
12 id: nodeId,
13 parent: null,
14 children: [],
15 internal: {
16 type: `GitHubRepoData`, // used to generate the resulting GraphQL query name
17 content: nodeContent,
18 contentDigest
19 }
20 }
22 // We create a new object that merges the data with it's metadata, finalising the shape of the node
23 const node = Object.assign({}, repoData, nodeMeta)
25 // And finally use the new node data to generate the entry in the GraphQL data source
26 createNode(node)

As a result of our new plugin, we now end up with the following structure and data being available:

gatsby-source-github-repo GraphQL data

This data can now be exposed in our Gatsby project to do with as we please.

Using the Plugin

gatsby-source-github-repo plugin on npm


You can install the latest copy of the plugin using:

npm i gatsby-source-github-repo@latest.

Then all you need to do is add the plugin configuration to your projects gatsby-config file:

2 plugins: [
3 {
4 resolve: 'gatsby-source-github-repo',
5 options: {
6 repoUrl: '',
7 }
8 },
9 ]

You can find the plugin on npm, or in the Gatsby plugin library.

Final thoughts

As I mentioned, I recently updated the plugin. I decided to switch from Cheerio to JSDom, which I've found a better experience when parsing raw HTML. This is mainly due to:

  • Cheerio's obfuscated internal functions producing erroneous/inconsistent results.
  • Cheerio uses a jQuery like syntax, where as JSDom uses vanilla JS window/document methods.
  • JSDom yields the same experience of using a DOM window, with all it's associated functionality.

Here's the final code:

1const fetch = require('node-fetch')
2const { JSDOM } = require('jsdom');
4exports.sourceNodes = async ({ actions, createNodeId, createContentDigest }, configOptions) => {
5 const { createNode } = actions
7 // Gatsby adds a configOption that's not needed for this plugin, delete it
8 delete configOptions.plugins
10 const { repoUrl, repoUrls } = configOptions
11 if (!repoUrl || typeof repoUrl !== 'string') {
12 throw new Error('You must supply a valid url string for the desired repo')
13 }
15 await fetch(repoUrl)
16 .then(res => res.text())
17 .then(body => {
18 const dom = new JSDOM(body);
19 const doc = dom.window.document;
21 const title = doc.querySelector('title').textContent
23 if (title.indexOf('Page not found') >= 0) {
24 throw new Error('Github page was not found at "' + repoUrl + '"')
25 }
27 const author = doc.querySelector('h1.public a') && doc.querySelector('h1.public a').textContent
28 const name = doc.querySelector('h1.public strong[itemprop="name"] a') && doc.querySelector('h1.public strong[itemprop="name"] a').textContent
29 const description = doc.querySelector('span[itemprop="about"]') && doc.querySelector('span[itemprop="about"]').textContent || 'Repo does not have a description.'
30 const website = doc.querySelector('span[itemprop="url"] a') && doc.querySelector('span[itemprop="url"] a').href || 'Repo does not have a website.'
32 const topics = Object.values(doc.querySelectorAll('div.list-topics-container a')).map(topicLink => {
33 let topic = topicLink.textContent
34 return topic.trim()
35 })
37 const commitCount = doc.querySelector('.numbers-summary li.commits span') && doc.querySelector('.numbers-summary li.commits span').textContent
38 const branchCount = doc.querySelector('.numbers-summary a[href*="/branches"] span') && doc.querySelector('.numbers-summary a[href*="/branches"] span').textContent
39 const releaseCount = doc.querySelector('.numbers-summary a[href*="/releases"] span') && doc.querySelector('.numbers-summary a[href*="/releases"] span').textContent
40 const contributorCount = doc.querySelector('.numbers-summary a[href*="/graphs/contributors"] span') && doc.querySelector('.numbers-summary a[href*="/graphs/contributors"] span').textContent
42 let licence = 'Repo does not have a licence'
43 if (doc.querySelector('.numbers-summary a[href*="/LICENSE"]')) {
44 // Remove SVG from licence a tag so we can access it's adjacent licence name
45 doc.querySelector('.numbers-summary a[href*="/LICENSE"] svg').parentNode.removeChild
46 licence = doc.querySelector('.numbers-summary a[href*="/LICENSE"]').textContent
47 }
49 const languageStats = Object.values(doc.querySelectorAll('ol.repository-lang-stats-numbers li a')).map(language => {
50 let lang = language.querySelector('span.lang') && language.querySelector('span.lang').textContent
51 return {
52 lang: lang.trim(),
53 percentage: language.querySelector('span.percent') && language.querySelector('span.percent').textContent,
54 }
55 })
57 const repoData = {
58 name: String(name).trim(),
59 author: String(author).trim(),
60 url: String(repoUrl),
61 description: String(description).trim(),
62 website: String(website).trim(),
63 topics: (topics.length > 0) ? topics : 'Repo does not have any defined topics.',
64 commitCount: String(commitCount).trim(),
65 branchCount: String(branchCount).trim(),
66 releaseCount: String(releaseCount).trim(),
67 contributorCount: String(contributorCount).trim(),
68 licence: String(licence).trim(),
69 languageStats
70 }
72 const nodeContent = JSON.stringify(repoData)
74 const nodeMeta = {
75 id: createNodeId(`${[name, author].join('-')}`),
76 parent: null,
77 children: [],
78 internal: {
79 type: `GitHubRepoData`,
80 content: nodeContent,
81 contentDigest: createContentDigest(repoData)
82 }
83 }
85 const node = Object.assign({}, repoData, nodeMeta)
86 createNode(node)
88 return repoData
89 })

I'm a lot happier with the code and it seems to be working nicely.

In regards to writing a Gatsby plugin, I found the experience simple and delightful, much like the rest of the Gatsby developer experience.

I urge anyone looking to handle non-local data and file resource for their Gatsby project to give it a try.