Adding an RSS feed to the Next.js application

Adding an RSS feed for the Next.js application is pretty straightforward.

  1. Install RSS as a dependency in your project
  2. 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
  3. 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: '',
    feed_url: '',

  // get all entries you want to be included in RSS feed
  const allPosts = await notesApi.getNotes(); => {
      title: post.title,
      url: `${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 }));

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.

Click here to share this article with your friends on Twitter if you liked it.