Launching the GitHub Discussions Blog Loader for Astro

2 min read

In a recent post I shared my new blog setup using GitHub Discussions as a blogging engine combined with Astro’s new Content Layer API coming in v5, and well, since then I haven’t been able to stop tinkering, which leads me to this post.

A cool feature of the new Content Layer API is the concept of loaders. Loaders essentially help encapsulate all the logic for fetching data from a data source and populating a content collection. And the best thing about these is that they can be packaged and distributed easily, which lead me think:

wouldn’t it be cool to package up the work I did in my last post into a loader that anyone can just install and use

and so, I did 😁

Installation

Installing the GitHub Discussions Blog loader can be done via npm

npm install github-discussions-blog-loader

Usage

You can then use the githubDiscussionsBlogLoader in your content configuration at src/content/config.ts:

import { defineCollection } from "astro:content";
import { githubDiscussionsBlogLoader } from "github-discussions-blog-loader";

const blogPosts = defineCollection({
  loader: githubDiscussionsBlogLoader({
      auth: GITHUB_ACCESS_TOKEN,
      repo: {
          name: GITHUB_REPO_NAME,
          owner: GITHUB_REPO_OWNER,
      },
  })
});

export const collections = { blogPosts };

Once configured you can then use this like any other content collection in Astro:

---
import type { GetStaticPaths } from "astro";
import { getCollection } from "astro:content";
import type { Post } from "github-discussions-blog-loader";
import Layout from "../../layouts/Layout.astro";

export const getStaticPaths: GetStaticPaths = async () => {
  const blogPosts = await getCollection("blogPosts");
  return blogPosts.map((blogPost) => ({
    params: {
      slug: blogPost.id,
    },
    props: { post: blogPost.data },
  }));
};

type Props = { post: Post };

const { post } = Astro.props;
---

<Layout title={post.title}>
  <h1>{post.title}</h1>
  <div set:html={post.body}></div>
</Layout>

Source Code

You can find the source code for the loader as well as full documentation on it’s configuration over on GitHub

https://github.com/mattbrailsford/github-discussions-blog-loader

Improvements Over Original Solution

As well as packaging things up, I’ve also made a few improvements over my original solution.

  • Now return author information should you have multiple authors on the git repo.
  • Now return category information so you can now use categories for post organisation.
  • Can now fetch all discussions not just those of a single category.
  • Now uses the inbuilt Astro markdown processor so you can easily extend it using standard extension points.

If you give building a blog on GitHub Discussions a go, please do let me know how you get on.

Until next time 👋