With my new site being built with Next.js, I needed to figure out a way to still provide RSS feeds and a sitemap using the MDX files as a source.
I use next-mdx-remote from Hashicorp for the parsing and rendering of my MDX files and with the latest major version, v3, it got to be a little tricky so hopefully you'll find this helpful!
RSS Feed
To generate an RSS feed for my Next.js site, I used the aptly named feed package and installed it as a dev dependency.
Installation
Implementation
I then created a file named feeds.tsx in my utils directory. And we'll start off with this:
From there, I start with some basic data like the date, my name and author information, as well as the site url and I also fetch the posts which are just local MDX files in the data directory.
Then I created a new Feed object.
Then we can finally start looping over our posts to add to the feed.
With the latest changes to the next-mdx-remote package and no longer having the renderToString method in v3,
we are using renderToStaticMarkup from react-dom/server to generate the markup to add to our feeds.
And then we can finally write those feeds to their appropriate files.
Now, how do we get these feeds to automatically run on build?
Easy! Just call it in the getStaticProps method in the blog index and it will generate on build.
I like to wrap it in a check for the VERCEL environment variable which will then only run when building on the Vercel platform, or if I pass in the environment variable when building locally.
Here is the entire feed.tsx file with all the steps completed.
Sitemap
For the sitemap functionality, I chose to use next-sitemap which provides a simple API to create a sitemap from your static, dynamic, and server side pages in Next.js.
I'm only using static pages on my site, but you can check out the README if you're interested in generating dynamic or server-side sitemaps.
Installation
Implementation
From there, I created a new file in the root of the project named, next-sitemap.js and I provided a basic configuration within.
You can find the different configuration options supported in the README
And then in my package.json, I added next-sitemap to the postbuild script.
From there, whenever you build your project you'll have a sitemap.xml and if you set generateRobotsTxt to true in the configuration, a robots.txt generated into your public directory.