Setting up an RSS Feed in a Next.js 13 App Directory
RSS (Rich Site Summary or Really Simple Syndication) feeds are an excellent way to distribute your website’s content, making it accessible to users and allowing them to stay updated on new posts.
In this tutorial, I’ll walk you through setting up an RSS feed for your Next.js 13 application.
We’ll be using the rss package to generate the feed and the contentlayer package to fetch our blog content. You can however implement this solution without contentlayer, and use the same methods you have used elsewhere to fetch your content.
Lets get started!
Steps
Section titled Steps1. Install the necessary packages
Section titled 1. Install the necessary packagesTo set up the RSS feed, we’ll need to install the rss
package to generate the feed, with the correct standards. Run the following command in your Next.js project directory:
2. Create a feed.xml routes
Section titled 2. Create a feed.xml routesTo create a rss.xml route in the Next.js app directory, create a feed.xml
folder in the top level of the app directory, then create a route.ts
in that directory. This is called a route handler.
3. Define the GET function
Section titled 3. Define the GET functionIn your route.ts
create an async get function
4. (Optional) Configure a global information/metadata file
Section titled 4. (Optional) Configure a global information/metadata fileAt this point, I highly recommend creating a site configuration/metadata file to pull information from, to use across your site. You may already have something similar set up for SEO metadata. For the examples below, I will be using a file called siteMetadata.ts
containing the following:
If you want to skip this, you can just replace anywhere we use siteMetadata
with a simple string.
5. Configure the RSS Feed
Section titled 5. Configure the RSS FeedInside the GET
function, create a new instance of the Rss
class and configure it with some basic site information. You can view all available feed options here.
This sets up the basic information about our RSS feed. Next we need to add the additional data, such as blog posts.
6. Add blog posts to the feed
Section titled 6. Add blog posts to the feedTo add your blog posts, we can use the .item
function on the feed we creating above. Using a loop,
we can do this for all our content. Add the following inside the GET
function, underneath the code
we entered above.
If using your own method of content fetching, just use the feed.item
section for your configuration.
7. Return the generated RSS feed.
Section titled 7. Return the generated RSS feed.Finally, we need to return the RSS feed as an XML response.
At the bottom of the RSS feed, add the following:
Now, when you visit /feed.xml
in your browser, you should see the RSS feed!
Complete feed.xml/route.ts file
Section titled Complete feed.xml/route.ts fileHere is the final working route.ts file. This is the file used to generate my rss feed.