Setting up RSS in a NextJS Blog

Since I'm working on getting this blog up and running, I wanted to also get RSS working well enough so folks can use their own readers. So far, I've found a few guides online on how to get it working in a nextjs site like I have, but I didn't really have much luck getting them working well enough so I'm documenting what I think works for me here.

After a bit of hacking, I decided to just use nextjs' API routes to solve this problem. I landed on this little bit of code located in /pages/api/rss.xml.ts (which serves /api/rss.xml through some goofy nextjs magic) in my blog's source tree:

/*
 * /pages/api/rss.xml.ts
 */
import type { NextApiRequest, NextApiResponse } from "next";
import RSS from "rss";
import { getPosts } from "../../lib/posts";

export default function handler(req: NextApiRequest, res: NextApiResponse<any>) {
  // Get all the posts
  const posts = getPosts();

  // create an RSS feed w/ some information
  var feed = new RSS({
    title: "Nick's Blog",
    feed_url: "https://nickw.io/api/rss.xml",
    site_url: "https://nickw.io",
    image_url: "https://nickw.io/favicon.ico",
  });

  // Simply add each post to the feed
  posts.forEach((post) => {
    feed.item({
      title: post.title,
      description: post.description,
      url: `https://nickw.io/post/${post.id}`,
      date: post.date,
      // TODO: description/content?
    });
  });

  res.setHeader("Content-Type", "application/rss+xml");
  res.setHeader("x-clacks-overhead", "GNU Bram Moolenaar");
  res.write(feed.xml());
  res.end();
}

Then, I added this to my site's <head>:

<link
  rel="alternate"
  type="application/rss+xml"
  title="Nick Wanninger's Blog"
  href="/api/rss.xml"
/>

So, all being well you should be able to subscribe to that RSS feed now! Only problem I can see right now is the feed technically regenerates each time someone requests it, but we will ignore that little performance problem for now. (it will be ignored forever)