Add an RSS Feed to Gatsby MDX Blog
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// ORnpm 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 title9 description10 siteUrl11 }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 title40 date41 }42 html43 }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.
The first query attribute let’s us query for site level attributes like
siteMetadata
. This data is important to constructsiteUrl
andguid
s.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.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.query
field inside this object stands for graphql query that retrieves all the pages in the blog. Note to add thepublished
filter if you use this format to hide drafts.gatsby-plugin-mdx
exposes anhtml
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 thecustom_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