Nextjs Rss Feed post image

Generate an RSS Feed for Your Next.js app

A few weeks ago, I was working on a update for my personal website and I also update the way I generate the RSS feed for my blog posts.

As a big fan of RSS feeds, I think it’s a great way to keep up with your favorite websites without having to visit them all the time. I’ll skip the part that generates the blog posts, since I’m using the MDXTS to manage my MDX files.

Asumming you have a Next.js app running, and a way to list your posts, the step to generate the RSS feed is pretty simple.

Step 1: Create a new directory

First, create a new directory in your app directory called feed.xml. With this new folder created, let’s create a file called route.ts. This file will be responsible for generating the RSS feed.

Before writing the code, let’s install the feed package.

npm install feed

With the package installed, let’s write the code to generate the RSS feed. Inside the route.ts file, let’s import the Feed class from the feed package and the blogPosts from the your data provider.

route.ts
import { Feed } from "feed";
import { blogPosts } from "@/your-data-provider";

export async function GET() {
  const siteUrl = "https://raisiqueira.io";
  const feedOptions = {
    title: "Raí Siqueira",
    language: "en",
    id: siteUrl,
    link: siteUrl,
    description: "Raí Siqueira's blog",
    image: `${siteUrl}/og.png`,
    copyright: `All rights reserved ${new Date().getFullYear()}, Raí Siqueira`,
    author: {
      name: "Raí Siqueira",
      link: `${siteUrl}/blog`,
    },
  };

  // Create a new feed object.
  const feed = new Feed(feedOptions);
  const posts = blogPosts();

  // Let's add the posts to the feed object.
  post.forEach((post) => {
    feed.addItem({
      title: post.title,
      id: `${siteUrl}/blog/${post.slug}`,
      link: `${siteUrl}/blog/${post.slug}`,
      description: post.excerpt,
      date: new Date(post.date).toISOString(),
      author: [
        {
          name: "Raí Siqueira",
          link: `${siteUrl}/blog`,
        },
      ],
    });
  });

  // Return the RSS feed
  return new Response(feed.rss2(), {
    headers: {
      "Content-Type": "application/atom+xml; charset=utf-8",
    },
  });
}

With the code above, we are creating a new RSS feed with the Feed class from the feed package. We are also adding the posts from the blogPosts function to the feed object. Now, if you visit the /feed.xml route in your Next.js app, you should see the RSS feed.

RSS Feed

Wrapping up

In this post, we learned how to generate an RSS feed for your Next.js app. We used the feed package to create the RSS feed and added the posts to the feed object. If you have any questions, feel free to reach out to me on Twitter .