DEV Community

Cover image for RSS Feed with Next.js 14 and App Router
Drazen Bebic
Drazen Bebic Subscriber

Posted on • Originally published at drazen.bebic.dev on

RSS Feed with Next.js 14 and App Router

Creating an RSS feed for your NextJS applications is easy peasy. The really "difficult" part lies with fetching the data and transforming it before it's passed to the RSS feed. This is especially true if you need to modify the data first (if the blog posts come in a Markdown format for example).

But to keep this guide simple, we will only focus on creating the RSS feed itself. So without further ado, this is how we do it:

Dependencies

Install the rss package with the package manager of your choice.

yarn add rss

npm install rss

pnpm add rss

feed.xml

Create the following file in your project: src/app/feed.xml/route.ts. This will allow us to handle the request for the /feed.xml URL of our website server-sided, without any React components.

Your route.ts should look a little like this:

import RSS from 'rss';

export async function GET() {
  // First we will add some basic blog info.
  const feed = new RSS({
    title: "Drazen's Tech Blog",
    description: 'I do stuff.',
    generator: 'RSS for Node and Next.js',
    feed_url: 'https://drazen.bebic.dev/feed.xml',
    site_url: 'https://drazen.bebic.dev',
    managingEditor: 'drazen@bebic.at (Drazen Bebic)',
    webMaster: 'drazen@bebic.at (Drazen Bebic)',
    copyright: 'Copyright 2024, Drazen Bebic',
    language: 'en-US',
    pubDate: new Date().toUTCString(),
    ttl: 60,
  });

  // Then we will add our individual blog posts. You can of course
  // fetch these from somewhere else.
  feed.item({
    title: 'Blog Post #1',
    description: 'Description of Blog Post #1',
    url: `https://drazen.bebic.dev/blog/blog-post-1`,
    categories: ['nextjs', 'blog'],
    author: 'Drazen Bebic',
    date: '2024-08-27',
  });
  feed.item({
    title: 'Blog Post #2',
    description: 'Description of Blog Post #2',
    url: `https://drazen.bebic.dev/blog/blog-post-2`,
    categories: ['nextjs', 'blog'],
    author: 'Drazen Bebic',
    date: '2024-08-28',
  });

  // And finally, we return a response with the appropriate
  // Content-Type header.
  return new Response(feed.xml({ indent: true }), {
    headers: {
      'Content-Type': 'application/xml; charset=utf-8',
    },
  });
}

Enter fullscreen mode Exit fullscreen mode

Accessing the route

Simply access the /feed.xml route of your application, you should see something like this:

RSS Feed Example

And that's something that RSS feed readers can work with. I use this to crosspost my blog to Dev.to (Hi dev.to readers! 👋).

Top comments (0)