Add an RSS Feed to Gatsby MDX Blog

Posted on January 23, 2020

Google Reader might be dead, but RSS lives through the hearts of some great applications like Feedly, Feedbin and Winds.

Adding an RSS Feed has long been a long time bucket list item and I’m happy to have ticked it off. You can now add an RSS Feed and subscribe to my posts at https://blog.agney.dev/rss.xml.

Here’s how you can do it too:

The first step on the Gatsby site is to install gatsby-plugin-feed.

yarn add gatsby-plugin-feed
// OR
npm i gatsby-plugin-feed

Second, let’s look at adding the plugin to gatsby-config.js:

1{
2 resolve: `gatsby-plugin-feed`,
3 options: {
4 query: `
5 {
6 site {
7 siteMetadata {
8 title
9 description
10 siteUrl
11 }
12 }
13 }
14 `,
15 feeds: [
16 {
17 serialize: ({ query: { site, allMdx } }) => {
18 return allMdx.edges.map(edge => {
19 return Object.assign({}, edge.node.frontmatter, {
20 description: edge.node.excerpt,
21 data: edge.node.frontmatter.date,
22 url: site.siteMetadata.siteUrl + edge.node.fields.slug,
23 guid: site.siteMetadata.siteUrl + edge.node.fields.slug,
24 custom_elements: [{ 'content:encoded': edge.node.html }],
25 });
26 });
27 },
28 query: `
29 {
30 allMdx(
31 limit: 1000,
32 sort: { order: DESC, fields: [frontmatter___date] },
33 filter: { frontmatter: { published: { ne: false } } }
34 ) {
35 edges {
36 node {
37 fields { slug }
38 frontmatter {
39 title
40 date
41 }
42 html
43 }
44 }
45 }
46 }
47 `,
48 output: '/rss.xml',
49 title: `Mindless - Agney's Technical Blog RSS Feed`,
50 site_url: `https://blog.agney.dev`,
51 },
52 ],
53 },
54 },

Let’s look at the options one by one.

  1. The first query attribute let’s us query for site level attributes like siteMetadata. This data is important to construct siteUrl and guids.

  2. We had a feeds array. This is an array so that you can create multiple feeds. For example, one for your blog and another for your podcast. Just seperate them into two objects.

  3. Inside feeds array, we have our feed object. This defines all the options for our RSS Feed. Because we have a MDX Blog, we need a custom serializer to transform pages into HTML objects that the RSS Feed readers understand.

  4. query field inside this object stands for graphql query that retrieves all the pages in the blog. Note to add the published filter if you use this format to hide drafts.

  5. gatsby-plugin-mdx exposes an html field for the purpose of building RSS blogs. But because the process is expensive, it is not build on development. This is passed on to the custom_elements field in serializer. You can find all available options in docs.

To see the output, you can run the following command in terminal and visit http://localhost:8000/rss.xml

gatsby build && gatsby serve

See sample on Github

Buy me a coffeeBuy me a coffee