HomeBlog
Github IconLinkedIn IconThreads IconMail Icon

Adding an RSS feed to your static Next.js site

A quick explanation of how I added an RSS feed to my blog

2023-12-23

While fixing up this blog, I decided I wanted to publish an RSS feed for it. I struggled a bit at first to figure out the best way to do this properly in a fully static Next.js site, so I'm writing this in case it might help someone in the future.

So... here it is:

// /app/rss.xml/route.ts
import { Feed } from "feed";

export async function GET() {
  const feed = new Feed({
    title: "David Richey's Blog",
    description: "My personal blog, mostly about programming",
    id: "https://darichey.com",
    link: "https://darichey.com",
    copyright: "All rights reserved",
  });

  // get allMyPosts from somewhere, populate the feed somehow
  for (const post of allMyPosts) {
    feed.addItem({
      title: post.title,
      description: post.subtitle,
      date: new Date(post.date),
      link: post.link,
    });
  }

  return new Response(feed.rss2());
}

That's all it takes! You can stop reading now if that's all you need.

Details

This takes advantage of Next.js Route Handlers. This approach was non-obvious to me, because, in my goal to create a static site, I had previously dismissed route handlers as a feature I could use. I viewed them as a purely dynamic thing (how is my static site going to handle a request?), but that is not the case! Specifically, GET handlers "render to a static file during next build".

In fact... this exact RSS use case is an example in the docs! In my defense, I did search 🥲 an image of the Next.js docs site with the search query "rss". No results are found.

Alternatives

Before backing up and considering route handlers, I tried a few different things...

In the end, I'm glad I stopped and read through the docs again, because the final product is infinitely better than any of those!