4 min read
A good blog needs an RSS feed, even if hardly anyone seems to use an RSS reader anymore. This article will explain how to create a RSS feed for a static blog. In this example we will use contentlayer, but it should work with other data sources too.
Feed generator
First we need a script to create the feed from our posts. The script will load the generated posts from the contentlayer directory.
I had to specify the whole path including the extension, otherwise node threw errors at me.
After that we use the feed library to create the feed and to convert our posts into RSS items. First we have to install the library and install date-fns as well. We need date-fns later to simplify working with dates.
Than we can create the feed and specify some information about our blog e.g.:
- title
- description
- url
- language
This could look as follows.
Now we can convert our blog posts to feed items. We start by sorting the posts by their date. Then we convert each post to a RSS item and add it to the feed.
The feed does not contain the content of our posts. If we want to include the content we can attach it as HTML. Now we should have everything in place and we can write the feed to the public directory:
The complete script should like the following.
Discoverability
In order for RSS readers to find our feed, we can help them with a link
tag in the head
of our page.
For Next.js 13 and the app directory, the root layout is the right place for the link
tag, since that is how it's included in every page.
Build
Now it's time to add our feed generator to the build:
Whenever our page is build using the build
script, our RSS feed gets build afterwards.
The order is important, because contentlayer have to run first in order to generate the posts.
Git
Because our RSS feed is generated, we should exclude it from our repository:
If we would not do that, we would see changes to the rss.xml
every time we work on our posts.
Posted in: nextjs, rss, feed, contentlayer