Adding an RSS feed to the Next.js application
Adding an RSS feed for the Next.js application is pretty straightforward.
- Install RSS as a dependency in your project
- Create an API route named rss.xml.ts in your /pages/api directory. If you’re not familiar with API routes, you can read about them here
- An example implementation of rss.xml.ts can look like this
import { NextApiHandler } from 'next';
import RSS from 'rss';
import { notesApi } from '../../lib/notesApi';
const rss: NextApiHandler = async (req, res) => {
const feed = new RSS({
title: 'Bartosz Jarocki',
site_url: 'https://jarocki.me',
feed_url: 'https://jarocki.me/api/rss.xml',
});
// get all entries you want to be included in RSS feed
const allPosts = await notesApi.getNotes();
allPosts.map((post) => {
feed.item({
title: post.title,
url: `https://jarocki.me/notes/${post.slug}`,
date: post.publishedAt,
description: post.description,
});
});
res.setHeader('Content-Type', 'text/xml');
// configure the cache
res.setHeader('Cache-Control', 'public, s-maxage=1200, stale-while-revalidate=600');
// actually write the RSS feed as formatted XML
res.write(feed.xml({ indent: true }));
res.end();
};
export default rss;
Full implementation can be found here.
If you’d like to serve your sitemap without using api in the url, you can use middleware to do that.
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
export function middleware(request: NextRequest) {
if (request.nextUrl.pathname.startsWith('/rss.xml')) {
return NextResponse.rewrite(new URL('/api/rss.xml', request.url));
}
}
This middleware implementation intercepts requests for the /rss.xml path, and rewrites them to /api/rss.xml.