{
"$type": "site.standard.document",
"content": {
"$type": "at.markpub.markdown",
"text": {
"$type": "at.markpub.text",
"markdown": "I recently decided to fully rebuild my blog from the ground up using Next.js. By default, there's no built-in support to auto-generate an RSS for blog posts like there are in so many starters for Gatsby. As such I needed to roll my own.\n\nUltimately, an RSS feed is just an XML file that gets updated with new entries as new posts are made. Lucklily, we can take advantage of the fact that committing a new blog post will trigger a new build of the site. Using that, we can update the build command in our `package.json` to run a node script before our actual build like this:\n\n```json\n\"scripts\": {\n\t\"build\": \"node ./buildFeed && next build\",\n},\n```\n\nNow we just need to update our `buildFeed.js` (which lives in our root directory) to create a new XML file when it's run. To do that I'm going to use 3 packages: `fs`, [`rss`](https://www.npmjs.com/package/rss), and [`next-mdx`](https://www.next-mdx.org/).\n\n```javascript\nconst fs = require('fs')\nconst RSS = require('rss')\nconst { getAllNodes } = require('next-mdx');\n```\n\nFirst we need to create a new RSS feed.\n\n```javascript\nconst feed = new RSS({\n\ttitle: 'My Blog',\n\tsite_url: 'https://my-blog.com'\n});\n```\n\nNext we need to get the blog posts to load into this feed.\n\n```javascript\nconst posts = await getAllNodes('post');\n```\n\nThen we need to iterate over our posts and add them to our feed.\n\n```javascript\nposts.forEach(post => {\n\tfeed.item({\n\t\ttitle: post.frontMatter.title,\n\t\tguid: post.slug,\n\t\turl: 'https://my-blog.com/post/' + post.url,\n\t\tdate: post.frontMatter.date\n\t});\n});\n```\n\nNow we have our feed built out, we just need to generate the XML and write it out to a file.\n\n```javascript\nconst xml = feed.xml({ indent: true });\nfx.writeFileSync('public/rss.xml', xml);\n```\n\nThis will write our `rss.xml` file to the public folder of our Next.js app so that it will be at a publicly available URL at `https://my-blog.com/rss.xml`.\n\n[See the gist for the full code](https://gist.github.com/arkmuntasser/7d73909b3c7d7cc8f61c915f1df1b65f)."
}
},
"description": "RSS feeds were the backbone of the original social web and we need to keep it alive.",
"path": "/posts/create-an-rss-feed-nextjs-mdx-blog",
"publishedAt": "2021-04-12T00:00:00.000Z",
"site": "at://did:plc:2lm4lab5fhnj6kaazrxopv37/site.standard.publication/self",
"tags": [
"javascript",
"next",
"mdx"
],
"title": "Creating an RSS feed with Next.js and Next-MDX"
}