May 30, 2024

How to Add a RSS Feed to Your Next.js 13/14 Website

  • NextJS
  • Tips & Tricks
  • RSS
  • Tutorial
  • Practical Coding
  • Web Development

Hey everyone,

In this tutorial, we'll walk through the steps to add an RSS feed to your Next13/14 website. This involves installing an NPM package for RSS, creating a function to generate the RSS feed, and setting up an API endpoint to serve the feed. Additionally, I'll explain why I prefer using RSS and introduce a helpful tool for managing your feeds.

If you want to read more about RSS, I recommend the specification on RSSBoard.

Why I use RSS?

I think the way social media and news platforms use AI to suggest content is limiting me on what I really want to see when I browse content. With RSS, I can choose which feeds to follow and avoid being bombarded with unwanted suggestions. This helps prevent the addictive nature of constantly updated feeds.

Why Should I Have an RSS Feed on My Website?

Having an RSS feed on your website provides several benefits:

  • Increased Accessibility: Allows your audience to subscribe to your content and receive updates without having to visit your site.
  • Better Engagement: Keeps your readers informed about new posts, improving engagement and retention.
  • SEO Benefits: Regular updates via RSS can help improve your website's search engine rankings.

FreshRSS

Before we start, I want to mention FreshRSS, a free, self-hostable feed aggregator. A very good friend of mine is self-hosting it, and if you're into self-hosting, you might like it too. If you aren't into self-hosting, they also offer Community Servers.

Tutorial

Install Package

First we need to install the rss NPM Package

1npm i rss
2# or
3yarn add rss
4
5# If you are using Typescript
6npm i @types/rss -D
7# or
8yarn add @types/rss --dev

Create the RSS Feed Generator Function

This function sets up the configuration, fetches all blog articles, and adds them to the feed. At the end, the function returns the XML string, which can be stored on your servers public directory or, as we are doing, served from a specific endpoint.

1// utils/createRSSFeed.ts
2
3import RSS from "rss";
4import getAllBlogPosts from "./graphql/getAllBlogPosts";
5import webConfig from "@/config/webConfig";
6
7const createRSSFeed = async () => {
8  const rssFeedOptions: RSS.FeedOptions = {
9    title: "David M. Rainer | My Blog Articles",
10    description: "Here you can find all my blog articles. Enjoy reading!",
11    site_url: "https://www.davidrainer.dev",
12    feed_url: "https://www.davidrainer.dev/blog/rss.xml",
13    pubDate: new Date().toISOString(),
14    copyright: `© ${new Date().getFullYear()} David Michael Rainer. All rights reserved.`,
15    language: "en",
16    categories: [
17      "Technology",
18      "Programming",
19      "Web Development",
20      "Health",
21      "Fitness",
22    ],
23    custom_elements: [
24      {
25        "dc:creator": "David Michael Rainer",
26      },
27    ],
28    ttl: 60,
29  };
30
31  const feed = new RSS(rssFeedOptions);
32  const allBlogArticles = await getAllBlogPosts();
33
34  allBlogArticles.forEach((article) => {
35    feed.item({
36      title: article.title,
37      description: article.summary,
38      url: `https://www.davidrainer.dev/blog/${article.slug}`,
39      date: new Date(article.attributes.publishedDate).toISOString(),
40      categories: article.categories,
41      author: article.author,
42    });
43  });
44
45  return feed.xml();
46};
47
48export default createRSSFeed;

Create API Endpoint

Next, create a new API endpoint to GET the created XML string. We'll set the dynamic value to force-static and the revalidate time to 60 minutes to comply with the TTL setting in the config above.

1// app/blog/rss.xml/route.ts
2
3import createRSSFeed from "@/utils/createRSSFeed";
4
5export const dynamic = "force-static";
6export const revalidate = 3600; // ttl time of the RSS feed is 60 minutes
7
8export async function GET() {
9  const rssXmlContent = await createRSSFeed();
10  return new Response(rssXmlContent, {
11    headers: { "Content-Type": "text/xml" },
12  });
13}
14

Tip You can also validate your RSS feed with the W3C Validation Service

I hope this helps you set up an RSS feed for your Next.js website.

Cheers, David