Using Gatsby with GitHub API

Gatsby is best known for it’s static site capabilities. Many people miss that since its normal React, they can also create their normal webapps with it too. Normally Gatsby reads the files off of the filesystem and parses them, we can also just query the API for those same files to get the realtime capabilities normal webapps have in addition to the benefits Gatsby provides.

Pulling pages from Github

Instead of the normal static site generation with GraphQL in Gatsby, we will be using fetch to get data from Github. GitHub’s API exposes the files in our repository.

For my uses, I’m making proxying the calls to GitHub on my own server (using Firebase).

export const getPage = functions.https.onRequest(async (request, response) => {
  const config = {
    headers: {
      Authorization: `Bearer ${functions.config().github.api.token}`,
    },
  };
  const result = await axios.get(
    `https://api.github.com/repos/CodeWorldSo/gmgt-website/contents/src/pages/${request.query.page}`,
    config
  );

  const data = result.data;

  response.send(data);
});

Our client code:

props.file would be the filename, like a-blog-post.md

  useEffect(() => {
    // request to my function, which calls Gatsby
    fetch(
      `${process.env.GATSBY_FUNCTIONS_DOMAIN}/getPage?page=mixtape/${props.file}`
    )
      .then((response) => response.json())
      .then((resultData) => {
        const data = frontMatter<MixTape>(atob(resultData.content));
        setData(data.attributes);
  }, []);

Re-using our components by parsing the yaml response

Gatsby uses frontmatter when generating pages. So, we can just call that on our response as well:

const data = frontMatter<MixTape>(atob(resultData.content));

Thus, you can even re-use your existing components!

In my case, Mixtapes is under our templates directory and is also used by Gatsby at build time.

  return (
    <>
      <MixtapesPageTemplate {...data} />
    </>

Wrapup

This post shows how you can add realtime data fetching into your Gatsby apps. While most of Gatsby focuses on the buildtime advantages, it is possible to have the best of both worlds.