Paulund

NextJS Add RSS Feed to Blog

Every blog can benefit from adding an RSS feed, it allows users to subscribe to your blog and get updates when you publish new content. In this post, we'll add an RSS feed to our NextJS blog.

What is an RSS Feed?

RSS stands for Really Simple Syndication, it's a way to publish frequently updated content such as blog posts, news, and podcasts. Users can subscribe to an RSS feed and get updates when new content is published.

Add RSS Feed to NextJS Blog

Out of the box there isn't a way of creating an RSS feed in NextJS, we'll need to use a package called rss to create the RSS feed.

First, we need to install the rss package:

npm install rss

The way this is going to work is for us to create a route on the site, which will then fetch all post information and generate the RSS feed.

Inside your app directory create a folder of feed inside here create a file called route.tsx

import RSS from "rss";
import { SITE_FEED, SITE_NAME, SITE_URL } from "@/lib/constants";
import { getPosts } from "@/lib/blog/api";

export async function GET() {
  const posts = getPosts();

  const feedOptions = {
    title: SITE_NAME,
    site_url: SITE_URL,
    feed_url: SITE_FEED,
    pubDate: new Date(),
  };
  const feed = new RSS(feedOptions);

  posts.forEach((post) => {
    feed.item({
      title: post.title,
      url: `${SITE_URL}/${post.slug}`,
      date: post.createdAt,
      description: post?.description,
    });
  });

  return new Response(feed.xml({ indent: true }), {
    headers: {
      "Content-Type": "application/xml; charset=utf-8",
    },
  });
}

This will use the rss package to create an RSS feed of all the posts on the site, then it will return this as an XML response.

Next, we need to add this route to the app router, open app/router.tsx and add the following:

You can test this is working by going to http://localhost:3000/feed and you should see the RSS feed.

Add RSS Link to Site

With the RSS feed created we need a way for the RSS feed to be found.

On the global layout file app/layout.tsx add the following inside the head tag:

<link
  rel="alternate"
  type="application/rss+xml"
  title="RSS Feed for Site"
  href="/feed"
/>

Further Reading

Dev.to allow you to sync your RSS feed with your Dev.to account, this is a great way to get more exposure for your blog. Everytime you make a post on your blog it will create a draft post on Dev.to automatically. Sync your RSS feed with Dev.to

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

Get 50% off forever using the code 50OFFUP.